diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..a54dadad --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: [zjs81] +custom: + - "https://paypal.me/zjs82" diff --git a/README.md b/README.md index acf1215a..42ad8800 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ MeshCore Open is a cross-platform mobile application for communicating with Mesh Get it on Obtainium +The [web client](https://meshcoreopen.org/install/web/) runs in Chromium (Chrome, Edge, Brave) over Web Bluetooth or Web Serial. Firefox and Safari do not support those APIs. TCP on the web needs a websocket bridge. + ## Screenshots @@ -48,7 +50,7 @@ MeshCore Open is a cross-platform mobile application for communicating with Mesh - **Live Map View**: Real-time visualization of mesh network nodes on an interactive map - **Node Filtering**: Filter by node type (chat, repeater, sensor) and time range - **Location Sharing**: Share GPS coordinates and custom markers with contacts -- **Offline Maps**: Download map tiles for offline use in remote areas +- **Offline Maps**: Download map tiles for offline use in remote areas (with [StadiaMaps](https://stadiamaps.com/pricing/) Free Subscription API-Key) - **MGRS Coordinates**: Support for Military Grid Reference System coordinate format ### Device Management @@ -131,6 +133,16 @@ MeshCore Open is a cross-platform mobile application for communicating with Mesh flutter run ``` +### Web (self-host) + +Use a Chromium browser. Device APIs are origin-gated, so serve the build over HTTPS. + +```bash +flutter build web --release +``` + +Then serve `build/web/` from your own host. See [install/web](https://meshcoreopen.org/install/web/) for browser support and caveats. + ### Building for Release **Android APK:** @@ -224,6 +236,10 @@ Messages are transmitted as binary frames using a custom protocol optimized for This is an open-source project. Contributions are welcome! +## SWHID and Archive badge +[![SWH](https://archive.softwareheritage.org/badge/origin/https://github.com/zjs81/meshcore-open/)](https://archive.softwareheritage.org/browse/origin/?origin_url=https://github.com/zjs81/meshcore-open) +[![SWH](https://archive.softwareheritage.org/badge/swh:1:dir:d37a80b06359730864150ad2aeadd46cce9abd55/)](https://archive.softwareheritage.org/swh:1:dir:d37a80b06359730864150ad2aeadd46cce9abd55;origin=https://github.com/zjs81/meshcore-open;visit=swh:1:snp:47656c4b55ab40a689ff8d2f045196725f05096b;anchor=swh:1:rev:0fe250230905fdd05dbedc0f546736990beacf53) + ### Development Guidelines - Follow the Flutter style guide diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d290213..bf8d4218 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,6 +7,15 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** include: package:flutter_lints/flutter.yaml linter: diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index c8028e0d..8aa73ce6 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -43,9 +43,22 @@ android { // arguments += listOf("-DANDROID_STL=c++_shared") // } // } - // ndk { - // abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86_64") - // } + // arm64-v8a only, deliberately. + // + // * ONNX Runtime (flutter_onnxruntime, used by the AEIC-SE image codec) + // ships a per-ABI .so. arm64-v8a alone costs ~18 MB of APK; a + // universal APK carrying armeabi-v7a and x86_64 as well costs ~56 MB. + // * llamadart only declares android-arm64 and android-x64 backends in + // pubspec.yaml's `hooks.user_defines`, so an armeabi-v7a build already + // has no translation backend at all. + // * The image codec needs ~2.7 GiB peak resident, which no 32-bit + // address space can provide regardless of ABI. + // + // Consequence: this APK will not install on 32-bit-only ARM devices or on + // x86_64 emulators. For emulator work, temporarily add "x86_64" here. + ndk { + abiFilters += listOf("arm64-v8a") + } } signingConfigs { @@ -67,6 +80,13 @@ android { } else { signingConfigs.getByName("debug") } + // ONNX Runtime resolves its Java classes from native code by name. + // Without these rules R8 renames them and the process SIGABRTs with + // "java_class == null" the instant the codec runs a model. + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) } } diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 00000000..aac0378c --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,19 @@ +# ONNX Runtime looks its Java classes up from native code with FindClass / +# GetMethodID, by literal name. R8 renames them, the lookup returns null, and +# the process dies with: +# +# JNI DETECTED ERROR IN APPLICATION: java_class == null +# at art::JNI::GetMethodID +# from convertToTensorInfo -> Java_ai_onnxruntime_OrtSession_run +# +# It is a hard SIGABRT in native code, so nothing in Dart can catch it: the app +# vanishes the moment the codec touches the model. Keep the whole package — +# these are the types the native layer reflects on to build tensors and read +# results back. +-keep class ai.onnxruntime.** { *; } +-keepclassmembers class ai.onnxruntime.** { *; } +-dontwarn ai.onnxruntime.** + +# The Flutter plugin's platform-channel handler, reached the same way. +-keep class com.masicai.flutteronnxruntime.** { *; } +-dontwarn com.masicai.flutteronnxruntime.** diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index ac3b4792..e4ef43fb 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index fb605bc8..ca7fe065 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -19,8 +19,8 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "8.9.1" apply false - id("org.jetbrains.kotlin.android") version "2.1.0" apply false + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false } include(":app") diff --git a/assets/fonts/Inter-OFL.txt b/assets/fonts/Inter-OFL.txt new file mode 100644 index 00000000..21f6aff9 --- /dev/null +++ b/assets/fonts/Inter-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/Inter.ttf b/assets/fonts/Inter.ttf new file mode 100644 index 00000000..047c92f6 Binary files /dev/null and b/assets/fonts/Inter.ttf differ diff --git a/assets/fonts/InterItalic.ttf b/assets/fonts/InterItalic.ttf new file mode 100644 index 00000000..c1775784 Binary files /dev/null and b/assets/fonts/InterItalic.ttf differ diff --git a/assets/fonts/JetBrainsMono-OFL.txt b/assets/fonts/JetBrainsMono-OFL.txt new file mode 100644 index 00000000..821a3dac --- /dev/null +++ b/assets/fonts/JetBrainsMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/JetBrainsMono.ttf b/assets/fonts/JetBrainsMono.ttf new file mode 100644 index 00000000..aa310be8 Binary files /dev/null and b/assets/fonts/JetBrainsMono.ttf differ diff --git a/docs/PRIVACY_POLICY.md b/docs/PRIVACY_POLICY.md index bdbe89d0..64bff9fb 100644 --- a/docs/PRIVACY_POLICY.md +++ b/docs/PRIVACY_POLICY.md @@ -1,6 +1,6 @@ # Privacy Policy for MeshCore Open -**Last Updated:** January 11, 2026 +**Last Updated:** August 23, 2026 ## Introduction @@ -11,16 +11,17 @@ MeshCore Open ("the App") is an open-source Flutter application for communicatin ### Data We Do NOT Collect MeshCore Open does **not**: -- Collect personal information -- Send data to external servers (except map tile requests) +- Collect personal information for the developer - Track your usage or behavior - Use analytics services - Require account creation -- Share any data with third parties +- Sell personal information + +The App does make limited requests to third-party services when you use features that require internet access, as described below. ### Data Stored Locally on Your Device -The App stores the following data **locally on your device only**: +The App stores the following data **locally on your device**: - **Messages**: Chat messages sent and received through the mesh network - **Contacts**: Names and identifiers of mesh network contacts @@ -30,7 +31,7 @@ The App stores the following data **locally on your device only**: - **Debug Logs**: Optional BLE and app debug logs (if enabled by user) - **Cached Map Tiles**: Offline map data for the mapping feature -All locally stored data remains on your device and is never transmitted to us or any third party. +This locally stored data is not transmitted to the MeshCore Open developer. Some features may send specific data to third-party services as described in the Third-Party Services section. ## Permissions @@ -45,12 +46,12 @@ These permissions are used solely to discover and communicate with MeshCore hard ### Location Permission - **ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION** -Required by Android for BLE scanning on Android 11 and below. The App does not track or store your location. Location data may be optionally shared over the mesh network if you choose to enable location sharing features. +Required by Android for BLE scanning on Android 11 and below. MeshCore Open does not use the phone's GPS to determine your location. Location data shown in the App comes from MeshCore devices and mesh advertisements. Location data may also be optionally shared over the mesh network if you choose to enable location sharing features. ### Internet Permission - **INTERNET** -Used only for downloading map tiles from OpenStreetMap tile servers when using the map feature. No personal data is transmitted. +Used for features that access third-party internet services, including map tiles, Line-of-Sight elevation lookups, optional model downloads, and optional GIF search. ### Notification Permission - **POST_NOTIFICATIONS** (Android 13+) @@ -65,7 +66,23 @@ Used to maintain BLE connection with your MeshCore device while the app is in th ## Third-Party Services ### Map Tiles -The App uses OpenStreetMap tile servers to display maps. When viewing maps, your device's IP address may be visible to the tile server. No other data is shared. See [OpenStreetMap's Privacy Policy](https://wiki.osmfoundation.org/wiki/Privacy_Policy) for more information. +The App uses OpenStreetMap and, when selected in settings, Stadia Maps tile servers to display maps. Map tile requests include tile coordinates that identify the geographic area being viewed, and your device's IP address may be visible to the tile provider. + +See [OpenStreetMap's Privacy Policy](https://wiki.osmfoundation.org/wiki/Privacy_Policy) and [Stadia Maps' Privacy Policy](https://stadiamaps.com/privacy/) for more information. + +### Line-of-Sight Elevation Lookups (Open-Meteo) +When you use the Line-of-Sight (LOS) analysis feature, the App sends latitude and longitude coordinates for points along the selected radio path to the Open-Meteo Elevation API. These coordinates come from MeshCore node positions or locations selected in the map, not from the phone's GPS. + +Open-Meteo uses these coordinates to return terrain elevation data needed for the LOS calculation. The request also exposes your device's IP address to Open-Meteo as part of normal internet communication. + +LOS elevation lookups are only made when the LOS feature is used. See [Open-Meteo's Terms and Privacy information](https://open-meteo.com/en/terms) for more information. + +### Model Downloads (Hugging Face) +The App can download optional translation models and the optional neural image-codec model bundle from Hugging Face when you choose to install or update those models in Settings. + +When a model download is requested, the App sends standard HTTP requests for the selected model files to `huggingface.co`. Your device's IP address is visible to Hugging Face as part of normal internet communication. The App does not upload your messages, contacts, mesh location data, or other locally stored content to Hugging Face as part of these model downloads. + +Model-download requests are only made when you choose to download or update a model. See [Hugging Face's Privacy Policy](https://huggingface.co/privacy) for more information. ### GIF Search (Giphy) The App includes a GIF picker feature powered by Giphy. When you use the GIF search feature: @@ -81,7 +98,7 @@ Messages sent through the MeshCore mesh network are transmitted over radio frequ ## Data Security -All data is stored locally on your device using standard Flutter/Android storage mechanisms. The App does not implement additional encryption for locally stored data beyond what the operating system provides. +All data stored locally on your device uses standard Flutter/Android storage mechanisms. The App does not implement additional encryption for locally stored data beyond what the operating system provides. ## Children's Privacy @@ -101,4 +118,4 @@ If you have questions about this Privacy Policy or the App's privacy practices, --- -**Summary**: MeshCore Open is a privacy-respecting app that stores all data locally on your device. We do not collect, track, or share your personal information. +**Summary**: MeshCore Open does not use the phone's GPS for location, does not include analytics, and does not collect personal information for the developer. Some optional features communicate with third-party services, including map tile providers, Open-Meteo for LOS elevation lookups, Hugging Face for model downloads, and Giphy for GIF search. diff --git a/documentation/README.md b/documentation/README.md index 13670134..a3700fc6 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -14,7 +14,8 @@ MeshCore Open is an open-source Flutter client for MeshCore LoRa mesh networking 8. [Notifications](notifications.md) - System notifications, unread badges, and notification preferences 9. [Repeater Management](repeater-management.md) - Repeater hub, status, CLI, telemetry, and neighbors 10. [Additional Features](additional-features.md) - GIF picker, localization, debug logs, SMAZ compression, and more -11. [BLE Protocol & Data Layer](ble-protocol.md) - Technical reference for the communication protocol and data architecture +11. [Routing Paths](routing-paths.md) - Path encoding, validation, device capability detection, and storage +12. [BLE Protocol & Data Layer](ble-protocol.md) - Technical reference for the communication protocol and data architecture ## App Overview diff --git a/documentation/additional-features.md b/documentation/additional-features.md index 997c2c11..6aeb37ed 100644 --- a/documentation/additional-features.md +++ b/documentation/additional-features.md @@ -183,7 +183,7 @@ An ML-based service that predicts expected delivery timeouts: - Applies a **1.5x safety margin** to raw predictions (the actual timeout issued is 1.5× the model's predicted delivery time) - Features with zero variance are automatically excluded from training - Blends per-contact statistics with ML predictions -- Falls back to `3000 + 3000 × pathLength` ms when insufficient data +- Falls back to `3000 + 3000 × pathLength` ms when insufficient data. Note: `pathLength` here refers to the stored hop count in the app's model/storage (number of hops), not the on-air encoded byte length. - Observations are persisted to storage via a 2-second debounced timer (observations within 2s of app termination may be lost) --- diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md new file mode 100644 index 00000000..56b4867f --- /dev/null +++ b/documentation/routing-paths.md @@ -0,0 +1,79 @@ +# Routing Paths + +This page covers how MeshCore Open represents, selects, validates, and stores routing paths in the UI and data layer. + +## Path Routing + +MeshCore supports variable-length multi-byte routing paths so the app can scale from small meshes to very large node sets. + +### Hash Width and Multi-Byte Paths + +The device capability determines the hash width (number of bytes per hop): + +| Width | Max Unique Nodes | Typical Use | +|-------|-----------------|-------------| +| 1 byte | 256 | Single-byte node IDs | +| 2 bytes | 65,536 | Medium meshes | +| 3 bytes | 16.7M | Large networks | +| 4 bytes | 4.3G | Very large meshes / future-proofing | + +### Device Capability Detection + +On device connection, the app reads the firmware capability to set `pathHashByteWidth`: + +```dart +// Read from device info response (offset 81) +final modeRaw = firmwareBytes.length >= 82 + ? (firmwareBytes[81] & 0xFF) + : 0; +final mode = modeRaw.clamp(0, 3); +_pathHashByteWidth = mode + 1; // 1, 2, 3, or 4 bytes per hop +``` + +The connector reads a single-mode byte and clamps to `0..3`, so the supported hop width is `1..4` bytes. UI code also clamps widths when rendering (typically to `1..4`) so 4-byte hops are handled end-to-end in the current codebase. + +### Path Data Structure + +Paths in messages and storage consist of: + + - **`pathLength` (model/storage)**: Hop count (number of hops). Negative values (e.g. `-1`) are used as a flood sentinel. + - **On-air `path_len` byte**: A packed byte that encodes hop count + hash width and is decoded into `pathLength` + `pathBytes` when parsing frames. + - **`pathBytes`**: Raw bytes of the path (concatenated hop prefixes), grouped by `pathHashByteWidth`. + - **`hopCount`**: Derived display value computed from bytes and width: `(byteCount + hashByteWidth - 1) ~/ hashByteWidth`. + - **Example**: With `pathHashByteWidth=2`, a 3-hop path has 6 bytes (`pathBytes.length = 6`) and `pathLength = 3`: + - `pathBytes = [0xA1, 0xA2, 0xB1, 0xB2, 0xC1, 0xC2]` + - Hops: `[0xA1A2]`, `[0xB1B2]`, `[0xC1C2]` + +### Hop Count Calculation + +Convert path byte length to hop count: + +```dart +int hopCount = (byteCount + hashByteWidth - 1) ~/ hashByteWidth; +``` + +Use this consistently when displaying hop counts in UI. Do not treat `pathLength` as a hop count when the path uses multi-byte hop hashes. + +### Path Usage in Different Message Types + +- **Direct messages**: Extract path from decrypted payload to trace sender route. +- **Channel messages**: Decrypt hop-by-hop routing chain from payload; the header carries the encoded byte length for the path blob, not the derived hop count. +- **Contact storage**: Path length in byte 32, raw path bytes in bytes 33-96, grouped by detected `pathHashByteWidth`. + +### UI Hop Count Display + +⚠️ **Important**: In screens like "Channel Message Path", prefer the actual decoded `pathBytes` hop count over `pathLength` metadata: + +```dart +// Preferred: use actual observed path length +final effectiveHopCount = (pathBytes.length + width - 1) ~/ width; + +// Avoid: using encoded byte length as if it were a hop count +// pathLength is bytes; converting it twice causes inflated counts +``` + +Example scenario: +- Radio header reports `pathLength: 32` bytes +- Decoded path bytes: `[0xAB, 0xCD]` (2 bytes = 1 hop with width=2) +- **Display**: "1 hop" (from `pathBytes`), not "32 hops" (which would double-count the encoded length) + diff --git a/documentation/settings.md b/documentation/settings.md index a2f4192a..8567cf4c 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -52,7 +52,7 @@ These settings are sent directly to the connected device firmware. ### Radio Settings Opens a dialog pre-populated with the device's current radio settings. Contains: -- **Preset dropdown**: Regional presets — selecting a preset immediately fills all fields below. Includes presets for Australia, Australia (Narrow), Australia SA WA QLD, Czech Republic, EU 433MHz, EU/UK (Long Range), EU/UK (Medium Range), EU/UK (Narrow), New Zealand, New Zealand (Narrow), Portugal 433, Portugal 869, numerous Russia city presets, Switzerland, USA Arizona, USA/Canada, and Vietnam +- **Preset dropdown**: Regional presets — selecting a preset immediately fills all fields below. Includes presets for Australia, Australia (Narrow), Australia (Mid), Australia SA WA QLD, Czech Republic, EU 433MHz, EU/UK (Long Range), EU/UK (Medium Range), EU/UK (Narrow), New Zealand, New Zealand (Narrow), Portugal 433, Portugal 869, numerous Russia city presets, Switzerland, USA Arizona, USA/Canada, and Vietnam - **Frequency** (MHz): Free text, validated 300–2500 MHz - **Bandwidth**: Dropdown (7.8 / 10.4 / 15.6 / 20.8 / 31.25 / 41.7 / 62.5 / 125 / 250 / 500 kHz) - **Spreading Factor**: SF5–SF12 @@ -129,6 +129,10 @@ A dedicated sub-screen for app-level preferences (nothing here is sent to the de - **Show Other Nodes**: Toggle room/sensor markers - **Time Filter**: All time / Last 1h / Last 6h / Last 24h / Last week - **Units**: Metric / Imperial +- **Raster Tile Source**: Sets the MAP theme and with that from where to get the map tile data: + - OpenStreetMap (Auto/Standard/Dark) is provided by the free OpenStreetMap tile server. (Can only be used for live view or already cached.) + - Stamen Terrain / AlidadeSmooth Dark / Outdoors / OSM Bright are [StadiaMaps.com raster tile maps](https://stadiamaps.com/products/maps/interactive-basemaps/) for which you can choose an Hosted Endpoint (Worldwide / Europe hosted) and have to provide the API key to your subscription. (You can cache these maps for offline Map usage.) + There will be no account provided by meshcore-open. You will have to get you own subscription. StadiaMaps offers a [free](https://stadiamaps.com/pricing/) subscription to download up to 200'000 Standart Raster Basemap tiles. - **Offline Map Cache**: Navigate to tile download screen ### Translation diff --git a/ios/ExportOptions.plist b/ios/ExportOptions.plist new file mode 100644 index 00000000..aadd0dac --- /dev/null +++ b/ios/ExportOptions.plist @@ -0,0 +1,16 @@ + + + + + method + app-store-connect + teamID + X74VJ4UAST + signingStyle + automatic + uploadSymbols + + destination + export + + diff --git a/ios/Podfile.lock b/ios/Podfile.lock index b0e98ca4..bc43ea0c 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -1,73 +1,21 @@ PODS: - Flutter (1.0.0) - - flutter_blue_plus_darwin (0.0.2): - - Flutter - - FlutterMacOS - flutter_foreground_task (0.0.1): - Flutter - - flutter_local_notifications (0.0.1): - - Flutter - - mobile_scanner (7.0.0): - - Flutter - - FlutterMacOS - - package_info_plus (0.4.5): - - Flutter - - share_plus (0.0.1): - - Flutter - - shared_preferences_foundation (0.0.1): - - Flutter - - FlutterMacOS - - sqflite_darwin (0.0.4): - - Flutter - - FlutterMacOS - - url_launcher_ios (0.0.1): - - Flutter DEPENDENCIES: - Flutter (from `Flutter`) - - flutter_blue_plus_darwin (from `.symlinks/plugins/flutter_blue_plus_darwin/darwin`) - flutter_foreground_task (from `.symlinks/plugins/flutter_foreground_task/ios`) - - flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`) - - mobile_scanner (from `.symlinks/plugins/mobile_scanner/darwin`) - - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - - share_plus (from `.symlinks/plugins/share_plus/ios`) - - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) - - sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`) - - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) EXTERNAL SOURCES: Flutter: :path: Flutter - flutter_blue_plus_darwin: - :path: ".symlinks/plugins/flutter_blue_plus_darwin/darwin" flutter_foreground_task: :path: ".symlinks/plugins/flutter_foreground_task/ios" - flutter_local_notifications: - :path: ".symlinks/plugins/flutter_local_notifications/ios" - mobile_scanner: - :path: ".symlinks/plugins/mobile_scanner/darwin" - package_info_plus: - :path: ".symlinks/plugins/package_info_plus/ios" - share_plus: - :path: ".symlinks/plugins/share_plus/ios" - shared_preferences_foundation: - :path: ".symlinks/plugins/shared_preferences_foundation/darwin" - sqflite_darwin: - :path: ".symlinks/plugins/sqflite_darwin/darwin" - url_launcher_ios: - :path: ".symlinks/plugins/url_launcher_ios/ios" SPEC CHECKSUMS: Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 - flutter_blue_plus_darwin: 20a08bfeaa0f7804d524858d3d8744bcc1b6dbc3 flutter_foreground_task: a159d2c2173b33699ddb3e6c2a067045d7cebb89 - flutter_local_notifications: a5a732f069baa862e728d839dd2ebb904737effb - mobile_scanner: 9157936403f5a0644ca3779a38ff8404c5434a93 - package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 - share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a - shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb - sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0 - url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b PODFILE CHECKSUM: e42b502c78c33aa1ed9d42eaea8960ce2139504b diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 7bf9b4cd..52009fe5 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; @@ -52,6 +53,7 @@ 718BC7DCCFC5C370705C12E5 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -67,6 +69,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, 9A698254711B63C3940A64CB /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -85,6 +88,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -180,13 +184,15 @@ 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, F0D7F2413C6E4B7A9B1C2D3E /* Fix Native Asset Minimum OS */, - B788CEDB957A87EE8AC593BB /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; @@ -220,6 +226,9 @@ Base, ); mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; @@ -283,39 +292,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - B788CEDB957A87EE8AC593BB /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Copy Pods Resources"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; - F0D7F2413C6E4B7A9B1C2D3E /* Fix Native Asset Minimum OS */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}", - ); - name = "Fix Native Asset Minimum OS"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "set -e\nFRAMEWORKS_DIR=\"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}\"\nMIN_OS=\"${IPHONEOS_DEPLOYMENT_TARGET}\"\nif [ ! -d \"$FRAMEWORKS_DIR\" ] || [ -z \"$MIN_OS\" ]; then\n exit 0\nfi\nfind \"$FRAMEWORKS_DIR\" -maxdepth 2 -name Info.plist | while read -r plist; do\n bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \"$plist\" 2>/dev/null || true)\n case \"$bundle_id\" in\n io.flutter.flutter.native-assets.*)\n /usr/libexec/PlistBuddy -c \"Set :MinimumOSVersion $MIN_OS\" \"$plist\" 2>/dev/null || \\\n /usr/libexec/PlistBuddy -c \"Add :MinimumOSVersion string $MIN_OS\" \"$plist\"\n ;;\n esac\ndone\n"; - }; DE3B2E091393835C0B38492E /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -338,6 +314,22 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; + F0D7F2413C6E4B7A9B1C2D3E /* Fix Native Asset Minimum OS */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}", + ); + name = "Fix Native Asset Minimum OS"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "set -e\nFRAMEWORKS_DIR=\"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}\"\nMIN_OS=\"${IPHONEOS_DEPLOYMENT_TARGET}\"\nif [ ! -d \"$FRAMEWORKS_DIR\" ] || [ -z \"$MIN_OS\" ]; then\n exit 0\nfi\nfind \"$FRAMEWORKS_DIR\" -maxdepth 2 -name Info.plist | while read -r plist; do\n bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \"$plist\" 2>/dev/null || true)\n case \"$bundle_id\" in\n io.flutter.flutter.native-assets.*)\n /usr/libexec/PlistBuddy -c \"Set :MinimumOSVersion $MIN_OS\" \"$plist\" 2>/dev/null || \\\n /usr/libexec/PlistBuddy -c \"Add :MinimumOSVersion string $MIN_OS\" \"$plist\"\n ;;\n esac\ndone\n"; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -446,7 +438,9 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = X74VJ4UAST; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( @@ -625,7 +619,9 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = X74VJ4UAST; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( @@ -647,7 +643,9 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = X74VJ4UAST; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( @@ -696,6 +694,20 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index e3773d42..c3fedb29 100644 --- a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -5,6 +5,24 @@ + + + + + + + + + + This app uses Bluetooth to communicate with MeshCore devices. NSCameraUsageDescription This app uses the camera to scan QR codes for joining communities. + NSPhotoLibraryUsageDescription + This app lets you pick a photo to compress and send over the mesh. UIApplicationSceneManifest UIApplicationSupportsMultipleScenes diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7dd550c4..6edcbe4e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -24,6 +24,16 @@ import '../services/ble_debug_log_service.dart'; import '../services/linux_ble_error_classifier.dart'; import '../services/linux_ble_pairing_service_stub.dart' if (dart.library.io) '../services/linux_ble_pairing_service.dart'; +import '../services/image_chunk_transport.dart' + show + ImageChunkOutcome, + ImageChunkTransport, + buildSendChannelDataFrame, + dataTypeAeicImage, + outPathUnknown, + respCodeChannelDataRecv, + senderPrefixFromKey; +import '../services/image_codec_service.dart'; import '../services/message_retry_service.dart'; import '../services/path_history_service.dart'; import '../services/app_settings_service.dart'; @@ -48,21 +58,57 @@ import '../utils/battery_utils.dart'; import '../utils/platform_info.dart'; import 'meshcore_uuids.dart'; import 'meshcore_protocol.dart'; +import 'pending_command_replies.dart'; class DirectRepeater { static const int maxAgeMinutes = 30; // Max age for direct repeater info - final int pubkeyFirstByte; + List pubkeyPrefix; + int pathHashWidth; + String? contactKeyHex; double snr; DateTime lastUpdated; DirectRepeater({ - required this.pubkeyFirstByte, + required List pubkeyPrefix, + required this.pathHashWidth, + this.contactKeyHex, required this.snr, DateTime? lastUpdated, - }) : lastUpdated = lastUpdated ?? DateTime.now(); + }) : pubkeyPrefix = List.unmodifiable(pubkeyPrefix), + lastUpdated = lastUpdated ?? DateTime.now(); - void update(double newSNR) { + String get pubkeyPrefixHex => pubkeyPrefix + .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) + .join(); + + bool matchesPrefix(List prefix) { + return pubkeyPrefix.length == prefix.length && + listEquals(pubkeyPrefix, prefix); + } + + bool matchesPathStart(List pathBytes, int pathHashByteWidth) { + final width = pathHashByteWidth.clamp(1, 4).toInt(); + if (pathBytes.length < width || pubkeyPrefix.length != width) { + return false; + } + return listEquals(pubkeyPrefix, pathBytes.sublist(0, width)); + } + + void update( + double newSNR, { + List? pubkeyPrefix, + int? pathHashWidth, + String? contactKeyHex, + }) { snr = newSNR; + if (pubkeyPrefix != null && + pubkeyPrefix.length >= this.pubkeyPrefix.length) { + this.pubkeyPrefix = List.unmodifiable(pubkeyPrefix); + } + if (pathHashWidth != null && pathHashWidth >= this.pathHashWidth) { + this.pathHashWidth = pathHashWidth; + } + this.contactKeyHex ??= contactKeyHex; lastUpdated = DateTime.now(); } @@ -127,6 +173,12 @@ class MeshCoreConnector extends ChangeNotifier { // Message windowing to limit memory usage static const int _messageWindowSize = 200; + // Cap on discovered (non-contact) nodes retained in memory. Adverts arrive + // continuously from the whole mesh, so without a bound this list grows for + // as long as the app stays connected. When full, the stalest node (oldest + // lastSeen) is evicted to make room for a newly heard one. + static const int _maxDiscoveredContacts = 500; + MeshCoreConnectionState _state = MeshCoreConnectionState.disconnected; BluetoothDevice? _device; BluetoothCharacteristic? _rxCharacteristic; @@ -137,6 +189,18 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + + /// Non-null while [disconnect] is tearing the transport down. Connect paths + /// join it so a teardown cannot finish after a new connection and reset the + /// state to `disconnected`. USB made this reachable: its native close now + /// waits out the kernel's closing_wait off the UI isolate, so the teardown + /// can outlive the tap that starts the next connection. + Future? _activeDisconnect; + + /// Set by [dispose]. A teardown started before disposal can still be running + /// (the USB native close waits out the kernel's closing_wait off the UI + /// isolate), so state publication is suppressed once the connector is gone. + bool _disposed = false; final MeshCoreUsbManager _usbManager = MeshCoreUsbManager(); final LinuxBlePairingService _linuxBlePairingService = LinuxBlePairingService(); @@ -152,7 +216,9 @@ class MeshCoreConnector extends ChangeNotifier { final Map> _conversations = {}; final Map> _channelMessages = {}; final List _pendingChannelSentQueue = []; - final List<_PendingCommandAck> _pendingGenericAckQueue = []; + final PendingCommandReplies _pendingGenericAckQueue = PendingCommandReplies( + staleAfter: _commandAckTimeout * 2, + ); static const String _reactionSendQueuePrefix = '__reaction_send__'; int _reactionSendQueueSequence = 0; final Set _loadedConversationKeys = {}; @@ -202,11 +268,19 @@ class MeshCoreConnector extends ChangeNotifier { double? _selfLongitude; final List _directRepeaters = List.empty(growable: true); bool _isLoadingContacts = false; + DateTime? _contactSyncRequestedAt; bool _hasLoadedContacts = false; bool _isLoadingChannels = false; bool _hasLoadedChannels = false; TimeoutPredictionService? _timeoutPredictionService; TranslationService? _translationService; + ImageCodecService? _imageCodecService; + // Holds the ImageReassembler, so partially received images survive across + // frames (chunks of one image arrive in separate GRP_DATA frames, and via the + // firmware offline queue they may be minutes apart). + ImageChunkTransport? _imageTransport; + void Function(ImageChunkOutcome outcome)? _onImageChunk; + void Function(int senderPrefix)? _onImageSenderPrefix; // Intentionally global (not per-contact): tracks overall network activity. // Frequent RX from any source indicates a busy network with more collisions. DateTime _lastRxTime = DateTime.now(); @@ -216,6 +290,9 @@ class MeshCoreConnector extends ChangeNotifier { DateTime _lastRadioRxTime = DateTime.fromMillisecondsSinceEpoch(0); DateTime _lastContactMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0); DateTime _lastChannelMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0); + DateTime _lastZeroHopAdvertAt = DateTime.fromMillisecondsSinceEpoch(0); + double? _lastZeroHopAdvertLatitude; + double? _lastZeroHopAdvertLongitude; static const int _radioQuietMs = 3000; static const int _radioQuietMaxWaitMs = 3000; @@ -227,6 +304,8 @@ class MeshCoreConnector extends ChangeNotifier { bool _batteryRequested = false; bool _awaitingSelfInfo = false; bool _hasReceivedDeviceInfo = false; + String? _manufacturerName; + String? _firmwareVersionString; // Initial sync is serialized for predictable progress. Firmware exposes one // FIFO queued-message stream, so direct/room frames are buffered until after // contacts are known. @@ -241,6 +320,12 @@ class MeshCoreConnector extends ChangeNotifier { bool _autoAddRoomServers = false; bool _autoAddSensors = false; bool _overwriteOldest = false; + int? _autoAddMaxHops; + bool _deviceConfigRequested = false; + List? _allowedRepeatFreqRanges; + bool _contactsStorageFull = false; + final StreamController _contactsFullController = + StreamController.broadcast(); bool _manualAddContacts = false; int _telemetryModeBase = 0; int _telemetryModeLoc = 0; @@ -295,6 +380,9 @@ class MeshCoreConnector extends ChangeNotifier { MessageRetryService? _retryService; PathHistoryService? _pathHistoryService; AppSettingsService? _appSettingsService; + + double get _initialRouteWeight => + _appSettingsService?.settings.initialRouteWeight ?? 1.0; BackgroundService? _backgroundService; final NotificationService _notificationService = NotificationService(); BleDebugLogService? _bleDebugLogService; @@ -312,12 +400,15 @@ class MeshCoreConnector extends ChangeNotifier { List _cachedChannels = []; final Map _channelSmazEnabled = {}; final Map _channelCyr2LatEnabled = {}; + final Map _channelUrlImagesEnabled = {}; final Map _channelCyr2LatProfileId = {}; final Map _channelRegions = {}; + Region _defaultRegion = ''; bool _lastSentWasCliCommand = false; // Track if last sent message was a CLI command final Map _contactSmazEnabled = {}; final Map _contactCyr2LatEnabled = {}; + final Map _contactUrlImagesEnabled = {}; final Map _contactCyr2LatProfileId = {}; final Set _knownContactKeys = {}; final Map _contactUnreadCount = {}; @@ -391,6 +482,13 @@ class MeshCoreConnector extends ChangeNotifier { ); } + Contact? getContactByPubKeyHex(String contactPubKeyHex) { + return _contacts.cast().firstWhere( + (c) => c?.publicKeyHex == contactPubKeyHex, + orElse: () => null, + ); + } + List get allContacts => List.unmodifiable([ ..._contacts, ..._discoveredContacts.where( @@ -414,7 +512,14 @@ class MeshCoreConnector extends ChangeNotifier { Stream get receivedFrames => _receivedFramesController.stream; Uint8List? get selfPublicKey => _selfPublicKey; String get selfPublicKeyHex => pubKeyToHex(_selfPublicKey ?? Uint8List(0)); + + /// First 2 bytes of the local public key, big-endian: the `senderPrefix` + /// stamped into every outgoing image chunk header. Null until SELF_INFO. + int? get imageSenderPrefix => senderPrefixFromKey(_selfPublicKey); + String? get selfName => _selfName; + String? get manufacturerName => _manufacturerName; + String? get firmwareVersionString => _firmwareVersionString; double? get selfLatitude => _selfLatitude; double? get selfLongitude => _selfLongitude; List get directRepeaters => _directRepeaters; @@ -444,6 +549,28 @@ class MeshCoreConnector extends ChangeNotifier { bool? get autoAddRoomServers => _autoAddRoomServers; bool? get autoAddSensors => _autoAddSensors; bool? get autoAddOverwriteOldest => _overwriteOldest; + + /// autoadd_max_hops from GET_AUTOADD_CONFIG (0 = no limit), null when the + /// firmware did not report it (pre-v1.13). + int? get autoAddMaxHops => _autoAddMaxHops; + + /// CMD_GET/SET_AUTOADD_CONFIG exist from companion v1.12.0 (ver code 8). + bool get supportsAutoAddConfig => (_firmwareVerCode ?? 0) >= 8; + + /// CMD_GET_ALLOWED_REPEAT_FREQ exists from ver code 9 (client repeat). + bool get supportsAllowedRepeatFreq => (_firmwareVerCode ?? 0) >= 9; + + /// Frequency ranges (kHz, inclusive) on which the firmware accepts client + /// repeat mode. Null until RESP_ALLOWED_REPEAT_FREQ has been received. + List? get allowedRepeatFreqRanges => + _allowedRepeatFreqRanges; + + /// True after PUSH_CODE_CONTACTS_FULL: the firmware could not store a new + /// contact. Cleared when a contact is removed or deleted. + bool get contactsStorageFull => _contactsStorageFull; + + /// Fires on each PUSH_CODE_CONTACTS_FULL. + Stream get contactsFullEvents => _contactsFullController.stream; int get telemetryModeBase => _telemetryModeBase; int get telemetryModeLoc => _telemetryModeLoc; int get telemetryModeEnv => _telemetryModeEnv; @@ -712,6 +839,15 @@ class MeshCoreConnector extends ChangeNotifier { return _contactSmazEnabled[contactKeyHex] ?? false; } + bool isChannelUrlImagesEnabled(int channelIndex) { + return _channelUrlImagesEnabled[channelIndex] ?? false; + } + + bool isContactUrlImagesEnabled(String contactKeyHex) { + _ensureContactUrlImagesSettingLoaded(contactKeyHex); + return _contactUrlImagesEnabled[contactKeyHex] ?? false; + } + bool hasChannelRegion(int channelIndex) { return (_channelRegions[channelIndex] ?? '').isNotEmpty; } @@ -720,6 +856,19 @@ class MeshCoreConnector extends ChangeNotifier { return _channelRegions[channelIndex] ?? ''; } + Region get defaultRegion => _defaultRegion; + + Region getEffectiveChannelRegion(int channelIndex) { + final region = getChannelRegion(channelIndex); + return region.isNotEmpty ? region : _defaultRegion; + } + + Future setDefaultRegion(Region region) async { + _defaultRegion = region; + notifyListeners(); + await _channelRegionStore.saveDefaultRegion(region); + } + void ensureContactSmazSettingLoaded(String contactKeyHex) { _ensureContactSmazSettingLoaded(contactKeyHex); } @@ -854,6 +1003,24 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + Future setChannelUrlImagesEnabled( + int channelIndex, + bool enabled, + ) async { + _channelUrlImagesEnabled[channelIndex] = enabled; + await _channelSettingsStore.saveUrlImagesEnabled(channelIndex, enabled); + notifyListeners(); + } + + Future setContactUrlImagesEnabled( + String contactKeyHex, + bool enabled, + ) async { + _contactUrlImagesEnabled[contactKeyHex] = enabled; + await _contactSettingsStore.saveUrlImagesEnabled(contactKeyHex, enabled); + notifyListeners(); + } + Future setChannelCyr2LatEnabled(int channelIndex, bool enabled) async { _channelCyr2LatEnabled[channelIndex] = enabled; if (enabled) { @@ -948,11 +1115,19 @@ class MeshCoreConnector extends ChangeNotifier { AppDebugLogService? appDebugLogService, BackgroundService? backgroundService, TimeoutPredictionService? timeoutPredictionService, + ImageCodecService? imageCodecService, + ImageChunkTransport? imageTransport, + void Function(ImageChunkOutcome outcome)? onImageChunk, + void Function(int senderPrefix)? onImageSenderPrefix, }) { _retryService = retryService; _pathHistoryService = pathHistoryService; _appSettingsService = appSettingsService; _translationService = translationService; + _imageCodecService = imageCodecService; + _imageTransport = imageTransport; + _onImageChunk = onImageChunk; + _onImageSenderPrefix = onImageSenderPrefix; _bleDebugLogService = bleDebugLogService; _appDebugLogService = appDebugLogService; _backgroundService = backgroundService; @@ -1016,6 +1191,7 @@ class MeshCoreConnector extends ChangeNotifier { } Future loadContactCache() async { + _contactUrlImagesEnabled.clear(); final cached = await _contactStore.loadContacts(); _knownContactKeys ..clear() @@ -1026,11 +1202,19 @@ class MeshCoreConnector extends ChangeNotifier { for (final contact in cached) { _ensureContactSmazSettingLoaded(contact.publicKeyHex); _ensureContactCyr2LatSettingLoaded(contact.publicKeyHex); + _ensureContactUrlImagesSettingLoaded(contact.publicKeyHex); } } Future _loadDiscoveredContactCache() async { final cached = await _discoveryContactStore.loadContacts(); + // Trim a previously-saved oversized list down to the freshest entries so a + // device that grew unbounded before the cap existed recovers on load. + if (cached.length > _maxDiscoveredContacts) { + cached.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + cached.removeRange(_maxDiscoveredContacts, cached.length); + unawaited(_discoveryContactStore.saveContacts(cached)); + } _discoveredContacts ..clear() ..addAll(cached); @@ -1039,12 +1223,16 @@ class MeshCoreConnector extends ChangeNotifier { Future loadChannelSettings({int? maxChannels}) async { _channelSmazEnabled.clear(); _channelCyr2LatEnabled.clear(); + _channelUrlImagesEnabled.clear(); _channelRegions.clear(); + _defaultRegion = _channelRegionStore.loadDefaultRegion(); final channelCount = maxChannels ?? _maxChannels; for (int i = 0; i < channelCount; i++) { _channelSmazEnabled[i] = await _channelSettingsStore.loadSmazEnabled(i); _channelCyr2LatEnabled[i] = await _channelSettingsStore .loadCyr2LatEnabled(i); + _channelUrlImagesEnabled[i] = await _channelSettingsStore + .loadUrlImagesEnabled(i); _channelRegions[i] = await _channelRegionStore.loadRegion(i); } } @@ -1144,10 +1332,13 @@ class MeshCoreConnector extends ChangeNotifier { int attempt, int timestampSeconds, ) async { - if (!isConnected || text.isEmpty) return; + if (!isConnected) throw StateError('Not connected'); + if (text.isEmpty) throw ArgumentError('Empty message text'); try { await _waitForRadioQuiet(lastInboundRxTime: _lastContactMsgRxTime); final outboundText = prepareContactOutboundText(contact, text); + // Wait for SENT so an ERR (unknown contact, packet pool full, text too + // long for this attempt) fails the message instead of timing out. await sendFrame( buildSendTextMsgFrame( contact.publicKey, @@ -1155,9 +1346,13 @@ class MeshCoreConnector extends ChangeNotifier { attempt: attempt, timestampSeconds: timestampSeconds, ), + waitForGenericAck: true, ); + } on TimeoutException catch (e) { + appLogger.warn('No SENT reply for message: $e', tag: 'Connector'); } catch (e) { appLogger.error('Failed to send message: $e', tag: 'Connector'); + rethrow; } } @@ -1637,6 +1832,18 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'USB', ); + await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectUsb ignored: already $_state after disconnect wait', + tag: 'USB', + ); + return; + } + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -1685,6 +1892,7 @@ class MeshCoreConnector extends ChangeNotifier { ); _setState(MeshCoreConnectionState.connected); + unawaited(_backgroundService?.start()); _pendingInitialChannelSync = true; _pendingInitialQueuedMessageSync = true; _pendingInitialContactsSync = true; @@ -1734,6 +1942,18 @@ class MeshCoreConnector extends ChangeNotifier { _appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP'); + await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connectTcp ignored: already $_state after disconnect wait', + tag: 'TCP', + ); + return; + } + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -1797,6 +2017,7 @@ class MeshCoreConnector extends ChangeNotifier { ); _setState(MeshCoreConnectionState.connected); + unawaited(_backgroundService?.start()); _pendingInitialChannelSync = true; _pendingInitialQueuedMessageSync = true; _pendingInitialContactsSync = true; @@ -1839,6 +2060,9 @@ class MeshCoreConnector extends ChangeNotifier { } } + @visibleForTesting + void handleFrameForTest(List data) => _handleFrame(data); + @visibleForTesting static bool shouldIgnoreLateTcpConnectError({ required bool manualDisconnect, @@ -1882,6 +2106,14 @@ class MeshCoreConnector extends ChangeNotifier { return; } + await _awaitActiveDisconnect(); + // The await is a suspension point: another connect may have claimed the + // connector while this one was waiting for the teardown. + if (_state == MeshCoreConnectionState.connecting || + _state == MeshCoreConnectionState.connected) { + return; + } + _activeTransport = MeshCoreTransportType.bluetooth; await stopScan(); @@ -2242,6 +2474,9 @@ class MeshCoreConnector extends ChangeNotifier { _pendingInitialChannelSync = true; } await _startBleInitialSync(); + if (_selfPublicKey != null) { + _reconnectAttempts = 0; + } } catch (e) { _appDebugLogService?.error('Connection error: $e', tag: 'BLE Connect'); final errorText = e.toString(); @@ -2520,9 +2755,13 @@ class MeshCoreConnector extends ChangeNotifier { void _resetConnectionHandshakeState() { _selfPublicKey = null; + // Partially received images belong to the previous session's sender prefix. + _imageTransport?.reassembler.clear(); _selfName = null; _selfLatitude = null; _selfLongitude = null; + _lastZeroHopAdvertLatitude = null; + _lastZeroHopAdvertLongitude = null; _awaitingSelfInfo = false; _webInitialHandshakeRequestSent = false; _selfInfoRetryTimer?.cancel(); @@ -2564,6 +2803,7 @@ class MeshCoreConnector extends ChangeNotifier { } bool get _shouldAutoReconnect => + !_disposed && !_manualDisconnect && _lastDeviceId != null && _activeTransport == MeshCoreTransportType.bluetooth; @@ -2577,7 +2817,6 @@ class MeshCoreConnector extends ChangeNotifier { void _cancelReconnectTimer() { _reconnectTimer?.cancel(); _reconnectTimer = null; - _reconnectAttempts = 0; } int _nextReconnectDelayMs() { @@ -2617,8 +2856,51 @@ class MeshCoreConnector extends ChangeNotifier { Future disconnect({ bool manual = true, bool skipBleDeviceDisconnect = false, + }) { + final inFlight = _activeDisconnect; + if (inFlight != null) { + if (manual) { + // A teardown started as automatic must still honour a later manual + // request, otherwise _manualDisconnect stays false and its tail + // schedules an auto-reconnect the user did not ask for. + _manualDisconnect = true; + _cancelReconnectTimer(); + unawaited(_backgroundService?.stop()); + } + return inFlight; + } + final teardown = _disconnectInternal( + manual: manual, + skipBleDeviceDisconnect: skipBleDeviceDisconnect, + ); + _activeDisconnect = teardown; + return teardown.whenComplete(() { + if (identical(_activeDisconnect, teardown)) { + _activeDisconnect = null; + } + }); + } + + /// Joins an in-flight [disconnect] so a new connection cannot be started + /// while the previous teardown is still running. + Future _awaitActiveDisconnect() async { + final pending = _activeDisconnect; + if (pending == null) return; + _appDebugLogService?.info( + 'Waiting for the in-flight disconnect to finish before connecting', + tag: 'Connection', + ); + try { + await pending; + } catch (_) { + // Teardown failures are logged by the disconnect path. + } + } + + Future _disconnectInternal({ + required bool manual, + required bool skipBleDeviceDisconnect, }) async { - if (_state == MeshCoreConnectionState.disconnecting) return; final transportAtDisconnect = _activeTransport; final transportLabel = switch (transportAtDisconnect) { MeshCoreTransportType.bluetooth => 'BLE', @@ -2634,11 +2916,17 @@ class MeshCoreConnector extends ChangeNotifier { if (manual) { _manualDisconnect = true; _cancelReconnectTimer(); + _reconnectAttempts = 0; unawaited(_backgroundService?.stop()); } else { _manualDisconnect = false; + // Only BLE reconnects on its own; nothing keeps TCP/USB alive. + if (transportAtDisconnect != MeshCoreTransportType.bluetooth) { + unawaited(_backgroundService?.stop()); + } } _setState(MeshCoreConnectionState.disconnecting); + _retryService?.failAllPending(); _stopBatteryPolling(); _stopRadioStatsPolling(); @@ -2661,6 +2949,19 @@ class MeshCoreConnector extends ChangeNotifier { _channelSyncTimeout = null; _channelSyncRetries = 0; await _translationService?.releaseModel(); + // The decode graph is ~833 MB resident; drop it with the connection. The + // connector never disposes services it does not own (main.dart does). + // + // Cancel first: `releaseModel` serialises behind the codec's exclusive + // lock, so disconnecting mid-decode would otherwise block this teardown + // for the ~1 s the inference takes and then tear the session out from + // under a job whose result nobody is waiting for any more. + _imageCodecService?.cancelCodecJob(); + await _imageCodecService?.releaseModel(); + // Partial images belong to this session's sender prefixes; a reconnect + // starts over. Dropping them also stops `evictExpired` from firing "image + // incomplete" failures into the store minutes after the radio went away. + _imageTransport?.reassembler.clear(); if (!skipBleDeviceDisconnect) { try { @@ -2689,9 +2990,14 @@ class MeshCoreConnector extends ChangeNotifier { _selfName = null; _selfLatitude = null; _selfLongitude = null; + _lastZeroHopAdvertLatitude = null; + _lastZeroHopAdvertLongitude = null; _clientRepeat = null; _rememberedNonRepeatRadioState = null; _firmwareVerCode = null; + _allowedRepeatFreqRanges = null; + _autoAddMaxHops = null; + _contactsStorageFull = false; _batteryMillivolts = null; _repeaterBatterySnapshots.clear(); _batteryRequested = false; @@ -2727,11 +3033,11 @@ class MeshCoreConnector extends ChangeNotifier { } _bleDebugLogService?.logFrame(data, outgoing: true); - final pendingAck = _trackPendingGenericAck( + final pendingAck = _pendingGenericAckQueue.track( data, channelSendQueueId: channelSendQueueId, - expectsGenericAck: expectsGenericAck || waitForGenericAck, - waitForAck: waitForGenericAck, + expectsOk: expectsGenericAck || waitForGenericAck, + waitForReply: waitForGenericAck, ); try { @@ -2770,7 +3076,7 @@ class MeshCoreConnector extends ChangeNotifier { try { await pendingAck!.completer!.future.timeout(const Duration(seconds: 5)); } on TimeoutException { - _pendingGenericAckQueue.remove(pendingAck); + _pendingGenericAckQueue.remove(pendingAck!); throw TimeoutException( 'Timed out waiting for firmware acknowledgement', ); @@ -2792,10 +3098,16 @@ class MeshCoreConnector extends ChangeNotifier { timer.cancel(); return; } - unawaited(requestBatteryStatus(force: true)); + unawaited( + requestBatteryStatus(force: true).catchError(_logTimerSendError), + ); }); } + void _logTimerSendError(Object error) { + _appDebugLogService?.warn('Periodic send failed: $error', tag: 'Connector'); + } + void _stopBatteryPolling() { _batteryPollTimer?.cancel(); _batteryPollTimer = null; @@ -2811,7 +3123,7 @@ class MeshCoreConnector extends ChangeNotifier { _gpsLocationPollTimer = null; return; } - unawaited(sendFrame(buildAppStartFrame())); + unawaited(sendFrame(buildAppStartFrame()).catchError(_logTimerSendError)); }); } @@ -2867,9 +3179,71 @@ class MeshCoreConnector extends ChangeNotifier { } catch (_) {} } + /// Sends CMD_SET_RADIO_PARAMS (same arguments as [buildSetRadioParamsFrame]) + /// and waits for the reply. Returns false when the firmware rejects it with + /// ERR_ILLEGAL_ARG (values out of range, or [clientRepeat] on a frequency + /// outside [allowedRepeatFreqRanges]) or does not answer in time. + Future setRadioParams( + int freqHz, + int bwHz, + int sf, + int cr, { + bool? clientRepeat, + }) async { + if (!isConnected) return false; + try { + await sendFrame( + buildSetRadioParamsFrame( + freqHz, + bwHz, + sf, + cr, + clientRepeat: clientRepeat, + ), + waitForGenericAck: true, + ); + return true; + } catch (e) { + _appDebugLogService?.warn( + 'SET_RADIO_PARAMS rejected: $e', + tag: 'Connector', + ); + return false; + } + } + Future setPathHashMode(int mode) async { if (!isConnected) return; - await sendFrame(buildSetPathHashModeFrame(mode.clamp(0, 2))); + final clampedMode = mode.clamp(0, 2).toInt(); + await sendFrame(buildSetPathHashModeFrame(clampedMode)); + final nextWidth = clampedMode + 1; + if (_pathHashByteWidth != nextWidth) { + _pathHashByteWidth = nextWidth; + _directRepeaters.clear(); + notifyListeners(); + } + } + + bool _isPathLenValidForCurrentMode(int pathLen, List pathBytes) { + return _isPathLenValidForMode(pathLen, pathBytes, _pathHashByteWidth); + } + + int? _encodePathLenForWidth( + int pathLen, + List pathBytes, + int pathHashWidth, + ) { + if (pathLen < 0 || pathLen == 0xFF) return pathLen; + if (!_isPathLenValidForMode(pathLen, pathBytes, pathHashWidth)) { + appLogger.warn( + 'Invalid path_len for mode: pathLen=$pathLen, ' + 'bytesLen=${pathBytes.length}, width=$pathHashWidth', + tag: 'Connector', + ); + return null; + } + final mode = (pathHashWidth - 1) & 0x03; + return (pathLen & 0x3F) | (mode << 6); } Future refreshDeviceInfo() async { @@ -2890,7 +3264,8 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildAppStartFrame()); await requestBatteryStatus(force: true); await sendFrame(buildGetCustomVarsFrame()); - await sendFrame(buildGetAutoAddFlagsFrame()); + _deviceConfigRequested = false; + _maybeRequestDeviceConfig(); _scheduleSelfInfoRetry(); } @@ -2913,10 +3288,35 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildAppStartFrame()); await sendFrame(buildGetCustomVarsFrame()); await requestBatteryStatus(); - await sendFrame(buildGetAutoAddFlagsFrame()); + _deviceConfigRequested = false; + _maybeRequestDeviceConfig(); _scheduleSelfInfoRetry(); } + /// Version-gated config queries, sent once the firmware version (DEVICE_INFO) + /// and SELF_INFO (which the auto-add reply handler relies on) are known. + void _maybeRequestDeviceConfig() { + if (_deviceConfigRequested || + !isConnected || + _firmwareVerCode == null || + _selfPublicKey == null) { + return; + } + _deviceConfigRequested = true; + if (supportsAutoAddConfig) { + unawaited( + sendFrame(buildGetAutoAddFlagsFrame()).catchError(_logTimerSendError), + ); + } + if (supportsAllowedRepeatFreq) { + unawaited( + sendFrame( + buildGetAllowedRepeatFreqFrame(), + ).catchError(_logTimerSendError), + ); + } + } + void _scheduleSelfInfoRetry() { _selfInfoRetryTimer?.cancel(); if (PlatformInfo.isWeb && @@ -2934,7 +3334,9 @@ class MeshCoreConnector extends ChangeNotifier { return; } attempts += 1; - unawaited(sendFrame(buildAppStartFrame())); + unawaited( + sendFrame(buildAppStartFrame()).catchError(_logTimerSendError), + ); if (attempts >= maxAttempts) { timer.cancel(); } @@ -2952,7 +3354,7 @@ class MeshCoreConnector extends ChangeNotifier { timer.cancel(); return; } - unawaited(sendFrame(buildAppStartFrame())); + unawaited(sendFrame(buildAppStartFrame()).catchError(_logTimerSendError)); }); } @@ -2961,16 +3363,28 @@ class MeshCoreConnector extends ChangeNotifier { (c) => c.publicKeyHex == contact.publicKeyHex, orElse: () => contact, ); + final hasDeviceLocation = + contact.latitude != null && contact.longitude != null; return contact.copyWith( rawPacket: tmp.rawPacket, - latitude: tmp.latitude, - longitude: tmp.longitude, + latitude: hasDeviceLocation ? contact.latitude : tmp.latitude, + longitude: hasDeviceLocation ? contact.longitude : tmp.longitude, ); } Future getContacts({int? since, bool preserveExisting = false}) async { if (!isConnected) return; + // The firmware answers ERR_BAD_STATE while an iteration is running, and + // clearing here would drop the contacts already received. A sync older + // than a minute is assumed lost (e.g. END_OF_CONTACTS never arrived). + final requestedAt = _contactSyncRequestedAt; + if (_isLoadingContacts && + requestedAt != null && + DateTime.now().difference(requestedAt) < const Duration(minutes: 1)) { + return; + } + _contactSyncRequestedAt = DateTime.now(); _isLoadingContacts = true; _preserveContactsOnRefresh = preserveExisting; _contactSyncTotal = null; @@ -2982,7 +3396,13 @@ class MeshCoreConnector extends ChangeNotifier { } notifyListeners(); - await sendFrame(buildGetContactsFrame(since: since)); + try { + await sendFrame(buildGetContactsFrame(since: since)); + } catch (_) { + _isLoadingContacts = false; + notifyListeners(); + rethrow; + } } Future refreshContacts() async { @@ -3021,9 +3441,15 @@ class MeshCoreConnector extends ChangeNotifier { // Check if this is a reaction - apply locally with pending status and route through retry service final reactionInfo = ReactionHelper.parseReaction(text); if (reactionInfo != null) { + appLogger.info('Sending reaction: ${reactionInfo.identifier()}'); _conversations.putIfAbsent(contact.publicKeyHex, () => []); final messages = _conversations[contact.publicKeyHex]!; + // No check for duplicates. If you want to do it again to resend, you can. + final String reactionID = reactionInfo.identifier(); + _processedContactReactions.putIfAbsent(contact.publicKeyHex, () => {}); + _processedContactReactions[contact.publicKeyHex]!.add(reactionID); + // Apply reaction locally with pending status _processOutgoingContactReaction(messages, reactionInfo, contact); _setReactionStatus( @@ -3065,18 +3491,21 @@ class MeshCoreConnector extends ChangeNotifier { translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, ); - _addMessage(contact.publicKeyHex, message); + _addMessage(contact.publicKeyHex, message); // recipient as "sender" notifyListeners(); final outboundText = prepareContactOutboundText(contact, text); await sendFrame(buildSendTextMsgFrame(contact.publicKey, outboundText)); } } + /// [pathHashWidth] defaults to the width implied by [customPath], falling + /// back to the radio's current mode (e.g. for zero-hop paths). Future setContactPath( Contact contact, Uint8List customPath, - int pathLen, - ) async { + int pathLen, { + int? pathHashWidth, + }) async { // Serialize path operations to prevent interleaved async calls from // leaving in-memory state inconsistent with the device. final prev = _pathOpLock; @@ -3086,14 +3515,24 @@ class MeshCoreConnector extends ChangeNotifier { try { if (!isConnected) return; + final width = + pathHashWidth ?? + (pathLen > 0 && customPath.length % pathLen == 0 + ? customPath.length ~/ pathLen + : _pathHashByteWidth); + final encodedPathLen = _encodePathLenForWidth(pathLen, customPath, width); + if (encodedPathLen == null) { + return; + } await sendFrame( buildUpdateContactPathFrame( contact.publicKey, customPath, - pathLen, + encodedPathLen, type: contact.type, flags: contact.flags, name: contact.name, + lastAdvert: _deviceLastAdvert(contact), ), ); // USB writes return instantly (no BLE flow control), so give the firmware @@ -3106,8 +3545,9 @@ class MeshCoreConnector extends ChangeNotifier { ); if (idx != -1) { _contacts[idx] = _contacts[idx].copyWith( - pathLength: customPath.length, + pathLength: pathLen, path: customPath, + pathHashWidth: width, ); notifyListeners(); } @@ -3116,6 +3556,15 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// The advert timestamp the firmware holds for [contact] (Contact.lastSeen + /// is parsed from that field); the stored copy is freshest. + DateTime _deviceLastAdvert(Contact contact) { + for (final c in _contacts) { + if (c.publicKeyHex == contact.publicKeyHex) return c.lastSeen; + } + return contact.lastSeen; + } + Future setContactFlags( Contact contact, { bool? isFavorite, @@ -3147,14 +3596,21 @@ class MeshCoreConnector extends ChangeNotifier { : (updatedFlags & ~contactFlagTeleEnv)) : updatedFlags; + final encodedPathLen = _encodePathLenForWidth( + latestContact.pathLength, + latestContact.path, + latestContact.pathHashWidth, + ); + if (encodedPathLen == null) return; await sendFrame( buildUpdateContactPathFrame( latestContact.publicKey, latestContact.path, - latestContact.pathLength, + encodedPathLen, type: latestContact.type, flags: updatedFlags, name: latestContact.name, + lastAdvert: latestContact.lastSeen, ), ); @@ -3167,6 +3623,7 @@ class MeshCoreConnector extends ChangeNotifier { name: latestContact.name, pathLength: latestContact.pathLength, path: latestContact.path, + pathHashWidth: latestContact.pathHashWidth, flags: updatedFlags, ); notifyListeners(); @@ -3234,6 +3691,18 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); + if (pathLen != null && + pathLen >= 0 && + !_isPathLenValidForCurrentMode(pathLen, pathBytes ?? Uint8List(0))) { + appLogger.warn( + 'setPathOverride: invalid path for ${contact.name}: ' + 'pathLen=$pathLen, bytesLen=${pathBytes?.length ?? 0}, ' + 'width=$_pathHashByteWidth', + tag: 'Connector', + ); + return; + } + // Update contact with new path override _contacts[index] = _contacts[index].copyWith( pathOverride: pathLen, @@ -3352,7 +3821,7 @@ class MeshCoreConnector extends ChangeNotifier { final updated = Contact.fromFrame(frame); if (updated == null) return; if (updated.publicKeyHex != contact.publicKeyHex) return; - final matchesLength = updated.pathLength == expectedLength; + final matchesLength = updated.path.length == expectedLength; final matchesBytes = _pathsEqual(updated.path, expectedPath); if (matchesLength && matchesBytes) { finish(true); @@ -3375,17 +3844,19 @@ class MeshCoreConnector extends ChangeNotifier { String? originalText, String? translatedLanguageCode, String? translationModelId, + ChannelMessage? replyTo, }) async { if (!isConnected || text.isEmpty) return; // Check if this is a reaction - if so, process it immediately instead of adding as a message final reactionInfo = ReactionHelper.parseReaction(text); if (reactionInfo != null) { + reactionInfo.senderName = selfName; // Check if we've already processed this reaction _processedChannelReactions.putIfAbsent(channel.index, () => {}); - final reactionIdentifier = - '${reactionInfo.targetHash}_${reactionInfo.emoji}'; + final reactionIdentifier = reactionInfo.identifier(); + // Maybe we should allow resending. Recipients can drop duplicates. if (_processedChannelReactions[channel.index]!.contains( reactionIdentifier, )) { @@ -3398,27 +3869,30 @@ class MeshCoreConnector extends ChangeNotifier { final messages = _channelMessages[channel.index]!; // Process reaction locally to update the UI immediately - _processReaction(messages, reactionInfo); - await _channelMessageStore.saveChannelMessages(channel.index, messages); + appLogger.info('Adding sent channel reaction, id: $reactionIdentifier'); + final reactionApplied = _processReaction(messages, reactionInfo); + if (reactionApplied) { + await _channelMessageStore.saveChannelMessages(channel.index, messages); - // Mark this reaction as processed - _processedChannelReactions[channel.index]!.add(reactionIdentifier); + // Mark this reaction as processed + _processedChannelReactions[channel.index]!.add(reactionIdentifier); - notifyListeners(); + notifyListeners(); - // Send the reaction to the device (don't add as a visible message) - final reactionQueueId = _nextReactionSendQueueId(); - _pendingChannelSentQueue.add(reactionQueueId); - await _runScopedChannelSend(() async { - await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); - await _sendFrameAndWaitForCommandAck( - buildSendChannelTextMsgFrame(channel.index, text), - channelSendQueueId: reactionQueueId, - expectsGenericAck: true, - successCode: respCodeSent, - ); - }, region: getChannelRegion(channel.index)); - return; + // Send the reaction to the device (don't add as a visible message) + final reactionQueueId = _nextReactionSendQueueId(); + _pendingChannelSentQueue.add(reactionQueueId); + await _runScopedChannelSend(() async { + await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); + await _sendFrameAndWaitForCommandAck( + buildSendChannelTextMsgFrame(channel.index, text), + channelSendQueueId: reactionQueueId, + ); + }, region: getEffectiveChannelRegion(channel.index)); + return; + } + // It looks like a reaction, but we did not find its target, so + // we continue to process it normally. } final message = ChannelMessage.outgoing( @@ -3428,21 +3902,192 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + replyTo: replyTo, ); _addChannelMessage(channel.index, message); _pendingChannelSentQueue.add(message.messageId); notifyListeners(); final outboundText = prepareChannelOutboundText(channel.index, text); - await _runScopedChannelSend(() async { - await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); - await _sendFrameAndWaitForCommandAck( - buildSendChannelTextMsgFrame(channel.index, outboundText), - channelSendQueueId: message.messageId, - expectsGenericAck: true, - successCode: respCodeSent, + // Resends reuse the timestamp, so they are the same packet: repeaters + // that already forwarded it drop the copy and recipients see it once. + Future transmit({bool isResend = false}) => + _runScopedChannelSend(() async { + await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); + await _sendFrameAndWaitForCommandAck( + buildSendChannelTextMsgFrame( + channel.index, + outboundText, + timestamp: message.timestamp.millisecondsSinceEpoch ~/ 1000, + ), + channelSendQueueId: isResend ? null : message.messageId, + ); + }, region: getEffectiveChannelRegion(channel.index)); + await transmit(); + + final settings = _appSettingsService?.settings; + if (settings != null && settings.channelMinHopsEnabled) { + unawaited( + _resendUntilMinHops( + message.messageId, + () => transmit(isResend: true), + minHops: settings.channelMinHops, + maxResends: settings.channelMinHopsRetries, + ), ); - }, region: getChannelRegion(channel.index)); + } + } + + /// How long to listen for a channel message to come back through the mesh + /// before resending it. + static const Duration _channelHopCheckDelay = Duration(seconds: 30); + + /// Resends a channel message until one of its echoes has travelled through + /// at least [minHops] repeaters, then gives up and marks it failed. + Future _resendUntilMinHops( + String messageId, + Future Function() resend, { + required int minHops, + required int maxResends, + }) async { + _channelHopChecks[messageId] = (resends: 0, maxResends: maxResends); + notifyListeners(); + var hops = 0; + try { + for (var attempt = 0; ; attempt++) { + await Future.delayed(_channelHopCheckDelay); + final message = _findChannelMessageById(messageId); + if (message == null) return; + if (message.status == ChannelMessageStatus.failed) return; + hops = message.pathLength ?? 0; + if (hops >= minHops) { + _appDebugLogService?.info( + 'Channel message reached $hops hops after $attempt resends', + tag: 'Channel resend', + ); + return; + } + if (attempt >= maxResends || !isConnected) break; + _appDebugLogService?.info( + 'Heard at $hops of $minHops hops; resending ' + '(${attempt + 1} of $maxResends)', + tag: 'Channel resend', + ); + _channelHopChecks[messageId] = ( + resends: attempt + 1, + maxResends: maxResends, + ); + notifyListeners(); + try { + await resend(); + } catch (e) { + _appDebugLogService?.warn( + 'Channel resend failed: $e', + tag: 'Channel resend', + ); + break; + } + } + _appDebugLogService?.warn( + 'Channel message only heard at $hops of $minHops hops; giving up', + tag: 'Channel resend', + ); + // It was sent and may well have travelled further than we can hear, so + // this is a warning, not a failure. + _channelHopShortfalls[messageId] = (hops: hops, required: minHops); + } finally { + _channelHopChecks.remove(messageId); + notifyListeners(); + } + } + + final Map _channelHopChecks = {}; + final Map _channelHopShortfalls = {}; + + /// Set when resending gave up before hearing the message through enough + /// repeaters. Kept for this session only. + ({int hops, int required})? channelHopShortfall(String messageId) => + _channelHopShortfalls[messageId]; + + /// Resend progress for a channel message still waiting to travel far + /// enough, or null when it is not being watched. + ({int resends, int maxResends})? channelResendProgress(String messageId) => + _channelHopChecks[messageId]; + + ChannelMessage? _findChannelMessageById(String messageId) { + for (final messages in _channelMessages.values) { + for (int i = messages.length - 1; i >= 0; i--) { + if (messages[i].messageId == messageId) return messages[i]; + } + } + return null; + } + + /// Minimum companion firmware version code whose CMD_SEND_CHANNEL_DATA (62) + /// / RESP_CODE_CHANNEL_DATA_RECV (27) layout matches ours (v1.15.0, ver 11). + static const int _minFirmwareVerCodeForChannelData = 11; + + /// True when the connected device can send/receive GRP_DATA blobs. + bool get supportsChannelData => + isConnected && + (_firmwareVerCode ?? 0) >= _minFirmwareVerCodeForChannelData; + + /// Sends one image's chunk [blobs] as GRP_DATA packets on [channelIndex], + /// strictly sequentially, inside a single scoped-send scope for the whole + /// image (the flood scope is global, so re-entering it per chunk would let + /// another channel's send interleave mid-image). + /// + /// [onProgress] fires after each chunk is acked, so the UI can show + /// "sending 2 of 3". + /// + /// IMPORTANT: the command ACK only proves the firmware accepted the blob and + /// queued a packet to the radio. It says nothing about transmission or + /// delivery — GRP_DATA is unacknowledged flood traffic, there is no + /// PUSH_CODE_SEND_CONFIRMED for it, and a chunk may still be lost on air. + /// That is what the XOR parity chunk is for. + /// + /// Returns false when the transport is unavailable (disconnected or firmware + /// too old); throws whatever [_sendFrameAndWaitForCommandAck] throws, i.e. + /// Exception('Command failed with error code N') where N is 1 + /// (unsupported command), 2 (bad channel index), 3 (packet pool full, worth + /// retrying) or 6 (illegal arg — blob too long or bad data type), or a + /// TimeoutException after _commandAckTimeout. + Future sendImageChunks( + List blobs, { + required int channelIndex, + required Duration interChunkDelay, + void Function(int sent, int total)? onProgress, + }) async { + if (blobs.isEmpty) return false; + if (!supportsChannelData) return false; + // `return` inside the scoped callback only exits the callback, so a + // disconnect mid-send used to fall through to `return true` below and the + // caller would record a complete outgoing image and tell the user "sent" + // after transmitting a prefix of the chunks. Track it explicitly. + var sentAll = true; + await _runScopedChannelSend(() async { + for (var i = 0; i < blobs.length; i++) { + if (!isConnected) { + sentAll = false; + return; + } + if (i > 0) await Future.delayed(interChunkDelay); + // Same collision avoidance as every other channel send. On a quiet mesh + // this returns almost immediately; interChunkDelay is what actually + // paces the chunks so we do not talk over our own previous packet. + await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); + await _sendFrameAndWaitForCommandAck( + buildSendChannelDataFrame( + channelIndex: channelIndex, + dataType: dataTypeAeicImage, + payload: blobs[i], + pathLen: outPathUnknown, // 0xFF => flood + ), + ); + onProgress?.call(i + 1, blobs.length); + } + }, region: getEffectiveChannelRegion(channelIndex)); + return sentAll; } Future _runScopedChannelSend( @@ -3477,57 +4122,29 @@ class MeshCoreConnector extends ChangeNotifier { } } - // Sends [data] and resolves once the device replies. [successCode] is the - // response code that signals success for this frame: SET_FLOOD_SCOPE replies - // with RESP_CODE_OK, whereas a channel text send replies with RESP_CODE_SENT. - // Waiting for the text send's RESP_CODE_SENT before the scope is reset - // guarantees the firmware has already built the packet with the active scope. + // Sends [data] and resolves once the device replies to this command. + // SET_FLOOD_SCOPE, CMD_SEND_CHANNEL_DATA and CMD_SEND_CHANNEL_TXT_MSG all + // reply with RESP_CODE_OK or an ERR (the firmware never sends RESP_CODE_SENT + // for channel sends). Replies are attributed through the generic-ack queue + // (see [_handleOk] and [_handleErrorFrame]) so an OK/ERR produced by another + // in-flight command cannot complete it. + // Waiting for the text send's reply before the scope is reset guarantees + // the firmware has already built the packet with the active scope. Future _sendFrameAndWaitForCommandAck( Uint8List data, { String? channelSendQueueId, - bool expectsGenericAck = false, - int successCode = respCodeOk, - }) async { - final completer = Completer(); - late final StreamSubscription subscription; - late final Timer timeout; - - void complete() { - if (!completer.isCompleted) completer.complete(); - } - - void completeError(Object error) { - if (!completer.isCompleted) completer.completeError(error); - } - - subscription = receivedFrames.listen((frame) { - if (frame.isEmpty) return; - if (frame[0] == successCode) { - complete(); - } else if (frame[0] == respCodeErr) { - final errCode = frame.length > 1 ? frame[1] : -1; - completeError(Exception('Command failed with error code $errCode')); - } - }); - - timeout = Timer(_commandAckTimeout, () { - completeError(TimeoutException('Command ACK timed out')); - }); - - try { - await sendFrame( - data, - channelSendQueueId: channelSendQueueId, - expectsGenericAck: expectsGenericAck, - ); - await completer.future; - } finally { - timeout.cancel(); - await subscription.cancel(); - } + }) { + return sendFrame( + data, + channelSendQueueId: channelSendQueueId, + waitForGenericAck: true, + ); } - Future removeContact(Contact contact) async { + Future removeContact( + Contact contact, { + bool keepMessages = false, + }) async { if (!isConnected) return; _handleDiscovery( @@ -3537,6 +4154,7 @@ class MeshCoreConnector extends ChangeNotifier { ); await sendFrame(buildRemoveContactFrame(contact.publicKey)); + _contactsStorageFull = false; _contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex); _knownContactKeys.remove(contact.publicKeyHex); unawaited(updateKnownDiscovered()); @@ -3550,7 +4168,7 @@ class MeshCoreConnector extends ChangeNotifier { _unreadStore.saveContactUnreadCount( Map.from(_contactUnreadCount), ); - _messageStore.clearMessages(contact.publicKeyHex); + if (!keepMessages) _messageStore.clearMessages(contact.publicKeyHex); notifyListeners(); } @@ -3581,16 +4199,23 @@ class MeshCoreConnector extends ChangeNotifier { // Manual saves must bypass the firmware's auto-add discovery policy. // CMD_IMPORT_CONTACT replays an advert and may remain discovery-only. + final encodedPathLen = _encodePathLenForWidth( + contact.pathLength, + contact.path, + contact.pathHashWidth, + ); + if (encodedPathLen == null) return false; await sendFrame( buildUpdateContactPathFrame( contact.publicKey, contact.path, - contact.pathLength, + encodedPathLen, type: contact.type, flags: contact.flags, name: contact.name, lat: contact.latitude, lon: contact.longitude, + lastAdvert: contact.lastSeen, lastModified: contact.lastSeen, ), waitForGenericAck: true, @@ -3612,9 +4237,10 @@ class MeshCoreConnector extends ChangeNotifier { type: contact.type, pathLength: contact.pathLength, path: contact.path, + pathHashWidth: contact.pathHashWidth, latitude: contact.latitude, longitude: contact.longitude, - lastSeen: DateTime.now(), + lastSeen: contact.lastSeen, flags: contact.flags, ), ); @@ -3797,6 +4423,11 @@ class MeshCoreConnector extends ChangeNotifier { Future sendSelfAdvert({bool flood = true}) async { if (!isConnected) return; await sendFrame(buildSendSelfAdvertFrame(flood: flood)); + if (!flood) { + _lastZeroHopAdvertAt = DateTime.now(); + _lastZeroHopAdvertLatitude = _selfLatitude; + _lastZeroHopAdvertLongitude = _selfLongitude; + } } Future rebootDevice() async { @@ -4035,6 +4666,7 @@ class MeshCoreConnector extends ChangeNotifier { final code = frame[0]; // debugPrint('RX frame: code=$code len=${frame.length}'); + final completedPendingReply = _pendingGenericAckQueue.completeReply(frame); switch (code) { case respCodeOk: @@ -4070,16 +4702,40 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); break; case pushCodeAdvert: - // Known contact was seen again - just a pub key, no action needed + // A stored contact advertised (or was just auto-added): pub key only. + if (frame.length >= 1 + pubKeySize) { + unawaited( + getContactByKey( + Uint8List.fromList(frame.sublist(1, 1 + pubKeySize)), + ).catchError(_logTimerSendError), + ); + } break; case pushCodeNewAdvert: debugPrint('Got New CONTACT'); - // It's the same format as respCodeContact, so we can reuse the handler - _handleContact(frame, isContact: false); + _handleNewAdvert(frame); break; case respCodeContact: debugPrint('Got CONTACT'); - _handleContact(frame); + _handleContact(frame, countTowardSync: !completedPendingReply); + break; + case pushCodeContactDeleted: + _handleContactDeleted(frame); + break; + case pushCodeContactsFull: + _appDebugLogService?.warn( + 'Firmware contact storage is full; new contact not stored', + tag: 'Connector', + ); + _contactsStorageFull = true; + _contactsFullController.add(null); + notifyListeners(); + break; + case respCodeAllowedRepeatFreq: + _allowedRepeatFreqRanges = List.unmodifiable( + parseAllowedRepeatFreqFrame(frame), + ); + notifyListeners(); break; case respCodeEndOfContacts: debugPrint('Got END_OF_CONTACTS'); @@ -4116,9 +4772,32 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeChannelMsgRecvV3: _handleIncomingChannelMessage(frame); break; + case respCodeChannelDataRecv: + // RESP_CODE 27 (GRP_DATA received) is delivered through the firmware + // offline queue in reply to CMD_SYNC_NEXT_MESSAGE, so the queued-message + // sync state machine MUST be advanced here — exactly like + // _handleIncomingChannelMessage does. Leaving code 27 unhandled stalls + // _queueSyncTimeout (5 s) x _maxQueueSyncRetries (3) per chunk and + // blocks every other queued message behind it. A receivedFrames + // listener cannot do this: the sync state is private. Advance exactly + // ONCE, before any async work. + if (_isSyncingQueuedMessages) { + _handleQueuedMessageReceived(); + } + // Advance the sync state machine ALWAYS (above), but only reassemble + // when the feature is actually on. Without this the "disabled" feature + // still reassembles, persists and displays received images: the store + // keeps them and channel_chat_screen renders every stored entry, so a + // user who never enabled image messages would see them appear. + if (_appSettingsService?.settings.imageMessagesEnabled ?? false) { + _handleIncomingChannelData(frame); + } + break; case respCodeSent: _handleMessageSent(frame); break; + case respCodeExportContact: + break; case respCodeNoMoreMessages: _handleNoMoreMessages(); break; @@ -4177,15 +4856,9 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Protocol', ); - if (_pendingGenericAckQueue.isEmpty) { - return; - } - - final failedAck = _pendingGenericAckQueue.removeAt(0); - failedAck.completer?.completeError( - Exception('Firmware rejected command with error code $errCode'), - ); - if (failedAck.commandCode != cmdSendChannelTxtMsg || + final failedAck = _pendingGenericAckQueue.takeErr(errCode); + if (failedAck == null || + failedAck.commandCode != cmdSendChannelTxtMsg || failedAck.channelSendQueueId == null) { return; } @@ -4203,7 +4876,10 @@ class MeshCoreConnector extends ChangeNotifier { ); if (contact != null) { - _pathHistoryService!.handlePathUpdated(contact); + _pathHistoryService!.handlePathUpdated( + contact, + initialWeight: _initialRouteWeight, + ); // Refresh just this specific contact instead of all contacts. // This avoids race conditions with _preserveContactsOnRefresh flag // that can occur when using refreshContactsSinceLastmod(). @@ -4254,12 +4930,56 @@ class MeshCoreConnector extends ChangeNotifier { _currentCr = reader.readByte(); _selfName = reader.readCString(); + + // The local public key only exists once SELF_INFO has arrived, so the + // image sender prefix (first 2 bytes, big-endian) is refreshed here. + final prefix = senderPrefixFromKey(_selfPublicKey); + if (prefix != null) { + _imageTransport?.senderPrefix = prefix; + _onImageSenderPrefix?.call(prefix); + } } catch (e) { _appDebugLogService?.error( 'Error parsing SELF_INFO frame: $e', tag: 'Connector', ); } + + const locationChangeEpsilon = 2.25e-4; // ~25 meters in degrees. + final lastAdvertLatitude = _lastZeroHopAdvertLatitude; + final lastAdvertLongitude = _lastZeroHopAdvertLongitude; + final currentLatitude = _selfLatitude; + final currentLongitude = _selfLongitude; + final latChanged = + lastAdvertLatitude != null && + currentLatitude != null && + (currentLatitude - lastAdvertLatitude).abs() >= locationChangeEpsilon; + final lonChanged = + lastAdvertLongitude != null && + currentLongitude != null && + (currentLongitude - lastAdvertLongitude).abs() >= locationChangeEpsilon; + final gpsSampleChanged = + hasValidLocation(currentLatitude, currentLongitude) && + (!hasValidLocation(lastAdvertLatitude, lastAdvertLongitude) || + latChanged || + lonChanged); + final effectiveGpsIntervalSeconds = + _appSettingsService?.resolvedGpsIntervalSeconds(_currentCustomVars) ?? + 0; + final timeSinceLastZeroHopAdvert = DateTime.now().difference( + _lastZeroHopAdvertAt, + ); + final shouldAutoSendZeroHopAdvert = + (gpsSampleChanged || (_clientRepeat ?? false)) && + _advertLocPolicy == 1 && + (_appSettingsService?.settings.autoSendZeroHopAdvertOnGpsUpdate ?? + false) && + effectiveGpsIntervalSeconds > 0 && + timeSinceLastZeroHopAdvert.inSeconds >= effectiveGpsIntervalSeconds; + if (shouldAutoSendZeroHopAdvert) { + unawaited(sendSelfAdvert(flood: false)); + } + final selfName = _selfName?.trim(); if (_activeTransport == MeshCoreTransportType.usb && selfName != null && @@ -4285,6 +5005,8 @@ class MeshCoreConnector extends ChangeNotifier { _contactStore.setPublicKeyHex = selfPublicKeyHex; _channelStore.setPublicKeyHex = selfPublicKeyHex; _unreadStore.setPublicKeyHex = selfPublicKeyHex; + _discoveryContactStore.setPublicKeyHex = selfPublicKeyHex; + _pathHistoryService?.setDevicePublicKey(selfPublicKeyHex); // Now that we have self info, we can load all the persisted data for this node _loadChannelOrder(); @@ -4300,6 +5022,7 @@ class MeshCoreConnector extends ChangeNotifier { _awaitingSelfInfo = false; _selfInfoRetryTimer?.cancel(); _selfInfoRetryTimer = null; + _maybeRequestDeviceConfig(); notifyListeners(); // Start the serialized initial sync pipeline after SELF_INFO. @@ -4313,17 +5036,35 @@ class MeshCoreConnector extends ChangeNotifier { } _firmwareVerCode = frame[1]; + // Manufacturer/model name (bytes 20..59) and firmware version (60..79) + String? readCString(int start, int maxLen) { + if (frame.length < start + maxLen) return null; + final bytes = frame.sublist(start, start + maxLen); + final end = bytes.indexOf(0); + final s = String.fromCharCodes( + end >= 0 ? bytes.sublist(0, end) : bytes, + ).trim(); + return s.isEmpty ? null : s; + } + + _manufacturerName = readCString(20, 40); + _firmwareVersionString = readCString(60, 20); + // Parse client_repeat from firmware v9+ (byte 80) if (frame.length >= 81) { _clientRepeat = frame[80] != 0; } // Path hash mode v10+ (byte 81): width = mode + 1 byte(s) per hop + final previousPathHashByteWidth = _pathHashByteWidth; if (frame.length >= 82) { final mode = (frame[81] & 0xFF).clamp(0, 2); _pathHashByteWidth = mode + 1; } else { _pathHashByteWidth = 1; } + if (_pathHashByteWidth != previousPathHashByteWidth) { + _directRepeaters.clear(); + } // Firmware reports MAX_CONTACTS / 2 for v3+ device info. final reportedContacts = frame[2]; @@ -4348,6 +5089,7 @@ class MeshCoreConnector extends ChangeNotifier { } } } + _maybeRequestDeviceConfig(); notifyListeners(); if (_shouldGateInitialChannelSync) { _maybeStartInitialChannelSync(); @@ -4419,7 +5161,7 @@ class MeshCoreConnector extends ChangeNotifier { // sender prefixes can be resolved against the current contact list. while (_deferredQueuedContactMessageFrames.isNotEmpty) { final frame = _deferredQueuedContactMessageFrames.removeAt(0); - await _handleIncomingMessage(frame); + await _handleIncomingMessage(frame, alreadyAdvancedQueueSync: true); } } finally { _deferQueuedContactMessagesUntilContacts = false; @@ -4493,6 +5235,7 @@ class MeshCoreConnector extends ChangeNotifier { autoAddRoomServer: true, autoAddSensor: true, overwriteOldest: _overwriteOldest, + maxHops: _autoAddMaxHops, ), ); await sendFrame( @@ -4520,7 +5263,6 @@ class MeshCoreConnector extends ChangeNotifier { spreadingFactor: _currentSf!, bandwidthHz: _currentBwHz!, codingRate: cr, - lowDataRateOptimize: _currentSf! >= 11, ); } return 50; // fallback: ~SF7/BW125 for 100 bytes @@ -4602,10 +5344,41 @@ class MeshCoreConnector extends ChangeNotifier { return physicsMax.clamp(0, _hardMaxTimeoutMs); } - void _handleContact(Uint8List frame, {bool isContact = true}) { + /// PUSH_CODE_NEW_ADVERT carries a contact the firmware did NOT store + /// (type not auto-added, beyond autoadd_max_hops, or storage full; + /// BaseChatMesh::onAdvertRecv), so it only feeds the discovered list. + void _handleNewAdvert(Uint8List frame) { + final contact = Contact.fromFrame(frame); + if (contact == null || listEquals(contact.publicKey, _selfPublicKey)) { + return; + } + _handleDiscovery(contact, frame); + notifyListeners(); + } + + /// PUSH_CODE_CONTACT_DELETED: the firmware overwrote this contact to make + /// room for a new one (auto-add overwrite-oldest). + void _handleContactDeleted(Uint8List frame) { + if (frame.length < 1 + pubKeySize) return; + final keyHex = pubKeyToHex( + Uint8List.fromList(frame.sublist(1, 1 + pubKeySize)), + ); + _appDebugLogService?.info( + 'Firmware deleted contact ${keyHex.substring(0, 8)} to make room', + tag: 'Connector', + ); + _contacts.removeWhere((c) => c.publicKeyHex == keyHex); + _knownContactKeys.remove(keyHex); + _contactsStorageFull = false; + unawaited(updateKnownDiscovered()); + unawaited(_persistContacts()); + notifyListeners(); + } + + void _handleContact(Uint8List frame, {bool countTowardSync = true}) { final contactTmp = Contact.fromFrame(frame); if (contactTmp != null) { - if (isContact && _isLoadingContacts) { + if (countTowardSync && _isLoadingContacts) { _contactSyncReceived++; } if (listEquals(contactTmp.publicKey, _selfPublicKey)) { @@ -4669,31 +5442,21 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); } else { - if ((_autoAddUsers && contact.type == advTypeChat) || - (_autoAddRepeaters && contact.type == advTypeRepeater) || - (_autoAddRoomServers && contact.type == advTypeRoom) || - (_autoAddSensors && contact.type == advTypeSensor) || - isContact) { - _contacts.add(contact); - appLogger.info( - 'Added new contact ${contact.name}: pathLen=${contact.pathLength}', - tag: 'Connector', - ); - } else { - appLogger.info( - "Discovered contact ${contact.name} (type ${contact.typeLabelRaw}) not added due to auto-add settings", - tag: 'Connector', - ); - notifyListeners(); - return; - } + _contacts.add(contact); + appLogger.info( + 'Added new contact ${contact.name}: pathLen=${contact.pathLength}', + tag: 'Connector', + ); } _knownContactKeys.add(contact.publicKeyHex); _loadMessagesForContact(contact.publicKeyHex); // Add path to history if we have a valid path if (_pathHistoryService != null && contact.pathLength >= 0) { - _pathHistoryService!.handlePathUpdated(contact); + _pathHistoryService!.handlePathUpdated( + contact, + initialWeight: _initialRouteWeight, + ); } notifyListeners(); @@ -4771,7 +5534,10 @@ class MeshCoreConnector extends ChangeNotifier { // Add path to history if we have a valid path if (_pathHistoryService != null && contact.pathLength >= 0) { - _pathHistoryService!.handlePathUpdated(contact); + _pathHistoryService!.handlePathUpdated( + contact, + initialWeight: _initialRouteWeight, + ); } notifyListeners(); @@ -4841,6 +5607,7 @@ class MeshCoreConnector extends ChangeNotifier { String senderName, DateTime timestamp, { Uint8List? pathBytes, + int? pathHashWidth, bool notify = false, }) { final normalized = senderName.trim().toLowerCase(); @@ -4864,7 +5631,11 @@ class MeshCoreConnector extends ChangeNotifier { for (var i = 0; i < _contacts.length; i++) { final contact = _contacts[i]; if (contact.type != advTypeChat) continue; - if (_pathMatchesContact(pathBytes, contact.publicKey)) { + if (_pathMatchesContact( + pathBytes, + contact.publicKey, + pathHashWidth: pathHashWidth, + )) { matches.add(i); } } @@ -4881,8 +5652,12 @@ class MeshCoreConnector extends ChangeNotifier { } } - bool _pathMatchesContact(Uint8List pathBytes, Uint8List publicKey) { - final w = _pathHashByteWidth; + bool _pathMatchesContact( + Uint8List pathBytes, + Uint8List publicKey, { + int? pathHashWidth, + }) { + final w = pathHashWidth ?? _pathHashByteWidth; if (pathBytes.isEmpty || publicKey.length < w) return false; for (int i = 0; i + w <= pathBytes.length; i += w) { final prefix = pathBytes.sublist(i, i + w); @@ -4893,12 +5668,15 @@ class MeshCoreConnector extends ChangeNotifier { return false; } - Future _handleIncomingMessage(Uint8List frame) async { + Future _handleIncomingMessage( + Uint8List frame, { + bool alreadyAdvancedQueueSync = false, + }) async { if (_selfPublicKey == null) return; // If we're syncing the queued messages, advance the queue immediately // before any potentially long async work (like translation/notifications). - if (_isSyncingQueuedMessages) { + if (_isSyncingQueuedMessages && !alreadyAdvancedQueueSync) { _handleQueuedMessageReceived(); } @@ -4991,6 +5769,8 @@ class MeshCoreConnector extends ChangeNotifier { await _notificationService.showMessageNotification( contactName: c?.name ?? 'Unknown', message: resolvedText, + urlImagesEnabled: + c != null && isContactUrlImagesEnabled(c.publicKeyHex), contactId: msg.senderKeyHex, badgeCount: getTotalUnreadCount(), ); @@ -5005,6 +5785,8 @@ class MeshCoreConnector extends ChangeNotifier { await _notificationService.showMessageNotification( contactName: c?.name ?? 'Unknown Room', message: resolvedText, + urlImagesEnabled: + c != null && isContactUrlImagesEnabled(c.publicKeyHex), contactId: msg.senderKeyHex, badgeCount: getTotalUnreadCount(), ); @@ -5012,9 +5794,6 @@ class MeshCoreConnector extends ChangeNotifier { }()); } } - _handleQueuedMessageReceived(); - } else if (_isSyncingQueuedMessages) { - _handleQueuedMessageReceived(); } } @@ -5104,7 +5883,7 @@ class MeshCoreConnector extends ChangeNotifier { isOutgoing: false, isCli: isCli, status: MessageStatus.delivered, - pathLength: pathLength == 0xFF ? 0 : pathLength, + pathLength: pathLength == 0xFF ? null : (pathLength & 0x3F), pathBytes: Uint8List(0), fourByteRoomContactKey: roomAuthorPrefix, ); @@ -5155,6 +5934,15 @@ class MeshCoreConnector extends ChangeNotifier { }); } + void _ensureContactUrlImagesSettingLoaded(String contactKeyHex) { + if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return; + _contactSettingsStore.loadUrlImagesEnabled(contactKeyHex).then((enabled) { + if (_contactUrlImagesEnabled[contactKeyHex] == enabled) return; + _contactUrlImagesEnabled[contactKeyHex] = enabled; + notifyListeners(); + }); + } + void _ensureContactCyr2LatProfileLoaded(String contactKeyHex) { if (_contactCyr2LatProfileId.containsKey(contactKeyHex)) return; _contactSettingsStore.loadCyr2LatProfileId(contactKeyHex).then((profileId) { @@ -5309,12 +6097,26 @@ class MeshCoreConnector extends ChangeNotifier { channelName: label, senderName: message.senderName, message: resolvedText, + urlImagesEnabled: isChannelUrlImagesEnabled(channelIndex), channelIndex: message.channelIndex, badgeCount: getTotalUnreadCount(), ); }()); } + /// Handles RESP_CODE_CHANNEL_DATA_RECV (GRP_DATA). Frames whose dataType is + /// not 0xAE1C — or that arrive before an [ImageChunkTransport] is installed — + /// are ignored without disturbing any other behaviour. + void _handleIncomingChannelData(Uint8List frame) { + // Anchor the post-RX backoff for our own next channel send, exactly as + // _handleIncomingChannelMessage does. + _lastChannelMsgRxTime = DateTime.now(); + final outcome = _imageTransport?.handleFrame(frame); + if (outcome == null) return; // Not an AEIC image chunk. + _onImageChunk?.call(outcome); + notifyListeners(); + } + void _handleIncomingChannelMessage(Uint8List frame) async { // If we're syncing the queued messages, advance the queue immediately // before any potentially long async work (like translation/notifications). @@ -5337,6 +6139,7 @@ class MeshCoreConnector extends ChangeNotifier { message.senderName, message.timestamp, pathBytes: message.pathBytes, + pathHashWidth: message.pathHashWidth, ); final isNew = _addChannelMessage(message.channelIndex!, message); _maybeIncrementChannelUnread(message, isNew: isNew); @@ -5351,9 +6154,6 @@ class MeshCoreConnector extends ChangeNotifier { _maybeNotifyChannelMessage(msg, translationResult: translationResult); }()); } - _handleQueuedMessageReceived(); - } else if (_isSyncingQueuedMessages) { - _handleQueuedMessageReceived(); } } @@ -5381,7 +6181,7 @@ class MeshCoreConnector extends ChangeNotifier { if (hash != channelHash) continue; try { final decryptedBytes = _decryptPayload(channel.psk, encrypted); - if (decryptedBytes == null || decryptedBytes.length < 6) return; + if (decryptedBytes == null || decryptedBytes.length < 6) continue; final decrypted = BufferReader(decryptedBytes); final timestampRaw = decrypted.readUInt32LE(); @@ -5414,6 +6214,7 @@ class MeshCoreConnector extends ChangeNotifier { isOutgoing: false, status: ChannelMessageStatus.sent, pathLength: packet.isFlood ? packet.hopCount : 0, + pathHashWidth: packet.pathHashWidth, pathBytes: packet.pathBytes, channelIndex: channel.index, packetHash: pktHash, @@ -5423,6 +6224,7 @@ class MeshCoreConnector extends ChangeNotifier { parsed.senderName, message.timestamp, pathBytes: message.pathBytes, + pathHashWidth: message.pathHashWidth, ); final isNew = _addChannelMessage(channel.index, message); _maybeIncrementChannelUnread(message, isNew: isNew); @@ -5484,10 +6286,6 @@ class MeshCoreConnector extends ChangeNotifier { retryService.updateMessageFromSent(ackHash, timeoutMs)) { return; } - - if (_markNextPendingChannelMessageSent()) { - return; - } } catch (e) { appLogger.warn('Error handling message sent frame: $e'); // Fallback to old behavior @@ -5504,19 +6302,6 @@ class MeshCoreConnector extends ChangeNotifier { } } - bool _markNextPendingChannelMessageSent() { - while (_pendingChannelSentQueue.isNotEmpty) { - final queuedMessageId = _pendingChannelSentQueue.removeAt(0); - if (_isReactionSendQueueId(queuedMessageId)) { - return true; - } - if (_markPendingChannelMessageSentById(queuedMessageId)) { - return true; - } - } - return false; - } - bool _markPendingChannelMessageSentById(String messageId) { for (final entry in _channelMessages.entries) { final channelMessages = entry.value; @@ -5568,13 +6353,9 @@ class MeshCoreConnector extends ChangeNotifier { } void _handleOk() { - if (_pendingGenericAckQueue.isEmpty) { - return; - } - - final pendingAck = _pendingGenericAckQueue.removeAt(0); - pendingAck.completer?.complete(); - if (pendingAck.commandCode != cmdSendChannelTxtMsg || + final pendingAck = _pendingGenericAckQueue.takeOk(); + if (pendingAck == null || + pendingAck.commandCode != cmdSendChannelTxtMsg || pendingAck.channelSendQueueId == null) { return; } @@ -5868,24 +6649,44 @@ class MeshCoreConnector extends ChangeNotifier { if (reactionInfo != null) { // Check if we've already processed this exact reaction _processedContactReactions.putIfAbsent(pubKeyHex, () => {}); - final reactionIdentifier = - '${reactionInfo.targetHash}_${reactionInfo.emoji}'; - + reactionInfo.senderName = _resolveContactSenderName(message, null, false); + final reactionIdentifier = reactionInfo.identifier(); final isDuplicate = _processedContactReactions[pubKeyHex]!.contains( reactionIdentifier, ); + if (isDuplicate) return; - if (!isDuplicate) { - // New reaction - process it - _processContactReaction(messages, reactionInfo, pubKeyHex); + // New reaction - process it + // For hashing and dup checking, we use null for sender names in + // normal 1:1 chats. This way if we and they have different ideas + // about what their name is, reactions still work. But for reaction + // reports, we want to know who sent what, rather than infer it later, + // so we'll add it to the reactionInfo before storing it. + reactionInfo.senderName ??= message.isOutgoing + ? selfName + : getContactByPubKeyHex(pubKeyHex)?.name ?? '???'; + final reactionApplied = _processContactReaction( + messages, + reactionInfo, + pubKeyHex, + ); + if (reactionApplied) { + appLogger.info('Adding reaction, id: $reactionIdentifier'); _messageStore.saveMessages(pubKeyHex, messages); // Mark as processed _processedContactReactions[pubKeyHex]!.add(reactionIdentifier); notifyListeners(); + return; // Don't add reaction as a visible message } - return; // Don't add reaction as a visible message + + // Looks like a reaction, but didn't match any message we have. + // for reactions matching our own format, because those are not very + // informative on their own, but the MC1 format is useful even if + // in raw form, so we'll let those through. + appLogger.info('No match for reaction, id: $reactionIdentifier'); + if (reactionInfo.hashType == HashType.ours) return; } messages.add(message); @@ -5896,18 +6697,15 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } - void _processContactReaction( + bool _processContactReaction( List messages, ReactionInfo reactionInfo, String contactPubKeyHex, ) { - final contact = _contacts.cast().firstWhere( - (c) => c?.publicKeyHex == contactPubKeyHex, - orElse: () => null, - ); + final contact = getContactByPubKeyHex(contactPubKeyHex); final isRoomServer = contact?.type == advTypeRoom; - ReactionHelper.applyReaction( + return ReactionHelper.applyReaction( messages: messages, reactionInfo: reactionInfo, // Incoming reactions in 1:1: match against outgoing messages only @@ -5953,10 +6751,7 @@ class MeshCoreConnector extends ChangeNotifier { ) { final messages = _conversations[pubKeyHex]; if (messages == null) return; - final contact = _contacts.cast().firstWhere( - (c) => c?.publicKeyHex == pubKeyHex, - orElse: () => null, - ); + final contact = getContactByPubKeyHex(pubKeyHex); final isRoomServer = contact?.type == advTypeRoom; for (int i = messages.length - 1; i >= 0; i--) { final msg = messages[i]; @@ -6115,27 +6910,36 @@ class MeshCoreConnector extends ChangeNotifier { final messages = _channelMessages[channelIndex]!; // Parse reaction info - final reactionInfo = ChannelMessage.parseReaction(message.text); + final reactionInfo = message.parseReaction(); if (reactionInfo != null) { // Check if we've already processed this exact reaction _processedChannelReactions.putIfAbsent(channelIndex, () => {}); - final reactionIdentifier = - '${reactionInfo.targetHash}_${reactionInfo.emoji}'; + final reactionIdentifier = reactionInfo.identifier(); final isDuplicate = _processedChannelReactions[channelIndex]!.contains( reactionIdentifier, ); - if (!isDuplicate) { - // New reaction - process it - _processReaction(messages, reactionInfo); + if (isDuplicate) return false; + + // New reaction - process it + final reactionApplied = _processReaction(messages, reactionInfo); + if (reactionApplied) { + appLogger.info('Adding channel reaction, id: $reactionIdentifier'); // Save updated messages _channelMessageStore.saveChannelMessages(channelIndex, messages); // Mark as processed _processedChannelReactions[channelIndex]!.add(reactionIdentifier); + return false; // Don't add reaction as a visible message } - return false; // Don't add reaction as a visible message + // Looks like a reaction, but didn't match any message we have. + // Old behavior is to silently drop these. We'll continue doing that + // for reactions matching our own format, because those are not very + // informative on their own, but the MC1 format is useful even if + // in raw form, so we'll let those through. + appLogger.info('No match for reaction, id: $reactionIdentifier'); + if (reactionInfo.hashType == HashType.ours) return false; } // Parse reply info from message text @@ -6143,13 +6947,15 @@ class MeshCoreConnector extends ChangeNotifier { ChannelMessage processedMessage = message; if (replyInfo != null) { - // Find original message by sender name (most recent match) - final originalMessage = _findMessageBySender( - messages, - replyInfo.mentionedNode, - ); + // Outgoing replies already carry the selected target. The wire format + // only names the sender, so incoming replies fall back to that + // sender's most recent message. + final hasReplyTarget = message.replyToMessageId != null; + final originalMessage = hasReplyTarget + ? null + : _findMessageBySender(messages, replyInfo.mentionedNode); - if (originalMessage != null) { + if (hasReplyTarget || originalMessage != null) { // Create new message with reply metadata processedMessage = ChannelMessage( senderKey: message.senderKey, @@ -6166,13 +6972,16 @@ class MeshCoreConnector extends ChangeNotifier { repeats: message.repeats, repeatCount: message.repeatCount, pathLength: message.pathLength, + pathHashWidth: message.pathHashWidth, pathBytes: message.pathBytes, pathVariants: message.pathVariants, channelIndex: message.channelIndex, messageId: message.messageId, - replyToMessageId: originalMessage.messageId, - replyToSenderName: originalMessage.senderName, - replyToText: originalMessage.text, + replyToMessageId: + message.replyToMessageId ?? originalMessage!.messageId, + replyToSenderName: + message.replyToSenderName ?? originalMessage!.senderName, + replyToText: message.replyToText ?? originalMessage!.text, ); } } @@ -6190,10 +6999,14 @@ class MeshCoreConnector extends ChangeNotifier { existing.pathVariants, processedMessage.pathVariants, ); + final hashWidth = + (existing.pathHashWidth ?? processedMessage.pathHashWidth ?? 1) + .clamp(1, 3) + .toInt(); final mergedPathLength = _mergePathLength( existing.pathLength, processedMessage.pathLength, - mergedPathBytes.length, + mergedPathBytes.length ~/ hashWidth, ); final newRepeatCount = existing.repeatCount + 1; final promotedFromPending = @@ -6202,6 +7015,7 @@ class MeshCoreConnector extends ChangeNotifier { messages[existingIndex] = existing.copyWith( repeatCount: newRepeatCount, pathLength: mergedPathLength, + pathHashWidth: existing.pathHashWidth ?? processedMessage.pathHashWidth, pathBytes: mergedPathBytes, pathVariants: mergedPathVariants, packetHash: existing.packetHash ?? processedMessage.packetHash, @@ -6235,11 +7049,11 @@ class MeshCoreConnector extends ChangeNotifier { return null; } - void _processReaction( + bool _processReaction( List messages, ReactionInfo reactionInfo, ) { - ReactionHelper.applyReaction( + return ReactionHelper.applyReaction( messages: messages, reactionInfo: reactionInfo, shouldSkip: (_) => false, @@ -6269,37 +7083,53 @@ class MeshCoreConnector extends ChangeNotifier { } } // Second pass: heuristic fallback (outgoing echo, old messages without hash) + int? selfEchoFallback; for (int i = messages.length - 1; i >= 0; i--) { - if (_isChannelRepeat(messages[i], incoming)) { - return i; + final existing = messages[i]; + if (!_isChannelRepeat(existing, incoming)) continue; + if (!existing.isOutgoing) return i; + // Our messages sent within one second share a timestamp. Skip any + // already tied to a different packet, and prefer the one whose text + // matches; the text can differ (reply prefix, cyr2lat), so otherwise + // fall back to the newest. + final existingHash = existing.packetHash; + if (existingHash != null && + incomingHash != null && + existingHash != incomingHash) { + continue; } + if (_sameChannelText(existing.text, incoming.text)) return i; + selfEchoFallback ??= i; } - return -1; + return selfEchoFallback ?? -1; + } + + bool _sameChannelText(String a, String b) { + String strip(String text) => + ChannelMessage.parseReplyMention(text)?.actualMessage ?? text; + return a == b || strip(a) == strip(b); } bool _isChannelRepeat(ChannelMessage existing, ChannelMessage incoming) { - if (existing.text != incoming.text) return false; + // A message we are sending is always new, even if its text matches an + // earlier one. + if (incoming.isOutgoing) return false; - // Self-echo: an outgoing message coming back via a repeater. The send is - // delayed by _waitForRadioQuiet (often 10s+) and propagation can add more, - // so the timestamp gap can easily exceed the cross-peer window. - final selfName = _selfName ?? 'Me'; - final isSelfEcho = - existing.isOutgoing && - !incoming.isOutgoing && - (incoming.senderName == selfName || existing.senderName == selfName); + // Every copy of one packet carries the sender's timestamp, and for our own + // messages that timestamp is the one we put in the send frame. Separate + // sends of the same text therefore differ here, while true repeats match. + final sameSecond = + existing.timestamp.millisecondsSinceEpoch ~/ 1000 == + incoming.timestamp.millisecondsSinceEpoch ~/ 1000; + if (!sameSecond) return false; - final windowMs = isSelfEcho ? 10 * 60 * 1000 : 30000; - final diffMs = - (existing.timestamp.millisecondsSinceEpoch - - incoming.timestamp.millisecondsSinceEpoch) - .abs(); - if (diffMs > windowMs) return false; - - if (existing.senderName == incoming.senderName) return true; - if (isSelfEcho) return true; - - return false; + // Our own echo can read differently from what we stored (a reply keeps its + // @[name] prefix, cyr2lat transliterates), so the timestamp decides. + if (existing.isOutgoing) { + return incoming.senderName == (_selfName ?? 'Me'); + } + return existing.senderName == incoming.senderName && + existing.text == incoming.text; } bool _shouldDropSelfChannelMessage(String senderName, Uint8List pathBytes) { @@ -6393,6 +7223,10 @@ class MeshCoreConnector extends ChangeNotifier { _txCharacteristic = null; // Preserve deviceId and displayName for UI display during reconnection // They're only cleared on manual disconnect via disconnect() method + _selfPublicKey = null; + _awaitingSelfInfo = false; + _selfInfoRetryTimer?.cancel(); + _selfInfoRetryTimer = null; _hasReceivedDeviceInfo = false; _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; @@ -6400,32 +7234,12 @@ class MeshCoreConnector extends ChangeNotifier { _pendingChannelSentQueue.clear(); _pendingGenericAckQueue.clear(); _reactionSendQueueSequence = 0; + _retryService?.failAllPending(); _setState(MeshCoreConnectionState.disconnected); _scheduleReconnect(); } - _PendingCommandAck? _trackPendingGenericAck( - Uint8List data, { - String? channelSendQueueId, - required bool expectsGenericAck, - required bool waitForAck, - }) { - if (!expectsGenericAck || data.isEmpty) return null; - final pendingAck = _PendingCommandAck( - commandCode: data[0], - channelSendQueueId: channelSendQueueId, - completer: waitForAck ? Completer() : null, - ); - if (pendingAck.completer != null) { - // sendFrame awaits this future after transport I/O; attach an error - // handler immediately in case USB returns an error response first. - unawaited(pendingAck.completer!.future.catchError((_) {})); - } - _pendingGenericAckQueue.add(pendingAck); - return pendingAck; - } - String _nextReactionSendQueueId() { _reactionSendQueueSequence++; return '$_reactionSendQueuePrefix$_reactionSendQueueSequence'; @@ -6493,13 +7307,20 @@ class MeshCoreConnector extends ChangeNotifier { } void _setState(MeshCoreConnectionState newState) { + if (_disposed) return; if (_state != newState) { _state = newState; + if (newState == MeshCoreConnectionState.connected) { + if (_appSettingsService?.settings.notificationsEnabled ?? false) { + unawaited(_notificationService.requestPermissionsOnce()); + } + } notifyListeners(); } } void markNotifyDirty() { + if (_disposed) return; if (_notifyListenersDirty && _notifyListenersTimer != null) { return; } @@ -6530,11 +7351,13 @@ class MeshCoreConnector extends ChangeNotifier { @override void notifyListeners() { + if (_disposed) return; markNotifyDirty(); } @override void dispose() { + _disposed = true; _scanSubscription?.cancel(); _isScanningSubscription?.cancel(); _connectionSubscription?.cancel(); @@ -6547,6 +7370,7 @@ class MeshCoreConnector extends ChangeNotifier { _radioStatsPollTimer?.cancel(); radioStatsNotifier.dispose(); _receivedFramesController.close(); + _contactsFullController.close(); _usbManager.dispose(); _tcpConnector.dispose(); @@ -6573,6 +7397,7 @@ class MeshCoreConnector extends ChangeNotifier { //final payloadVer = (header >> 6) & 0x03; final pathLenRaw = packet.readByte(); final pathByteLen = _decodePathByteLen(pathLenRaw); + final pathHashWidth = _decodePathHashWidth(pathLenRaw); final pathBytes = packet.readBytes(pathByteLen); final payload = packet.readBytes(packet.remaining); @@ -6583,6 +7408,7 @@ class MeshCoreConnector extends ChangeNotifier { rawPacket, payload, pathBytes, + pathHashWidth, routeType, snr, ); @@ -6595,6 +7421,87 @@ class MeshCoreConnector extends ChangeNotifier { } } + void importContact(Uint8List frame) { + final packet = BufferReader(frame); + int payloadType = 0; + Uint8List pathBytes = Uint8List(0); + int pathHashWidth = 1; + try { + packet.skipBytes(1); // Skip frame type byte + packet.skipBytes(1); // Skip SNR byte + packet.skipBytes(1); // Skip RSSI byte + final header = packet.readByte(); + final routeType = header & 0x03; + payloadType = (header >> 2) & 0x0F; + if (routeType == _routeTransportFlood || + routeType == _routeTransportDirect) { + packet.skipBytes(4); // Skip transport-specific bytes + } + //final payloadVer = (header >> 6) & 0x03; + final pathLenRaw = packet.readByte(); + final pathByteLen = _decodePathByteLen(pathLenRaw); + pathHashWidth = _decodePathHashWidth(pathLenRaw); + pathBytes = packet.readBytes(pathByteLen); + } catch (e) { + appLogger.warn('Malformed RX frame: $e', tag: 'Connector'); + return; + } + double? latitude; + double? longitude; + String name = ''; + Uint8List publicKey = Uint8List(0); + int type = 0; + int timestamp = 0; + bool hasLocation = false; + bool hasName = false; + if (payloadType != payloadTypeADVERT) { + appLogger.warn('Unexpected payload type: $payloadType', tag: 'Connector'); + return; + } + try { + publicKey = packet.readBytes(32); + timestamp = packet.readInt32LE(); + //TODO add signature verification + packet.skipBytes(64); // Skip signature for now + final flags = packet.readByte(); + type = flags & 0x0F; + hasLocation = (flags & 0x10) != 0; + // For future use: + //final hasFeature1 = (flags & 0x20) != 0; + //final hasFeature2 = (flags & 0x40) != 0; + hasName = (flags & 0x80) != 0; + if (hasLocation && packet.remaining >= 8) { + latitude = packet.readInt32LE() / 1e6; + longitude = packet.readInt32LE() / 1e6; + } + if (hasName && packet.remaining > 0) { + name = packet.readCString(); + } + } catch (e) { + appLogger.warn('Malformed advert frame: $e', tag: 'Connector'); + return; + } + + importDiscoveredContact( + Contact( + rawPacket: frame, + publicKey: publicKey, + name: name, + type: type, + pathLength: pathBytes.isEmpty + ? -1 + : (pathBytes.length ~/ pathHashWidth), + // Store hop order reversed for easier outgoing messages; keep bytes + // inside each multi-byte hop in their original order. + path: _reversePathByHop(pathBytes, pathHashWidth), + pathHashWidth: pathHashWidth, + latitude: latitude, + longitude: longitude, + lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), + ), + ); + } + bool hasValidLocation(double? latitude, double? longitude) { const double epsilon = 1e-6; final lat = latitude ?? 0.0; @@ -6610,6 +7517,7 @@ class MeshCoreConnector extends ChangeNotifier { Uint8List rawPacket, Uint8List payload, Uint8List path, + int pathHashWidth, int routeType, double snr, ) { @@ -6668,29 +7576,29 @@ class MeshCoreConnector extends ChangeNotifier { publicKey: publicKey, name: name, type: type, - pathLength: path.length, - path: Uint8List.fromList( - path.reversed.toList(), - ), // Store path in reverse for easier use in outgoing messages + pathLength: path.isEmpty ? -1 : (path.length ~/ pathHashWidth), + // Store hop order reversed for easier outgoing messages; keep bytes + // inside each multi-byte hop in their original order. + path: _reversePathByHop(path, pathHashWidth), + pathHashWidth: pathHashWidth, latitude: latitude, longitude: longitude, lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), ); - if ((_autoAddUsers && type == advTypeChat) || + // The firmware decides whether to store it: PUSH_CODE_ADVERT (then + // GET_CONTACT_BY_KEY) adds it to _contacts and notifies. + final mayAutoAdd = + (_autoAddUsers && type == advTypeChat) || (_autoAddRepeaters && type == advTypeRepeater) || (_autoAddRoomServers && type == advTypeRoom) || - (_autoAddSensors && type == advTypeSensor)) { - _handleContactAdvert(newContact); - _handleDiscovery( - newContact, - rawPacket, - noNotify: true, - addActive: true, - ); - } else { - _handleDiscovery(newContact, rawPacket); - } - _updateDirectRepeater(newContact, snr, path); + (_autoAddSensors && type == advTypeSensor); + _handleDiscovery(newContact, rawPacket, noNotify: mayAutoAdd); + _updateDirectRepeater( + newContact, + snr, + path, + pathHashWidth: pathHashWidth, + ); return; } @@ -6714,8 +7622,9 @@ class MeshCoreConnector extends ChangeNotifier { latitude: hasLocation ? latitude : existing.latitude, longitude: hasLocation ? longitude : existing.longitude, name: hasName ? name : existing.name, - path: Uint8List.fromList(path.reversed.toList()), - pathLength: path.length, + path: _reversePathByHop(path, pathHashWidth), + pathHashWidth: pathHashWidth, + pathLength: path.isEmpty ? -1 : (path.length ~/ pathHashWidth), lastMessageAt: mergedLastMessageAt, lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), pathOverride: existing.pathOverride, // Preserve user's path choice @@ -6725,10 +7634,18 @@ class MeshCoreConnector extends ChangeNotifier { // Add path to history if we have a valid path if (_pathHistoryService != null && _contacts[existingIndex].pathLength >= 0) { - _pathHistoryService!.handlePathUpdated(_contacts[existingIndex]); + _pathHistoryService!.handlePathUpdated( + _contacts[existingIndex], + initialWeight: _initialRouteWeight, + ); } - _updateDirectRepeater(_contacts[existingIndex], snr, path); + _updateDirectRepeater( + _contacts[existingIndex], + snr, + path, + pathHashWidth: pathHashWidth, + ); appLogger.info( 'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_contacts[existingIndex].pathLength}', @@ -6737,10 +7654,42 @@ class MeshCoreConnector extends ChangeNotifier { } } - void _updateDirectRepeater(Contact contact, double snr, Uint8List path) { - final pubkeyFirstByte = path.isNotEmpty - ? path.last - : contact.publicKey.first; + void _updateDirectRepeater( + Contact contact, + double snr, + Uint8List path, { + required int pathHashWidth, + }) { + final hashWidth = pathHashWidth.clamp(1, 4).toInt(); + if (path.isNotEmpty && path.length < hashWidth) { + return; + } + final pathStartIndex = path.isNotEmpty ? path.length - hashWidth : 0; + final publicKeyPrefixEnd = math + .min(hashWidth, contact.publicKey.length) + .toInt(); + final pubkeyPrefix = path.isNotEmpty + ? path.sublist(pathStartIndex) + : contact.publicKey.sublist(0, publicKeyPrefixEnd); + final contactKeyHex = _resolveDirectRepeaterContactKeyHex( + contact, + pubkeyPrefix, + path.isEmpty, + ); + final knownRepeaters = contactKeyHex == null + ? _directRepeaters + .where( + (r) => + r.contactKeyHex != null && + _contactKeyMatchesPrefix(r.contactKeyHex!, pubkeyPrefix), + ) + .toList() + : const []; + final knownRepeater = knownRepeaters.length == 1 + ? knownRepeaters.first + : null; + final effectiveContactKeyHex = + contactKeyHex ?? knownRepeater?.contactKeyHex; _directRepeaters.removeWhere((r) => r.isStale()); @@ -6751,9 +7700,25 @@ class MeshCoreConnector extends ChangeNotifier { return; } - final isTracked = _directRepeaters.where( - (r) => r.pubkeyFirstByte == pubkeyFirstByte, - ); + final isTracked = _directRepeaters.where((r) { + if (knownRepeater != null) { + return identical(r, knownRepeater); + } + if (effectiveContactKeyHex != null) { + return r.contactKeyHex == effectiveContactKeyHex || + (r.contactKeyHex == null && + _contactKeyMatchesPrefix( + effectiveContactKeyHex, + r.pubkeyPrefix, + )); + } + if (r.contactKeyHex == null && + r.pathHashWidth == hashWidth && + r.matchesPrefix(pubkeyPrefix)) { + return true; + } + return false; + }).toList(); final sortedRepeaters = List.from(_directRepeaters) ..sort((a, b) => b.snr.compareTo(a.snr)); @@ -6769,15 +7734,70 @@ class MeshCoreConnector extends ChangeNotifier { if (isTracked.isNotEmpty) { final repeater = isTracked.first; - repeater.update(snr); + repeater.update( + snr, + pubkeyPrefix: pubkeyPrefix, + pathHashWidth: hashWidth, + contactKeyHex: effectiveContactKeyHex, + ); + if (effectiveContactKeyHex != null) { + _directRepeaters.removeWhere( + (r) => + !identical(r, repeater) && + (r.contactKeyHex == effectiveContactKeyHex || + (r.contactKeyHex == null && + _contactKeyMatchesPrefix( + effectiveContactKeyHex, + r.pubkeyPrefix, + ))), + ); + } } else if (_directRepeaters.length < 5) { _directRepeaters.add( - DirectRepeater(pubkeyFirstByte: pubkeyFirstByte, snr: snr), + DirectRepeater( + pubkeyPrefix: pubkeyPrefix, + pathHashWidth: hashWidth, + contactKeyHex: effectiveContactKeyHex, + snr: snr, + ), ); } notifyListeners(); } + String? _resolveDirectRepeaterContactKeyHex( + Contact contact, + List pubkeyPrefix, + bool pathIsEmpty, + ) { + if (pathIsEmpty && + (contact.type == advTypeRepeater || contact.type == advTypeRoom)) { + return contact.publicKeyHex; + } + + final prefixMatches = allContacts + .where( + (c) => + (c.type == advTypeRepeater || c.type == advTypeRoom) && + _contactKeyMatchesPrefix(c.publicKeyHex, pubkeyPrefix), + ) + .toList(); + if (prefixMatches.length == 1) { + return prefixMatches.first.publicKeyHex; + } + + return null; + } + + bool _contactKeyMatchesPrefix(String contactKeyHex, List pubkeyPrefix) { + // Normalize both sides to upper-case hex to avoid case-sensitive mismatches. + final normalizedPrefixHex = pubkeyPrefix + .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) + .join(); + final normalizedContactKeyHex = contactKeyHex.toUpperCase(); + return normalizedContactKeyHex.startsWith(normalizedPrefixHex); + } + void _handleAutoAddConfig(Uint8List frame) { final reader = BufferReader(frame); try { @@ -6788,6 +7808,7 @@ class MeshCoreConnector extends ChangeNotifier { _autoAddRoomServers = (flags & autoAddRoomServerFlag) != 0; _autoAddSensors = (flags & autoAddSensorFlag) != 0; _overwriteOldest = (flags & autoAddOverwriteOldestFlag) != 0; + _autoAddMaxHops = frame.length > 2 ? frame[2] : null; } catch (e) { appLogger.error('Failed to parse auto-add config: $e', tag: 'Connector'); } @@ -6814,6 +7835,7 @@ class MeshCoreConnector extends ChangeNotifier { type: contact.type, pathLength: contact.pathLength, path: contact.path, + pathHashWidth: contact.pathHashWidth, latitude: contact.latitude, longitude: contact.longitude, lastSeen: contact.lastSeen, @@ -6832,6 +7854,7 @@ class MeshCoreConnector extends ChangeNotifier { type: contact.type, pathLength: contact.pathLength, path: contact.path, + pathHashWidth: contact.pathHashWidth, latitude: contact.latitude, longitude: contact.longitude, lastSeen: contact.lastSeen, @@ -6839,6 +7862,10 @@ class MeshCoreConnector extends ChangeNotifier { isActive: addActive, flags: 0, ); + + if (_discoveredContacts.length >= _maxDiscoveredContacts) { + _evictStalestDiscoveredContact(); + } _discoveredContacts.add(disContact); unawaited(_persistDiscoveredContacts()); @@ -6856,6 +7883,19 @@ class MeshCoreConnector extends ChangeNotifier { } } + void _evictStalestDiscoveredContact() { + if (_discoveredContacts.isEmpty) return; + var stalestIndex = 0; + for (int i = 1; i < _discoveredContacts.length; i++) { + if (_discoveredContacts[i].lastSeen.isBefore( + _discoveredContacts[stalestIndex].lastSeen, + )) { + stalestIndex = i; + } + } + _discoveredContacts.removeAt(stalestIndex); + } + void removeAllDiscoveredContacts() { _discoveredContacts.clear(); unawaited(_persistDiscoveredContacts()); @@ -6900,13 +7940,43 @@ const int _payloadTypeGroupText = 0x05; const int _cipherMacSize = 2; /// Decodes the firmware's encoded path_len byte into actual byte length. -/// Bits 0-5: hash count (0-63), Bits 6-7: hash size code (0=1byte, 1=2bytes, 2=3bytes). +/// Bits 0-5: hash count (0-63), Bits 6-7: hash size code (0=1byte ... 3=4bytes). int _decodePathByteLen(int pathLenRaw) { + if (pathLenRaw == 0xFF || pathLenRaw == 0) return 0; final hashCount = pathLenRaw & 63; - final hashSize = ((pathLenRaw >> 6) & 0x03) + 1; + final hashSize = _decodePathHashWidth(pathLenRaw); return hashCount * hashSize; } +int _decodePathHashWidth(int pathLenRaw) { + if (pathLenRaw == 0xFF) return 1; + return ((pathLenRaw >> 6) & 0x03) + 1; +} + +bool _isPathLenValidForMode( + int pathLen, + List pathBytes, + int pathHashWidth, +) { + if (pathLen < 0 || pathLen > 0x3F) return false; + if (pathHashWidth < 1 || pathHashWidth > 3) return false; + final width = pathHashWidth; + final maxHopCountByBytes = maxPathSize ~/ width; + if (pathLen > maxHopCountByBytes) return false; + return pathBytes.length <= maxPathSize && pathBytes.length == pathLen * width; +} + +Uint8List _reversePathByHop(Uint8List pathBytes, int pathHashWidth) { + if (pathBytes.isEmpty) return Uint8List(0); + final width = pathHashWidth.clamp(1, 4).toInt(); + final reversed = []; + for (var i = pathBytes.length; i > 0; i -= width) { + final start = (i - width).clamp(0, pathBytes.length).toInt(); + reversed.addAll(pathBytes.sublist(start, i)); + } + return Uint8List.fromList(reversed); +} + class _RawPacket { final int header; final int routeType; @@ -6930,6 +8000,7 @@ class _RawPacket { routeType == _routeFlood || routeType == _routeTransportFlood; int get hopCount => pathLenRaw & 63; + int get pathHashWidth => ((pathLenRaw >> 6) & 0x03) + 1; } class _ParsedText { @@ -6953,15 +8024,3 @@ class _RepeaterAckContext { required this.messageBytes, }); } - -class _PendingCommandAck { - final int commandCode; - final String? channelSendQueueId; - final Completer? completer; - - _PendingCommandAck({ - required this.commandCode, - this.channelSendQueueId, - this.completer, - }); -} diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index 45e157e5..c01eb8d1 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -213,6 +213,7 @@ const int cmdGetStats = 56; const int cmdSendAnonReq = 57; const int cmdSetAutoAddConfig = 58; const int cmdGetAutoAddConfig = 59; +const int cmdGetAllowedRepeatFreq = 60; const int cmdSetPathHashMode = 61; // Text message types @@ -262,6 +263,7 @@ const int respCodeChannelMsgRecvV3 = 17; const int respCodeChannelInfo = 18; const int respCodeCustomVars = 21; const int respCodeAutoAddConfig = 25; +const int respCodeAllowedRepeatFreq = 26; const int respCodeStats = 24; const int statsTypeCore = 0; @@ -282,6 +284,8 @@ const int pushCodeNewAdvert = 0x8A; const int pushCodeTelemetryResponse = 0x8B; const int pushCodeBinaryResponse = 0x8C; const int pushCodeControlData = 0x8E; +const int pushCodeContactDeleted = 0x8F; +const int pushCodeContactsFull = 0x90; // Contact/advertisement types const int advTypeChat = 1; @@ -339,6 +343,10 @@ const int maxFrameSize = 172; const int appProtocolVersion = 4; // Matches firmware MAX_TEXT_LEN (10 * CIPHER_BLOCK_SIZE). const int maxTextPayloadBytes = 160; +// From attempt 4 on the firmware appends [0][attempt] to the DM payload, so +// the text must fit in MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket). +const int maxFullLengthTextAttempt = 3; +const int maxTextPayloadBytesAfterFullLengthAttempts = maxTextPayloadBytes - 2; const int _sendTextMsgOverheadBytes = 1 + 1 + 1 + 4 + 6 + 1 + 2; // +2 safety margin const int _sendChannelTextMsgOverheadBytes = @@ -532,8 +540,12 @@ Uint8List buildSendTextMsgFrame( // Build CMD_SEND_CHANNEL_TXT_MSG frame // Format: [cmd][txt_type][channel_idx][timestamp x4][text...] -Uint8List buildSendChannelTextMsgFrame(int channelIndex, String text) { - final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; +Uint8List buildSendChannelTextMsgFrame( + int channelIndex, + String text, { + int? timestamp, +}) { + timestamp ??= DateTime.now().millisecondsSinceEpoch ~/ 1000; final writer = BufferWriter(); writer.writeByte(cmdSendChannelTxtMsg); writer.writeByte(txtTypePlain); @@ -587,9 +599,9 @@ Uint8List buildGetStatsFrame(int statsType) { return Uint8List.fromList([cmdGetStats, statsType & 0xFF]); } -/// Path hash width on air: [61][0][mode], mode 0..2 → (mode+1) bytes per hop hash. +/// Path hash width on air: [61][0][mode], mode 0..3 → (mode+1) bytes per hop hash. Uint8List buildSetPathHashModeFrame(int mode) { - final m = mode.clamp(0, 2); + final m = mode.clamp(0, 2).toInt(); return Uint8List.fromList([cmdSetPathHashMode, 0, m]); } @@ -713,7 +725,9 @@ Uint8List buildResetPathFrame(Uint8List pubKey) { } // Build CMD_ADD_UPDATE_CONTACT frame to set custom path -// Format: [cmd][pub_key x32][type][flags][path_len][path x64][name x32][Lat? x4, Lon? x4][timestamp? x4] +// Format: [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4][Lat? x4, Lon? x4][lastmod? x4] +// The firmware stores last_advert as the contact's replay guard, so it must be +// the contact's own advert timestamp (0 when unknown), never the phone clock. Uint8List buildUpdateContactPathFrame( Uint8List pubKey, Uint8List path, @@ -723,6 +737,7 @@ Uint8List buildUpdateContactPathFrame( String name = '', double? lat, double? lon, + DateTime? lastAdvert, DateTime? lastModified, }) { final writer = BufferWriter(); @@ -737,9 +752,10 @@ Uint8List buildUpdateContactPathFrame( // Name (32 bytes, null-padded) writer.writeCString(name, maxNameSize); - // Timestamp - final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; - writer.writeUInt32LE(timestamp); + final lastAdvertSeconds = lastAdvert == null + ? 0 + : lastAdvert.millisecondsSinceEpoch ~/ 1000; + writer.writeUInt32LE(lastAdvertSeconds.clamp(0, 0xFFFFFFFF).toInt()); // Optional [Lat x4, Lon x4][timestamp x4] tail per the doc comment above. // Emit 8 bytes of position (zero-filled when only lastModified is provided) @@ -777,28 +793,51 @@ Uint8List buildGetAutoAddFlagsFrame() { return Uint8List.fromList([cmdGetAutoAddConfig]); } +Uint8List buildGetAllowedRepeatFreqFrame() { + return Uint8List.fromList([cmdGetAllowedRepeatFreq]); +} + +typedef RepeatFreqRange = ({int lowKHz, int highKHz}); + +// RESP_ALLOWED_REPEAT_FREQ: [code] then [lower_khz u32][upper_khz u32] pairs. +List parseAllowedRepeatFreqFrame(Uint8List frame) { + final ranges = []; + final data = ByteData.sublistView(frame); + for (var i = 1; i + 8 <= frame.length; i += 8) { + ranges.add(( + lowKHz: data.getUint32(i, Endian.little), + highKHz: data.getUint32(i + 4, Endian.little), + )); + } + return ranges; +} + // Calculate LoRa airtime for a packet // Based on Semtech SX127x datasheet formula // Returns airtime in milliseconds +// Preamble defaults to the firmware's per-SF length (32 up to SF8, 16 above, +// RadioLibWrappers.h preambleLengthForSF); LDRO defaults to the RadioLib rule +// (symbol time > 16 ms). int calculateLoRaAirtime({ required int payloadBytes, required int spreadingFactor, required int bandwidthHz, required int codingRate, - int preambleSymbols = 8, - bool lowDataRateOptimize = false, + int? preambleSymbols, + bool? lowDataRateOptimize, bool explicitHeader = true, }) { // Symbol duration (Ts) in milliseconds final symbolDuration = (1 << spreadingFactor) / (bandwidthHz / 1000.0); // Preamble time - final preambleTime = (preambleSymbols + 4.25) * symbolDuration; + final preamble = preambleSymbols ?? (spreadingFactor <= 8 ? 32 : 16); + final preambleTime = (preamble + 4.25) * symbolDuration; // Payload symbol count final headerBytes = explicitHeader ? 0 : 20; final crc = 1; // CRC enabled - final de = lowDataRateOptimize ? 1 : 0; + final de = (lowDataRateOptimize ?? symbolDuration > 16.0) ? 1 : 0; final numerator = 8 * payloadBytes - 4 * spreadingFactor + 28 + 16 * crc - headerBytes; @@ -831,7 +870,6 @@ int calculateMessageTimeout({ spreadingFactor: sf, bandwidthHz: bwHz, codingRate: cr, - lowDataRateOptimize: sf >= 11, ); if (pathLength < 0) { @@ -1004,6 +1042,7 @@ Uint8List buildSetAutoAddConfigFrame({ required bool autoAddRoomServer, required bool autoAddSensor, required bool overwriteOldest, + int? maxHops, }) { final writer = BufferWriter(); writer.writeByte(cmdSetAutoAddConfig); @@ -1014,6 +1053,8 @@ Uint8List buildSetAutoAddConfigFrame({ if (autoAddSensor) flags |= autoAddSensorFlag; if (overwriteOldest) flags |= autoAddOverwriteOldestFlag; writer.writeByte(flags); + // Optional autoadd_max_hops (firmware keeps its value when omitted). + if (maxHops != null) writer.writeByte(maxHops.clamp(0, 64).toInt()); return writer.toBytes(); } diff --git a/lib/connector/pending_command_replies.dart b/lib/connector/pending_command_replies.dart new file mode 100644 index 00000000..43968c02 --- /dev/null +++ b/lib/connector/pending_command_replies.dart @@ -0,0 +1,183 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../services/image_chunk_transport.dart' show cmdSendChannelData; +import 'meshcore_protocol.dart'; + +/// A command waiting for its reply from the companion firmware. +class PendingCommandReply { + final int commandCode; + + /// Response code the firmware sends on success (RESP_CODE_OK or a specific + /// RESP_CODE_*). Any command may instead be answered with RESP_CODE_ERR. + final int replyCode; + + /// For GET_CONTACT_BY_KEY: only a CONTACT frame for this key is the reply. + final Uint8List? matchKey; + final String? channelSendQueueId; + final Completer? completer; + final DateTime createdAt = DateTime.now(); + + PendingCommandReply({ + required this.commandCode, + required this.replyCode, + this.matchKey, + this.channelSendQueueId, + this.completer, + }); +} + +/// Success reply for each command whose single reply is OK/ERR or a specific +/// RESP_CODE (companion MyMesh.cpp handleCmdFrame). Commands with no reply +/// (REBOOT) or a multi-code reply (SYNC_NEXT_MESSAGE) are not tracked. +int? replyCodeForCommand(Uint8List data) { + switch (data[0]) { + case cmdSendChannelTxtMsg: + case cmdSetDeviceTime: + case cmdSendSelfAdvert: + case cmdSetAdvertName: + case cmdAddUpdateContact: + case cmdSetRadioParams: + case cmdSetRadioTxPower: + case cmdResetPath: + case cmdSetAdvertLatLon: + case cmdRemoveContact: + case cmdShareContact: + case cmdImportContact: + case cmdSetChannel: + case cmdSetOtherParams: + case cmdSetCustomVar: + case cmdSetFloodScope: + case cmdSendControlData: + case cmdSetAutoAddConfig: + case cmdSetPathHashMode: + case cmdSendChannelData: + return respCodeOk; + case cmdSendTxtMsg: + case cmdSendLogin: + case cmdSendStatusReq: + case cmdSendTracePath: + case cmdSendBinaryReq: + case cmdSendAnonReq: + return respCodeSent; + case cmdSendTelemetryReq: + // The 4-byte 'self' form answers with PUSH_CODE_TELEMETRY_RESPONSE. + return data.length > 4 ? respCodeSent : null; + case cmdAppStart: + return respCodeSelfInfo; + case cmdDeviceQuery: + return respCodeDeviceInfo; + case cmdGetContacts: + return respCodeContactsStart; + case cmdGetContactByKey: + return respCodeContact; + case cmdGetDeviceTime: + return respCodeCurrTime; + case cmdExportContact: + return respCodeExportContact; + case cmdGetBattAndStorage: + return respCodeBattAndStorage; + case cmdGetChannel: + return respCodeChannelInfo; + case cmdGetCustomVar: + return respCodeCustomVars; + case cmdGetStats: + return respCodeStats; + case cmdGetAutoAddConfig: + return respCodeAutoAddConfig; + case cmdGetAllowedRepeatFreq: + return respCodeAllowedRepeatFreq; + } + return null; +} + +/// FIFO of commands awaiting a reply. The firmware handles commands in order +/// and answers each with OK, ERR or a specific RESP_CODE, so an ERR belongs +/// to the oldest pending command and an OK to the oldest one expecting OK. +class PendingCommandReplies { + PendingCommandReplies({required this.staleAfter}); + + /// Entries older than this are dropped so a lost reply cannot swallow a + /// later, unrelated OK/ERR. Awaited entries time out in sendFrame first. + final Duration staleAfter; + final List _queue = []; + + int get length => _queue.length; + + PendingCommandReply? track( + Uint8List data, { + String? channelSendQueueId, + bool expectsOk = false, + bool waitForReply = false, + }) { + if (data.isEmpty) return null; + final replyCode = + replyCodeForCommand(data) ?? (expectsOk ? respCodeOk : null); + if (replyCode == null) return null; + final pending = PendingCommandReply( + commandCode: data[0], + replyCode: replyCode, + matchKey: data[0] == cmdGetContactByKey && data.length >= 1 + pubKeySize + ? Uint8List.fromList(data.sublist(1, 1 + pubKeySize)) + : null, + channelSendQueueId: channelSendQueueId, + completer: waitForReply ? Completer() : null, + ); + if (pending.completer != null) { + // The sender awaits this future after transport I/O; attach an error + // handler now in case the ERR arrives first. + unawaited(pending.completer!.future.catchError((_) {})); + } + _queue.add(pending); + return pending; + } + + void remove(PendingCommandReply pending) => _queue.remove(pending); + + void clear() => _queue.clear(); + + /// Completes the oldest command whose success reply is [frame]'s code. + bool completeReply(Uint8List frame) { + if (frame.isEmpty) return false; + final code = frame[0]; + if (code == respCodeOk || code == respCodeErr) return false; + final key = code == respCodeContact && frame.length >= 1 + pubKeySize + ? frame.sublist(1, 1 + pubKeySize) + : null; + final index = _queue.indexWhere( + (p) => + p.replyCode == code && + (p.matchKey == null || listEquals(p.matchKey, key)), + ); + if (index < 0) return false; + _queue.removeAt(index).completer?.complete(); + return true; + } + + /// Attributes RESP_CODE_OK; commands expecting a specific reply are skipped. + PendingCommandReply? takeOk() { + _pruneStale(); + final index = _queue.indexWhere((p) => p.replyCode == respCodeOk); + if (index < 0) return null; + final pending = _queue.removeAt(index); + pending.completer?.complete(); + return pending; + } + + /// Attributes RESP_CODE_ERR to the oldest pending command. + PendingCommandReply? takeErr(int errCode) { + _pruneStale(); + if (_queue.isEmpty) return null; + final pending = _queue.removeAt(0); + pending.completer?.completeError( + Exception('Command failed with error code $errCode'), + ); + return pending; + } + + void _pruneStale() { + final cutoff = DateTime.now().subtract(staleAfter); + _queue.removeWhere((p) => p.createdAt.isBefore(cutoff)); + } +} diff --git a/lib/helpers/guessed_location_estimator.dart b/lib/helpers/guessed_location_estimator.dart new file mode 100644 index 00000000..6ad837b2 --- /dev/null +++ b/lib/helpers/guessed_location_estimator.dart @@ -0,0 +1,164 @@ +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:latlong2/latlong.dart'; + +import 'path_helper.dart'; + +typedef GuessCandidate = ({Uint8List publicKey, List<(List, int)> paths}); + +typedef GuessInput = ({ + List candidates, + List<(Uint8List, double, double)> anchors, + (double, double)? selfPosition, + double? maxRangeKm, +}); + +/// Longest single radio link we trust when matching hops to repeaters. The +/// free-space estimate from the radio settings runs to hundreds of km, far +/// beyond real terrestrial links, so it is capped here. +const double maxPlausibleLinkKm = 150; + +/// Runs in a background isolate: estimates positions for nodes without a +/// location from the repeaters their paths end on. Returns +/// (candidate index, lat, lon, high confidence) for each placed node. +/// +/// Paths run from our radio outward, so the last hop is the repeater that +/// heard the node directly. Short hop hashes collide, so each path is walked +/// from our own position and every hop is matched to the nearest repeater with +/// that prefix that is within radio range of the previous hop. +List<(int, double, double, bool)> estimateGuessedLocations(GuessInput input) { + const distance = Distance(); + final maxLinkKm = min( + input.maxRangeKm ?? maxPlausibleLinkKm, + maxPlausibleLinkKm, + ); + final maxLinkM = maxLinkKm * 1000; + + final anchorsByPrefix = >{}; + for (final (key, lat, lon) in input.anchors) { + for (var width = 1; width <= 3 && width <= key.length; width++) { + anchorsByPrefix + .putIfAbsent(PathHelper.formatHopHex(key.sublist(0, width)), () => []) + .add(LatLng(lat, lon)); + } + } + final self = input.selfPosition; + final selfPosition = self == null ? null : LatLng(self.$1, self.$2); + + LatLng? lastHopAnchor(List pathBytes, int hopWidth) { + final hops = PathHelper.splitPathBytes(pathBytes, hopWidth); + var previous = selfPosition; + LatLng? resolved; + for (final hop in hops) { + resolved = null; + final candidates = anchorsByPrefix[PathHelper.formatHopHex(hop)]; + if (candidates == null) continue; + if (previous == null) { + // Without a reference point only an unambiguous prefix is trusted. + if (candidates.length == 1) resolved = candidates.first; + } else { + double? best; + for (final candidate in candidates) { + final d = distance(previous, candidate); + if (d <= maxLinkM && (best == null || d < best)) { + best = d; + resolved = candidate; + } + } + } + if (resolved != null) previous = resolved; + } + return resolved; + } + + final result = <(int, double, double, bool)>[]; + for (var i = 0; i < input.candidates.length; i++) { + final candidate = input.candidates[i]; + + // One vote per observed path for the repeater it ended on. + final votes = {}; + for (final (pathBytes, hopWidth) in candidate.paths) { + if (pathBytes.isEmpty || hopWidth < 1) continue; + final anchor = lastHopAnchor(pathBytes, hopWidth); + if (anchor != null) votes[anchor] = (votes[anchor] ?? 0) + 1; + } + if (votes.isEmpty) continue; + + // A node cannot hear two repeaters more than two links apart; drop + // outliers, falling back to the most-voted anchor if none agree. + var anchors = votes.keys.toList(); + if (anchors.length > 1) { + final consistent = anchors + .where( + (a) => anchors.any((b) => b != a && distance(a, b) <= 2 * maxLinkM), + ) + .toList(); + anchors = consistent.isNotEmpty + ? consistent + : [votes.entries.reduce((a, b) => b.value > a.value ? b : a).key]; + } + + final LatLng position; + if (anchors.length == 1) { + // Spread single-anchor guesses around the anchor so they stay visible. + position = _offsetGuessedPosition( + anchors[0], + candidate.publicKey, + radiusMeters: 330, + ); + } else { + var lat = 0.0, lon = 0.0, total = 0; + for (final a in anchors) { + final weight = votes[a]!; + lat += a.latitude * weight; + lon += a.longitude * weight; + total += weight; + } + position = _offsetGuessedPosition( + LatLng(lat / total, lon / total), + candidate.publicKey, + radiusMeters: anchors.length >= 3 ? 80 : 120, + ); + } + if (!isPlausibleLocation(position.latitude, position.longitude)) { + continue; + } + result.add((i, position.latitude, position.longitude, anchors.length >= 2)); + } + return result; +} + +bool isPlausibleLocation(double lat, double lon) { + const double epsilon = 1e-6; + return (lat.abs() > epsilon || lon.abs() > epsilon) && + lat >= -90.0 && + lat <= 90.0 && + lon >= -180.0 && + lon <= 180.0; +} + +LatLng _offsetGuessedPosition( + LatLng anchor, + Uint8List publicKey, { + required double radiusMeters, +}) { + final seed = _guessSeed(publicKey); + final angle = ((seed & 0xFFFF) / 0x10000) * 2 * pi; + final latOffsetDeg = (radiusMeters / 111320.0) * cos(angle); + final lonScale = max(cos(anchor.latitude * pi / 180.0).abs(), 0.2); + final lonOffsetDeg = (radiusMeters / (111320.0 * lonScale)) * sin(angle); + return LatLng( + anchor.latitude + latOffsetDeg, + anchor.longitude + lonOffsetDeg, + ); +} + +int _guessSeed(Uint8List publicKey) { + var seed = 0x811C9DC5; + for (final byte in publicKey) { + seed ^= byte; + seed = (seed * 0x01000193) & 0x7FFFFFFF; + } + return seed; +} diff --git a/lib/helpers/image_send_flow.dart b/lib/helpers/image_send_flow.dart new file mode 100644 index 00000000..8c5f84d0 --- /dev/null +++ b/lib/helpers/image_send_flow.dart @@ -0,0 +1,78 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; + +import '../l10n/l10n.dart'; +import '../widgets/image_send_codec_binding.dart'; +import '../widgets/image_send_preview_sheet.dart'; + +/// Shared "attach an image" flow, used by both the direct-message and channel +/// chat screens so the two surfaces cannot drift apart. +/// +/// Picks a photo, then shows [ImageSendPreviewSheet] so the user sees the +/// packet count and airtime *before* committing to a send that may occupy the +/// channel for seconds. Returns null if the user backed out at either step. +/// +/// The caller owns the actual transmission: this only produces the payload. +Future pickAndPreviewImage({ + required BuildContext context, + required ImageSendCodec codec, + ImagePicker? picker, +}) async { + final XFile? picked; + try { + picked = await (picker ?? ImagePicker()).pickImage( + source: ImageSource.gallery, + // The codec centre-crops to 512x512 anyway, so there is nothing to gain + // from decoding a 12 MP original -- but stay well above 512 so the crop + // still has detail to work with. + maxWidth: 2048, + maxHeight: 2048, + ); + } on Exception catch (e) { + debugPrint('image pick failed: $e'); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + ); + } + return null; + } + + if (picked == null) return null; // user cancelled the picker + + final Uint8List bytes; + int originalBytes; + try { + bytes = await picked.readAsBytes(); + originalBytes = bytes.length; + if (!kIsWeb) { + // length() is the on-disk size, which is what we want to show against the + // transmitted size; fall back to the in-memory length if it fails. + try { + originalBytes = await File(picked.path).length(); + } on FileSystemException { + // keep the in-memory length + } + } + } on Exception catch (e) { + debugPrint('image read failed: $e'); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + ); + } + return null; + } + + if (!context.mounted) return null; + + return showImageSendPreviewSheet( + context: context, + imageBytes: bytes, + originalFileBytes: originalBytes, + codec: codec, + ); +} diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart new file mode 100644 index 00000000..3f2a7835 --- /dev/null +++ b/lib/helpers/message_url_image_helper.dart @@ -0,0 +1,340 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:flutter/material.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:http/http.dart' as http; + +/// Finds and renders image URLs embedded in ordinary text messages. +/// +/// This is deliberately separate from MeshCore's transmitted channel-image +/// protocol, which is handled by [ReceivedImageStore]. +class MessageUrlImageHelper { + static final Map> _verifiedImageCache = + >{}; + static const int _maxMessageImageCacheEntries = 200; + static final LinkedHashMap> _messageImageCache = + LinkedHashMap>(); + + /// HTTP client used to resolve sharing pages. + /// + /// Tests override this because `flutter_test` blocks real network requests. + @visibleForTesting + static http.Client? httpClient; + + static final RegExp _pyxPattern = RegExp( + r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''', + caseSensitive: false, + ); + + static final RegExp _ipfsUrlPattern = RegExp( + r'''https?://[^\s<>'"`]+/(?:ipfs|ipns)/[^\s<>'"`]+''', + caseSensitive: false, + ); + + static final RegExp _ipfsCidPattern = RegExp( + r'''ipfs:(?://)?([^\s<>'"`]+)''', + caseSensitive: false, + ); + + static final RegExp _ibbSharePattern = RegExp( + r'''https?://(?:www\.)?ibb\.co/[^\s<>'"`/?#]+(?:[/?#][^\s<>'"`]*)?''', + caseSensitive: false, + ); + + static final RegExp _imagePattern = RegExp( + r'''https?://[^\s<>'"`]+?\.(?:png|jpe?g|webp)(?:\?[^\s<>'"`]+)?(?:#[^\s<>'"`]+)?''', + caseSensitive: false, + ); + + /// Checks locally whether [text] contains a URL format this helper supports. + /// This deliberately does not resolve sharing pages or fetch image data. + static bool hasPotentialImageUrl(String text) { + return _pyxPattern.hasMatch(text) || + _ipfsUrlPattern.hasMatch(text) || + _ipfsCidPattern.hasMatch(text) || + _ibbSharePattern.hasMatch(text) || + _imagePattern.hasMatch(text); + } + + static Future parse(String text) async { + final trimmed = text.trim(); + if (trimmed.isEmpty) return null; + + final pyxMatch = _pyxPattern.firstMatch(trimmed); + if (pyxMatch != null) { + return 'https://pyx.li/i/${pyxMatch.group(1)!}.jpg'; + } + + final ipfsUrlMatch = _ipfsUrlPattern.firstMatch(trimmed); + if (ipfsUrlMatch != null) { + return _trimBoundary(ipfsUrlMatch.group(0)!); + } + + final ipfsCidMatch = _ipfsCidPattern.firstMatch(trimmed); + if (ipfsCidMatch != null) { + final cid = _trimBoundary(ipfsCidMatch.group(1)!); + return 'https://ipfs.io/ipfs/$cid'; + } + + final ibbMatch = _ibbSharePattern.firstMatch(trimmed); + if (ibbMatch != null) { + return _extractFromUrl( + _trimBoundary(ibbMatch.group(0)!), + RegExp( + r''']+property=["']og:image["'][^>]+content=["']([^"']+)["']''', + caseSensitive: false, + ), + ); + } + + final imageMatch = _imagePattern.firstMatch(trimmed); + if (imageMatch != null) { + return _trimBoundary(imageMatch.group(0)!); + } + + return null; + } + + static Future parseVerified(String text) async { + final imageUrl = await parse(text); + if (imageUrl == null) return null; + + final verified = await _verifyImageUrl(imageUrl); + return verified ? imageUrl : null; + } + + /// Caches successful URL-image parsing by stable message identity. + /// + /// Null results are evicted so temporary connectivity or host failures can + /// be retried when a message is shown again. + static Future parseVerifiedForMessage( + String messageId, + String text, + ) { + final cached = _messageImageCache.remove(messageId); + if (cached != null) { + _messageImageCache[messageId] = cached; + return cached; + } + + final parsing = parseVerified(text); + _messageImageCache[messageId] = parsing; + parsing.then((imageUrl) { + if (imageUrl == null && + identical(_messageImageCache[messageId], parsing)) { + _messageImageCache.remove(messageId); + } else if (imageUrl != null) { + while (_messageImageCache.length > _maxMessageImageCacheEntries) { + _messageImageCache.remove(_messageImageCache.keys.first); + } + } + }); + return parsing; + } + + static Future _extractFromUrl(String pageUrl, RegExp pattern) async { + try { + final uri = Uri.parse(pageUrl); + final client = httpClient; + final response = await (client == null ? http.get(uri) : client.get(uri)) + .timeout(const Duration(seconds: 8)); + if (response.statusCode < 200 || response.statusCode >= 300) { + return null; + } + final value = pattern.firstMatch(response.body)?.group(1); + if (value == null || value.isEmpty) return null; + + final imageUrl = uri.resolve(value.replaceAll('&', '&')); + return imageUrl.scheme == 'http' || imageUrl.scheme == 'https' + ? imageUrl.toString() + : null; + } catch (_) { + return null; + } + } + + static String _trimBoundary(String value) { + return value.trim().replaceAll(RegExp(r"[.,;:!?]+$"), ''); + } + + static Future _verifyImageUrl(String imageUrl) { + final cached = _verifiedImageCache[imageUrl]; + if (cached != null) return cached; + + final verification = _tryLoadImage(imageUrl); + _verifiedImageCache[imageUrl] = verification; + verification.then((verified) { + if (!verified && identical(_verifiedImageCache[imageUrl], verification)) { + _verifiedImageCache.remove(imageUrl); + } + }); + return verification; + } + + static Future _tryLoadImage(String imageUrl) async { + final completer = Completer(); + final stream = CachedNetworkImageProvider( + imageUrl, + ).resolve(const ImageConfiguration()); + + late final ImageStreamListener listener; + listener = ImageStreamListener( + (_, _) { + if (!completer.isCompleted) completer.complete(true); + stream.removeListener(listener); + }, + onError: (_, _) { + if (!completer.isCompleted) completer.complete(false); + stream.removeListener(listener); + }, + ); + + stream.addListener(listener); + + return completer.future.timeout( + const Duration(seconds: 8), + onTimeout: () { + stream.removeListener(listener); + return false; + }, + ); + } +} + +class MessageUrlImageFutureBuilder extends StatefulWidget { + const MessageUrlImageFutureBuilder({ + super.key, + required this.messageId, + required this.text, + required this.builder, + }); + + final String messageId; + final String text; + final AsyncWidgetBuilder builder; + + @override + State createState() => + _MessageUrlImageFutureBuilderState(); +} + +class _MessageUrlImageFutureBuilderState + extends State { + late Future _imageFuture; + + @override + void initState() { + super.initState(); + _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( + widget.messageId, + widget.text, + ); + } + + @override + void didUpdateWidget(covariant MessageUrlImageFutureBuilder oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.messageId != widget.messageId) { + _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( + widget.messageId, + widget.text, + ); + } + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _imageFuture, + builder: widget.builder, + ); + } +} + +class MessageUrlImagePreview extends StatelessWidget { + const MessageUrlImagePreview({super.key, required this.imageUrl}); + + final String imageUrl; + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () { + showDialog( + context: context, + builder: (context) => Dialog( + insetPadding: const EdgeInsets.all(12), + backgroundColor: Colors.black, + child: SizedBox( + width: double.infinity, + height: double.infinity, + child: Stack( + children: [ + Positioned.fill( + child: InteractiveViewer( + boundaryMargin: const EdgeInsets.all(80), + minScale: 1.0, + maxScale: 3.0, + child: Center( + child: CachedNetworkImage( + imageUrl: imageUrl, + fit: BoxFit.contain, + placeholder: (context, url) => const Center( + child: CircularProgressIndicator(strokeWidth: 2), + ), + errorWidget: (context, url, error) => const Center( + child: Icon( + Icons.broken_image, + color: Colors.white, + ), + ), + ), + ), + ), + ), + Positioned( + top: 12, + right: 12, + child: IconButton( + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(Icons.close, color: Colors.white), + style: IconButton.styleFrom( + backgroundColor: Colors.black54, + ), + ), + ), + ], + ), + ), + ), + ); + }, + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: SizedBox( + width: 240, + height: 240, + child: CachedNetworkImage( + imageUrl: imageUrl, + fit: BoxFit.contain, + placeholder: (context, url) => ColoredBox( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: const Center( + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + errorWidget: (context, url, error) => Container( + padding: const EdgeInsets.all(12), + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Text( + 'Unable to load image', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/helpers/path_helper.dart b/lib/helpers/path_helper.dart index bd599c00..02a3dcaa 100644 --- a/lib/helpers/path_helper.dart +++ b/lib/helpers/path_helper.dart @@ -1,5 +1,7 @@ -import '../models/contact.dart'; +import 'package:flutter/foundation.dart'; + import '../connector/meshcore_protocol.dart'; +import '../models/contact.dart'; class PathHelper { static String formatPathHex(List pathBytes) { @@ -12,10 +14,17 @@ class PathHelper { return byte.toRadixString(16).padLeft(2, '0').toUpperCase(); } + static String formatHopHex(List hopBytes) { + return hopBytes + .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) + .join(); + } + static String? hopName(int byte, List allContacts) { final matches = allContacts .where( (c) => + c.publicKey.isNotEmpty && c.publicKey.first == byte && (c.type == advTypeRepeater || c.type == advTypeRoom), ) @@ -25,12 +34,57 @@ class PathHelper { return matches.map((c) => c.name).join(' | '); } + static List splitPathBytes( + List pathBytes, + int hashByteWidth, + ) { + if (pathBytes.isEmpty) return const []; + + final width = hashByteWidth.clamp(1, 3).toInt(); + final hops = []; + for (int i = 0; i < pathBytes.length; i += width) { + final endIdx = (i + width).clamp(0, pathBytes.length).toInt(); + final hopBytes = pathBytes.sublist(i, endIdx); + if (hopBytes.isNotEmpty) { + hops.add(Uint8List.fromList(hopBytes)); + } + } + return hops; + } + + /// Resolves path bytes to contact names, supporting multi-byte hash widths. + /// + /// Groups path bytes according to [hashByteWidth]: + /// - 1: Single byte per hop (256 unique nodes) + /// - 2: Two bytes per hop (65K unique nodes) + /// - 3: Three bytes per hop (16M unique nodes) static String resolvePathNames( List pathBytes, List allContacts, + int hashByteWidth, ) { - return pathBytes - .map((b) => hopName(b, allContacts) ?? hopHex(b)) - .join(' \u2192 '); + if (pathBytes.isEmpty) return ''; + + final parts = []; + + for (final hopBytes in splitPathBytes(pathBytes, hashByteWidth)) { + final hex = formatHopHex(hopBytes); + + final matches = allContacts.where((c) { + if (c.publicKey.length < hopBytes.length) return false; + if (c.type != advTypeRepeater && c.type != advTypeRoom) return false; + return listEquals(c.publicKey.sublist(0, hopBytes.length), hopBytes); + }).toList(); + + if (matches.isEmpty) { + parts.add(hex); + } else if (matches.length == 1) { + parts.add(matches.first.name); + } else { + parts.add(matches.map((c) => c.name).join(' | ')); + } + } + + return parts.join(' \u2192 '); } } diff --git a/lib/helpers/path_hop_resolver.dart b/lib/helpers/path_hop_resolver.dart index 19f26001..a6f2c018 100644 --- a/lib/helpers/path_hop_resolver.dart +++ b/lib/helpers/path_hop_resolver.dart @@ -1,6 +1,7 @@ import 'package:latlong2/latlong.dart'; import '../connector/meshcore_protocol.dart'; +import 'path_helper.dart'; import '../models/contact.dart'; class PathHopResolver { @@ -11,30 +12,35 @@ class PathHopResolver { required List contacts, LatLng? endpoint, bool resolveFromEnd = false, + int pathHashByteWidth = 1, }) { - final candidatesByPrefix = >{}; + final width = pathHashByteWidth.clamp(1, 3).toInt(); + final candidatesByPrefix = >{}; for (final contact in contacts) { - if (contact.publicKey.isEmpty) continue; + if (contact.publicKey.length < width) continue; if (contact.type != advTypeRepeater && contact.type != advTypeRoom) { continue; } - candidatesByPrefix - .putIfAbsent(contact.publicKey.first, () => []) - .add(contact); + final prefix = PathHelper.formatHopHex( + contact.publicKey.sublist(0, width), + ); + candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); } for (final candidates in candidatesByPrefix.values) { candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); } - final resolved = List.filled(pathBytes.length, null); + final hops = PathHelper.splitPathBytes(pathBytes, width); + final resolved = List.filled(hops.length, null); final indexes = resolveFromEnd - ? List.generate(pathBytes.length, (i) => pathBytes.length - 1 - i) - : List.generate(pathBytes.length, (i) => i); + ? List.generate(hops.length, (i) => hops.length - 1 - i) + : List.generate(hops.length, (i) => i); final distance = Distance(); var previousPosition = endpoint; for (final index in indexes) { - final candidates = candidatesByPrefix[pathBytes[index]]; + final candidates = + candidatesByPrefix[PathHelper.formatHopHex(hops[index])]; if (candidates == null || candidates.isEmpty) continue; var bestIndex = 0; diff --git a/lib/helpers/reaction_helper.dart b/lib/helpers/reaction_helper.dart index 36118ca3..58928284 100644 --- a/lib/helpers/reaction_helper.dart +++ b/lib/helpers/reaction_helper.dart @@ -1,10 +1,29 @@ +import 'dart:typed_data'; +import 'dart:convert'; +import 'package:characters/characters.dart'; +import 'package:crypto/crypto.dart'; +import 'package:base32/base32.dart'; +import 'package:base32/encodings.dart'; import '../widgets/emoji_picker.dart'; +enum HashType { ours, mc1 } + class ReactionInfo { final String targetHash; final String emoji; + HashType hashType; + String? senderName; // Who sent the reaction - ReactionInfo({required this.targetHash, required this.emoji}); + ReactionInfo({ + required this.targetHash, + required this.emoji, + required this.hashType, + this.senderName, + }); + + String identifier() { + return '$targetHash:$emoji:$hashType:${senderName ?? ""}'; + } } class ReactionHelper { @@ -26,25 +45,34 @@ class ReactionHelper { required int Function(T) getTimestampSecs, required String? Function(T) getSenderName, required String Function(T) getMessageText, - required Map Function(T) getReactions, + required Map> Function(T) getReactions, required bool Function(T) shouldSkip, - required void Function(int index, Map newReactions) updateMessage, }) { final targetHash = reactionInfo.targetHash; + final hashFunc = switch (reactionInfo.hashType) { + HashType.ours => computeReactionHash, + HashType.mc1 => ((ts, senderName, text) => _concatenateHashAndSender( + computeReactionHashMC1(ts, senderName, text), + senderName, + )), + }; for (int i = messages.length - 1; i >= 0; i--) { final msg = messages[i]; if (shouldSkip(msg)) continue; - final msgHash = computeReactionHash( + final msgHash = hashFunc( getTimestampSecs(msg), getSenderName(msg), getMessageText(msg), ); if (msgHash == targetHash) { - final currentReactions = Map.from(getReactions(msg)); - currentReactions[reactionInfo.emoji] = - (currentReactions[reactionInfo.emoji] ?? 0) + 1; + final currentReactions = Map>.from( + getReactions(msg), + ); + (currentReactions[reactionInfo.emoji] ??= []).add( + reactionInfo.senderName, + ); updateMessage(i, currentReactions); return true; } @@ -97,17 +125,122 @@ class ReactionHelper { return hash.toRadixString(16).padLeft(4, '0'); } + // Compute the type of reaction hash used by MeshCoreOne. + static String computeReactionHashMC1( + int timestampSeconds, + String? senderName, + String messageText, + ) { + // raw hash is first 5 bytes of SHA-256(UTF-8 text + uint32-LE sender timestamp) + Uint8List messageBytes = utf8.encode(messageText); + ByteData timestampBytes = ByteData(4) + ..setUint32(0, timestampSeconds, Endian.little); + final hash = sha256 + .convert(messageBytes + timestampBytes.buffer.asUint8List()) + .bytes + .sublist(0, 5); + + // encode as 8 chars of Crockford base32 + return base32 + .encode(Uint8List.fromList(hash), encoding: Encoding.crockford) + .toLowerCase(); + // Note: Crockford32 defines permissive decoding and allows some + // substitutions (e.g. I, i, l -> 1) but we never decode the hashes, we + // just compare them. If someone sends a miscoded hash that should be + // equivalent, we won't match it and it won't work. But it's not worth + // accommodating, because no one is going to be hand copying hashes. + } + + // MeshCoreOne-style reaction hashes don't depend on the sender name, + // and we're expected to check the hash and sender name separately. + // Our own reaction hashes include it. Rather than store the sender + // Name in ReactionInfo and complicate the logic in applyReaction(), + // we just tack the senderName onto the end of the "hash". + static String _concatenateHashAndSender(String hash, String? senderName) { + return "$hash:${senderName ?? ''}"; + } + + static ReactionInfo? parseReaction(String text) { + return parseReactionOurs(text) ?? + parseReactionMC1(text) ?? + parseReactionMC1Legacy(text); + } + + static bool _looksLikeEmoji(String emoji) { + // Make sure it's a single grapheme. + if (Characters(emoji).length > 1) return false; + + // Below are some emoji-validating tests, copied from MeshTrax. + // https://github.com/venamartin/meshtrax/ + // It's nice to avoid false positives just to save us some processing, + // but it's not crucial, as we will either apply a reaction or show it + // as a message. Text that is not actually a hash is unlikely to match + // a message. + if (emoji.isEmpty) return false; + // Emoji, not prose: nearly all emoji start at U+2000 or above; the + // exceptions (keycaps, ©/®) carry a variation selector U+FE0F or a + // combining keycap U+20E3. Ordinary ASCII text fails both tests. + if (!(emoji.runes.first >= 0x2000 || + emoji.runes.any((r) => r == 0xFE0F || r == 0x20E3))) { + return false; + } + return true; + } + + static ReactionInfo? parseReactionMC1(String text) { + // See https://github.com/Avi0n/MeshCoreOne/blob/main/docs/Reactions.md + // This regex matches both the channel format, which includes the sender name, + // and the chat (DM) format, which omits it. + final regex = RegExp(r'^(?:@\[(.*)])?(.+?)\n([a-tv-zA-TV-Z0-9]{8})$'); + final match = regex.firstMatch(text); + if (match == null) return null; + + final senderName = match.group(1); + final emoji = match.group(2)!; + final hash = match.group(3)?.toLowerCase(); + if (!_looksLikeEmoji(emoji)) return null; + + return ReactionInfo( + targetHash: _concatenateHashAndSender(hash!, senderName), + emoji: emoji, + hashType: HashType.mc1, + ); + } + + static ReactionInfo? parseReactionMC1Legacy(String text) { + // See https://github.com/Avi0n/MeshCoreOne/blob/main/docs/Reactions.md + // This regex matches both the channel format, which includes the sender name, + // and the chat (DM) format, which omits it. + final regex = RegExp(r'^(.+?)(?:@\[(.*)])?\n([a-tv-zA-TV-Z0-9]{8})$'); + final match = regex.firstMatch(text); + if (match == null) return null; + + final hash = match.group(3)?.toLowerCase(); + final senderName = match.group(2); + final emoji = match.group(1)!; + if (!_looksLikeEmoji(emoji)) return null; + + return ReactionInfo( + targetHash: _concatenateHashAndSender(hash!, senderName), + emoji: emoji, + hashType: HashType.mc1, + ); + } + /// Parse reaction format: r:HASH:INDEX (where INDEX is 2-char hex emoji index) /// Returns null if text is not a valid reaction format - static ReactionInfo? parseReaction(String text) { + static ReactionInfo? parseReactionOurs(String text) { final regex = RegExp(r'^r:([0-9a-f]{4}):([0-9a-f]{2})$'); final match = regex.firstMatch(text); if (match == null) return null; final emoji = indexToEmoji(match.group(2)!); if (emoji == null) return null; - - return ReactionInfo(targetHash: match.group(1)!, emoji: emoji); + return ReactionInfo( + targetHash: match.group(1)!, + emoji: emoji, + hashType: HashType.ours, + ); } /// Encode a reaction message that parseReaction() can parse. diff --git a/lib/helpers/snack_bar_builder.dart b/lib/helpers/snack_bar_builder.dart index 913e783f..e44ecc26 100644 --- a/lib/helpers/snack_bar_builder.dart +++ b/lib/helpers/snack_bar_builder.dart @@ -58,7 +58,7 @@ void showDismissibleSnackBar( showCloseIcon: showCloseIcon, closeIconColor: closeIconColor, duration: duration ?? const Duration(seconds: 4), - persist: persist, + persist: persist ?? false, animation: animation, onVisible: onVisible, dismissDirection: dismissDirection ?? DismissDirection.down, diff --git a/lib/helpers/utf8_length_limiter.dart b/lib/helpers/utf8_length_limiter.dart index 4188ec6a..235b84b2 100644 --- a/lib/helpers/utf8_length_limiter.dart +++ b/lib/helpers/utf8_length_limiter.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import 'package:characters/characters.dart'; import 'package:flutter/services.dart'; class Utf8LengthLimitingTextInputFormatter extends TextInputFormatter { @@ -19,34 +20,55 @@ class Utf8LengthLimitingTextInputFormatter extends TextInputFormatter { TextEditingValue newValue, ) { if (maxBytes <= 0) return oldValue; - if (_effectiveByteLength(newValue.text) <= maxBytes) return newValue; + final newBytes = _effectiveByteLength(newValue.text); + if (newBytes <= maxBytes || + newBytes <= _effectiveByteLength(oldValue.text)) { + return newValue; + } - final truncated = _truncateToMaxBytes(newValue.text, maxBytes); + final oldText = oldValue.text; + final newText = newValue.text; + var prefix = 0; + while (prefix < oldText.length && + prefix < newText.length && + oldText.codeUnitAt(prefix) == newText.codeUnitAt(prefix)) { + prefix++; + } + if (prefix > 0 && + prefix < newText.length && + _isLowSurrogate(newText.codeUnitAt(prefix))) { + prefix--; + } + var suffix = 0; + while (suffix < oldText.length - prefix && + suffix < newText.length - prefix && + oldText.codeUnitAt(oldText.length - 1 - suffix) == + newText.codeUnitAt(newText.length - 1 - suffix)) { + suffix++; + } + final suffixStart = newText.length - suffix; + if (suffix > 0 && _isLowSurrogate(newText.codeUnitAt(suffixStart))) { + suffix--; + } + + final head = newText.substring(0, prefix); + final tail = newText.substring(newText.length - suffix); + final inserted = newText.substring(prefix, newText.length - suffix); + + final kept = StringBuffer(); + for (final char in inserted.characters) { + if (_effectiveByteLength('$head$kept$char$tail') > maxBytes) break; + kept.write(char); + } + + final cursor = head.length + kept.length; return TextEditingValue( - text: truncated, - selection: TextSelection.collapsed(offset: truncated.length), + text: '$head$kept$tail', + selection: TextSelection.collapsed(offset: cursor), composing: TextRange.empty, ); } - String _truncateToMaxBytes(String text, int limit) { - if (encoder != null) { - final runes = text.runes.toList(); - while (runes.isNotEmpty && - _effectiveByteLength(String.fromCharCodes(runes)) > maxBytes) { - runes.removeLast(); - } - return String.fromCharCodes(runes); - } - final buffer = StringBuffer(); - var used = 0; - for (final rune in text.runes) { - final char = String.fromCharCode(rune); - final charBytes = utf8.encode(char).length; - if (used + charBytes > limit) break; - buffer.write(char); - used += charBytes; - } - return buffer.toString(); - } + bool _isLowSurrogate(int codeUnit) => + codeUnit >= 0xDC00 && codeUnit <= 0xDFFF; } diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index c9923e75..d956701a 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -100,17 +100,19 @@ "settings_locationInvalid": "Невалидна ширина или дължина.", "settings_latitude": "Широчина", "settings_longitude": "Дължина", + "settings_autoZeroHopAdvertOnGpsUpdate": "Автоматична zero-hop обява при GPS обновяване", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Когато GPS местоположението се промени, изпрати zero-hop обява (изисква местоположение в обявата).", "settings_privacyMode": "Режим на поверителност", - "settings_privacyModeSubtitle": "Скриване на име/местоположение в рекламите", - "settings_privacyModeToggle": "Активирайте режим на поверителност, за да скриете името и местоположението си в рекламите.", + "settings_privacyModeSubtitle": "Скриване на име/местоположение в обявите", + "settings_privacyModeToggle": "Активирайте режим на поверителност, за да скриете името и местоположението си в обявите.", "settings_privacyModeEnabled": "Режим на поверителност е активиран", "settings_privacyModeDisabled": "Режим на поверителност е деактивиран", "settings_actions": "Действия", "settings_deleteAllPaths": "Изтрий всички пътища", "settings_deleteAllPathsSubtitle": "Изчисти всички данни за пътищата от контактите.", - "settings_sendAdvertisement": "Изпрати реклама", + "settings_sendAdvertisement": "Изпрати обява", "settings_sendAdvertisementSubtitle": "Излъчи присъствието сега", - "settings_advertisementSent": "Рекламата е изпратена", + "settings_advertisementSent": "Обявата е изпратена", "settings_syncTime": "Време за синхронизация", "settings_syncTimeSubtitle": "Задайте часовника на устройството да отговаря на времето на телефона.", "settings_timeSynchronized": "Синхронизирано във времето", @@ -183,7 +185,7 @@ "appSettings_languageBg": "Български", "appSettings_notifications": "Уведомления", "appSettings_enableNotifications": "Включи известията", - "appSettings_enableNotificationsSubtitle": "Получавайте известия за съобщения и реклами", + "appSettings_enableNotificationsSubtitle": "Получавайте известия за съобщения и обяви", "appSettings_notificationPermissionDenied": "Отказвано е разрешение за известия", "appSettings_notificationsEnabled": "Известията са включени", "appSettings_notificationsDisabled": "Известията са изключени", @@ -191,7 +193,7 @@ "appSettings_messageNotificationsSubtitle": "Показвай известие при получаване на нови съобщения", "appSettings_channelMessageNotifications": "Известия за канални съобщения", "appSettings_channelMessageNotificationsSubtitle": "Показвай известие при получаване на съобщения от канали", - "appSettings_advertisementNotifications": "Уведомления за реклами", + "appSettings_advertisementNotifications": "Уведомления за обяви", "appSettings_advertisementNotificationsSubtitle": "Покажи известие, когато бъдат открити нови възли.", "appSettings_messaging": "Съобщения", "appSettings_clearPathOnMaxRetry": "Изчисти пътя при максимален брой опити", @@ -199,7 +201,7 @@ "appSettings_pathsWillBeCleared": "Пътищата ще бъдат почистени след 5 неуспешни опита.", "appSettings_pathsWillNotBeCleared": "Пътищата няма да бъдат автоматично изчистени.", "appSettings_autoRouteRotation": "Автоматична ротация на маршрутите", - "appSettings_autoRouteRotationSubtitle": "Превключвайте между най-добрите пътища и режим на наводняване", + "appSettings_autoRouteRotationSubtitle": "Превключвайте между най-добрите пътища и режим Flood", "appSettings_autoRouteRotationEnabled": "Автоматичната ротация на маршрутите е включена", "appSettings_autoRouteRotationDisabled": "Автоматичната ротация на маршрутите е изключена", "appSettings_battery": "Батерия", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Последни 6 часа", "appSettings_last24Hours": "Последно 24 часа", "appSettings_lastWeek": "Миналата седмица", + "appSettings_rasterTileSource": "Източник на растерни плочки", + "appSettings_stadiaEndpoint": "Крайна точка на Stadia", + "appSettings_stadiaApiKey": "API ключ за Stadia", + "appSettings_stadiaApiKeyRequired": "Задължително за използване на Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Конфигурирано: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Въведете своя API ключ за Stadia Maps. Приложението го използва за заявки за растерни плочки.", "appSettings_offlineMapCache": "Кеш на офлайн карти", "appSettings_noAreaSelected": "Няма избрана област", "appSettings_areaSelectedZoom": "Избрана е област (мащаб {minZoom}-{maxZoom})", @@ -260,7 +275,7 @@ "appSettings_appDebugLoggingDisabled": "Дневникът за отстраняване на грешки на приложението е изключен.", "contacts_title": "Контакти", "contacts_noContacts": "Няма контакти към момента.", - "contacts_contactsWillAppear": "Контактите ще се появят, когато устройствата рекламират.", + "contacts_contactsWillAppear": "Контактите ще се появят, когато устройствата изпратят обява.", "contacts_searchContacts": "Търсене на контакти...", "contacts_noUnreadContacts": "Няма непрочетени контакти", "contacts_noContactsFound": "Няма намерени контакти или групи.", @@ -470,6 +485,7 @@ } } }, + "chat_selectSendAction": "Изберете действие за изпращане", "chat_sendGif": "Изпрати GIF", "chat_reply": "Отговори", "chat_addReaction": "Добави Реакция", @@ -562,7 +578,7 @@ "chat_pathManagement": "Управление на пътищата", "chat_routingMode": "Режим на маршрутизиране", "chat_autoUseSavedPath": "Автоматично (използвай запазения път)", - "chat_forceFloodMode": "Принуди режим на наводняване", + "chat_forceFloodMode": "Принуди режим Flood", "chat_recentAckPaths": "Последни ACK пътища (докоснете, за да използвате):", "chat_pathHistoryFull": "Историята на пътя е пълна. Премахнете записи, за да добавите нови.", "chat_hopSingular": "скок", @@ -585,7 +601,7 @@ "chat_clearPathSubtitle": "Принуди преоткриване при следващо изпращане", "chat_pathCleared": "Пътят е почистен. Следващото съобщение ще открие маршрута отново.", "chat_floodModeSubtitle": "Използвайте превключвателя за маршрутизиране в лентата на приложението.", - "chat_floodModeEnabled": "Режимът на наводняване е включен. Включете го отново чрез иконата за маршрутизиране в лентата на приложението.", + "chat_floodModeEnabled": "Режимът Flood е включен. Изключете го чрез иконата за маршрутизиране в лентата на приложението.", "chat_fullPath": "Пълен път", "chat_pathDetailsNotAvailable": "Подробности за пътя все още не са налични. Опитайте да изпратите съобщение, за да ги обновите.", "chat_pathSetHops": "Пътят е зададен: {hopCount} {hopCount, plural, =1{скок} other{скока}} - {status}", @@ -606,7 +622,7 @@ "chat_path": "Път", "chat_publicKey": "Публичен ключ", "chat_compressOutgoingMessages": "Компресиране на изходящи съобщения", - "chat_floodForced": "Наводняване (принудително)", + "chat_floodForced": "Flood (принудително)", "chat_directForced": "Директно (принудително)", "chat_hopsForced": "{count} скока (принудително)", "@chat_hopsForced": { @@ -616,7 +632,7 @@ } } }, - "chat_floodAuto": "Наводняване (автоматично)", + "chat_floodAuto": "Flood (автоматично)", "chat_direct": "Директно", "chat_poiShared": "Споделена точка на интерес", "chat_unread": "Непрочетени: {count}", @@ -769,6 +785,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "Север {north}, Юг {south}, Изток {east}, Запад {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -834,7 +900,7 @@ "login_routing": "Маршрутизиране", "login_routingMode": "Режим на маршрутизиране", "login_autoUseSavedPath": "Автоматично (използвай запазения път)", - "login_forceFloodMode": "Принуди режим на наводняване", + "login_forceFloodMode": "Принуди режим Flood", "login_managePaths": "Управление на пътищата", "login_login": "Вход", "login_attempt": "Опитвате {current}/{max}", @@ -877,7 +943,7 @@ }, "path_enterCustomPath": "Въведете персонализиран път", "path_currentPathLabel": "Текущ път", - "path_hexPrefixInstructions": "Въведете 2-символни шестнадесетични префикси за всеки хоп, разделени с кама.", + "path_hexPrefixInstructions": "Въведете 2-символни шестнадесетични префикси за всеки скок, разделени със запетая.", "path_hexPrefixExample": "A1,F2,3C (всяка нода използва първия байт от публичния си ключ)", "path_labelHexPrefixes": "Пътеки (шестнадесетични префикси)", "path_helperMaxHops": "Максимум 64 скока. Всеки префикс е 2 шестнадесетични знака (1 байт).", @@ -907,7 +973,7 @@ "repeater_statusTitle": "Статус на повтарянето", "repeater_routingMode": "Режим на маршрутизиране", "repeater_autoUseSavedPath": "Автоматично (използвай запазения път)", - "repeater_forceFloodMode": "Принуди режим на наводняване", + "repeater_forceFloodMode": "Принуди режим Flood", "repeater_pathManagement": "Управление на пътища", "repeater_refresh": "Презареди", "repeater_statusRequestTimeout": "Заявката за статус премина прекалено дълго.", @@ -952,7 +1018,7 @@ } } }, - "repeater_packetTxTotal": "Общо: {total}, Наводнение: {flood}, Директно: {direct}", + "repeater_packetTxTotal": "Общо: {total}, Flood: {flood}, Директно: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -966,7 +1032,7 @@ } } }, - "repeater_packetRxTotal": "Общо: {total}, Наводнение: {flood}, Директно: {direct}", + "repeater_packetRxTotal": "Общо: {total}, Flood: {flood}, Директно: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -980,7 +1046,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Поливане: {flood}, Директен: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Директен: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1026,9 +1092,9 @@ "repeater_guestAccess": "Достъп за гости", "repeater_guestAccessSubtitle": "Разрешете само четене за гости", "repeater_privacyMode": "Режим на поверителност", - "repeater_privacyModeSubtitle": "Скриване на име/местоположение в рекламите", - "repeater_advertisementSettings": "Настройки на рекламите", - "repeater_localAdvertInterval": "Интервал на местната реклама", + "repeater_privacyModeSubtitle": "Скриване на име/местоположение в обявите", + "repeater_advertisementSettings": "Настройки на обявите", + "repeater_localAdvertInterval": "Интервал на локалната обява", "repeater_localAdvertIntervalMinutes": "{minutes} минути", "@repeater_localAdvertIntervalMinutes": { "placeholders": { @@ -1037,7 +1103,7 @@ } } }, - "repeater_floodAdvertInterval": "Интервал на рекламата за наводняване", + "repeater_floodAdvertInterval": "Интервал на Flood обявата", "repeater_floodAdvertIntervalHours": "{hours} часа", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1046,7 +1112,7 @@ } } }, - "repeater_encryptedAdvertInterval": "Криптиран интервал на рекламата", + "repeater_encryptedAdvertInterval": "Криптиран интервал на обявата", "repeater_dangerZone": "Опасна зона", "repeater_rebootRepeater": "Рестартирай повторителя", "repeater_rebootRepeaterSubtitle": "Рестартира повторителя.", @@ -1102,14 +1168,14 @@ "repeater_ownerInfo": "Информация за оператора", "repeater_ownerInfoHelper": "Публични метаданни за този повторител", "repeater_refreshOwnerInfo": "Обновете информацията за оператора", - "repeater_floodMax": "Максимален брой хопове при наводняване", - "repeater_floodMaxHelper": "Максималният брой хопове, които един пакет може да премине (0-64)", + "repeater_floodMax": "Максимален брой скокове при Flood", + "repeater_floodMaxHelper": "Максималният брой скокове, които един пакет може да премине (0-64)", "repeater_advancedSettings": "Разширени настройки", "repeater_advancedSettingsSubtitle": "Експериментални настройки за опитни оператори", "repeater_pathHashMode": "Режим за хеширане на пътища", "repeater_pathHashModeHelper": "Байтовете, използвани за кодиране на идентификатора на този повторител в таговете за откриване на потоци/цикли, са: 0=1 байт (256 идентификатора, до 64 скока), 1=2 байта (65 000 идентификатора, до 32 скока), 2=3 байта (16 милиона идентификатора, до 21 скока). Версиите 1.13 и по-старите фърмуери използват многобайтови пътища - само след като мрежата е актуализирана до версия 1.14 или по-нова.", "repeater_txDelay": "Забавяне на Flood TX", - "repeater_txDelayHelper": "Разстоянието между пакетите при наводняване като множител на времето за пренос на пакета (0-2, по подразбиране 0.5). По-висока стойност означава по-малко сблъсъци, но по-бавно предаване.", + "repeater_txDelayHelper": "Разстоянието между пакетите при Flood трафик като множител на времето за пренос на пакета (0-2, по подразбиране 0.5). По-висока стойност означава по-малко сблъсъци, но по-бавно предаване.", "repeater_directTxDelay": "Забавяне на директното предаване", "repeater_directTxDelayHelper": "Интервал за директен (не-масов) трафик, като множител на времето за пренос на пакета (0-2, по подразбиране 0.3).", "repeater_intThresh": "Праг на смущенията", @@ -1117,10 +1183,10 @@ "repeater_agcResetInterval": "Интервал за нулиране на AGC", "repeater_agcResetIntervalHelper": "Колко често да се рестартира автоматичната настройка на усилването, за да се възстанови от състояние, в което усилването е блокирано. Времето за рестартиране е няколко секунди, като се определя като кратна на 4. 0 деактивира периодичното рестартиране.", "repeater_actionsTitle": "Действия", - "repeater_sendAdvert": "Изпрати реклама за наводняване", - "repeater_sendAdvertSubtitle": "Публикувай реклама за наводняване в мрежата.", - "repeater_sendAdvertZeroHop": "Изпрати реклама без хопове", - "repeater_sendAdvertZeroHopSubtitle": "Публикувай реклама, която достига до целевата аудитория само чрез директно разпространение.", + "repeater_sendAdvert": "Изпрати Flood обява", + "repeater_sendAdvertSubtitle": "Разпространи Flood обява в мрежата.", + "repeater_sendAdvertZeroHop": "Изпрати обява с нулев скок", + "repeater_sendAdvertZeroHopSubtitle": "Разпространи обява само с един скок (без повторители).", "repeater_clockSync": "Синхронизирай часовника сега", "repeater_clockSyncSubtitle": "Настройте времето на телефона си да съвпада с времето на повторителя.", "repeater_actionSucceeded": "{action} успешно", @@ -1205,9 +1271,9 @@ "repeater_cliQuickGetTx": "Вземи TX", "repeater_cliQuickNeighbors": "Съседи", "repeater_cliQuickVersion": "Версия", - "repeater_cliQuickAdvertise": "Рекламирай", + "repeater_cliQuickAdvertise": "Обяви", "repeater_cliQuickClock": "Часовник", - "repeater_cliHelpAdvert": "Изпраща рекламен пакет", + "repeater_cliHelpAdvert": "Изпраща пакет за обява", "repeater_cliHelpReboot": "Рестартира устройството. (Забележка, може да получите 'Timeout', което е нормално)", "repeater_cliHelpClock": "Показва текущото време според часовника на всяко устройство.", "repeater_cliHelpPassword": "Задава се нова администраторска парола за устройството.", @@ -1217,19 +1283,19 @@ "repeater_cliHelpSetTx": "Задава се мощността на предаване на LoRa в dBm (отчитане спрямо референтно ниво).", "repeater_cliHelpSetRepeat": "Активира или деактивира ролята на репитера за този възел.", "repeater_cliHelpSetAllowReadOnly": "(Сървър на стаята) Ако е \"включено\", тогава влизането с празен парола ще бъде разрешено, но не може да публикува в стаята (само четене).", - "repeater_cliHelpSetFloodMax": "Задава максималния брой хопове на входящ пакет за заливване (ако >= max, пакетът не се предава).", + "repeater_cliHelpSetFloodMax": "Задава максималния брой скокове на входящ Flood пакет (ако >= max, пакетът не се предава).", "repeater_cliHelpSetIntThresh": "Задава праг на интерференцията (в dB). По подразбиране е 14. Задайте на 0, за да деактивирате откриването на интерференция на каналите.", "repeater_cliHelpSetAgcResetInterval": "Задава интервала за рестартиране на Автоматичния контролер за усилване. Задайте на 0, за да го деактивирате.", "repeater_cliHelpSetMultiAcks": "Активира или деактивира функцията 'двойни ACKs'.", - "repeater_cliHelpSetAdvertInterval": "Задава интервала на таймера в минути за изпращане на локален (безпроблемен) рекламен пакет. Задайте на 0, за да го деактивирате.", - "repeater_cliHelpSetFloodAdvertInterval": "Задава интервала на таймера в часове за изпращане на пакет с реклама за наводнение. Задайте на 0, за да го деактивирате.", + "repeater_cliHelpSetAdvertInterval": "Задава интервала на таймера в минути за изпращане на локален (нулев скок) пакет за обява. Задайте на 0, за да го деактивирате.", + "repeater_cliHelpSetFloodAdvertInterval": "Задава интервала на таймера в часове за изпращане на Flood пакет за обява. Задайте на 0, за да го деактивирате.", "repeater_cliHelpSetGuestPassword": "Задава/обновява паролата на гост. (за повторители, гостите могат да изпращат заявката \"Get Stats\")", "repeater_cliHelpSetName": "Задава име на обявата.", - "repeater_cliHelpSetLat": "Задава географска ширина на картата с реклами (в десетими градуси).", - "repeater_cliHelpSetLon": "Задава обхвата на дължина на картата на рекламата. (десетими градуса)", + "repeater_cliHelpSetLat": "Задава географска ширина на картата за обявата (в десетични градуси).", + "repeater_cliHelpSetLon": "Задава географска дължина на картата за обявата. (десетични градуси)", "repeater_cliHelpSetRadio": "Задава напълно нови радио параметри и ги запазва в предпочитанията. Изисква команда \"рестарт\", за да бъдат приложени.", "repeater_cliHelpSetRxDelay": "Зададени (експериментални) основи (трябва да е > 1 за ефект) за прилагане на леко забавяне на получените пакети, базирано на силата на сигнала/резултата. Задайте на 0, за да го деактивирате.", - "repeater_cliHelpSetTxDelay": "Задава фактор, умножен по времето на въздух за пакет в режим на наводнение и с рандомизирана система за слотове, за да забави предаването му (за да намали вероятността от сблъсъци).", + "repeater_cliHelpSetTxDelay": "Задава фактор, умножен по времето на въздух за Flood пакет и с рандомизирана система за слотове, за да забави предаването му (за да намали вероятността от сблъсъци).", "repeater_cliHelpSetDirectTxDelay": "Същото като txdelay, но за прилагане на случайна забавяне при препращането на пакети в директен режим.", "repeater_cliHelpSetBridgeEnabled": "Активиране/Деактивиране на мост.", "repeater_cliHelpSetBridgeDelay": "Задайте забавяне преди преизпращане на пакети.", @@ -1243,9 +1309,9 @@ "repeater_cliHelpLogStart": "Започва записване на пакети във файловата система.", "repeater_cliHelpLogStop": "Спира записването на пакети във файловата система.", "repeater_cliHelpLogErase": "Изтрива логовете от пакета от файловата система.", - "repeater_cliHelpNeighbors": "Показва списък с други възли на репитер, чути чрез нулев хоп реклами. Всяка линия е id-prefix-hex:timestamp:snr-times-4", + "repeater_cliHelpNeighbors": "Показва списък с други възли на повторител, чути чрез обяви с нулев скок. Всяка линия е id-prefix-hex:timestamp:snr-times-4", "repeater_cliHelpNeighborRemove": "Премахва първия съвпадащ запис (по префикси на pubkey (hex)) от списъка с съседи.", - "repeater_cliHelpRegion": "(сериен режим) Изброява всички дефинирани региони и текущите разрешения за наводнения.", + "repeater_cliHelpRegion": "(сериен режим) Изброява всички дефинирани региони и текущите разрешения за Flood.", "repeater_cliHelpRegionLoad": "Забележка: това е специално многокомандно извикване. Всяка следваща команда е име на регион (отстъпен с интервали, за да се покаже йерархията, с минимум един интервал). Завършва се чрез изпращане на празен ред/команда.", "repeater_cliHelpRegionGet": "Търси регион с даден префикс на име (или \"\" за глобалния обхват). Отговаря с \"-> region-name (parent-name) 'F'\"", "repeater_cliHelpRegionPut": "Добавя или актуализира дефиниция на регион с дадено име.", @@ -1259,7 +1325,7 @@ "repeater_cliHelpGpsOnOff": "Включва/Изключва GPS захранването.", "repeater_cliHelpGpsSync": "Синхронизира времето на възела с GPS часовника.", "repeater_cliHelpGpsSetLoc": "Задава координатите на нодата по GPS и запазва предпочитанията.", - "repeater_cliHelpGpsAdvert": "Предоставя конфигурацията на рекламата за местоположението на възела:\n- none: не включвайте местоположението в рекламите\n- share: споделяйте gps местоположението (от SensorManager)\n- prefs: рекламирайте местоположението, съхранено в предпочитанията", + "repeater_cliHelpGpsAdvert": "Предоставя конфигурацията на обявата за местоположението на възела:\n- none: не включвайте местоположението в обявите\n- share: споделяйте gps местоположението (от SensorManager)\n- prefs: обявявайте местоположението, съхранено в предпочитанията", "repeater_cliHelpGpsAdvertSet": "Задава конфигурация на обявите за местоположение.", "repeater_commandsListTitle": "Списък с команди", "repeater_commandsListNote": "ЗАБЕЛЕЖКА: за различните команди \"set ...\", също така съществува команда \"get ...\".", @@ -1417,7 +1483,7 @@ } }, "channelPath_unknownPath": "Неизвестно", - "channelPath_floodPath": "Поливане", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Директно", "channelPath_observedZeroOf": "0 от {total} скокове", "@channelPath_observedZeroOf": { @@ -1693,14 +1759,14 @@ "appSettings_enableMessageTracing": "Разрешаване на проследяване на съобщения", "appSettings_enableMessageTracingSubtitle": "Показване на подробни метаданни за маршрутизация и синхронизация за съобщения", "contacts_contactImported": "Контактът е импортиран.", - "contacts_zeroHopAdvert": "Реклама без скок", + "contacts_zeroHopAdvert": "Обява без скок", "contacts_contactImportFailed": "Контактът не е успешно импортиран.", - "contacts_floodAdvert": "Реклама за наводняване", + "contacts_floodAdvert": "Flood обява", "contacts_addContactFromClipboard": "Добави контакт от клипборда", "contacts_copyAdvertToClipboard": "Копирай обявата в клипборда", "contacts_ShareContact": "Копирай контакт в клипборда", "contacts_ShareContactZeroHop": "Сподели контакт чрез обява", - "contacts_contactAdvertCopied": "Рекламата е копирана в клипборда.", + "contacts_contactAdvertCopied": "Обявата е копирана в клипборда.", "contacts_zeroHopContactAdvertFailed": "Неуспешно изпращане на контакт.", "contacts_zeroHopContactAdvertSent": "Изпратен контакт по обява.", "contacts_contactAdvertCopyFailed": "Копирането на обявата в клипборда не успя.", @@ -1725,7 +1791,7 @@ "settings_gpxExportAllContacts": "Местоположения на всички контакти", "settings_gpxExportShareText": "Картинни данни изнесени от meshcore-open", "settings_gpxExportShareSubject": "meshcore-open износ на данни за карта в формат GPX", - "pathTrace_someHopsNoLocation": "Един или повече от хмелите липсва местоположение!", + "pathTrace_someHopsNoLocation": "Един или повече от скоковете няма определено местоположение!", "map_pathTraceCancelled": "Отменен е следването на пътя.", "pathTrace_clearTooltip": "Изчисти пътя", "map_removeLast": "Премахни последното", @@ -2201,7 +2267,7 @@ "repeater_sensors": "Датчици", "repeater_cliHelpPowerOff": "Изключва устройството. (не се очаква отговор)", "repeater_cliHelpClkReboot": "Възстановява часовника до известна историческа дата и рестартира устройството.", - "repeater_cliHelpAdvertZeroHop": "Изпраща реклама, която достига само до съседни устройства (само до съседни мрежи).", + "repeater_cliHelpAdvertZeroHop": "Изпраща обява, която достига само до съседни устройства (само до съседни мрежи).", "repeater_cliHelpStartOta": "Стартира актуализация на фърмуера чрез въздушното, на всички поддържани платки.", "repeater_cliHelpTime": "Задава времето на устройството към зададените секунди от началото на Unix ерата. Времето не може да се върне назад.", "repeater_cliHelpBoard": "Показва производителя на платката / идентификатора на хардуера.", @@ -2212,7 +2278,7 @@ "repeater_cliHelpSetDutyCycle": "Задава максимално допустимия процент на използване на времето за предаване (от 1 до 100 процента). Вътрешно коригира фактора за времето на предаване.", "repeater_cliHelpSetPrvKey": "(Само за серийни номера) Заменя личната част от ключа за идентификация на устройството. Необходимо е да се рестартира устройството, за да се приложи. Генерира нов публичен ключ.", "repeater_cliHelpSetRadioRxGain": "(Само за SX126x) Превключва усиления на приемния сигнал (RX gain) за подобрена чувствителност при по-високо потребление на ток.", - "repeater_cliHelpSetOwnerInfo": "Задава низовете с информация за контакт на собственика, които са включени в рекламите. Използвайте '|' за нови редове.", + "repeater_cliHelpSetOwnerInfo": "Задава низовете с информация за контакт на собственика, които са включени в обявите. Използвайте '|' за нови редове.", "repeater_cliHelpSetPathHashMode": "Задава режима за хеширане на пътищата. 0 = за стари системи, 1 = за стандартни системи, 2 = за строги системи. Влияе върху начина, по който се съпоставят маршрутите.", "repeater_cliHelpSetLoopDetect": "Задава чувствителността за откриване на цикли в маршрутизацията: изключена, минимална, умерена или строга.", "repeater_cliHelpSetFreq": "(Само за серийно управление) Бързо задава само честотата. Необходимо е рестартиране. Препоръчително е да се използват настройките за \"радио\", за да се зададат всички параметри.", @@ -2232,15 +2298,15 @@ "repeater_cliHelpGetAgcResetInterval": "Показва интервала за рестартиране на AGC в секунди.", "repeater_cliHelpGetMultiAcks": "Показва дали режимът \"двоен ACK\" е активиран (1) или деактивиран (0).", "repeater_cliHelpGetAllowReadOnly": "Показва дали е разрешено само четене за гостите.", - "repeater_cliHelpGetAdvertInterval": "Показва времето на рекламата в минути.", - "repeater_cliHelpGetFloodAdvertInterval": "Показва интервала на рекламата за навод в часове.", + "repeater_cliHelpGetAdvertInterval": "Показва интервала на обявата в минути.", + "repeater_cliHelpGetFloodAdvertInterval": "Показва интервала на Flood обявата в часове.", "repeater_cliHelpGetGuestPassword": "Показва зададения парол за гост.", "repeater_cliHelpGetLat": "Показва зададената географска ширина.", "repeater_cliHelpGetLon": "Показва зададената дължина.", "repeater_cliHelpGetRxDelay": "Показва основната стойност на забавянето на сигнала.", - "repeater_cliHelpGetTxDelay": "Показва коефициента за забавяне при режим на наводняване.", + "repeater_cliHelpGetTxDelay": "Показва коефициента за забавяне при режим Flood.", "repeater_cliHelpGetDirectTxDelay": "Показва коефициента за забавяне при директен режим.", - "repeater_cliHelpGetFloodMax": "Показва максималния брой на повторни наводнения.", + "repeater_cliHelpGetFloodMax": "Показва максималния брой скокове при Flood.", "repeater_cliHelpGetOwnerInfo": "Показва информацията за контакт на собственика.", "repeater_cliHelpGetPathHashMode": "Показва режима на хеширане на пътя (0/1/2).", "repeater_cliHelpGetLoopDetect": "Показва чувствителността към откриване на цикли.", @@ -2262,8 +2328,8 @@ "repeater_cliHelpSensorList": "Показва всички настройки на потребителските сензори, разделени на страници, започвайки от опционален индекс.", "repeater_cliHelpRegionDefault": "Показва текущия обхват на региона по подразбиране.", "repeater_cliHelpRegionDefaultSet": "Задава обхвата на региона по подразбиране. Използвайте \"\", за да го изчистите.", - "repeater_cliHelpRegionListAllowed": "Списва регионите, които позволяват преминаване на превозни средства при наводнение.", - "repeater_cliHelpRegionListDenied": "Списва региони, които забраняват движението по пътищата при наводнения.", + "repeater_cliHelpRegionListAllowed": "Списва регионите, които разрешават Flood трафик.", + "repeater_cliHelpRegionListDenied": "Списва региони, които забраняват Flood трафик.", "repeater_cliHelpStatsPackets": "(Само за серия) Показва статистически данни на ниво пакет.", "repeater_cliHelpStatsRadio": "(Само за конкретен сериал) Показва радиостатистика.", "repeater_cliHelpStatsCore": "(Само за серийния номер) Показва основните статистически данни за фърмуера.", @@ -2403,9 +2469,9 @@ "contacts_searchClose": "Затвори търсене", "routing_title": "Маршрутизиране", "routing_modeAuto": "Автоматично", - "routing_modeFlood": "Наводняване", + "routing_modeFlood": "Flood", "routing_modeManual": "Ръчно", - "routing_modeAutoHint": "Автоматично избира най-добрия известен път, а при липса на информация използва стратегия за наводняване.", + "routing_modeAutoHint": "Автоматично избира най-добрия известен път, а при липса на такъв използва режим Flood.", "routing_modeFloodHint": "Излъчва през всички повторители. Най-надеждният начин, но изисква повече време в ефира.", "routing_modeManualHint": "Винаги следва точно пътя, който сте определили.", "routing_currentRoute": "Текущ маршрут", @@ -2421,10 +2487,10 @@ "routing_qualityGood": "Добър първи опит", "routing_qualityFair": "Приемлив първи скок", "routing_qualityWorked": "Работил", - "routing_qualityFlood": "Получено чрез наводняване", + "routing_qualityFlood": "Получено чрез Flood", "routing_qualityUntested": "Нетестирано", "routing_neverWorked": "Никога не е потвърдено", - "routing_floodDelivery": "Доставка при наводняване", + "routing_floodDelivery": "Доставка чрез Flood", "pathEditor_title": "Създаване на път", "pathEditor_hopCounter": "{count} от 64 скока", "pathEditor_noHops": "Все още няма добавени скокове. Можете да използвате бутоните по-долу, за да ги добавите по ред, или да запазите пътя без скокове, за да го изпратите директно.", @@ -2540,5 +2606,260 @@ "pathMap_noLocation": "Без посочено местоположение", "pathMap_followPacket": "Проследи пакета", "pathMap_unfollowPacket": "Спри проследяването на пакета", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Региони", + "settings_regionSettingsSubtitle": "Управляне на хранилищни региони", + "settings_regionManagement_screenTitle": "Регионално управление", + "settings_regionNameHint": "Възразна название на региона", + "settings_regionAddRegion": "Добавете регион", + "settings_regionFetchRegions": "Извън рептерите от региони", + "settings_regionFetchRegionsFail": "Не бъде открити никако региони", + "settings_regionFetchRegionsAlreadyExists": "Тата регион е уже добавена", + "settings_regionName": "Регионноименоване", + "settings_regionDeleted": "Регион отстранен", + "settings_deleteRegion": "Удаляне на регион", + "settings_deleteRegionConfirm": "Състрясна: отпиште \"{region}\" от списка региони?", + "settings_infoHardware": "Оборудование", + "settings_infoFirmware": "Програмно-оборонни системни программи (фirmware)", + "repeater_pathHashModeOption0": "0 - 1 байт", + "repeater_pathHashModeOption1": "1 - 2 байта", + "repeater_pathHashModeOption2": "2 - 3 байта", + "repeater_pathHashModeOption3": "3 - 4 байта", + "appSettings_batteryLipoHv": "LiPo ВЗГ (3,0-4,35 В)", + "channels_regionSetTo": "Регион: {region}", + "channels_regionNotSet": "Регион: ние", + "channels_regionSelect_Title": "Выберете регион", + "channels_clearRegion": "Чиста зона", + "chat_sendImageLora": "Изпращане на изображение чрез MeshCore", + "chat_imagePickFailed": "Не мог да откривам та изображин", + "chat_receivedGif": "Получил GIF", + "repeater_keySettings": "Изменяне на идентичности ключа", + "repeater_keySettingsSubtitle": "Замени ключовият пар от публични/частни", + "repeater_prvKey": "Частни ключ", + "repeater_prvKeyHelper": "Нова приватна ключ на повторчето, 128-символовна шестнадатерична строка.", + "repeater_generatePrvKey": "Генериране на случайна ключи", + "repeater_stopGeneratingPrvKey": "Прервана поискна на ключова парта", + "repeater_pubKey": "Публична ключ", + "repeater_pubKeyHelper": "Та е публичната ключ, която се свързува с генериранта приватна ключ. Трябва да не настройте тоа напрямо.", + "repeater_pubKeyPrefix": "Желата префикс", + "repeater_pubKeyPrefixHelper": "Наискате публична ключ, който почева с този шестнадатницил. Ожидавани проби: {tries}.", + "imageMessages_enableTitle": "Абilitiraм изображените сообщения", + "imageMessages_enableSubtitle": "Изправате изображения чрез сетката. Треба е одноразовна загрузка модел на изображение.", + "imageMessages_modelSectionTitle": "Изображени модель", + "imageMessages_downloadModel": "Скачане", + "imageMessages_cancelDownload": "Отмена", + "imageMessages_removeModel": "Удалете модель", + "imageMessages_modelReady": "Готов", + "imageMessages_modelNotPublished": "Еще не опубликовано — тази версия не може да скане.", + "imageMessages_downloadFailed": "Модел за изображение не може да бъде скачан.", + "imageMessages_autoProcessTitle": "Автоматически обрабатвате изображения", + "imageMessages_autoProcessSubtitle": "Катализиране на всята изображение сразу по пришествие. Използване на около 2 ГБ на втора пъти; откажете от реконструкцията чаке при натискане.", + "imageSend_title": "Изпрати изображение", + "imageSend_cropNote": "Масштабиран до 512 × 512 · соотношение сторон не съхранясе", + "imageSend_originalSize": "Късно на използване на език:", + "imageSend_onAirSize": "В ефир", + "imageSend_quality": "Качество", + "imageSend_qualityStandard": "Стандарт", + "imageSend_qualityHigh": "Высок", + "imageSend_packetsLabel": "Пакети", + "imageSend_airtimeLabel": "Времето на изкъсване", + "imageSend_sizeLabel": "Баланса", + "imageSend_packetsCount": "{count} {count, plural, =1{пакет} other{пакета}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Настройки на радио неизвестни", + "imageSend_radioUnknownBody": "Усредете се с устройство, за да се отработа часът на изстъпане.", + "imageSend_longSendTitle": "Долга пресилка", + "imageSend_longSendBody": "Тази буде поддержива открит отряд на около {duration}.", + "imageSend_floodNote": "Flood маршрутизация: всеки повторител в обхват препредава всеки пакет, затова каналът остава зает по-дълго от посоченото тук време.", + "imageSend_parityTitle": "Возобновителен пакет", + "imageSend_paritySubtitle": "Едно дополително пакет. Групни извещания не принимаются, след това разбирателят едно пакетто, какщо е пропущен един пакет.", + "imageSend_send": "Отправляй", + "imageSend_cancel": "Отмена", + "imageSend_encodeFailed": "Тази изображение не може да бъде кодирано.", + "imageSend_codecDownloading": "Модел на изображение еще разгрузира.", + "imageSend_codecUnavailable": "Изглед отправа не е доступен на този устройство.", + "imageSend_codecDisabled": "Изображенията на извещенията е отключена в настройките.", + "imageSend_deviceUnsupported": "Та радиота не може да пресылава изображени пакети. Подключите устройство, който работи с компанионски прошивка 13 или новия.", + "imageSend_directMessagesUnsupported": "Изображенията се превозводя се как групова информация, следато да се отправят единствено на канал — не в лична вестка.", + "imageSend_tooLarge": "Таата изображение е кодирано в по-числа пакети, отгоре както формат на сетта разрешава.", + "imageSend_sentConfirmation": "Изображението е изпратено като {count} {count, plural, =1{пакет} other{пакета}}.", + "imageSend_sendFailed": "Изображение не може да бъде отправено: {error}", + "imageSend_sendingProgress": "Отправка наизображение — пакет {sent} от {total}", + "receivedImage_senderPrefix": "Узъдето {prefix}", + "receivedImage_incoming": "{received} от {total} пакета", + "receivedImage_queued": "Ожидането за декодиране", + "receivedImage_tapToDecode": "Натискнете за декодиране", + "receivedImage_decoding": "Повторно… за приблизително 1 секунда", + "receivedImage_incomplete": "Изображение неполно — {received} от {total} пакети отправили", + "receivedImage_corrupt": "Изображение не може да бъде воссоздано", + "receivedImage_decoderMissing": "Получена изображение — разгадка на изображение е вреjan", + "receivedImage_evicted": "Изображение не е хранитено", + "receivedImage_retry": "Повтори", + "receivedImage_decodeAgain": "Правилейте заново", + "receivedImage_openSettings": "Настройте", + "receivedImage_tapToProcess": "Натискнете за обработка", + "receivedImage_awaiting": "{bytes} байта · {packets} {packets, plural, =1{пакет} other{пакета}}", + "imageSend_secondsValue": "{seconds} секунди", + "imageSend_minutesSecondsValue": "{minutes} мин {seconds} сек", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "urlImage_enable": "Активиране на URL изображения", + "urlImage_possible": "Възможно изображение от URL; активирайте го в Настройки.", + "settings_radioSettingsNotApplied": "Радиото не приложи тези настройки", + "settings_publicKeyCopied": "Публичният ключ е копиран", + "channels_noFreeSlots": "Няма свободни канални места", + "reaction_report": "Емоджи реакции", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_frequencyInvalid": "Невалидна честота (150-2500 MHz)", + "repeater_txPowerRangeHelper": "от -9 до 30 dBm", + "repeater_recvErrors": "Грешки при приемане", + "room_postsStored": "Публикации", + "room_postsPushed": "Изпратени публикации", + "repeater_cliRegionLoadActive": "Режим на зареждане на региони: изпращайте по едно име на регион на ред, с отстъп от интервали под съответния родител (добавете F след името, за да разрешите flood). Редовете не получават отговор. Изпратете празен ред, за да завършите, след което изпратете „region save“, за да запазите резултата.", + "repeater_cliRegionLoadHint": "Ред за регион или празно за завършване", + "repeater_cliRegionLoadEnd": "(край на зареждането на региони)", + "repeater_cliHelpRegionDef": "Задава верига от региони с една команда: всяко име се добавя под предишното; „name,parent“ добавя името и продължава под указания родител. Връща списъка с региони.", + "repeater_cliHelpSetFloodMaxUnscoped": "Задава максималния брой скокове за препращане на flood пакети без определена регионална област (0-64).", + "repeater_cliHelpSetFloodMaxAdvert": "Задава максималния брой скокове за препращане на flood обяви (0-64).", + "repeater_cliHelpGetFloodMaxUnscoped": "Показва максималния брой скокове за flood пакети без определена област.", + "repeater_cliHelpGetFloodMaxAdvert": "Показва максималния брой скокове за flood обяви.", + "repeater_cliHelpSetRadioFemRxGain": "Превключва RX усилването (LNA) на LoRa предния модул. Платки без такъв отговарят с „Error: unsupported“.", + "repeater_cliHelpSetRadioFemTxGain": "Превключва TX усилването (PA) на LoRa предния модул. Платки без такъв отговарят с „Error: unsupported“.", + "repeater_cliHelpGetRadioFemRxGain": "Показва дали RX усилването на LoRa предния модул е включено.", + "repeater_cliHelpGetRadioFemTxGain": "Показва дали TX усилването на LoRa предния модул е включено.", + "repeater_bridgeNote": "Налично само за прошивка с мост (RS232 или ESP-NOW).", + "chat_longMessageRetryNote": "Над 158 байта: изпраща се най-много {count} пъти" } diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index dc4c9dab..bf7c00e0 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Ungültiger Breiten- oder Längengrad.", "settings_latitude": "Breitengrad", "settings_longitude": "Längengrad", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatische Zero-Hop-Ankündigung bei GPS-Update", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Wenn sich der GPS-Standort ändert, eine Zero-Hop-Ankündigung senden (erfordert Standort in der Ankündigung).", "settings_privacyMode": "Privatsphärenmodus", "settings_privacyModeSubtitle": "Name und Standort in Ankündigungen verbergen", "settings_privacyModeToggle": "Privatsphärenmodus aktivieren, um Namen und Standort in Ankündigungen zu verbergen.", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Letzte 6 Stunden", "appSettings_last24Hours": "Letzte 24 Stunden", "appSettings_lastWeek": "Letzte Woche", + "appSettings_rasterTileSource": "Quelle für Rasterkacheln", + "appSettings_stadiaEndpoint": "Stadia-Endpunkt", + "appSettings_stadiaApiKey": "Stadia-API-Schlüssel", + "appSettings_stadiaApiKeyRequired": "Für die Nutzung von Stadia Maps erforderlich", + "appSettings_stadiaApiKeyConfigured": "Konfiguriert: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Geben Sie Ihren Stadia-Maps-API-Schlüssel ein. Die App verwendet ihn für Rasterkachel-Anfragen.", "appSettings_offlineMapCache": "Offline-Karten-Cache", "appSettings_noAreaSelected": "Kein Bereich ausgewählt", "appSettings_areaSelectedZoom": "Bereich ausgewählt (Zoom {minZoom}-{maxZoom})", @@ -492,6 +507,7 @@ } } }, + "chat_selectSendAction": "Sendeaktion auswählen", "chat_sendGif": "GIF senden", "chat_reply": "Antworten", "chat_addReaction": "Reaktion hinzufügen", @@ -584,7 +600,7 @@ "chat_pathManagement": "Pfadverwaltung", "chat_routingMode": "Routenmodus", "chat_autoUseSavedPath": "Automatisch (gespeicherten Pfad verwenden)", - "chat_forceFloodMode": "Flut-Modus erzwingen", + "chat_forceFloodMode": "Flood-Modus erzwingen", "chat_recentAckPaths": "Aktuelle ACK-Pfade (antippen, um zu verwenden):", "chat_pathHistoryFull": "Die Pfadhistorie ist voll. Entferne Einträge, um neue hinzuzufügen.", "chat_hopSingular": "Sprung", @@ -607,7 +623,7 @@ "chat_clearPathSubtitle": "Setze Pfad zurück, erkenne neuen Pfad bei nächster Sendung.", "chat_pathCleared": "Pfad zurückgesetzt. Nächste Nachricht wird Route neu entdecken.", "chat_floodModeSubtitle": "Verwende den Routingschalter in der App-Leiste", - "chat_floodModeEnabled": "Flutmodus aktiviert.", + "chat_floodModeEnabled": "Flood-Modus aktiviert.", "chat_fullPath": "Vollständiger Pfad", "chat_pathDetailsNotAvailable": "Die Pfaddetails sind noch nicht verfügbar. Versuchen Sie, eine Nachricht zu senden, um zu aktualisieren.", "chat_pathSetHops": "Pfad gesetzt: {hopCount} {hopCount, plural, =1{hop} other{hops}} - {status}", @@ -628,7 +644,7 @@ "chat_path": "Pfad", "chat_publicKey": "Öffentlicher Schlüssel", "chat_compressOutgoingMessages": "Komprimieren ausgehender Nachrichten", - "chat_floodForced": "Geflutet (erzwungen)", + "chat_floodForced": "Flood (erzwungen)", "chat_directForced": "Direkt (erzwungen)", "chat_hopsForced": "{count} Sprünge (erzwungen)", "@chat_hopsForced": { @@ -638,7 +654,7 @@ } } }, - "chat_floodAuto": "Geflutet (automatisch)", + "chat_floodAuto": "Flood (automatisch)", "chat_direct": "Direkt", "chat_poiShared": "Geteilter POI", "chat_unread": "Ungelesen: {count}", @@ -791,6 +807,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -856,7 +922,7 @@ "login_routing": "Routen", "login_routingMode": "Routenmodus", "login_autoUseSavedPath": "Automatisch (gespeicherten Pfad verwenden)", - "login_forceFloodMode": "Flut-Modus erzwingen", + "login_forceFloodMode": "Flood-Modus erzwingen", "login_managePaths": "Pfadverwaltung", "login_login": "Anmelden", "login_attempt": "Versuche {current}/{max}", @@ -929,7 +995,7 @@ "repeater_statusTitle": "Repeater-Status", "repeater_routingMode": "Routing-Modus", "repeater_autoUseSavedPath": "Automatisch (gespeicherten Pfad verwenden)", - "repeater_forceFloodMode": "Flut-Modus erzwingen", + "repeater_forceFloodMode": "Flood-Modus erzwingen", "repeater_pathManagement": "Pfadverwaltung", "repeater_refresh": "Aktualisieren", "repeater_statusRequestTimeout": "Statusanfrage abgelaufen.", @@ -1129,7 +1195,7 @@ "repeater_advancedSettings": "Erweitert", "repeater_advancedSettingsSubtitle": "Feinabstimmung für erfahrene Betreiber", "repeater_pathHashMode": "Hash-Modus für Pfade", - "repeater_pathHashModeHelper": "Bytes, die zur Kodierung der ID dieses Repeaters in Flood-Pfad-/Schleifen-Erkennung-Tags verwendet werden. 0 = 1 Byte (256 IDs, bis zu 64 Hops), 1 = 2 Bytes (65.000 IDs, bis zu 32 Hops), 2 = 3 Bytes (16 Millionen IDs, bis zu 21 Hops). Firmware-Versionen 1.13 und älter verwenden mehrstellige Pfade – ab Version 1.14+ wird nur ein Pfad erstellt, sobald das Netzwerk aktiv ist.", + "repeater_pathHashModeHelper": "Bytes, die zur Kodierung der ID dieses Repeaters in Flood-Pfad-/Schleifen-Erkennung-Tags verwendet werden. 0 = 1 Byte (256 IDs, bis zu 64 Sprüngen), 1 = 2 Bytes (65.000 IDs, bis zu 32 Sprüngen), 2 = 3 Bytes (16 Millionen IDs, bis zu 21 Sprüngen). Firmware-Versionen 1.13 und älter verwenden mehrstellige Pfade – ab Version 1.14+ wird nur ein Pfad erstellt, sobald das Netzwerk aktiv ist.", "repeater_txDelay": "Flood-TX-Verzögerung", "repeater_txDelayHelper": "Abstand für Flood-Verkehr als Faktor der Paket-Sendezeit (0-2, Standard 0,5). Höher = weniger Kollisionen, aber langsamere Zustellung.", "repeater_directTxDelay": "Direkte TX-Verzögerung", @@ -1244,9 +1310,9 @@ "repeater_cliHelpSetAgcResetInterval": "Legt das Intervall für das Zurücksetzen des Auto Gain Controllers fest. Auf 0 setzen, um die Funktion zu deaktivieren.", "repeater_cliHelpSetMultiAcks": "Aktiviert oder deaktiviert die Funktion 'Doppel-ACKs'.", "repeater_cliHelpSetAdvertInterval": "Legt das Timer-Intervall in Minuten fest, um ein lokales (ohne-Weiterleitung) Ankündigungspaket zu senden. Auf 0 setzen, um die Funktion zu deaktivieren.", - "repeater_cliHelpSetFloodAdvertInterval": "Legt das Timer-Intervall in Stunden für den Versand eines Flut-Ankündigungspacket fest. Auf 0 setzen, um es zu deaktivieren.", + "repeater_cliHelpSetFloodAdvertInterval": "Legt das Timer-Intervall in Stunden für den Versand eines Flood-Ankündigungspaket fest. Auf 0 setzen, um es zu deaktivieren.", "repeater_cliHelpSetGuestPassword": "Legt/aktualisiert das Gastpasswort fest. (für Repeater können Gast-Logins die \"Get Stats\"-Anfrage senden)", - "repeater_cliHelpSetName": "Legt den Anzeigenamen fest.", + "repeater_cliHelpSetName": "Legt den Ankündigungsnamen fest.", "repeater_cliHelpSetLat": "Legt die Breitengrad der Ankündigung fest. (dezimale Grad)", "repeater_cliHelpSetLon": "Legt die Längengrade der Ankündigung fest. (dezimale Grad)", "repeater_cliHelpSetRadio": "Legt komplett neue Radio-Parameter fest und speichert diese als Präferenzen. Benötigt einen \"Reboot\"-Befehl, um sie anzuwenden.", @@ -1272,7 +1338,7 @@ "repeater_cliHelpRegionGet": "Sucht die Region mit dem gegebenen Namenspräfix (oder \"\\\" für den globalen Scope) und antwortet mit \"-> region-name (parent-name) 'F'\".", "repeater_cliHelpRegionPut": "Fügt eine Region-Definition mit dem angegebenen Namen hinzu oder aktualisiert diese.", "repeater_cliHelpRegionRemove": "Löscht eine Regiondefinition mit dem angegebenen Namen. (muss genau übereinstimmen und keine Kindregionen haben)", - "repeater_cliHelpRegionAllowf": "Legt die 'Flut'-Berechtigung für die angegebene Region fest. ('' für den globalen/legacy-Bereich)", + "repeater_cliHelpRegionAllowf": "Legt die 'Flood'-Berechtigung für die angegebene Region fest. ('' für den globalen/legacy-Bereich)", "repeater_cliHelpRegionDenyf": "Entfernt die \"F\"lood-Berechtigung für die angegebene Region. (ANMERKUNG: in dieser Phase wird nicht empfohlen, dies auf dem globalen/legacy-Bereich zu verwenden!!)", "repeater_cliHelpRegionHome": "Antwortet mit der aktuellen 'Home'-Region. (Hinweis wurde bisher nirgendwo angewendet, für zukünftige Zwecke reserviert)", "repeater_cliHelpRegionHomeSet": "Legt die 'Home'-Region fest.", @@ -1281,8 +1347,8 @@ "repeater_cliHelpGpsOnOff": "Schaltet die GPS-Leistung ein/aus.", "repeater_cliHelpGpsSync": "Synchronisiert die Knotenzeit mit der GPS-Uhr.", "repeater_cliHelpGpsSetLoc": "Setze die Position des Knotens auf GPS-Koordinaten und speichere die Präferenzen.", - "repeater_cliHelpGpsAdvert": "Gibt Konfiguration für die Standortanzeige des Knotens:\n- none: Standort nicht in Anzeigen einbeziehen\n- share: GPS-Standort teilen (von SensorManager)\n- prefs: Standort aus Einstellungen anzeigen", - "repeater_cliHelpGpsAdvertSet": "Legt die Standort-Anzeigekonfiguration fest.", + "repeater_cliHelpGpsAdvert": "Gibt Konfiguration für die Standort-Ankündigung des Knotens:\n- none: Standort nicht in Ankündigungen einbeziehen\n- share: GPS-Standort teilen (von SensorManager)\n- prefs: Standort aus den Einstellungen ankündigen", + "repeater_cliHelpGpsAdvertSet": "Legt die Standort-Ankündigungskonfiguration fest.", "repeater_commandsListTitle": "Befehlsliste", "repeater_commandsListNote": "ACHTUNG: Für die verschiedenen „set ...“-Befehle gibt es auch einen „get ...“-Befehl.", "repeater_general": "Allgemein", @@ -1516,7 +1582,7 @@ } }, "channelPath_unknownPath": "Unbekannt", - "channelPath_floodPath": "Geflutet", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Direkt", "channelPath_observedZeroOf": "0 von {total} Sprüngen", "@channelPath_observedZeroOf": { @@ -1592,7 +1658,7 @@ } }, "repeater_neighbors": "Nachbarn", - "repeater_neighborsSubtitle": "Anzahl der Hop-Nachbarn anzeigen.", + "repeater_neighborsSubtitle": "Anzahl der Sprungnachbarn anzeigen.", "neighbors_receivedData": "Empfangene Nachbarsdaten", "neighbors_requestTimedOut": "Anfrage durch Timeout fehlgeschlagen.", "neighbors_errorLoading": "Fehler beim Laden der Nachbarn: {error}", @@ -1797,14 +1863,14 @@ "contacts_contactImported": "Kontakt wurde importiert.", "contacts_contactImportFailed": "Kontakt konnte nicht importiert werden", "contacts_zeroHopAdvert": "Zero-Hop-Ankündigung", - "contacts_floodAdvert": "Flut-Ankündigung", + "contacts_floodAdvert": "Flood-Ankündigung", "contacts_addContactFromClipboard": "Kontakt aus Zwischenablage hinzufügen", - "contacts_ShareContactZeroHop": "Kontakt über Anzeige teilen", + "contacts_ShareContactZeroHop": "Kontakt über Ankündigung teilen", "contacts_copyAdvertToClipboard": "Ankündigung in die Zwischenablage kopieren", "contacts_ShareContact": "Kontakt in die Zwischenablage kopieren", "contacts_zeroHopContactAdvertFailed": "Kontakt konnte nicht gesendet werden.", - "contacts_zeroHopContactAdvertSent": "Kontakt über Anzeige gesendet", - "contacts_contactAdvertCopied": "Anzeige in die Zwischenablage kopiert.", + "contacts_zeroHopContactAdvertSent": "Kontakt über Ankündigung gesendet", + "contacts_contactAdvertCopied": "Ankündigung in die Zwischenablage kopiert.", "contacts_contactAdvertCopyFailed": "Kopieren der Ankündigung in die Zwischenablage fehlgeschlagen.", "notification_activityTitle": "MeshCore Aktivität", "notification_messagesCount": "{count} {count, plural, =1{Nachricht} other{Nachrichten}}", @@ -2328,7 +2394,7 @@ "repeater_sensors": "Sensoren", "repeater_cliHelpPowerOff": "Schaltet das Gerät aus. (keine Antwort erwartet)", "repeater_cliHelpClkReboot": "Setzt die Uhr auf einen bekannten Zeitpunkt zurück und startet das Gerät neu.", - "repeater_cliHelpAdvertZeroHop": "Sendet eine Werbeanzeige, die nur an unmittelbare Nachbarn gesendet wird (ohne Zwischenstation).", + "repeater_cliHelpAdvertZeroHop": "Sendet eine Ankündigung, die nur an unmittelbare Nachbarn gesendet wird (ohne Zwischenstation).", "repeater_cliHelpStartOta": "Startet ein Firmware-Update über Funk, das auf unterstützten Boards durchgeführt wird.", "repeater_cliHelpTime": "Stellt die Gerätuhr auf die angegebene Unix-Epoche in Sekunden ein. Die Uhr kann nicht rückwärts laufen.", "repeater_cliHelpBoard": "Zeigt den Hersteller/die Hardware-Kennung an.", @@ -2359,13 +2425,13 @@ "repeater_cliHelpGetAgcResetInterval": "Zeigt das Intervall für die Rücksetzung des AGC in Sekunden an.", "repeater_cliHelpGetMultiAcks": "Zeigt an, ob der Modus \"doppelte ACK\"-Funktion aktiviert (1) oder deaktiviert (0) ist.", "repeater_cliHelpGetAllowReadOnly": "Zeigt an, ob der Zugriff für Gäste nur in Lesemodus erlaubt ist.", - "repeater_cliHelpGetAdvertInterval": "Zeigt die Dauer des lokalen Werbeintervalls in Minuten an.", - "repeater_cliHelpGetFloodAdvertInterval": "Zeigt die Dauer der Werbeunterbrechung in Stunden an.", + "repeater_cliHelpGetAdvertInterval": "Zeigt die Dauer des lokalen Ankündigungsintervalls in Minuten an.", + "repeater_cliHelpGetFloodAdvertInterval": "Zeigt die Dauer des Flood-Ankündigungsintervalls in Stunden an.", "repeater_cliHelpGetGuestPassword": "Zeigt das konfigurierte Gast-Passwort an.", "repeater_cliHelpGetLat": "Zeigt die konfigurierte Breitengrade.", "repeater_cliHelpGetLon": "Zeigt die konfigurierte Länge an.", "repeater_cliHelpGetRxDelay": "Zeigt den Basiswert für die Verzögerungszeit an.", - "repeater_cliHelpGetTxDelay": "Zeigt den Faktor für die Übertragungsverzögerung im Notfallmodus an.", + "repeater_cliHelpGetTxDelay": "Zeigt den Faktor für die Übertragungsverzögerung im Flood-Modus an.", "repeater_cliHelpGetDirectTxDelay": "Zeigt den Faktor für die Verzögerung im Direktmodus an.", "repeater_cliHelpGetFloodMax": "Zeigt die maximale Anzahl von Sprüngen für Flood-Pakete an.", "repeater_cliHelpGetOwnerInfo": "Zeigt die Zeichenkette mit den Kontaktinformationen des Eigentümers an.", @@ -2560,28 +2626,30 @@ "messageStatus_pending": "Wird gesendet", "messageStatus_failed": "Senden fehlgeschlagen", "messageStatus_repeated": "Mehrfach gehört", + "urlImage_enable": "URL-Bilder anzeigen", + "urlImage_possible": "Mögliches URL-Bild; in den Einstellungen aktivieren.", "contacts_moreOptions": "Weitere Optionen", "contacts_searchOpen": "Suche öffnen", "contacts_searchClose": "Suche schließen", "routing_title": "Routenplanung", "routing_modeAuto": "Automatisch", - "routing_modeFlood": "Flut", + "routing_modeFlood": "Flood", "routing_modeManual": "Manuell", "routing_modeFloodHint": "Über alle Repeater senden. Am zuverlässigsten, aber mit höherem Funkzeitbedarf.", - "routing_modeAutoHint": "Wählt automatisch den besten bekannten Pfad und wechselt auf Flut, wenn keiner bekannt ist.", + "routing_modeAutoHint": "Wählt automatisch den besten bekannten Pfad und wechselt in den Flood-Modus, wenn keiner bekannt ist.", "routing_modeManualHint": "Sendet immer genau den von Ihnen festgelegten Pfad.", "routing_currentRoute": "Aktuelle Route", "routing_directNoHops": "Direkt - keine Repeater-Sprünge", - "routing_noPathYet": "Noch kein Pfad gefunden. Die nächste Nachricht wird geflutet, bis eine Route entdeckt ist.", + "routing_noPathYet": "Noch kein Pfad gefunden. Die nächste Nachricht wird im Flood-Modus gesendet, bis eine Route entdeckt ist.", "routing_floodBroadcast": "Über alle Repeater senden", "routing_editPath": "Pfad bearbeiten", "routing_forgetPath": "Pfad vergessen", "routing_knownPaths": "Bekannte Pfade", "routing_knownPathsHint": "Tippen Sie auf einen Pfad, um zu ihm zu wechseln.", "routing_inUse": "In Verwendung", - "routing_qualityStrong": "Starker erster Hop", - "routing_qualityGood": "Guter erster Hop", - "routing_qualityFair": "Ausreichender erster Hop", + "routing_qualityStrong": "Starker erster Sprung", + "routing_qualityGood": "Guter erster Sprung", + "routing_qualityFair": "Ausreichender erster Sprung", "routing_qualityWorked": "Hat zugestellt", "routing_qualityFlood": "Per Flood gehört", "routing_qualityUntested": "Nicht getestet", @@ -2702,5 +2770,231 @@ "pathMap_noLocation": "Keine Standortdaten", "pathMap_followPacket": "Ansicht auf Paket fixieren", "pathMap_unfollowPacket": "Fixierung aufheben", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionFetchRegions": "Regionen von Wiederholern abrufen", + "settings_regionFetchRegionsFail": "Es wurden keine Regionen gefunden.", + "settings_regionFetchRegionsAlreadyExists": "Diese Region wurde bereits hinzugefügt", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 Byte", + "repeater_pathHashModeOption1": "1 - 2 Bytes", + "repeater_pathHashModeOption2": "2 - 3 Bytes", + "repeater_pathHashModeOption3": "3 - 4 Bytes", + "appSettings_batteryLipoHv": "LiPo HV (3,0–4,35 V)", + "chat_sendImageLora": "Bild über MeshCore senden", + "chat_imagePickFailed": "Konnte dieses Bild nicht öffnen.", + "chat_receivedGif": "Erhalten eines GIF", + "repeater_keySettings": "Identitätsschlüssel ändern", + "repeater_keySettingsSubtitle": "Ändern Sie das öffentliche/private Schlüsselpaar", + "repeater_prvKey": "Privatschlüssel", + "repeater_prvKeyHelper": "Ein neuer privater Schlüssel für den Repeater, eine 128-stellige Hexadezimalzeichenkette.", + "repeater_generatePrvKey": "Generiere ein zufälliges Schlüsselpaar", + "repeater_stopGeneratingPrvKey": "Suchvorgang für Schlüsselpaar unterbrechen", + "repeater_pubKey": "Öffentlicher Schlüssel", + "repeater_pubKeyHelper": "Dies ist der öffentliche Schlüssel, der zum generierten privaten Schlüssel gehört. Sie können dies nicht direkt festlegen.", + "repeater_pubKeyPrefix": "Gewünschtes Präfix", + "repeater_pubKeyPrefixHelper": "Suchen Sie einen öffentlichen Schlüssel, der mit diesen Hexadezimalziffern beginnt. Erwartete Versuche: {tries}.", + "imageMessages_enableTitle": "Bildnachrichten aktivieren", + "imageMessages_enableSubtitle": "Bilder über das Netzwerk senden. Einmaliges Herunterladen eines Bildmodells erforderlich.", + "imageMessages_modelSectionTitle": "Bildmodell", + "imageMessages_downloadModel": "Herunterladen", + "imageMessages_cancelDownload": "Stornieren", + "imageMessages_removeModel": "Modell entfernen", + "imageMessages_modelReady": "Bereit", + "imageMessages_modelNotPublished": "Noch nicht veröffentlicht – dieser Build kann es nicht herunterladen.", + "imageMessages_downloadFailed": "Das Bildmodell konnte nicht heruntergeladen werden.", + "imageMessages_autoProcessTitle": "Automatisch Bilder verarbeiten", + "imageMessages_autoProcessSubtitle": "Rekonstruiere jedes Bild sofort nach dem Eintreffen. Verbraucht etwa 2 GB Arbeitsspeicher für jede zweite Wiederherstellung; deaktiviere die automatische Rekonstruktion mit einem Tippen.", + "imageSend_title": "Bild senden", + "imageSend_cropNote": "Für 512 × 512 skaliert · Seitenverhältnis nicht erhalten", + "imageSend_originalSize": "Originaltext:\n\nThe quick brown fox jumps over the lazy dog.\n\nÜbersetzung:\n\nDer schnelle braune Fuchs springt über den faulen Hund.", + "imageSend_onAirSize": "On air", + "imageSend_quality": "Qualität", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Hoch", + "imageSend_packetsLabel": "Pakete", + "imageSend_airtimeLabel": "Sendezeit", + "imageSend_sizeLabel": "Nutzlast", + "imageSend_packetsCount": "{count} {count, plural, =1{Paket} other{Pakete}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Radioeinstellungen unbekannt", + "imageSend_radioUnknownBody": "Verbinden Sie das Gerät, damit die Sendezeit berechnet werden kann.", + "imageSend_longSendTitle": "Lange Übertragung", + "imageSend_longSendBody": "Dies hält den Kanal für etwa {duration}.", + "imageSend_floodNote": "Flood-Weiterleitung: Jeder Repeater im Bereich leitet jedes Paket weiter, wodurch der Kanal länger als dieser Zeitraum beschäftigt bleibt.", + "imageSend_parityTitle": "Wiederherstellungspaket", + "imageSend_paritySubtitle": "Ein zusätzliches Paket. Gruppen-Nachrichten werden nicht bestätigt, daher kann der Empfänger das Bild rekonstruieren, falls ein Paket verloren geht.", + "imageSend_send": "Senden", + "imageSend_cancel": "Stornieren", + "imageSend_encodeFailed": "Dieses Bild konnte nicht kodiert werden.", + "imageSend_codecDownloading": "Das Bildmodell wird noch heruntergeladen.", + "imageSend_codecUnavailable": "Bildversand ist auf diesem Gerät nicht verfügbar.", + "imageSend_codecDisabled": "Bildnachrichten sind in den Einstellungen deaktiviert.", + "imageSend_deviceUnsupported": "Dieses Radio kann keine Bildpakete senden. Verbinden Sie ein Gerät mit der Companion-Firmware-Version 13 oder neuer.", + "imageSend_directMessagesUnsupported": "Bilder werden als Gruppendaten übertragen, daher können sie nur an einen Kanal gesendet werden – nicht per Direktnachricht.", + "imageSend_tooLarge": "Dieses Bild wurde in mehr Pakete kodiert, als das Mesh-Format zulässt.", + "imageSend_sentConfirmation": "Bild gesendet als {count} {count, plural, =1{Paket} other{Pakete}}.", + "imageSend_sendFailed": "Das Bild konnte nicht gesendet werden: {error}", + "imageSend_sendingProgress": "Bildversand — Paket {sent} von {total}", + "receivedImage_senderPrefix": "Kritisch: Diese Platzhalter {prefix} beibehalten.", + "receivedImage_incoming": "{received} von {total} Paketen", + "receivedImage_queued": "Warten auf die Entschlüsselung", + "receivedImage_tapToDecode": "Tippen Sie, um zu entschlüsseln", + "receivedImage_decoding": "Rekonstruktion… ca. 1 s", + "receivedImage_incomplete": "Bild unvollständig — {received} von {total} Paketen eingetroffen", + "receivedImage_corrupt": "Das Bild konnte nicht rekonstruiert werden.", + "receivedImage_decoderMissing": "Bild empfangen — Bilddekodierung fehlgeschlagen", + "receivedImage_evicted": "Bild nicht mehr gespeichert", + "receivedImage_retry": "Versuchen Sie es erneut", + "receivedImage_decodeAgain": "Entschlüsseln Sie es erneut", + "receivedImage_openSettings": "Einrichten", + "receivedImage_tapToProcess": "Klicken Sie, um fortzufahren", + "receivedImage_awaiting": "{bytes} Bytes · {packets} {packets, plural, =1{Paket} other{Pakete}}", + "imageSend_secondsValue": "{seconds} s", + "imageSend_minutesSecondsValue": "{minutes} Min {seconds} Sek", + "channels_noFreeSlots": "Alle Kanal-Slots sind belegt", + "chat_longMessageRetryNote": "Über 158 Byte: wird höchstens {count} Mal gesendet", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "reaction_report": "Emoji-Reaktionen", + "repeater_bridgeNote": "Nur verfügbar bei Firmware, die mit einer Bridge (RS232 oder ESP-NOW) gebaut wurde.", + "repeater_cliHelpGetFloodMaxAdvert": "Zeigt die maximale Hop-Anzahl für Flood-Ankündigungen an.", + "repeater_cliHelpGetFloodMaxUnscoped": "Zeigt die maximale Hop-Anzahl für Flood-Pakete ohne Region-Scope an.", + "repeater_cliHelpGetRadioFemRxGain": "Zeigt, ob der RX-Gain des LoRa-Frontend-Moduls aktiviert ist.", + "repeater_cliHelpGetRadioFemTxGain": "Zeigt, ob der TX-Gain des LoRa-Frontend-Moduls aktiviert ist.", + "repeater_cliHelpRegionDef": "Definiert in einem Befehl eine Kette von Regionen: Jeder Name wird unter dem vorherigen hinzugefügt; \"name,parent\" fügt den Namen hinzu und setzt dann unter der angegebenen übergeordneten Region fort. Antwortet mit der Regionsliste.", + "repeater_cliHelpSetFloodMaxAdvert": "Legt die maximale Hop-Anzahl für die Weiterleitung von Flood-Ankündigungen fest (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Legt die maximale Hop-Anzahl für die Weiterleitung von Flood-Paketen ohne Region-Scope fest (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Schaltet den RX-Gain (LNA) des LoRa-Frontend-Moduls um. Boards ohne dieses Modul antworten mit \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Schaltet den TX-Gain (PA) des LoRa-Frontend-Moduls um. Boards ohne dieses Modul antworten mit \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Regions-Ladevorgang: Sende pro Zeile einen Regionsnamen, eingerückt mit Leerzeichen unter der übergeordneten Region (F nach dem Namen anhängen, um Flood zu erlauben). Zeilen erhalten keine Antwort. Sende eine Leerzeile zum Abschließen, dann \"region save\", um das Ergebnis zu speichern.", + "repeater_cliRegionLoadEnd": "(Ende des Regions-Ladevorgangs)", + "repeater_cliRegionLoadHint": "Regionszeile, oder leer zum Abschließen", + "repeater_frequencyInvalid": "Ungültige Frequenz (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Empfangsfehler", + "repeater_txPowerRangeHelper": "-9 bis 30 dBm", + "room_postsPushed": "Gesendete Beiträge", + "room_postsStored": "Beiträge", + "settings_publicKeyCopied": "Öffentlicher Schlüssel kopiert", + "settings_radioSettingsNotApplied": "Das Funkgerät hat diese Einstellungen nicht übernommen" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index bcbe3005..ef1e75de 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -30,10 +30,45 @@ "common_disable": "Disable", "common_undo": "Undo", "messageStatus_sent": "Sent", - "messageStatus_delivered": "Delivered", + "messageStatus_delivered": "Delivered. The contact confirmed they got it.", "messageStatus_pending": "Sending", "messageStatus_failed": "Failed to send", "messageStatus_repeated": "Heard repeated", + "messageStatus_failedChannel": "Your radio couldn't send this message.", + "messageStatus_resending": "Not heard through enough repeaters yet. Resent {resends} of {maxResends} times.", + "@messageStatus_resending": { + "placeholders": { + "resends": { + "type": "int" + }, + "maxResends": { + "type": "int" + } + } + }, + "messageStatus_hopsNotReached": "Sent, but only heard back through {hops} of {required} repeaters. It may still have gone further than your radio can hear.", + "@messageStatus_hopsNotReached": { + "placeholders": { + "hops": { + "type": "int" + }, + "required": { + "type": "int" + } + } + }, + "messageStatus_sentChannel": "Sent. Channels don't confirm delivery, so this only means your radio sent it.", + "messageStatus_sentDirect": "Sent. Waiting for the contact to confirm.", + "messageStatus_heardRepeatedCount": "Heard repeated {count, plural, =1{once} other{{count} times}}. Nearby repeaters passed it on.", + "@messageStatus_heardRepeatedCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "urlImage_enable": "Enable URL images", + "urlImage_possible": "Possible URL image; enable it in Settings.", "common_reboot": "Reboot", "common_loading": "Loading...", "common_notAvailable": "—", @@ -158,8 +193,14 @@ "settings_radioSettings": "Radio Settings", "settings_radioSettingsSubtitle": "Frequency, power, spreading factor", "settings_radioSettingsUpdated": "Radio settings updated", + "settings_radioSettingsNotApplied": "The radio did not apply these settings", "settings_regionSettings": "Regions", - "settings_regionSettingsSubtitle": "Manage stored regions", + "settings_regionSettingsSubtitle": "Limit channel floods to an area", + "settings_regionEmptyExplanation": "Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.", + "settings_regionFetchFromRepeaters": "Fetch from repeaters", + "settings_regionDefault": "Default region", + "settings_regionDefaultSubtitle": "Used by channels without their own region", + "settings_regionDefaultNone": "None", "settings_regionManagement_screenTitle": "Region Management", "settings_regionNameHint": "Enter region name", "settings_regionAddRegion": "Add region", @@ -199,14 +240,18 @@ "settings_privacySubtitle": "Control what information is shared.", "settings_privacySettingsDescription": "Choose what information your device shares with others.", "settings_denyAll": "Deny all", - "settings_allowByContact": "Allow by contact flags", + "settings_allowByContact": "Only contacts I allow", "settings_allowAll": "Allow all", - "settings_telemetryBaseMode": "Telemetry Base Mode", - "settings_telemetryLocationMode": "Telemetry Location Mode", - "settings_telemetryEnvironmentMode": "Telemetry Environment Mode", + "settings_telemetryBaseMode": "Who can request battery and status", + "settings_telemetryLocationMode": "Who can request my location", + "settings_telemetryEnvironmentMode": "Who can request sensor data", + "settings_telemetryPerContactHint": "To allow a contact, open their chat and choose Contact Settings from the menu.", "settings_advertLocation": "Advert Location", "settings_advertLocationSubtitle": "Include location in advert.", + "settings_autoZeroHopAdvertOnGpsUpdate": "Auto Zero-Hop Advert On GPS Update", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "App setting: when your GPS position changes, automatically advertise your new location to nearby nodes only (requires Advert Location).", "settings_multiAck": "Multi-ACKs", + "settings_multiAckSubtitle": "Send extra ACKs for better delivery; uses more airtime", "settings_telemetryModeUpdated": "Telemetry mode updated", "settings_actions": "Actions", "settings_deleteAllPaths": "Delete All Paths", @@ -244,21 +289,44 @@ "settings_infoStatus": "Status", "settings_infoBattery": "Battery", "settings_infoPublicKey": "Public Key", + "settings_publicKeyCopied": "Public key copied", "settings_infoContactsCount": "Contacts Count", "settings_infoChannelCount": "Channel Count", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", "settings_presets": "Presets", + "settings_presetCustom": "Custom", + "settings_radioMatchWarning": "All nodes you talk to must use the same frequency, bandwidth, SF and CR.", "settings_frequency": "Frequency (MHz)", - "settings_frequencyHelper": "300.0 - 2500.0", - "settings_frequencyInvalid": "Invalid frequency (300-2500 MHz)", + "settings_frequencyHelper": "150.0 - 2500.0", + "settings_frequencyInvalid": "Invalid frequency (150-2500 MHz)", "settings_bandwidth": "Bandwidth", "settings_spreadingFactor": "Spreading Factor", "settings_codingRate": "Coding Rate", "settings_txPower": "TX Power (dBm)", - "settings_txPowerHelper": "0 - 22", - "settings_txPowerInvalid": "Invalid TX power (0-22 dBm)", + "settings_txPowerRangeHelper": "{min} to {max} dBm", + "@settings_txPowerRangeHelper": { + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "settings_txPowerInvalid": "Invalid TX power", "settings_clientRepeat": "Off-Grid Repeat", + "settings_clientRepeatFrequencyNote": "Frequency set to {freq} MHz for off-grid repeat", + "@settings_clientRepeatFrequencyNote": { + "placeholders": { + "freq": { + "type": "String" + } + } + }, "settings_clientRepeatSubtitle": "Allow this device to repeat mesh packets for others", - "settings_clientRepeatFreqWarning": "Off-grid repeat requires 433, 869, or 918 MHz frequency", + "settings_clientRepeatFreqWarning": "Off-grid repeat requires 433, 869.495, or 918 MHz frequency", "settings_error": "Error: {message}", "@settings_error": { "placeholders": { @@ -290,8 +358,39 @@ "appSettings_languageBg": "Български", "appSettings_languageRu": "Русский", "appSettings_languageUk": "Українська", - "appSettings_enableMessageTracing": "Enable Message Tracing", - "appSettings_enableMessageTracingSubtitle": "Show detailed routing and timing metadata for messages", + "repeater_pathHashModeOption0": "1 byte", + "repeater_pathHashModeOption1": "2 bytes", + "repeater_pathHashModeOption2": "3 bytes", + "repeater_pathHashModeOption3": "4 bytes", + "settings_pathHashModeHelper": "Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.", + "settings_requiresFirmware": "Requires firmware {version} or newer", + "@settings_requiresFirmware": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "appSettings_channelMinHops": "Resend channel messages until they travel far enough", + "appSettings_channelMinHopsSubtitle": "If your message isn't heard coming back through enough repeaters, send it again. Uses more airtime.", + "appSettings_channelMinHopsCount": "Required hops: {count}", + "@appSettings_channelMinHopsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "appSettings_channelMinHopsRetries": "Resend up to {count, plural, =1{1 time} other{{count} times}}", + "@appSettings_channelMinHopsRetries": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "appSettings_enableMessageTracing": "Show full repeater path in messages", + "appSettings_enableMessageTracingSubtitle": "Also show repeat counts and trip times. Long-press a message and choose Path for full details.", "appSettings_notifications": "Notifications", "appSettings_enableNotifications": "Enable Notifications", "appSettings_enableNotificationsSubtitle": "Receive notifications for messages and adverts", @@ -300,6 +399,8 @@ "appSettings_notificationsDisabled": "Notifications disabled", "appSettings_messageNotifications": "Message Notifications", "appSettings_messageNotificationsSubtitle": "Show notification when receiving new messages", + "appSettings_batteryOptimization": "Background Activity", + "appSettings_batteryOptimizationSubtitle": "Set MeshCore Open to \"Don't optimize\" in battery settings so messages keep arriving in the background", "appSettings_channelMessageNotifications": "Channel Message Notifications", "appSettings_channelMessageNotificationsSubtitle": "Show notification when receiving channel messages", "appSettings_advertisementNotifications": "Advertisement Notifications", @@ -337,6 +438,7 @@ "appSettings_batteryNmc": "18650 NMC (3.0-4.2V)", "appSettings_batteryLifepo4": "LiFePO4 (2.6-3.65V)", "appSettings_batteryLipo": "LiPo (3.0-4.2V)", + "appSettings_batteryLipoHv": "LiPo HV (3.0-4.35V)", "appSettings_mapDisplay": "Map Display", "appSettings_showRepeaters": "Show Repeaters", "appSettings_showRepeatersSubtitle": "Display repeater nodes on the map", @@ -361,6 +463,19 @@ "appSettings_last6Hours": "Last 6 hours", "appSettings_last24Hours": "Last 24 hours", "appSettings_lastWeek": "Last week", + "appSettings_rasterTileSource": "Raster Tile Source", + "appSettings_stadiaEndpoint": "Stadia Endpoint", + "appSettings_stadiaApiKey": "Stadia API Key", + "appSettings_stadiaApiKeyRequired": "Required for Stadia Maps usage", + "appSettings_stadiaApiKeyConfigured": "Configured: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Enter your Stadia Maps API key. This app uses it for raster tile requests.", "appSettings_offlineMapCache": "Offline Map Cache", "appSettings_unitsTitle": "Units", "appSettings_unitsMetric": "Metric (m / km)", @@ -453,6 +568,26 @@ } } }, + "contacts_removeFromContacts": "Remove from contacts", + "contacts_removeFromContactsConfirm": "{contactName} will move to Discovered contacts. Chat history will be deleted.", + "@contacts_removeFromContactsConfirm": { + "placeholders": { + "contactName": { + "type": "String" + } + } + }, + "contacts_keepChatHistory": "Keep chat history", + "contacts_remove": "Remove", + "contacts_discoveredNearby": "Discovered nearby ({count})", + "@contacts_discoveredNearby": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "contacts_noContactsDiscoveredHint": "Nodes your radio hears but hasn't added yet are listed in Discovered contacts", "contacts_manageRepeater": "Manage Repeater", "contacts_manageRoom": "Manage Room Server", "contacts_roomLogin": "Room Server Login", @@ -546,6 +681,10 @@ } }, "channels_private": "Private", + "channels_hashtag": "Hashtag", + "channels_addSectionJoin": "Join existing", + "channels_addSectionCreate": "Create new", + "channels_dragToReorder": "Drag to reorder", "channels_editChannel": "Edit channel", "channels_muteChannel": "Mute channel", "channels_unmuteChannel": "Unmute channel", @@ -637,6 +776,7 @@ } }, "channels_publicChannelAdded": "Public channel added", + "channels_noFreeSlots": "All channel slots are in use", "channels_sortBy": "Sort by", "channels_sortManual": "Manual", "channels_sortAZ": "A-Z", @@ -666,6 +806,10 @@ "channels_regionNotSet": "Region: none", "channels_regionSelect_Title": "Select a region", "channels_clearRegion": "Clear region", + "channels_regionDefaultSuffix": "(default)", + "channels_regionSelectExplanation": "Flood messages on this channel will only be forwarded by repeaters in the selected region.", + "channels_regionEmpty": "No regions yet.", + "channels_manageRegions": "Manage regions", "chat_noMessages": "No messages yet", "chat_sendMessage": "Send message", "chat_sendMessageTo": "Send a message to {contactName}", @@ -718,10 +862,20 @@ } } }, + "chat_selectSendAction": "Select send action", "chat_sendGif": "Send GIF", + "chat_removeGif": "Remove GIF", + "chat_cancelReply": "Cancel reply", + "chat_sendImageLora": "Send low-res image over radio", + "chat_imagePickFailed": "Couldn't open that image", + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "chat_receivedGif": "Received a GIF", "chat_reply": "Reply", "chat_addReaction": "Add Reaction", "chat_me": "Me", + "reaction_report": "Emoji Reactions", "emojiCategorySmileys": "Smileys", "emojiCategoryGestures": "Gestures", "emojiCategoryHearts": "Hearts", @@ -894,6 +1048,7 @@ "chat_pathDeviceNotConfirmed": "Device not confirmed yet.", "chat_type": "Type", "chat_path": "Path", + "chat_viewPathOnMap": "View path on map", "chat_publicKey": "Public Key", "chat_compressOutgoingMessages": "Compress outgoing messages", "chat_floodForced": "Flood (forced)", @@ -919,6 +1074,8 @@ }, "chat_markAsUnread": "Mark as Unread", "chat_newMessages": "New messages", + "chat_today": "Today", + "chat_yesterday": "Yesterday", "chat_openLink": "Open Link?", "chat_openLinkConfirmation": "Do you want to open this link in your browser?", "chat_open": "Open", @@ -940,12 +1097,14 @@ "map_visible": "Visible", "map_hidden": "Hidden", "map_centerOnNode": "Center on node", + "map_centerOnMe": "Center on my location", "map_details": "Details", "map_noGps": "No GPS", "map_noResults": "No matching nodes", "map_lineOfSight": "Line of Sight", "map_losScreenTitle": "Line of Sight", "map_noNodesWithLocation": "No nodes with location data", + "map_noNodesLocationHint": "No nodes with a recent location. Widen the time filter, or set your own location in Settings.", "map_nodesNeedGps": "Nodes need to share their GPS coordinates\nto appear on the map", "map_nodesCount": "Nodes: {count}", "@map_nodesCount": { @@ -1011,6 +1170,9 @@ "map_markers": "Markers", "map_showSharedMarkers": "Show shared markers", "map_showGuessedLocations": "Show guessed node locations", + "map_clusterNodes": "Group nearby nodes", + "map_groupChip": "Group", + "map_clusterNodesSubtitle": "When zoomed out, show nearby nodes as one numbered circle", "map_showDiscoveryContacts": "Show Discovery Contacts", "map_guessedLocation": "Guessed location", "map_lastSeenTime": "Last Seen Time", @@ -1018,6 +1180,7 @@ "map_sharedAt": "Shared", "map_joinRoom": "Join Room", "map_manageRepeater": "Manage Repeater", + "map_manageServer": "Manage Server", "map_tapToAdd": "Tap on nodes to add them to the path.", "map_runTrace": "Run path trace", "map_runTraceWithReturnPath": "Return back on the same path.", @@ -1091,6 +1254,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1149,10 +1362,13 @@ "login_roomLogin": "Room Server Login", "login_password": "Password", "login_enterPassword": "Enter password", + "login_showPassword": "Show password", + "login_hidePassword": "Hide password", "login_savePassword": "Save password", "login_savePasswordSubtitle": "Password will be stored securely on this device", - "login_repeaterDescription": "Enter the repeater password for guest or admin access.", + "login_repeaterDescription": "The admin password unlocks settings and the CLI. A guest password (or blank) shows status only.", "login_roomDescription": "Enter the room password for guest or admin access.", + "login_advanced": "Advanced", "login_routing": "Routing", "login_routingMode": "Routing mode", "login_autoUseSavedPath": "Auto (use saved path)", @@ -1181,6 +1397,7 @@ "login_failedMessage": "Login failed. Either the password is incorrect or the repeater is unreachable.", "common_reload": "Reload", "common_clear": "Clear", + "common_clearSearch": "Clear search", "path_currentPathLabel": "Current path", "path_noRepeatersFound": "No repeaters or room servers found.", "repeater_management": "Repeater Management", @@ -1189,6 +1406,8 @@ "room_guest": "Room Server Information", "repeater_managementTools": "Management Tools", "repeater_guestTools": "Guest Tools", + "repeater_roleAdmin": "ADMIN", + "repeater_roleGuest": "GUEST", "repeater_status": "Status", "repeater_statusSubtitle": "View repeater status, stats, and neighbors", "repeater_telemetry": "Telemetry", @@ -1407,8 +1626,25 @@ "repeater_floodMaxHelper": "Maximum hops a flood packet may travel (0-64)", "repeater_advancedSettings": "Advanced", "repeater_advancedSettingsSubtitle": "Tuning knobs for experienced operators", - "repeater_pathHashMode": "Path hash mode", - "repeater_pathHashModeHelper": "Bytes used to encode this repeater's ID in flood path/loop-detect tags. 0=1 byte (256 IDs, up to 64 hops), 1=2 bytes (65K IDs, up to 32 hops), 2=3 bytes (16M IDs, up to 21 hops). v1.13 and older firmware drops multi-byte paths — only raise once your network is on v1.14+.", + "repeater_pathHashMode": "Node ID size in paths", + "repeater_pathHashModeHelper": "Size of this repeater's ID in the paths of adverts it sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Does not affect forwarding; v1.14+ repeaters forward all sizes, but older firmware drops packets with 2- or 3-byte IDs.", + "repeater_keySettings": "Change Identity Keys", + "repeater_keySettingsSubtitle": "Change the public/private keypair", + "repeater_prvKey": "Private key", + "repeater_prvKeyHelper": "A new private key for the repeater, a 128-character hex string.", + "repeater_generatePrvKey": "Generate a random keypair", + "repeater_stopGeneratingPrvKey": "Interrupt search for keypair", + "repeater_pubKey": "Public key", + "repeater_pubKeyHelper": "This is the public key that goes with the generated private key. You can't set this directly.", + "repeater_pubKeyPrefix": "Desired prefix", + "repeater_pubKeyPrefixHelper": "Find a public key that starts with these hex digits. Expected tries needed: {tries}.", + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, "repeater_txDelay": "Flood TX delay", "repeater_txDelayHelper": "Retransmit spacing for flood traffic, as a multiplier of the packet's airtime (0-2, default 0.5). Higher = fewer collisions but slower delivery.", "repeater_directTxDelay": "Direct TX delay", @@ -1466,6 +1702,9 @@ "repeater_refreshPacketForwarding": "Refresh Packet Forwarding", "repeater_refreshGuestAccess": "Refresh Guest Access", "repeater_refreshPrivacyMode": "Refresh Privacy Mode", + "repeater_refreshAll": "Refresh all", + "repeater_settingsNotLoaded": "Settings haven't been loaded from this repeater yet.", + "repeater_settingsLoadIncomplete": "Some settings could not be loaded. Use the refresh buttons to retry.", "repeater_refreshed": "{label} refreshed", "@repeater_refreshed": { "placeholders": { @@ -1566,6 +1805,25 @@ "repeater_cliHelpGpsAdvertSet": "Sets location advert configuration.", "repeater_commandsListTitle": "Commands List", "repeater_commandsListNote": "NOTE: for the various \"set ...\" commands, there is also a \"get ...\" command.", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_frequencyInvalid": "Invalid frequency (150-2500 MHz)", + "repeater_txPowerRangeHelper": "-9 to 30 dBm", + "repeater_recvErrors": "Receive Errors", + "room_postsStored": "Posts", + "room_postsPushed": "Posts Pushed", + "repeater_cliRegionLoadActive": "Region load mode: send one region name per line, indented with spaces under its parent (add F after the name to allow flood). Lines get no reply. Send an empty line to finish, then \"region save\" to keep the result.", + "repeater_cliRegionLoadHint": "Region line, or empty to finish", + "repeater_cliRegionLoadEnd": "(end of region load)", + "repeater_cliHelpRegionDef": "Defines a chain of regions in one command: each name is added under the previous one; \"name,parent\" adds the name, then continues under the given parent. Replies with the region list.", + "repeater_cliHelpSetFloodMaxUnscoped": "Sets the maximum hop count for forwarding flood packets that have no region scope (0-64).", + "repeater_cliHelpSetFloodMaxAdvert": "Sets the maximum hop count for forwarding flood adverts (0-64).", + "repeater_cliHelpGetFloodMaxUnscoped": "Shows the maximum hop count for unscoped flood packets.", + "repeater_cliHelpGetFloodMaxAdvert": "Shows the maximum hop count for flood adverts.", + "repeater_cliHelpSetRadioFemRxGain": "Toggles the LoRa front-end module's RX gain (LNA). Boards without one reply \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Toggles the LoRa front-end module's TX gain (PA). Boards without one reply \"Error: unsupported\".", + "repeater_cliHelpGetRadioFemRxGain": "Shows whether the LoRa front-end module's RX gain is on.", + "repeater_cliHelpGetRadioFemTxGain": "Shows whether the LoRa front-end module's TX gain is on.", + "repeater_bridgeNote": "Only available on firmware built with a bridge (RS232 or ESP-NOW).", "repeater_general": "General", "repeater_settingsCategory": "Settings", "repeater_bridge": "Bridge", @@ -1589,10 +1847,10 @@ "repeater_cliHelpPowersavingOnOff": "Enables or disables powersaving mode (where supported).", "repeater_cliHelpErase": "(Serial only) Formats the device file system. Wipes all settings and contacts.", "repeater_cliHelpSetDutyCycle": "Sets the maximum allowed transmit duty cycle as a percentage (1-100). Internally adjusts the airtime factor.", - "repeater_cliHelpSetPrvKey": "(Serial only) Replaces the device identity private key. Reboot required to apply. Generates a new public key.", + "repeater_cliHelpSetPrvKey": "Replaces the device identity private key. Reboot required to apply. Generates a new public key.", "repeater_cliHelpSetRadioRxGain": "(SX126x only) Toggles boosted RX gain for improved sensitivity at higher current draw.", "repeater_cliHelpSetOwnerInfo": "Sets the owner contact info string included in adverts. Use '|' for newlines.", - "repeater_cliHelpSetPathHashMode": "Sets the path-hash mode. 0 = legacy, 1 = standard, 2 = strict. Affects how routing paths are matched.", + "repeater_cliHelpSetPathHashMode": "Sets the node ID size used in this repeater's adverts: 0 = 1 byte (up to 64 hops), 1 = 2 bytes (up to 32 hops), 2 = 3 bytes (up to 21 hops). 3 is reserved. Does not affect which sizes are forwarded. Requires firmware v1.14+.", "repeater_cliHelpSetLoopDetect": "Sets the routing loop-detection sensitivity: off, minimal, moderate, or strict.", "repeater_cliHelpSetFreq": "(Serial only) Quickly sets just the frequency. Reboot required. Prefer \"set radio\" for full radio params.", "repeater_cliHelpSetBridgeChannel": "(ESPNow bridge only) Sets the WiFi channel (1-14) used by the bridge.", @@ -1621,7 +1879,7 @@ "repeater_cliHelpGetDirectTxDelay": "Shows the direct-mode txdelay factor.", "repeater_cliHelpGetFloodMax": "Shows the maximum flood hop count.", "repeater_cliHelpGetOwnerInfo": "Shows the owner contact info string.", - "repeater_cliHelpGetPathHashMode": "Shows the path-hash mode (0/1/2).", + "repeater_cliHelpGetPathHashMode": "Shows the node ID size mode used in adverts (0 = 1 byte, 1 = 2 bytes, 2 = 3 bytes).", "repeater_cliHelpGetLoopDetect": "Shows the loop-detection sensitivity.", "repeater_cliHelpGetAcl": "(Serial only) Lists the access-control entries on a repeater.", "repeater_cliHelpGetBridgeEnabled": "Shows whether the bridge is enabled.", @@ -2302,6 +2560,11 @@ "contacts_floodAdvert": "Flood Advert", "contacts_copyAdvertToClipboard": "Copy Advert to Clipboard", "contacts_addContactFromClipboard": "Add Contact from Clipboard", + "contacts_scanQrCode": "Scan QR Code", + "contacts_scanQrInstructions": "Point the camera at a MeshCore contact QR code", + "contacts_qrFromGallery": "Scan QR from Gallery", + "contacts_noQrCodeFound": "No QR code found in the selected image.", + "contacts_qrGalleryFailed": "Could not open the gallery.", "contacts_ShareContact": "Copy contact to Clipboard", "contacts_ShareContactZeroHop": "Share contact by advert", "contacts_zeroHopContactAdvertSent": "Sent contact by advert.", @@ -2359,6 +2622,7 @@ "settings_gpxExportShareSubject": "meshcore-open GPX map data export", "snrIndicator_nearByRepeaters": "Nearby Repeaters", "snrIndicator_lastSeen": "Last seen", + "snrIndicator_nearByRepeatersDescription": "Repeaters your radio heard directly, most recently heard first.", "contactsSettings_title": "Contacts settings", "contactsSettings_autoAddTitle": "Automatic Discovery", "contactsSettings_otherTitle": "Other contact related settings", @@ -2389,6 +2653,8 @@ "appSettings_languageKo": "Korean", "radioStats_tooltip": "Radio & mesh stats", "radioStats_screenTitle": "Radio stats", + "radioStats_sectionSignal": "Signal", + "radioStats_sectionAirtime": "Airtime", "radioStats_notConnected": "Connect to a device to view radio statistics.", "radioStats_firmwareTooOld": "Radio statistics require companion firmware v8 or newer.", "radioStats_waiting": "Waiting for data…", @@ -2445,6 +2711,17 @@ "radioStats_settingsTile": "Radio stats", "radioStats_settingsSubtitle": "Noise floor, RSSI, SNR, and airtime", "translation_title": "Translation", + "imageMessages_enableTitle": "Enable image messages", + "imageMessages_enableSubtitle": "Send images over the mesh. Requires a one-time image model download.", + "imageMessages_modelSectionTitle": "Image model", + "imageMessages_downloadModel": "Download", + "imageMessages_cancelDownload": "Cancel", + "imageMessages_removeModel": "Remove model", + "imageMessages_modelReady": "Ready", + "imageMessages_modelNotPublished": "Not published yet — this build cannot download it.", + "imageMessages_downloadFailed": "The image model could not be downloaded.", + "imageMessages_autoProcessTitle": "Process images automatically", + "imageMessages_autoProcessSubtitle": "Reconstruct every image as soon as it arrives. Uses about 2 GB of memory for a second each time; leave off to reconstruct with a tap instead.", "translation_enableTitle": "Enable translation", "translation_enableSubtitle": "Translate incoming messages and allow pre-send translation.", "translation_composerTitle": "Translate before sending", @@ -2626,5 +2903,196 @@ "pathMap_expandPanel": "Expand panel", "pathMap_noLocation": "No location", "pathMap_followPacket": "Lock view to packet", - "pathMap_unfollowPacket": "Unlock view from packet" + "pathMap_unfollowPacket": "Unlock view from packet", + "imageSend_title": "Send image", + "imageSend_cropNote": "Resized to 512 × 512 · aspect ratio not preserved", + "imageSend_lossyNote": "Compressed to about {bytes} bytes. The receiver's model reconstructs it, so details will differ.", + "@imageSend_lossyNote": { + "placeholders": { + "bytes": { + "type": "int" + } + } + }, + "imageSend_viewOriginal": "Original", + "imageSend_viewReconstruction": "What recipients see", + "imageSend_reconstructionUnavailable": "This device can't preview the reconstruction.", + "imageSend_modelNotDownloaded": "The image model isn't downloaded yet. Download it in Settings to send images.", + "imageSend_originalSize": "Original", + "imageSend_onAirSize": "On air", + "imageSend_quality": "Quality", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "High", + "imageSend_packetsLabel": "Packets", + "imageSend_airtimeLabel": "Time on air", + "imageSend_sizeLabel": "Payload", + "imageSend_packetsCount": "{count} {count, plural, =1{packet} other{packets}}", + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "imageSend_range": "{min}–{max}", + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Radio settings unknown", + "imageSend_radioUnknownBody": "Connect to a device so the time on air can be calculated.", + "imageSend_longSendTitle": "Long transmission", + "imageSend_longSendBody": "This will hold the channel for about {duration}.", + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "imageSend_floodNote": "Flood routing: every repeater in range retransmits each packet, so the channel stays busy longer than this.", + "imageSend_parityTitle": "Add recovery packet", + "imageSend_paritySubtitle": "One extra packet. Group messages are not acknowledged, so this lets the receiver rebuild the image if a single packet is lost.", + "imageSend_send": "Send", + "imageSend_cancel": "Cancel", + "imageSend_encodeFailed": "This image could not be encoded.", + "imageSend_codecDownloading": "The image model is still downloading.", + "imageSend_codecUnavailable": "Image sending is not available on this device.", + "imageSend_codecDisabled": "Image messages are turned off in settings.", + "imageSend_deviceUnsupported": "This radio cannot send image packets. Connect a device running companion firmware 13 or newer.", + "imageSend_directMessagesUnsupported": "Images travel as group data, so they can only be sent to a channel — not in a direct message.", + "imageSend_tooLarge": "That image encoded to more packets than the mesh format allows.", + "imageSend_sentConfirmation": "Image sent as {count} {count, plural, =1{packet} other{packets}}.", + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "imageSend_sendFailed": "The image could not be sent: {error}", + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "imageSend_sendingProgress": "Sending image — packet {sent} of {total}", + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "receivedImage_senderPrefix": "Node {prefix}", + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "receivedImage_incoming": "{received} of {total} packets", + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "receivedImage_queued": "Waiting to decode", + "receivedImage_tapToDecode": "Tap to decode", + "receivedImage_decoding": "Reconstructing… about 1 s", + "receivedImage_incomplete": "Image incomplete — {received} of {total} packets arrived", + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "receivedImage_corrupt": "Image could not be reconstructed", + "receivedImage_decoderMissing": "Image received — image decoding is off", + "receivedImage_evicted": "Image no longer stored", + "receivedImage_retry": "Try again", + "receivedImage_decodeAgain": "Decode again", + "receivedImage_openSettings": "Set up", + "receivedImage_tapToProcess": "Tap to process", + "receivedImage_save": "Save image", + "receivedImage_shareCaption": "AI-reconstructed from {bytes} bytes; fine detail is generated, not transmitted.", + "@receivedImage_shareCaption": { + "placeholders": { + "bytes": { + "type": "int" + } + } + }, + "receivedImage_packetInfo": "Packet info", + "receivedImage_parityRecovered": "One packet was rebuilt from the recovery packet.", + "receivedImage_decodeTime": "Reconstructed in {ms} ms", + "@receivedImage_decodeTime": { + "placeholders": { + "ms": { + "type": "int" + } + } + }, + "receivedImage_saveFailed": "Couldn't save the image", + "receivedImage_awaiting": "{bytes} bytes · {packets} {packets, plural, =1{packet} other{packets}}", + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "imageSend_secondsValue": "{seconds} s", + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "imageSend_minutesSecondsValue": "{minutes} m {seconds} s", + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "chat_longMessageRetryNote": "Over 158 bytes: sent at most {count} times", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 303f8cb5..2ff7f68c 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Latitud o longitud inválidos.", "settings_latitude": "Latitud", "settings_longitude": "Longitud", + "settings_autoZeroHopAdvertOnGpsUpdate": "Anuncio de cero saltos automático al actualizar GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Cuando cambie la ubicación GPS, enviar un anuncio de cero saltos (requiere ubicación en anuncio).", "settings_privacyMode": "Modo de privacidad", "settings_privacyModeSubtitle": "Ocultar nombre/ubicación en anuncios", "settings_privacyModeToggle": "Activar el modo de privacidad para ocultar tu nombre y ubicación en los anuncios.", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Últimas 6 horas", "appSettings_last24Hours": "Últimas 24 horas", "appSettings_lastWeek": "La semana pasada", + "appSettings_rasterTileSource": "Fuente de teselas ráster", + "appSettings_stadiaEndpoint": "Punto de acceso de Stadia", + "appSettings_stadiaApiKey": "Clave API de Stadia", + "appSettings_stadiaApiKeyRequired": "Obligatorio para usar Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Configurado: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Introduce tu clave API de Stadia Maps. La aplicación la usa para solicitar teselas ráster.", "appSettings_offlineMapCache": "Caché de mapa sin conexión", "appSettings_noAreaSelected": "No se ha seleccionado ningún área", "appSettings_areaSelectedZoom": "Área seleccionada (zoom {minZoom}-{maxZoom})", @@ -492,6 +507,7 @@ } } }, + "chat_selectSendAction": "Seleccionar acción de envío", "chat_sendGif": "Enviar GIF", "chat_reply": "Responder", "chat_addReaction": "Añadir Reacción", @@ -791,6 +807,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1106,7 +1172,7 @@ "repeater_refreshMultiAcks": "Actualizar ACK múltiples", "repeater_networkHealth": "Salud de la red", "repeater_loopDetect": "Detección de bucles", - "repeater_loopDetectHelper": "Crea paquetes de \"flujo\" que parezcan bucles de enrutamiento.", + "repeater_loopDetectHelper": "Descarta los paquetes de inundación que parezcan bucles de enrutamiento", "repeater_loopDetectOff": "Desactivado", "repeater_loopDetectMinimal": "Mínimo", "repeater_loopDetectModerate": "Moderado", @@ -1229,7 +1295,7 @@ "repeater_cliQuickVersion": "Versión", "repeater_cliQuickAdvertise": "Anunciar", "repeater_cliQuickClock": "Reloj", - "repeater_cliHelpAdvert": "Envía un paquete de publicidad", + "repeater_cliHelpAdvert": "Envía un paquete de anuncio", "repeater_cliHelpReboot": "Reinicia el dispositivo. (ten en cuenta, es normal que aparezca 'Timeout')", "repeater_cliHelpClock": "Muestra la hora actual según el reloj del dispositivo.", "repeater_cliHelpPassword": "Establece una nueva contraseña de administrador para el dispositivo.", @@ -1247,8 +1313,8 @@ "repeater_cliHelpSetFloodAdvertInterval": "Establece el intervalo del temporizador en horas para enviar un paquete de anuncio masivo. Establecer en 0 para desactivarlo.", "repeater_cliHelpSetGuestPassword": "Establece/actualiza la contraseña del invitado. (para repetidores, los inicios de sesión de invitado pueden enviar la solicitud \"Obtener Estadísticas\")", "repeater_cliHelpSetName": "Establece el nombre del anuncio.", - "repeater_cliHelpSetLat": "Establece la latitud del mapa de publicidad. (grados decimales)", - "repeater_cliHelpSetLon": "Establece la longitud del mapa de la publicidad. (grados decimales)", + "repeater_cliHelpSetLat": "Establece la latitud del mapa del anuncio. (grados decimales)", + "repeater_cliHelpSetLon": "Establece la longitud del mapa del anuncio. (grados decimales)", "repeater_cliHelpSetRadio": "Establece parámetros de radio completamente nuevos y los guarda en las preferencias. Requiere un comando \"reboot\" para aplicarlos.", "repeater_cliHelpSetRxDelay": "Configura (experimental) la base para aplicar un ligero retraso a los paquetes recibidos, según la fuerza de la señal/puntuación. Establece en 0 para desactivar.", "repeater_cliHelpSetTxDelay": "Establece un factor multiplicado con el tiempo de aire para un paquete de modo de inundación y con un sistema de ranura aleatorio, para retrasar su reenvío (para disminuir la probabilidad de colisiones).", @@ -1272,7 +1338,7 @@ "repeater_cliHelpRegionGet": "Busca la región con el prefijo de nombre dado (o \"\" para el ámbito global). Responde con \"-> nombre-región (nombre-padre) 'F'\"", "repeater_cliHelpRegionPut": "Agrega o actualiza una definición de región con el nombre dado.", "repeater_cliHelpRegionRemove": "Elimina una definición de región con el nombre dado. (debe coincidir exactamente y no tener regiones hijas)", - "repeater_cliHelpRegionAllowf": "Establece el permiso de 'F'lujo para la región dada. ('' para el ámbito global/legado)", + "repeater_cliHelpRegionAllowf": "Establece el permiso de 'F'lood para la región dada. ('' para el ámbito global/legado)", "repeater_cliHelpRegionDenyf": "Elimina el permiso de 'F'lood para la región especificada. (NOTA: en esta etapa NO se recomienda utilizarlo en el ámbito global/legado!!)", "repeater_cliHelpRegionHome": "Responde con la región 'home' actual. (Aún no se ha aplicado en ninguna parte, reservado para el futuro).", "repeater_cliHelpRegionHomeSet": "Establece la región 'hogar'.", @@ -1281,8 +1347,8 @@ "repeater_cliHelpGpsOnOff": "Activa o desactiva el modo GPS.", "repeater_cliHelpGpsSync": "Sincroniza la hora del nodo con el reloj GPS.", "repeater_cliHelpGpsSetLoc": "Establece la posición del nodo a las coordenadas GPS y guarda las preferencias.", - "repeater_cliHelpGpsAdvert": "Da la configuración de la publicidad del nodo de ubicación:\n- ninguno: no incluir la ubicación en las publicidad\n- compartir: compartir la ubicación GPS (del SensorManager)\n- preferencias: publicidad la ubicación almacenada en preferencias", - "repeater_cliHelpGpsAdvertSet": "Configura la configuración de la publicidad de la ubicación.", + "repeater_cliHelpGpsAdvert": "Da la configuración de anuncio de ubicación del nodo:\n- ninguno: no incluir la ubicación en los anuncios\n- compartir: compartir la ubicación GPS (del SensorManager)\n- preferencias: anunciar la ubicación almacenada en preferencias", + "repeater_cliHelpGpsAdvertSet": "Configura la configuración de anuncio de la ubicación.", "repeater_commandsListTitle": "Lista de comandos", "repeater_commandsListNote": "NOTA: para los diversos comandos \"set...\", también existe un comando \"get...\".", "repeater_general": "General", @@ -2360,8 +2426,8 @@ "repeater_cliHelpGetAgcResetInterval": "Muestra el intervalo de reinicio del AGC en segundos.", "repeater_cliHelpGetMultiAcks": "Indica si el modo de confirmación doble está activado (1) o desactivado (0).", "repeater_cliHelpGetAllowReadOnly": "Indica si se permite el acceso de solo lectura para los usuarios invitados.", - "repeater_cliHelpGetAdvertInterval": "Muestra el intervalo de publicidad local en minutos.", - "repeater_cliHelpGetFloodAdvertInterval": "Muestra el intervalo de publicidad para la emisión de la señal de inundación, expresado en horas.", + "repeater_cliHelpGetAdvertInterval": "Muestra el intervalo de anuncio local en minutos.", + "repeater_cliHelpGetFloodAdvertInterval": "Muestra el intervalo de anuncio por inundación, en horas.", "repeater_cliHelpGetGuestPassword": "Muestra la contraseña de invitado configurada.", "repeater_cliHelpGetLat": "Muestra la latitud configurada.", "repeater_cliHelpGetLon": "Muestra la longitud configurada.", @@ -2390,8 +2456,8 @@ "repeater_cliHelpSensorList": "Muestra todas las configuraciones de sensores personalizadas, paginadas a partir de un índice de inicio opcional.", "repeater_cliHelpRegionDefault": "Muestra el ámbito predeterminado actual.", "repeater_cliHelpRegionDefaultSet": "Establece el ámbito regional predeterminado. Utilice \"\" para restablecer a la configuración predeterminada.", - "repeater_cliHelpRegionListAllowed": "Enumera las regiones que permiten el paso de vehículos debido a inundaciones.", - "repeater_cliHelpRegionListDenied": "Enumera las regiones que prohíben el tráfico debido a las inundaciones.", + "repeater_cliHelpRegionListAllowed": "Enumera las regiones que permiten el tráfico por inundación.", + "repeater_cliHelpRegionListDenied": "Enumera las regiones que prohíben el tráfico por inundación.", "repeater_cliHelpStatsPackets": "(Solo para series) Muestra estadísticas a nivel de paquetes.", "repeater_cliHelpStatsRadio": "(Solo para transmisiones en serie) Muestra estadísticas de radio.", "repeater_cliHelpStatsCore": "(Solo para series) Muestra estadísticas clave del firmware.", @@ -2674,5 +2740,260 @@ "pathMap_noLocation": "Sin ubicación", "pathMap_followPacket": "Seguir paquete", "pathMap_unfollowPacket": "Dejar de seguir el paquete", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regiones", + "settings_regionSettingsSubtitle": "Gestionar regiones almacenadas", + "settings_regionManagement_screenTitle": "Gestión de Regiones", + "settings_regionNameHint": "Nombre de la región", + "settings_regionAddRegion": "Añadir región", + "settings_regionFetchRegions": "Obtener regiones de repetidores", + "settings_regionFetchRegionsFail": "No se encontraron regiones", + "settings_regionFetchRegionsAlreadyExists": "Esta región ya ha sido agregada", + "settings_regionName": "Nombre de la Región", + "settings_regionDeleted": "Región eliminada", + "settings_deleteRegion": "Eliminar Región", + "settings_deleteRegionConfirm": "¿Eliminar \"{region}\" de la lista de regiones?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 bytes", + "repeater_pathHashModeOption2": "2 - 3 bytes", + "repeater_pathHashModeOption3": "3 - 4 bytes", + "appSettings_batteryLipoHv": "LiPo HV (3.0-4.35V)", + "channels_regionSetTo": "Región: {region}", + "channels_regionNotSet": "Región: ninguna", + "channels_regionSelect_Title": "Seleccione una región", + "channels_clearRegion": "Zona despejada", + "chat_sendImageLora": "Enviar imagen mediante MeshCore", + "chat_imagePickFailed": "No pude abrir esa imagen", + "chat_receivedGif": "Recibido un GIF", + "repeater_keySettings": "Cambiar Claves de Identidad", + "repeater_keySettingsSubtitle": "Cambiar la pareja de claves pública/privada", + "repeater_prvKey": "Clave privada", + "repeater_prvKeyHelper": "Una nueva clave privada para el repetidor, una cadena hexadecimal de 128 caracteres.", + "repeater_generatePrvKey": "Genera un par de claves aleatorias", + "repeater_stopGeneratingPrvKey": "Interrumpir la búsqueda de par de claves", + "repeater_pubKey": "Clave pública", + "repeater_pubKeyHelper": "Esta es la clave pública que corresponde a la clave privada generada. No se puede establecer directamente.", + "repeater_pubKeyPrefix": "Prefijo deseado", + "repeater_pubKeyPrefixHelper": "Encuentre una clave pública que comience con estos dígitos hexadecimales. Se esperan {tries} intentos.", + "imageMessages_enableTitle": "Mensajes de imagen", + "imageMessages_enableSubtitle": "Enviar imágenes a través de la malla. Requiere la descarga de un modelo de imagen único.", + "imageMessages_modelSectionTitle": "Modelo de imagen", + "imageMessages_downloadModel": "Descargar", + "imageMessages_cancelDownload": "Cancelar", + "imageMessages_removeModel": "Eliminar modelo", + "imageMessages_modelReady": "Listo", + "imageMessages_modelNotPublished": "Aún no publicado — esta versión no puede descargarlo.", + "imageMessages_downloadFailed": "El modelo de imagen no pudo ser descargado.", + "imageMessages_autoProcessTitle": "Procesar imágenes automáticamente", + "imageMessages_autoProcessSubtitle": "Reconstruya cada imagen tan pronto como llegue. Utiliza aproximadamente 2 GB de memoria durante un segundo cada vez; desactívelo para reconstruir con un toque.", + "imageSend_title": "Enviar imagen", + "imageSend_cropNote": "Redimensionado a 512 × 512 · la relación de aspecto no se conservó", + "imageSend_originalSize": "Texto original", + "imageSend_onAirSize": "En emisión", + "imageSend_quality": "Calidad", + "imageSend_qualityStandard": "Estándar", + "imageSend_qualityHigh": "Alto", + "imageSend_packetsLabel": "Paquetes", + "imageSend_airtimeLabel": "Tiempo en pantalla", + "imageSend_sizeLabel": "Carga útil", + "imageSend_packetsCount": "{count} {count, plural, =1{paquete} other{paquetes}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Configuración de radio desconocida", + "imageSend_radioUnknownBody": "Conéctese a un dispositivo para que se pueda calcular la hora de transmisión.", + "imageSend_longSendTitle": "Larga transmisión", + "imageSend_longSendBody": "Esto mantendrá el canal durante aproximadamente {duration}.", + "imageSend_floodNote": "Enrutamiento de inundación: cada repetidor dentro del rango retransmite cada paquete, por lo que el canal permanece ocupado durante más tiempo que esto.", + "imageSend_parityTitle": "Paquete de recuperación", + "imageSend_paritySubtitle": "Un paquete adicional. Los mensajes grupales no son reconocidos, por lo que esto permite al receptor reconstruir la imagen si se pierde un solo paquete.", + "imageSend_send": "Enviar", + "imageSend_cancel": "Cancelar", + "imageSend_encodeFailed": "Esta imagen no pudo ser codificada.", + "imageSend_codecDownloading": "El modelo de imagen todavía se está descargando.", + "imageSend_codecUnavailable": "El envío de imágenes no está disponible en este dispositivo.", + "imageSend_codecDisabled": "Los mensajes de imagen están desactivados en la configuración.", + "imageSend_deviceUnsupported": "Esta radio no puede enviar paquetes de imagen. Conecte un dispositivo con el firmware Companion versión 13 o superior.", + "imageSend_directMessagesUnsupported": "Las imágenes se transmiten como datos grupales, por lo que solo se pueden enviar a un canal, no mediante mensajes directos.", + "imageSend_tooLarge": "Esa imagen se codificó en más paquetes de los que permite el formato de malla.", + "imageSend_sentConfirmation": "Imagen enviada como {count} {count, plural, =1{paquete} other{paquetes}}.", + "imageSend_sendFailed": "La imagen no pudo ser enviada: {error}", + "imageSend_sendingProgress": "Envío de imagen — paquete {sent} de {total}", + "receivedImage_senderPrefix": "Nodo {prefix}", + "receivedImage_incoming": "{received} de {total} paquetes", + "receivedImage_queued": "Esperando descifrar", + "receivedImage_tapToDecode": "Toque para decodificar", + "receivedImage_decoding": "Reconstruyendo… aproximadamente 1 segundo", + "receivedImage_incomplete": "Imagen incompleta — {received} de {total} paquetes llegados", + "receivedImage_corrupt": "La imagen no pudo ser reconstruida", + "receivedImage_decoderMissing": "Imagen recibida — la decodificación de la imagen no funciona", + "receivedImage_evicted": "Imagen ya no almacenada", + "receivedImage_retry": "Inténtalo de nuevo", + "receivedImage_decodeAgain": "Decodificar de nuevo", + "receivedImage_openSettings": "Configurar", + "receivedImage_tapToProcess": "Toque para procesar", + "receivedImage_awaiting": "{bytes} bytes · {packets} {packets, plural, =1{paquete} other{paquetes}}", + "imageSend_secondsValue": "{seconds} segundos", + "imageSend_minutesSecondsValue": "{minutes} min {seconds} s", + "channels_noFreeSlots": "Todos los espacios de canal están en uso", + "chat_longMessageRetryNote": "Más de 158 bytes: se envía como máximo {count} veces", + "reaction_report": "Reacciones con Emoji", + "repeater_bridgeNote": "Solo disponible en firmware compilado con un puente (RS232 o ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Muestra el número máximo de saltos para los anuncios por inundación.", + "repeater_cliHelpGetFloodMaxUnscoped": "Muestra el número máximo de saltos para los paquetes de inundación sin ámbito.", + "repeater_cliHelpGetRadioFemRxGain": "Muestra si la ganancia RX del módulo frontal de LoRa está activada.", + "repeater_cliHelpGetRadioFemTxGain": "Muestra si la ganancia TX del módulo frontal de LoRa está activada.", + "repeater_cliHelpRegionDef": "Define una cadena de regiones en un solo comando: cada nombre se añade bajo el anterior; \"name,parent\" añade el nombre y continúa bajo el padre indicado. Responde con la lista de regiones.", + "repeater_cliHelpSetFloodMaxAdvert": "Establece el número máximo de saltos para reenviar anuncios por inundación (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Establece el número máximo de saltos para reenviar paquetes de inundación que no tienen ámbito regional (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Activa o desactiva la ganancia RX (LNA) del módulo frontal de LoRa. Las placas que no lo tengan responden \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Activa o desactiva la ganancia TX (PA) del módulo frontal de LoRa. Las placas que no lo tengan responden \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Modo de carga de regiones: envíe un nombre de región por línea, sangrado con espacios bajo su región padre (añada F después del nombre para permitir inundación). Las líneas no reciben respuesta. Envíe una línea vacía para terminar y luego \"region save\" para guardar el resultado.", + "repeater_cliRegionLoadEnd": "(fin de la carga de regiones)", + "repeater_cliRegionLoadHint": "Línea de región, o vacía para terminar", + "repeater_frequencyInvalid": "Frecuencia inválida (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Errores de Recepción", + "repeater_txPowerRangeHelper": "-9 a 30 dBm", + "room_postsPushed": "Publicaciones Enviadas", + "room_postsStored": "Publicaciones", + "settings_publicKeyCopied": "Clave pública copiada", + "settings_radioSettingsNotApplied": "La radio no aplicó esta configuración", + "urlImage_enable": "Habilitar imágenes de URL", + "urlImage_possible": "Posible imagen de URL; actívala en Configuración.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 2c90f639..053e0be7 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Latitude ou longitude invalide.", "settings_latitude": "Latitude", "settings_longitude": "Longitude", + "settings_autoZeroHopAdvertOnGpsUpdate": "Annonce zéro saut automatique lors de la mise à jour GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Lorsque la position GPS change, envoyer une annonce zéro saut (nécessite la position dans l'annonce).", "settings_privacyMode": "Mode de confidentialité", "settings_privacyModeSubtitle": "Masquer le nom et la localisation dans les annonces", "settings_privacyModeToggle": "Activez le mode confidentialité pour masquer votre nom et votre localisation dans les annonces.", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Dernières 6 heures", "appSettings_last24Hours": "Dernières 24 heures", "appSettings_lastWeek": "La semaine dernière", + "appSettings_rasterTileSource": "Source de tuiles raster", + "appSettings_stadiaEndpoint": "Point de terminaison Stadia", + "appSettings_stadiaApiKey": "Clé API Stadia", + "appSettings_stadiaApiKeyRequired": "Requis pour l’utilisation de Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Configuré : {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Entrez votre clé API Stadia Maps. Cette application l’utilise pour les requêtes de tuiles raster.", "appSettings_offlineMapCache": "Cache de carte hors ligne", "appSettings_noAreaSelected": "Aucune zone sélectionnée", "appSettings_areaSelectedZoom": "Zone sélectionnée (zoom {minZoom}-{maxZoom})", @@ -492,6 +507,7 @@ } } }, + "chat_selectSendAction": "Sélectionner une action d’envoi", "chat_sendGif": "Envoyer un GIF", "chat_reply": "Répondre", "chat_addReaction": "Ajouter une réaction", @@ -791,6 +807,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, O {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1239,7 +1305,7 @@ "repeater_cliHelpSetTx": "Définit la puissance de transmission LoRa en dBm (réinitialisation requise pour appliquer).", "repeater_cliHelpSetRepeat": "Active ou désactive le rôle du répéteur pour ce nœud.", "repeater_cliHelpSetAllowReadOnly": "(Room server) Si \"activé\", alors un mot de passe vide permettra la connexion, mais ne permettra pas de publier dans la pièce. (lecture seule uniquement)", - "repeater_cliHelpSetFloodMax": "Définit le nombre maximal de sauts pour les paquets de balayage entrants (si >= max, le paquet n'est pas acheminé).", + "repeater_cliHelpSetFloodMax": "Définit le nombre maximal de sauts pour les paquets flood entrants (si >= max, le paquet n'est pas acheminé).", "repeater_cliHelpSetIntThresh": "Définit le seuil d'interférence (en dB). La valeur par défaut est de 14. Définir sur 0 désactive la détection des interférences de canal.", "repeater_cliHelpSetAgcResetInterval": "Définit l'intervalle pour réinitialiser le contrôleur de gain automatique. Mettez à 0 pour désactiver.", "repeater_cliHelpSetMultiAcks": "Active ou désactive la fonctionnalité « double ACKs ».", @@ -1272,7 +1338,7 @@ "repeater_cliHelpRegionGet": "Recherche la région avec le préfixe de nom donné (ou \"\" pour l'étendue globale). Répond avec \"-> nom-de-région (nom-parent) 'F'\"", "repeater_cliHelpRegionPut": "Ajoute ou met à jour une définition de région avec le nom donné.", "repeater_cliHelpRegionRemove": "Supprime une définition de région avec le nom donné.", - "repeater_cliHelpRegionAllowf": "Définit les autorisations de \"Flot\" pour la région donnée. ('' pour la portée globale/héritée)", + "repeater_cliHelpRegionAllowf": "Définit les autorisations de 'F'lood pour la région donnée. ('' pour la portée globale/héritée)", "repeater_cliHelpRegionDenyf": "Supprime l'autorisation 'F'lood' pour la région donnée. (NOTE : à ce stade, il n'est pas conseillé de l'utiliser sur l'étendue globale/héritée !! )", "repeater_cliHelpRegionHome": "Répond avec la région 'maison' actuelle. (Note appliquée nulle part pour l'instant, réservée à une utilisation future)", "repeater_cliHelpRegionHomeSet": "Définit la région 'maison'.", @@ -2328,7 +2394,7 @@ "repeater_sensors": "Capteurs", "repeater_cliHelpPowerOff": "Éteint l'appareil. (aucune réponse n'est attendue)", "repeater_cliHelpClkReboot": "Réinitialise l'horloge à une époque connue et redémarre l'appareil.", - "repeater_cliHelpAdvertZeroHop": "Envoie une publicité sans intermédiaire (uniquement aux voisins immédiats).", + "repeater_cliHelpAdvertZeroHop": "Envoie une annonce zéro saut (uniquement aux voisins immédiats).", "repeater_cliHelpStartOta": "Démarre une mise à jour du firmware par voie radio sur les cartes prises en charge.", "repeater_cliHelpTime": "Définit l'heure de l'appareil sur les secondes de l'époque Unix spécifiée. L'heure ne peut pas reculer.", "repeater_cliHelpBoard": "Indique le fabricant du panneau / l'identifiant du matériel.", @@ -2359,8 +2425,8 @@ "repeater_cliHelpGetAgcResetInterval": "Indique l'intervalle de réinitialisation de l'AGC en secondes.", "repeater_cliHelpGetMultiAcks": "Indique si le mode \"double ACK\" est activé (1) ou désactivé (0).", "repeater_cliHelpGetAllowReadOnly": "Indique si l'accès en lecture seule pour les invités est autorisé.", - "repeater_cliHelpGetAdvertInterval": "Indique l'intervalle publicitaire local en minutes.", - "repeater_cliHelpGetFloodAdvertInterval": "Indique l'intervalle publicitaire pour la diffusion de l'annonce en heures.", + "repeater_cliHelpGetAdvertInterval": "Indique l'intervalle d'annonce locale en minutes.", + "repeater_cliHelpGetFloodAdvertInterval": "Indique l'intervalle des annonces flood, en heures.", "repeater_cliHelpGetGuestPassword": "Affiche le mot de passe invité configuré.", "repeater_cliHelpGetLat": "Affiche la latitude configurée.", "repeater_cliHelpGetLon": "Affiche la longitude configurée.", @@ -2674,5 +2740,260 @@ "pathMap_noLocation": "Aucune localisation", "pathMap_followPacket": "Verrouiller la vue sur le paquet", "pathMap_unfollowPacket": "Déverrouiller la vue du paquet", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Régions", + "settings_regionSettingsSubtitle": "Gérer les régions stockées", + "settings_regionManagement_screenTitle": "Gestion de région", + "settings_regionNameHint": "Entrer le nom de la région", + "settings_regionAddRegion": "Ajouter une région", + "settings_regionFetchRegions": "Récupérer les régions à partir des répéteurs", + "settings_regionFetchRegionsFail": "Aucune région n'a été trouvée", + "settings_regionFetchRegionsAlreadyExists": "Cette région a déjà été ajoutée", + "settings_regionName": "Nom de la région", + "settings_regionDeleted": "Région supprimée", + "settings_deleteRegion": "Supprimer la région", + "settings_deleteRegionConfirm": "Supprimez {region} de la liste des régions ?", + "settings_infoHardware": "Matériel", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 octet", + "repeater_pathHashModeOption1": "1 à 2 octets", + "repeater_pathHashModeOption2": "2 à 3 octets", + "repeater_pathHashModeOption3": "3 à 4 octets", + "appSettings_batteryLipoHv": "Tension élevée LiPo (3,0-4,35 V)", + "channels_regionSetTo": "Région : {region}", + "channels_regionNotSet": "Région : aucune", + "channels_regionSelect_Title": "Choisissez une région", + "channels_clearRegion": "Zone dégagée", + "chat_sendImageLora": "Envoyer une image via MeshCore", + "chat_imagePickFailed": "Je n'ai pas pu ouvrir cette image", + "chat_receivedGif": "Reçu un GIF", + "repeater_keySettings": "Modifier les clés d'identité", + "repeater_keySettingsSubtitle": "Modifier la paire de clés publique/privée", + "repeater_prvKey": "Clé privée", + "repeater_prvKeyHelper": "Une nouvelle clé privée pour le répéteur, une chaîne hexadécimale de 128 caractères.", + "repeater_generatePrvKey": "Générez une paire de clés aléatoire", + "repeater_stopGeneratingPrvKey": "Arrêter la recherche de la paire de clés", + "repeater_pubKey": "Clé publique", + "repeater_pubKeyHelper": "Voici la clé publique associée à la clé privée générée. Vous ne pouvez pas la définir directement.", + "repeater_pubKeyPrefix": "Préfixe souhaité", + "repeater_pubKeyPrefixHelper": "Trouvez une clé publique qui commence par ces chiffres hexadécimaux. Nombre de tentatives nécessaires : {tries}.", + "imageMessages_enableTitle": "Messages avec images", + "imageMessages_enableSubtitle": "Envoyer des images via le maillage. Nécessite un téléchargement unique du modèle d'image.", + "imageMessages_modelSectionTitle": "Modèle d'image", + "imageMessages_downloadModel": "Télécharger", + "imageMessages_cancelDownload": "Annuler", + "imageMessages_removeModel": "Supprimer le modèle", + "imageMessages_modelReady": "Prêt", + "imageMessages_modelNotPublished": "Non publié — cette version ne peut pas le télécharger.", + "imageMessages_downloadFailed": "Le modèle d'image ne pouvait pas être téléchargé.", + "imageMessages_autoProcessTitle": "Traiter automatiquement les images", + "imageMessages_autoProcessSubtitle": "Reconstruisez chaque image dès son arrivée. Cela utilise environ 2 Go de mémoire pendant une seconde à chaque fois ; désactivez la reconstruction au toucher pour éviter cela.", + "imageSend_title": "Envoyer l'image", + "imageSend_cropNote": "Redimensionné à 512 × 512 · le rapport d’aspect n’a pas été conservé", + "imageSend_originalSize": "Texte original\n\nVeuillez traduire le texte suivant en français :", + "imageSend_onAirSize": "En direct", + "imageSend_quality": "Qualité", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Haut", + "imageSend_packetsLabel": "Paquets", + "imageSend_airtimeLabel": "Durée de diffusion", + "imageSend_sizeLabel": "Charge utile", + "imageSend_packetsCount": "{count} {count, plural, =1{paquet} other{paquets}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Réglages de la radio inconnus", + "imageSend_radioUnknownBody": "Connectez-vous à un appareil afin que l'heure de diffusion puisse être calculée.", + "imageSend_longSendTitle": "Longue transmission", + "imageSend_longSendBody": "Cela maintiendra la chaîne pendant environ {duration}.", + "imageSend_floodNote": "Routage flood : chaque répéteur dans la zone retransmet chaque paquet, de sorte que le canal reste occupé plus longtemps que cela.", + "imageSend_parityTitle": "Paquet de récupération", + "imageSend_paritySubtitle": "Un paquet supplémentaire. Les messages de groupe ne sont pas reconnus, ce qui permet au destinataire de reconstruire l'image si un seul paquet est perdu.", + "imageSend_send": "Envoyer", + "imageSend_cancel": "Annuler", + "imageSend_encodeFailed": "Cette image ne peut pas être encodée.", + "imageSend_codecDownloading": "Le modèle d'image est toujours en téléchargement.", + "imageSend_codecUnavailable": "L'envoi d'images n'est pas disponible sur cet appareil.", + "imageSend_codecDisabled": "Les messages d'images sont désactivés dans les paramètres.", + "imageSend_deviceUnsupported": "Cette radio ne peut pas envoyer de paquets d'images. Connectez un appareil exécutant le firmware compagnon version 13 ou ultérieure.", + "imageSend_directMessagesUnsupported": "Les images se déplacent en tant que données de groupe, elles ne peuvent donc être envoyées que sur un canal — et non par message direct.", + "imageSend_tooLarge": "Cette image a été encodée en plus de paquets que le format de maillage ne permet.", + "imageSend_sentConfirmation": "Image envoyée en {count} {count, plural, =1{paquet} other{paquets}}.", + "imageSend_sendFailed": "L'image n'a pas pu être envoyée : {error}", + "imageSend_sendingProgress": "Envoi de l'image — paquet {sent} sur {total}", + "receivedImage_senderPrefix": "Nœud {prefix}", + "receivedImage_incoming": "{received} sur {total} paquets", + "receivedImage_queued": "En attendant de décoder", + "receivedImage_tapToDecode": "Tapez pour décoder", + "receivedImage_decoding": "Reconstitution… d’environ 1 s", + "receivedImage_incomplete": "Image incomplète — {received} sur {total} paquets reçus", + "receivedImage_corrupt": "L'image ne pouvait pas être reconstruite", + "receivedImage_decoderMissing": "Image reçue — le décodage de l'image est interrompu", + "receivedImage_evicted": "Image non stockée", + "receivedImage_retry": "Réessayez", + "receivedImage_decodeAgain": "Décoder à nouveau", + "receivedImage_openSettings": "Mettre en place", + "receivedImage_tapToProcess": "Tapez pour traiter", + "receivedImage_awaiting": "{bytes} octets · {packets} {packets, plural, =1{paquet} other{paquets}}", + "imageSend_secondsValue": "{seconds} s", + "imageSend_minutesSecondsValue": "{minutes} minutes {seconds} secondes", + "channels_noFreeSlots": "Tous les emplacements de canaux sont utilisés", + "chat_longMessageRetryNote": "Plus de 158 octets : envoi au maximum {count} fois", + "reaction_report": "Réactions emoji", + "repeater_bridgeNote": "Disponible uniquement sur un firmware compilé avec un pont (RS232 ou ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Affiche le nombre maximal de sauts pour les annonces flood.", + "repeater_cliHelpGetFloodMaxUnscoped": "Affiche le nombre maximal de sauts pour les paquets flood sans portée régionale.", + "repeater_cliHelpGetRadioFemRxGain": "Indique si le gain RX du module frontal LoRa est activé.", + "repeater_cliHelpGetRadioFemTxGain": "Indique si le gain TX du module frontal LoRa est activé.", + "repeater_cliHelpRegionDef": "Définit une chaîne de régions en une seule commande : chaque nom est ajouté sous le précédent ; \"name,parent\" ajoute le nom, puis continue sous le parent indiqué. Répond avec la liste des régions.", + "repeater_cliHelpSetFloodMaxAdvert": "Définit le nombre maximal de sauts pour la retransmission des annonces flood (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Définit le nombre maximal de sauts pour la retransmission des paquets flood sans portée régionale (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Active ou désactive le gain RX (LNA) du module frontal LoRa. Les cartes qui n'en ont pas répondent \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Active ou désactive le gain TX (PA) du module frontal LoRa. Les cartes qui n'en ont pas répondent \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Mode de chargement des régions : envoyez un nom de région par ligne, indenté avec des espaces sous sa région parente (ajoutez F après le nom pour autoriser le flood). Les lignes ne reçoivent pas de réponse. Envoyez une ligne vide pour terminer, puis \"region save\" pour conserver le résultat.", + "repeater_cliRegionLoadEnd": "(fin du chargement des régions)", + "repeater_cliRegionLoadHint": "Ligne de région, ou vide pour terminer", + "repeater_frequencyInvalid": "Fréquence invalide (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Erreurs de réception", + "repeater_txPowerRangeHelper": "-9 à 30 dBm", + "room_postsPushed": "Publications envoyées", + "room_postsStored": "Publications", + "settings_publicKeyCopied": "Clé publique copiée", + "settings_radioSettingsNotApplied": "La radio n'a pas appliqué ces paramètres", + "urlImage_enable": "Activer les images URL", + "urlImage_possible": "Image URL possible ; activez-la dans les Paramètres.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 044f1490..cdd19370 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -161,6 +161,8 @@ "settings_locationIntervalInvalid": "Az intervallumnak legalább 60 másodpercnek kell lennie, és kevesebbnek kell lennie 86 400 másodpercnél.", "settings_latitude": "Szélesség", "settings_longitude": "Hosszúság", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatikus zero-hop hirdetés GPS-frissítéskor", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Ha a GPS-helyzet megváltozik, küldjön zero-hop hirdetést (a hirdetésben helymegadás szükséges).", "settings_contactSettings": "Kapcsolati beállítások", "settings_contactSettingsSubtitle": "A névjegyek hozzáadásának beállításai.", "settings_privacyMode": "Adatvédelmi mód", @@ -173,7 +175,7 @@ "settings_deleteAllPathsSubtitle": "Törölje az összes elérési utat a névjegyekből.", "settings_sendAdvertisement": "Hirdetés küldése", "settings_sendAdvertisementSubtitle": "Jelenlét a közvetítésben most", - "settings_advertisementSent": "Reklám elküldve", + "settings_advertisementSent": "Hirdetés elküldve", "settings_syncTime": "Szinkronizálási idő", "settings_syncTimeSubtitle": "Az eszköz órájának beállítása a telefon idejére", "settings_timeSynchronized": "Idő szinkronizálva", @@ -262,7 +264,7 @@ "appSettings_messageNotificationsSubtitle": "Értesítés megjelenítése új üzenetek fogadásakor", "appSettings_channelMessageNotifications": "Csatorna üzenetek értesítései", "appSettings_channelMessageNotificationsSubtitle": "Értesítés megjelenítése csatornaüzenetek fogadásakor", - "appSettings_advertisementNotifications": "Reklám Értesítések", + "appSettings_advertisementNotifications": "Hirdetési értesítések", "appSettings_advertisementNotificationsSubtitle": "Értesítés megjelenítése új csomópontok felfedezésekor", "appSettings_messaging": "Üzenetküldés", "appSettings_clearPathOnMaxRetry": "Útvonal törlése a Max. újrapróbálkozásnál", @@ -332,6 +334,19 @@ "appSettings_last6Hours": "Utolsó 6 óra", "appSettings_last24Hours": "Az elmúlt 24 óra", "appSettings_lastWeek": "Múlt héten", + "appSettings_rasterTileSource": "Raszteres csempeforrás", + "appSettings_stadiaEndpoint": "Stadia végpont", + "appSettings_stadiaApiKey": "Stadia API-kulcs", + "appSettings_stadiaApiKeyRequired": "A Stadia Maps használatához kötelező", + "appSettings_stadiaApiKeyConfigured": "Konfigurálva: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Adja meg a Stadia Maps API-kulcsát. Az alkalmazás ezt használja raszteres csempekérésekhez.", "appSettings_offlineMapCache": "Offline térképgyorsítótár", "appSettings_unitsTitle": "Egységek", "appSettings_unitsMetric": "Metrikus (m/km)", @@ -642,6 +657,7 @@ } } }, + "chat_selectSendAction": "Küldési művelet kiválasztása", "chat_sendGif": "GIF küldése", "chat_reply": "Válasz", "chat_addReaction": "Reakció hozzáadása", @@ -758,7 +774,7 @@ "chat_clearPathSubtitle": "A parancs új küldéskor újra kell aktivizálnia.", "chat_pathCleared": "Út megtisztítva. A következő üzenet újra felfedezi az útvonalat.", "chat_floodModeSubtitle": "Használja a \"útvonal\" kapcsolót az alkalmazás sávjában.", - "chat_floodModeEnabled": "Árvízvédelmi mód bekapcsolva. A visszaállítás a alkalmazásban található útvonal ikon segítségével.", + "chat_floodModeEnabled": "Elárasztás mód bekapcsolva. A visszaállítás a alkalmazásban található útvonal ikon segítségével.", "chat_fullPath": "Teljes útvonal", "chat_pathDetailsNotAvailable": "Az útvonal részletei még nem elérhetők. Próbálja meg küldeni egy üzenetet, hogy frissítse az információkat.", "chat_pathSetHops": "Path set: {hopCount} {hopCount, plural, =1{hop} other{hops}} - {status}", @@ -779,7 +795,7 @@ "chat_path": "Útvonal", "chat_publicKey": "Nyilvános kulcs", "chat_compressOutgoingMessages": "A kimenő üzenetek tömörítése", - "chat_floodForced": "Árvíz (kényszerített)", + "chat_floodForced": "Elárasztás (kényszerített)", "chat_directForced": "Közvetlen (kényszerített)", "chat_hopsForced": "{count} ugrás (kényszerített)", "@chat_hopsForced": { @@ -789,7 +805,7 @@ } } }, - "chat_floodAuto": "Árvíz (automatikus)", + "chat_floodAuto": "Elárasztás (automatikus)", "chat_direct": "Közvetlen", "chat_poiShared": "POI megosztva", "chat_unread": "Olvasatlan: {count}", @@ -952,6 +968,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "É {north}, D {south}, K {east}, Ny {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1138,7 +1204,7 @@ } } }, - "repeater_packetTxTotal": "Összesen: {total}, Árvíz: {flood}, Közvetlen: {direct}", + "repeater_packetTxTotal": "Összesen: {total}, Elárasztás: {flood}, Közvetlen: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -1152,7 +1218,7 @@ } } }, - "repeater_packetRxTotal": "Összesen: {total}, Árvíz: {flood}, Közvetlen: {direct}", + "repeater_packetRxTotal": "Összesen: {total}, Elárasztás: {flood}, Közvetlen: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -1166,7 +1232,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Árvíz: {flood}, Közvetlen: {direct}", + "repeater_duplicatesFloodDirect": "Elárasztás: {flood}, Közvetlen: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1213,7 +1279,7 @@ "repeater_guestAccessSubtitle": "Csak olvasási hozzáférés engedélyezése a vendégek számára", "repeater_privacyMode": "Adatvédelmi mód", "repeater_privacyModeSubtitle": "Név/hely elrejtése a hirdetésekben", - "repeater_advertisementSettings": "Reklámbeállítások", + "repeater_advertisementSettings": "Hirdetésbeállítások", "repeater_localAdvertInterval": "Helyi hirdetési intervallum", "repeater_localAdvertIntervalMinutes": "{minutes} perc", "@repeater_localAdvertIntervalMinutes": { @@ -1223,7 +1289,7 @@ } } }, - "repeater_floodAdvertInterval": "Árvízi hirdetési intervallum", + "repeater_floodAdvertInterval": "Elárasztási hirdetési intervallum", "repeater_floodAdvertIntervalHours": "{hours} óra", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1270,7 +1336,7 @@ "repeater_refreshMultiAcks": "Többszörös ACK-ek frissítése", "repeater_networkHealth": "Hálózat állapota", "repeater_loopDetect": "Hurokérzékelés", - "repeater_loopDetectHelper": "Dobd el az útválasztó huroknak tűnő árvízcsomagokat", + "repeater_loopDetectHelper": "Dobd el az útválasztó huroknak tűnő elárasztási csomagokat", "repeater_loopDetectOff": "Le", "repeater_loopDetectMinimal": "Minimális", "repeater_loopDetectModerate": "Mérsékelt", @@ -1288,14 +1354,14 @@ "repeater_ownerInfo": "Üzemeltető információ", "repeater_ownerInfoHelper": "Nyilvános metaadatok ehhez az átjátszóhoz", "repeater_refreshOwnerInfo": "Frissítse az operátor adatait", - "repeater_floodMax": "Árvíz max ugrás", - "repeater_floodMaxHelper": "Maximum ugrások, amelyeket egy árvízcsomag utazhat (0-64)", + "repeater_floodMax": "Elárasztás max ugrás", + "repeater_floodMaxHelper": "Maximum ugrások, amelyeket egy elárasztási csomag utazhat (0-64)", "repeater_advancedSettings": "Fejlett", "repeater_advancedSettingsSubtitle": "Hangológombok tapasztalt kezelőknek", "repeater_pathHashMode": "Útvonal hash mód", "repeater_pathHashModeHelper": "Az átjátszó azonosítójának elárasztási útvonal/hurokészlelési címkékbe való kódolására használt bájtok. 0 = 1 bájt (256 azonosító, legfeljebb 64 ugrás), 1 = 2 bájt (65 000 azonosító, legfeljebb 32 ugrás), 2 = 3 bájt (16 millió azonosító, legfeljebb 21 ugrás). A v1.13 és régebbi firmware eldobja a többbájtos elérési utat – csak akkor emelje meg, ha a hálózat a v1.14+ verziót használja.", "repeater_txDelay": "Áradási TX késleltetés", - "repeater_txDelayHelper": "Újraküldési térköz az árvízi forgalomhoz, a csomag sugárzási idejének szorzójaként (0-2, alapértelmezett 0,5). Magasabb = kevesebb ütközés, de lassabb szállítás.", + "repeater_txDelayHelper": "Újraküldési térköz az elárasztási forgalomhoz, a csomag sugárzási idejének szorzójaként (0-2, alapértelmezett 0,5). Magasabb = kevesebb ütközés, de lassabb szállítás.", "repeater_directTxDelay": "Közvetlen TX késleltetés", "repeater_directTxDelayHelper": "A közvetlen (nem elárasztásos) forgalom újraküldési távolsága a csomag sugárzási idejének szorzójaként (0-2, alapértelmezett 0,3).", "repeater_intThresh": "Interferencia küszöb", @@ -1303,8 +1369,8 @@ "repeater_agcResetInterval": "AGC reset intervallum", "repeater_agcResetIntervalHelper": "Milyen gyakran kell visszaállítani a rádió automatikus erősítésszabályozását, hogy helyreálljon a beragadt erősítési állapotból. A másodpercek, 4 többszörösére csökkentve. 0 letiltja az időszakos visszaállításokat.", "repeater_actionsTitle": "Akciók", - "repeater_sendAdvert": "Árvízhirdetés küldése", - "repeater_sendAdvertSubtitle": "Adjon árvízreklámot a hálózaton keresztül", + "repeater_sendAdvert": "Elárasztási hirdetés küldése", + "repeater_sendAdvertSubtitle": "Küldjön elárasztási hirdetést a hálózaton keresztül", "repeater_sendAdvertZeroHop": "Zéró ugrású hirdetés küldése", "repeater_sendAdvertZeroHopSubtitle": "Egyugrásos hirdetés sugárzása (közvetítés nélkül)", "repeater_clockSync": "Óra szinkronizálása most", @@ -1393,7 +1459,7 @@ "repeater_cliQuickVersion": "Változat", "repeater_cliQuickAdvertise": "Hirdet", "repeater_cliQuickClock": "Óra", - "repeater_cliHelpAdvert": "Reklámcsomagot küld", + "repeater_cliHelpAdvert": "Hirdetési csomagot küld", "repeater_cliHelpReboot": "Újraindítja az eszközt. (megjegyzendő, hogy \"Időtúllépés\" jelenik meg, ami normális)", "repeater_cliHelpClock": "Megjeleníti az aktuális időt az eszköz órájánként.", "repeater_cliHelpPassword": "Új rendszergazdai jelszót állít be az eszközhöz.", @@ -1403,12 +1469,12 @@ "repeater_cliHelpSetTx": "A LoRa adási teljesítményét dBm-ben állítja be. (újraindítás az alkalmazáshoz)", "repeater_cliHelpSetRepeat": "Engedélyezi vagy letiltja a csomópont ismétlő szerepét.", "repeater_cliHelpSetAllowReadOnly": "(Szobaszerver) Ha 'be', akkor az üres jelszó bejelentkezés engedélyezett, de nem lehet postázni a szobába. (csak olvasható)", - "repeater_cliHelpSetFloodMax": "Beállítja a bejövő árvízcsomag ugrásainak maximális számát (ha >= max, a csomag nem kerül továbbításra)", + "repeater_cliHelpSetFloodMax": "Beállítja a bejövő elárasztási csomag ugrásainak maximális számát (ha >= max, a csomag nem kerül továbbításra)", "repeater_cliHelpSetIntThresh": "Beállítja az interferencia küszöböt (DB-ben). Az alapértelmezett érték 14. Állítsa 0-ra a csatornainterferencia-érzékelés letiltásához.", "repeater_cliHelpSetAgcResetInterval": "Beállítja az Auto Gain Controller alaphelyzetbe állításának intervallumát. A letiltáshoz állítsa 0-ra.", "repeater_cliHelpSetMultiAcks": "Engedélyezi vagy letiltja a „dupla ACK” funkciót.", "repeater_cliHelpSetAdvertInterval": "Beállítja a helyi (nulla ugrású) hirdetési csomag küldésének időzítési időközét percekben. A letiltáshoz állítsa 0-ra.", - "repeater_cliHelpSetFloodAdvertInterval": "Beállítja az időzítő intervallumát órákban az árvízhirdetési csomag küldéséhez. A letiltáshoz állítsa 0-ra.", + "repeater_cliHelpSetFloodAdvertInterval": "Beállítja az időzítő intervallumát órákban az elárasztási hirdetési csomag küldéséhez. A letiltáshoz állítsa 0-ra.", "repeater_cliHelpSetGuestPassword": "Beállítja/frissíti a vendég jelszavát. (Repeaterek esetén a vendégbejelentkezés elküldheti a \"Statisztikák lekérése\" kérést)", "repeater_cliHelpSetName": "Beállítja a hirdetés nevét.", "repeater_cliHelpSetLat": "Beállítja a hirdetéstérkép szélességi fokát. (tizedes fok)", @@ -1431,7 +1497,7 @@ "repeater_cliHelpLogErase": "Törli a csomagnaplókat a fájlrendszerből.", "repeater_cliHelpNeighbors": "Megjeleníti a nulla ugrású hirdetéseken keresztül hallható egyéb átjátszó csomópontok listáját. Minden sor id-prefix-hex:timestamp:snr-times-4", "repeater_cliHelpNeighborRemove": "Eltávolítja az első egyező bejegyzést (a pubkey előtag (hex) alapján) a szomszédok listájából.", - "repeater_cliHelpRegion": "(csak soros) Felsorolja az összes meghatározott régiót és az aktuális árvízi engedélyeket.", + "repeater_cliHelpRegion": "(csak soros) Felsorolja az összes meghatározott régiót és az aktuális elárasztási engedélyeket.", "repeater_cliHelpRegionLoad": "MEGJEGYZÉS: ez egy speciális többparancsos hívás. Minden következő parancs egy régiónév (szóközökkel behúzva a szülőhierarchiát jelölve, legalább egy szóközzel). Üres sor/parancs küldésével megszűnik.", "repeater_cliHelpRegionGet": "Régiót keres adott név előtaggal (vagy \"*\" a globális hatókörhöz). A válasz a következővel: \"-> régiónév (szülőnév) 'F'\"", "repeater_cliHelpRegionPut": "Adott névvel rendelkező régiódefiníció hozzáadása vagy frissítése.", @@ -1589,7 +1655,7 @@ "channelPath_viewMap": "Térkép megtekintése", "channelPath_otherObservedPaths": "Egyéb megfigyelt utak", "channelPath_repeaterHops": "Repeater Hops", - "channelPath_noHopDetails": "Ennél a csomagnál a komlórészletek nincsenek megadva.", + "channelPath_noHopDetails": "Ennél a csomagnál az ugrásrészletek nincsenek megadva.", "channelPath_messageDetails": "Üzenet részletei", "channelPath_senderLabel": "Feladó", "channelPath_timeLabel": "Idő", @@ -1631,7 +1697,7 @@ } }, "channelPath_unknownPath": "Ismeretlen", - "channelPath_floodPath": "Árvíz", + "channelPath_floodPath": "Elárasztás", "channelPath_directPath": "Közvetlen", "channelPath_observedZeroOf": "0 / {total} ugrás", "@channelPath_observedZeroOf": { @@ -1839,7 +1905,7 @@ "pathTrace_failed": "Az útvonal nyomon követése nem sikerült.", "pathTrace_notAvailable": "Útvonal nyomkövetés nem érhető el.", "pathTrace_refreshTooltip": "Path Trace frissítése.", - "pathTrace_someHopsNoLocation": "Egy vagy több komló helye hiányzik!", + "pathTrace_someHopsNoLocation": "Egy vagy több ugrás helye hiányzik!", "pathTrace_clearTooltip": "Tiszta útvonal.", "losSelectStartEnd": "Válassza ki a LOS kezdő és záró csomópontját.", "losRunFailed": "A rálátás ellenőrzése sikertelen: {error}", @@ -1994,7 +2060,7 @@ "contacts_contactImported": "A névjegy importálása megtörtént.", "contacts_contactImportFailed": "Nem sikerült importálni a névjegyet.", "contacts_zeroHopAdvert": "Zero Hop hirdetés", - "contacts_floodAdvert": "Árvíz hirdetés", + "contacts_floodAdvert": "Elárasztási hirdetés", "contacts_copyAdvertToClipboard": "Hirdetés másolása a vágólapra", "contacts_addContactFromClipboard": "Névjegy hozzáadása a vágólapról", "contacts_ShareContact": "Névjegy másolása a vágólapra", @@ -2271,7 +2337,7 @@ "repeater_cliHelpGetMultiAcks": "Megmutatja, hogy a dupla ACK mód be van-e kapcsolva (1) vagy ki (0).", "repeater_cliHelpGetAllowReadOnly": "Megmutatja, hogy a vendég csak olvasási hozzáférés engedélyezett-e.", "repeater_cliHelpGetAdvertInterval": "A helyi hirdetési intervallumot mutatja percben.", - "repeater_cliHelpGetFloodAdvertInterval": "Megjeleníti az árvízhirdetés intervallumát órákban.", + "repeater_cliHelpGetFloodAdvertInterval": "Megjeleníti az elárasztási hirdetés intervallumát órákban.", "repeater_cliHelpGetGuestPassword": "Megjeleníti a beállított vendégjelszót.", "repeater_cliHelpGetLat": "Megjeleníti a beállított szélességi fokot.", "repeater_cliHelpGetLon": "A beállított hosszúságot mutatja.", @@ -2300,8 +2366,8 @@ "repeater_cliHelpSensorList": "Felsorolja az összes egyéni érzékelőbeállítást, oldalszámozással az opcionális kezdőindexből.", "repeater_cliHelpRegionDefault": "Megjeleníti az aktuális alapértelmezett régióhatókört.", "repeater_cliHelpRegionDefaultSet": "Beállítja az alapértelmezett régió hatókört. A törléshez használja a \"\" parancsot.", - "repeater_cliHelpRegionListAllowed": "Felsorolja azokat a régiókat, amelyek lehetővé teszik az árvízi forgalmat.", - "repeater_cliHelpRegionListDenied": "Felsorolja azokat a régiókat, amelyek megtagadják az árvízi forgalmat.", + "repeater_cliHelpRegionListAllowed": "Felsorolja azokat a régiókat, amelyek lehetővé teszik az elárasztási forgalmat.", + "repeater_cliHelpRegionListDenied": "Felsorolja azokat a régiókat, amelyek megtagadják az elárasztási forgalmat.", "repeater_cliHelpStatsPackets": "(Csak soros) Csomag szintű statisztikákat jelenít meg.", "repeater_cliHelpStatsRadio": "(Csak soros) Rádióstatisztikák megjelenítése.", "repeater_cliHelpStatsCore": "(Csak soros) Az alapvető firmware-statisztikák megjelenítése.", @@ -2441,7 +2507,7 @@ "contacts_searchClose": "Keresés bezárása", "routing_title": "Útválasztás", "routing_modeAuto": "Auto", - "routing_modeFlood": "Árvíz", + "routing_modeFlood": "Elárasztás", "routing_modeManual": "Kézikönyv", "routing_modeAutoHint": "Automatikusan kiválasztja a legismertebb utat, és elárasztja, ha nem ismert.", "routing_modeFloodHint": "Minden átjátszón keresztül sugároz. A legmegbízhatóbb, de több műsoridőt használ.", @@ -2459,14 +2525,14 @@ "routing_qualityGood": "Jó első ugrás", "routing_qualityFair": "Tisztességes első ugrás", "routing_qualityWorked": "Szállított", - "routing_qualityFlood": "Árvízen keresztül hallatszott", + "routing_qualityFlood": "Elárasztáson keresztül hallatszott", "routing_qualityUntested": "Nem tesztelt", "routing_neverWorked": "soha nem erősítették meg", - "routing_floodDelivery": "Árvízi szállítás", + "routing_floodDelivery": "Elárasztási szállítás", "pathEditor_title": "Építsd meg az útvonalat", "pathEditor_hopCounter": "{count} 64 ugrásból", "pathEditor_noHops": "Még nincs ugrás. Koppintson az alábbi ismétlőkre, ha sorrendben szeretné felvenni őket, vagy mentse ugrás nélkül a közvetlen küldéshez.", - "pathEditor_addHops": "Sorrendben adjuk hozzá a komlót", + "pathEditor_addHops": "Sorrendben adjuk hozzá az ugrásokat", "pathEditor_searchRepeaters": "Ismétlő keresése", "pathEditor_advancedHex": "Haladó: nyers hexadecimális útvonal", "pathEditor_hexLabel": "Hexadecimális előtagok", @@ -2578,5 +2644,261 @@ "pathMap_noLocation": "Nincs hely", "pathMap_followPacket": "Nézet zárolása a csomaghoz", "pathMap_unfollowPacket": "A nézet feloldása a csomagból", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Tájak", + "settings_regionSettingsSubtitle": "Kincstani megjelenítette gyakorlatos területeket", + "settings_regionManagement_screenTitle": "Regionális Kezelés", + "settings_regionNameHint": "Felhasználja a regioni név", + "settings_regionAddRegion": "Egyes region", + "settings_regionFetchRegions": "Féregelmezők a repeaterekból", + "settings_regionFetchRegionsFail": "Nem található egyéb területek", + "settings_regionFetchRegionsAlreadyExists": "Ez a terítet nemisértették meg.", + "settings_regionName": "Feldúr Neve", + "settings_regionDeleted": "Felült region", + "settings_deleteRegion": "Felajánlatos Tér", + "settings_deleteRegionConfirm": "Kell kiszámítsd a {region}ot a részekre?", + "settings_infoHardware": "Hardverő", + "settings_infoFirmware": "Firmver", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 szavak", + "repeater_pathHashModeOption2": "2 - 3 bajt", + "repeater_pathHashModeOption3": "3 - 4 bajt", + "appSettings_batteryLipoHv": "LiPo HV (3.0-4.35V)", + "channels_regionSetTo": "Tájékoztatás: A {region} -t\n\nEz a tájékoztatás a magyar nyelvben a következően kell szóva:\n\nTájékoztatás: A {region} -t", + "channels_regionNotSet": "Tájékoztetés: nem", + "channels_regionSelect_Title": "Válassz egy regionot", + "channels_clearRegion": "Kéres kör", + "chat_sendImageLora": "Kép küldése MeshCore-on keresztül", + "chat_imagePickFailed": "Nem tudtam ezt a fenti fényre kapni", + "chat_receivedGif": "GIF-ot kapott", + "repeater_keySettings": "Képzőítsekei jelölt", + "repeater_keySettingsSubtitle": "Közelítse a közlekedési/private képlékt", + "repeater_prvKey": "Kis házas", + "repeater_prvKeyHelper": "Kínai nyelvben:\n\nA repeteróhoz új képes kód, 128 karakteri hex-kód.", + "repeater_generatePrvKey": "Egy random képléktár generáld meg", + "repeater_stopGeneratingPrvKey": "Kéypair szavakat kérdéset kaphatás", + "repeater_pubKey": "Kiváló kiegészítő", + "repeater_pubKeyHelper": "Ez a kiváló kód, amely tükrözi a gyártott kiegészítő kódot. Ezet nem lehet megjelenítani direktusan.", + "repeater_pubKeyPrefix": "Kiváló prefix", + "repeater_pubKeyPrefixHelper": "Kiválasztsa meg a közös kódot, amely az alábbi hex-kifüggőnek előre van. Várható kiválasztások száma: {tries}.", + "imageMessages_enableTitle": "Fenti hírüket biztosítani", + "imageMessages_enableSubtitle": "Fényokat a hálózatban küldd el. Egyértelmű fénymodell hozzáadásra kell.", + "imageMessages_modelSectionTitle": "Image model", + "imageMessages_downloadModel": "Hozzáladás", + "imageMessages_cancelDownload": "Színviselés", + "imageMessages_removeModel": "Kisnövezdés", + "imageMessages_modelReady": "Hozzá", + "imageMessages_modelNotPublished": "Érkeztetve nem — ez a építési módszert nem lehet lejobbítani.", + "imageMessages_downloadFailed": "Életmódelmát nem tudtam hozni.", + "imageMessages_autoProcessTitle": "Automatikusan kínaltatja fénybetek", + "imageMessages_autoProcessSubtitle": "Minden fenti image-t kiválasztsa meg, amikor érkezik. Minden más esetben 2 GB fényre kell szükséges; megoldja a rekonstruálisi a támogatásra egy klikkel.", + "imageSend_title": "Felhasználj az image", + "imageSend_cropNote": "512 × 512 órák számára megosztva · képszöget nem biztosítva", + "imageSend_originalSize": "Következtetés:", + "imageSend_onAirSize": "Erőben", + "imageSend_quality": "Hosszú Képesség", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "High: Magas", + "imageSend_packetsLabel": "Paketek", + "imageSend_airtimeLabel": "Kiválasztás a fent", + "imageSend_sizeLabel": "Kártya", + "imageSend_packetsCount": "{count} {count, plural, =1{csomag} other{csomag}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Radiooldalok nem tudom", + "imageSend_radioUnknownBody": "Kizárdhoz kapcsolódd a rendszert, hogy a súly az az álló időt lehet elismerni.", + "imageSend_longSendTitle": "Uzun hírás", + "imageSend_longSendBody": "Ez megbízható a kanal {duration}-n.", + "imageSend_floodNote": "Fúró irányozás: Minden repeater a fúró körüléggel megköveti mindkét paketet, ezért a kanal eltartja más a lehetséges időt.", + "imageSend_parityTitle": "Korzolás paksa", + "imageSend_paritySubtitle": "Egy kibőbbes kapszula. Gruppos hírselek nem érkezik, ezért az empfangó nem kell elismerni a jel, ha egy egyes kapszula kaland, hogy nem teljesen érkezz.", + "imageSend_send": "Keresés", + "imageSend_cancel": "Színviselés", + "imageSend_encodeFailed": "Ez a fényet nem tudtam kódolni.", + "imageSend_codecDownloading": "Érdekesz az image model megstálása még van.", + "imageSend_codecUnavailable": "Felhasználó észintje nem kapható ezen a rendszert.", + "imageSend_codecDisabled": "Image hírletek belsőoldal elkalmáznak a konfigurációban.", + "imageSend_deviceUnsupported": "Ez a radio nem tudja verseni színekfájltakat. Habilítd a kompatibilis firmware 13 vagy újabb versionot kapcsált eszközet.", + "imageSend_directMessagesUnsupported": "Fényiak gyakorolják grupos adatban, ezért nem lehetek versenek egy hozzáfűzésre, csak egy kanalra.", + "imageSend_tooLarge": "A figyelmetes fentet nem kínálhat a körközlettel ismétálás elterjesztésére.", + "imageSend_sentConfirmation": "Kép elküldve {count} {count, plural, =1{csomagként} other{csomagként}}.", + "imageSend_sendFailed": "Fentami nem tűnik: {error}", + "imageSend_sendingProgress": "Felhasználó: Lehet a következőkét kifejezetet – {sent} paket {total}", + "receivedImage_senderPrefix": "Node {prefix}", + "receivedImage_incoming": "Kulcsfontosságú: Kiválasztja meg a {received} {total} paketot", + "receivedImage_queued": "Kódoláshoz küldőzve", + "receivedImage_tapToDecode": "Kódoláshoz klikd el", + "receivedImage_decoding": "Korlátozás… egy 1 perc után", + "receivedImage_incomplete": "Kérem, az {received} {total} paketet kapottak.", + "receivedImage_corrupt": "Fény nem tudtam megrealítani", + "receivedImage_decoderMissing": "Kezd az image — image decodálás nem kapható", + "receivedImage_evicted": "Fény nem tartalmazva", + "receivedImage_retry": "Kérem kell próbálni", + "receivedImage_decodeAgain": "Kodoldó", + "receivedImage_openSettings": "Jelzése", + "receivedImage_tapToProcess": "Klikd a feljelenítést", + "receivedImage_awaiting": "{bytes} bájt · {packets} {packets, plural, =1{csomag} other{csomag}}", + "imageSend_secondsValue": "{seconds} sekünd\n\n(Note: The placeholder {seconds} is kept unchanged as requested.)", + "imageSend_minutesSecondsValue": "{minutes} per {seconds} sekünd\n\n(Note: The original text appears to be a placeholder format rather than a complete sentence. The translation reflects the literal structure while preserving the placeholders as requested.)", + "channels_noFreeSlots": "Minden csatornahely foglalt", + "chat_longMessageRetryNote": "158 bájt felett: legfeljebb {count} alkalommal küldve", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "reaction_report": "Emoji reakciók", + "repeater_bridgeNote": "Csak híddal (RS232 vagy ESP-NOW) épített firmware-en érhető el.", + "repeater_cliHelpGetFloodMaxAdvert": "Megjeleníti az elárasztási hirdetések maximális ugrásszámát.", + "repeater_cliHelpGetFloodMaxUnscoped": "Megjeleníti a hatókör nélküli elárasztási csomagok maximális ugrásszámát.", + "repeater_cliHelpGetRadioFemRxGain": "Megjeleníti, hogy a LoRa front-end modul RX erősítése be van-e kapcsolva.", + "repeater_cliHelpGetRadioFemTxGain": "Megjeleníti, hogy a LoRa front-end modul TX erősítése be van-e kapcsolva.", + "repeater_cliHelpRegionDef": "Egy paranccsal régiók láncát határozza meg: minden név az előző alá kerül; a \"name,parent\" hozzáadja a nevet, majd a megadott szülő alatt folytatja. Válaszként a régiólistát adja.", + "repeater_cliHelpSetFloodMaxAdvert": "Beállítja az elárasztási hirdetések továbbításának maximális ugrásszámát (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Beállítja a hatókör nélküli elárasztási csomagok továbbításának maximális ugrásszámát (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Ki-/bekapcsolja a LoRa front-end modul RX erősítését (LNA). Az ezzel nem rendelkező áramkörök válasza \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Ki-/bekapcsolja a LoRa front-end modul TX erősítését (PA). Az ezzel nem rendelkező áramkörök válasza \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Régióbetöltési mód: soronként küldjön egy régiónevet, szóközökkel behúzva a szülője alá (a név után F hozzáadásával engedélyezhető az elárasztás). A sorokra nem érkezik válasz. Egy üres sor küldésével fejezze be, majd a \"region save\" paranccsal mentse az eredményt.", + "repeater_cliRegionLoadEnd": "(régióbetöltés vége)", + "repeater_cliRegionLoadHint": "Régiósor, vagy üres a befejezéshez", + "repeater_frequencyInvalid": "Érvénytelen frekvencia (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Vételi hibák", + "repeater_txPowerRangeHelper": "-9-től 30 dBm-ig", + "room_postsPushed": "Kiküldött bejegyzések", + "room_postsStored": "Bejegyzések", + "settings_publicKeyCopied": "Nyilvános kulcs másolva", + "settings_radioSettingsNotApplied": "A rádió nem alkalmazta ezeket a beállításokat", + "urlImage_enable": "URL-képek engedélyezése", + "urlImage_possible": "Lehetséges URL-kép; engedélyezze a Beállításokban." } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 2df230ae..d1ce950a 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -140,6 +140,7 @@ "settings_infoStatus": "Stato", "settings_infoBattery": "Batteria", "settings_infoPublicKey": "Chiave Pubblica", + "settings_publicKeyCopied": "Chiave pubblica copiata", "settings_infoContactsCount": "Numero di contatti", "settings_infoChannelCount": "Numero di canali", "settings_presets": "Preset", @@ -191,7 +192,7 @@ "appSettings_messageNotificationsSubtitle": "Mostra notifica all'arrivo di nuovi messaggi", "appSettings_channelMessageNotifications": "Notifiche Messaggi Canale", "appSettings_channelMessageNotificationsSubtitle": "Mostra notifica all'arrivo di messaggi nel canale", - "appSettings_advertisementNotifications": "Notifiche Pubblicitarie", + "appSettings_advertisementNotifications": "Notifiche degli Annunci", "appSettings_advertisementNotificationsSubtitle": "Mostra notifica quando vengono scoperti nuovi nodi", "appSettings_messaging": "Messaggi", "appSettings_clearPathOnMaxRetry": "Cancella percorso al massimo dei tentativi", @@ -240,6 +241,19 @@ "appSettings_last6Hours": "Ultimi 6 ore", "appSettings_last24Hours": "Ultime 24 ore", "appSettings_lastWeek": "La settimana scorsa", + "appSettings_rasterTileSource": "Sorgente tile raster", + "appSettings_stadiaEndpoint": "Endpoint Stadia", + "appSettings_stadiaApiKey": "Chiave API Stadia", + "appSettings_stadiaApiKeyRequired": "Obbligatoria per usare Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Configurata: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Inserisci la chiave API di Stadia Maps. Questa app la usa per le richieste di tile raster.", "appSettings_offlineMapCache": "Cache Mappa Offline", "appSettings_noAreaSelected": "Nessun'area selezionata", "appSettings_areaSelectedZoom": "Area selezionata (zoom {minZoom}-{maxZoom})", @@ -538,6 +552,7 @@ } } }, + "chat_selectSendAction": "Seleziona azione di invio", "chat_sendGif": "Invia GIF", "chat_reply": "Rispondi", "chat_addReaction": "Aggiungi Reazione", @@ -837,6 +852,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1158,7 +1223,7 @@ "repeater_loopDetectModerate": "Moderato", "repeater_loopDetectStrict": "Rigido", "repeater_dutyCycle": "Ciclo di lavoro", - "repeater_dutyCycleHelper": "Percentuale massima di utilizzo dello spazio pubblicitario", + "repeater_dutyCycleHelper": "Percentuale massima di airtime", "repeater_dutyCyclePercent": "{percent}%", "@repeater_dutyCyclePercent": { "placeholders": { @@ -1170,12 +1235,12 @@ "repeater_ownerInfo": "Informazioni sull'operatore", "repeater_ownerInfoHelper": "Metadati pubblici per questo ripetitore", "repeater_refreshOwnerInfo": "Aggiorna le informazioni sull'operatore", - "repeater_floodMax": "Massimo numero di salti in caso di inondazione", + "repeater_floodMax": "Numero massimo di salti in flood", "repeater_floodMaxHelper": "Numero massimo di pacchetti che un flusso può attraversare (0-64)", "repeater_advancedSettings": "Avanzato", "repeater_advancedSettingsSubtitle": "Manopole di regolazione per operatori esperti", "repeater_pathHashMode": "Modalità di hashing del percorso", - "repeater_pathHashModeHelper": "Byte utilizzati per codificare l'ID di questo ripetitore nei tag per il rilevamento del percorso/loop. 0=1 byte (256 ID, fino a 64 salti), 1=2 byte (65.000 ID, fino a 32 salti), 2=3 byte (16 milioni di ID, fino a 21 salti). Le versioni 1.13 e precedenti utilizzano percorsi multi-byte: è necessario attivare la rete prima di utilizzare questa funzionalità (a partire dalla versione 1.14).", + "repeater_pathHashModeHelper": "Byte utilizzati per codificare l'ID di questo ripetitore nei tag di percorso flood/rilevamento loop. 0=1 byte (256 ID, fino a 64 salti), 1=2 byte (65.000 ID, fino a 32 salti), 2=3 byte (16 milioni di ID, fino a 21 salti). Il firmware precedente alla v1.14 usava sempre percorsi a 1 byte; v1.14 e versioni successive possono essere configurate per percorsi a 2 o 3 byte.", "repeater_txDelay": "Ritardo a Flood, TX", "repeater_txDelayHelper": "Riassegnare lo spazio tra i pacchetti per gestire il traffico intenso, come un moltiplicatore del tempo di trasmissione (da 0 a 2, valore predefinito 0,5). Un valore più alto significa meno collisioni, ma una trasmissione più lenta.", "repeater_directTxDelay": "Ritardo diretto TX", @@ -1185,8 +1250,8 @@ "repeater_agcResetInterval": "Intervallo di ripristino di AGC", "repeater_agcResetIntervalHelper": "Con quale frequenza è necessario resettare il controllo automatico del guadagno per ripristinare il funzionamento dopo un'interruzione. Impostare su secondi, ridotti a multipli di 4. Disattivare la reimpostazione periodica.", "repeater_actionsTitle": "Azioni", - "repeater_sendAdvert": "Inviare annuncio relativo alle inondazioni", - "repeater_sendAdvertSubtitle": "Trasmettere un annuncio pubblicitario relativo alle inondazioni attraverso la rete.", + "repeater_sendAdvert": "Invia annuncio flood", + "repeater_sendAdvertSubtitle": "Trasmettere un annuncio flood attraverso la rete.", "repeater_sendAdvertZeroHop": "Inviare un annuncio senza intermediari", "repeater_sendAdvertZeroHopSubtitle": "Trasmettere un annuncio a un solo hop (senza ripetitori)", "repeater_clockSync": "Sincronizza l'orologio ora", @@ -1275,7 +1340,7 @@ "repeater_cliQuickVersion": "Versione", "repeater_cliQuickAdvertise": "Annuncia", "repeater_cliQuickClock": "Orologio", - "repeater_cliHelpAdvert": "Invia un pacchetto pubblicitario", + "repeater_cliHelpAdvert": "Invia un pacchetto di annuncio", "repeater_cliHelpReboot": "Riavvia il dispositivo. (nota, potresti ottenere 'Timeout' che è normale)", "repeater_cliHelpClock": "Mostra l'ora corrente per l'orologio di ciascun dispositivo.", "repeater_cliHelpPassword": "Imposta una nuova password di amministratore per il dispositivo.", @@ -1285,16 +1350,16 @@ "repeater_cliHelpSetTx": "Imposta la potenza di trasmissione LoRa in dBm (riavvia per applicare).", "repeater_cliHelpSetRepeat": "Abilita o disabilita il ruolo del ripetitore per questo nodo.", "repeater_cliHelpSetAllowReadOnly": "(Server stanza) Se 'on', allora l'accesso con una password vuota sarà consentito, ma non sarà possibile pubblicare nella stanza. (solo lettura).", - "repeater_cliHelpSetFloodMax": "Imposta il numero massimo di salti per i pacchetti di inondazione in entrata (se >= max, il pacchetto non viene inoltrato)", + "repeater_cliHelpSetFloodMax": "Imposta il numero massimo di salti per i pacchetti flood in entrata (se >= max, il pacchetto non viene inoltrato)", "repeater_cliHelpSetIntThresh": "Imposta il Limite di Interferenza (in dB). Il valore predefinito è 14. Imposta su 0 per disabilitare il rilevamento delle interferenze del canale.", "repeater_cliHelpSetAgcResetInterval": "Imposta l'intervallo per resettare il controllore Automatico del Guadagno. Imposta su 0 per disabilitare.", "repeater_cliHelpSetMultiAcks": "Abilita o disabilita la funzione 'double ACKs'.", - "repeater_cliHelpSetAdvertInterval": "Imposta l'intervallo del timer in minuti per inviare un pacchetto di pubblicità locale (senza salto). Imposta su 0 per disabilitare.", - "repeater_cliHelpSetFloodAdvertInterval": "Imposta l'intervallo del timer in ore per inviare un pacchetto pubblicitario di massa. Imposta su 0 per disabilitare.", + "repeater_cliHelpSetAdvertInterval": "Imposta l'intervallo del timer in minuti per inviare un pacchetto di annuncio locale (senza salto). Imposta su 0 per disabilitare.", + "repeater_cliHelpSetFloodAdvertInterval": "Imposta l'intervallo del timer in ore per inviare un pacchetto di annuncio flood. Imposta su 0 per disabilitare.", "repeater_cliHelpSetGuestPassword": "Imposta/aggiorna la password dell'ospite. (per ripetitori, gli accessi degli ospiti possono inviare la richiesta \"Get Stats\")", "repeater_cliHelpSetName": "Imposta il nome dell'annuncio.", - "repeater_cliHelpSetLat": "Imposta la latitudine della mappa pubblicitaria. (gradi decimali)", - "repeater_cliHelpSetLon": "Imposta la longitudine della mappa pubblicitaria. (gradi decimali)", + "repeater_cliHelpSetLat": "Imposta la latitudine della mappa dell'annuncio. (gradi decimali)", + "repeater_cliHelpSetLon": "Imposta la longitudine della mappa dell'annuncio. (gradi decimali)", "repeater_cliHelpSetRadio": "Imposta completamente nuovi parametri radio e li salva nelle preferenze. Richiede un comando \"reboot\" per l'applicazione.", "repeater_cliHelpSetRxDelay": "Impostazioni (experimental) base (deve essere > 1 per l'effetto) per applicare un leggero ritardo ai pacchetti ricevuti, in base alla forza del segnale/punteggio. Imposta a 0 per disabilitare.", "repeater_cliHelpSetTxDelay": "Imposta un fattore moltiplicativo sul tempo di trasmissione dei pacchetti in modalità flood e su un sistema a slot casuali, per ritardarne l'inoltro (riducendo la probabilità di collisioni).", @@ -1313,7 +1378,7 @@ "repeater_cliHelpLogErase": "Elimina i log del pacchetto dal file system.", "repeater_cliHelpNeighbors": "Mostra un elenco di altri nodi repeater ricevuti tramite annunci zero-hop. Ogni riga è id-prefisso-esadecimale:timestamp:snr-volte-4", "repeater_cliHelpNeighborRemove": "Rimuove la prima corrispondenza in base al prefisso (esadecimale) della pubkey, dalla lista dei vicini.", - "repeater_cliHelpRegion": "(solo serie) Elenca tutte le regioni definite e le autorizzazioni di allagamento correnti.", + "repeater_cliHelpRegion": "(solo serie) Elenca tutte le regioni definite e le autorizzazioni flood correnti.", "repeater_cliHelpRegionLoad": "NOTA: questo è un'invocazione multi-comando speciale. Ogni comando successivo è un nome di regione (indentato con spazi per indicare la gerarchia parentale, con almeno uno spazio). Terminata inviando una riga vuota/comando.", "repeater_cliHelpRegionGet": "Cerca la regione con il prefisso del nome dato (o \"\" per l'ambito globale). Risponde con \"-> nome-regione (nome-genitore) 'F'\"", "repeater_cliHelpRegionPut": "Aggiunge o aggiorna una definizione di regione con il nome specificato.", @@ -1673,7 +1738,6 @@ "settings_locationGPSEnableSubtitle": "Abilita l'aggiornamento automatico della posizione tramite GPS.", "settings_locationIntervalSec": "Intervallo GPS (Secondi)", "settings_locationIntervalInvalid": "L'intervallo deve essere di almeno 60 secondi e inferiore a 86400 secondi.", - "contacts_manageRoom": "Gestisci server stanza", "room_management": "Gestione del Server di Camera", "@community_joinConfirmation": { "placeholders": { @@ -1837,10 +1901,15 @@ "appSettings_enableMessageTracing": "Abilita tracciamento messaggi", "appSettings_enableMessageTracingSubtitle": "Mostra metadati dettagliati su instradamento e tempi per i messaggi", "contacts_zeroHopAdvert": "Annuncio Zero Hop", - "contacts_floodAdvert": "Annuncio alluvionale", + "contacts_floodAdvert": "Annuncio Flood", "contacts_copyAdvertToClipboard": "Copia Annuncio negli Appunti", "contacts_addContactFromClipboard": "Aggiungere contatto dalla clipboard", "contacts_clipboardEmpty": "La clipboard è vuota.", + "contacts_scanQrCode": "Scansiona codice QR", + "contacts_scanQrInstructions": "Inquadra un codice QR di un contatto MeshCore", + "contacts_qrFromGallery": "Scansiona QR dalla galleria", + "contacts_noQrCodeFound": "Nessun codice QR trovato nell'immagine selezionata.", + "contacts_qrGalleryFailed": "Impossibile aprire la galleria.", "contacts_ShareContact": "Copia contatto negli Appunti", "contacts_contactImported": "Il contatto è stato importato.", "contacts_contactImportFailed": "Contatto non importato con successo.", @@ -1883,7 +1952,6 @@ } }, "notification_receivedNewMessage": "Nuovo messaggio ricevuto", - "notification_receivedNewMessage": "Nuovo messaggio ricevuto", "settings_gpxExportRepeaters": "Esporta ripetitori / server di stanza in GPX", "settings_gpxExportContacts": "Esporta compagni in GPX", "settings_gpxExportSuccess": "Esportazione del file GPX completata con successo.", @@ -1899,7 +1967,7 @@ "settings_gpxExportAllContacts": "Tutte le posizioni dei contatti", "settings_gpxExportShareText": "Dati mappa esportati da meshcore-open", "settings_gpxExportShareSubject": "meshcore-open esportazione dati mappa GPX", - "pathTrace_someHopsNoLocation": "Uno o più hop non hanno una posizione!", + "pathTrace_someHopsNoLocation": "Uno o più salti non hanno una posizione!", "map_removeLast": "Rimuovi ultimo", "map_pathTraceCancelled": "Tracciamento del percorso annullato.", "pathTrace_clearTooltip": "Cancella percorso", @@ -2058,52 +2126,7 @@ "listFilter_addToFavorites": "Aggiungi ai preferiti", "listFilter_removeFromFavorites": "Rimuovi dai preferiti", "listFilter_favorites": "Preferiti", - "@contacts_searchFavorites": { - "placeholders": { - "number": { - "type": "int" - }, - "str": { - "type": "String" - } - } - }, - "@contacts_searchUsers": { - "placeholders": { - "number": { - "type": "int" - }, - "str": { - "type": "String" - } - } - }, - "@contacts_searchRepeaters": { - "placeholders": { - "number": { - "type": "int" - }, - "str": { - "type": "String" - } - } - }, - "@contacts_searchRoomServers": { - "placeholders": { - "number": { - "type": "int" - }, - "str": { - "type": "String" - } - } - }, - "contacts_searchUsers": "Cerca {number}{str} utenti...", - "contacts_searchContactsNoNumber": "Cerca contatti...", - "contacts_searchFavorites": "Cerca {number}{str} preferiti...", "contacts_unread": "Non letti", - "contacts_searchRepeaters": "Cerca {number}{str} ripetitori...", - "contacts_searchRoomServers": "Cerca {number}{str} server stanza...", "contactsSettings_title": "Impostazioni dei contatti", "settings_contactSettings": "Impostazioni di contatto", "contactsSettings_otherTitle": "Altre impostazioni relative ai contatti", @@ -2207,6 +2230,8 @@ "settings_telemetryEnvironmentMode": "Modalità di ambiente di telemetria", "settings_advertLocation": "Posizione dell'annuncio", "settings_advertLocationSubtitle": "Includi la posizione nell'annuncio", + "settings_autoZeroHopAdvertOnGpsUpdate": "Annuncio zero-hop automatico all'aggiornamento GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Quando la posizione GPS cambia, invia un annuncio zero-hop (richiede la posizione nell'annuncio).", "settings_privacy": "Impostazioni sulla privacy", "settings_denyAll": "Negare tutto", "settings_privacySubtitle": "Controlla le informazioni che vengono condivise.", @@ -2407,7 +2432,7 @@ "repeater_cliHelpGetAgcResetInterval": "Indica l'intervallo di reset dell'AGC in secondi.", "repeater_cliHelpGetMultiAcks": "Indica se la modalità \"ACK doppio\" è attiva (1) o disattivata (0).", "repeater_cliHelpGetAllowReadOnly": "Indica se è consentito l'accesso in sola lettura per gli ospiti.", - "repeater_cliHelpGetAdvertInterval": "Indica l'intervallo pubblicitario locale in minuti.", + "repeater_cliHelpGetAdvertInterval": "Indica l'intervallo di annuncio locale in minuti.", "repeater_cliHelpGetFloodAdvertInterval": "Indica l'intervallo dell'annuncio flood, espresso in ore.", "repeater_cliHelpGetGuestPassword": "Visualizza la password del guest configurata.", "repeater_cliHelpGetLat": "Mostra la latitudine configurata.", @@ -2721,5 +2746,259 @@ "pathMap_noLocation": "Nessuna posizione", "pathMap_followPacket": "Blocca la vista sul pacchetto", "pathMap_unfollowPacket": "Sblocca la vista dal pacchetto", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regioni", + "settings_regionSettingsSubtitle": "Gestione delle regioni salvate", + "settings_regionManagement_screenTitle": "Gestione Regionale", + "settings_regionNameHint": "Inserisci il nome della regione", + "settings_regionAddRegion": "Aggiungi regione", + "settings_regionFetchRegions": "Recupera le regioni dai ripetitori", + "settings_regionFetchRegionsFail": "Non sono state trovate regioni", + "settings_regionFetchRegionsAlreadyExists": "Questa regione è già stata aggiunta", + "settings_regionName": "Nome della Regione", + "settings_regionDeleted": "Regione cancellata", + "settings_deleteRegion": "Elimina Regione", + "settings_deleteRegionConfirm": "Rimuovere \"{region}\" dalla lista delle regioni?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 byte", + "repeater_pathHashModeOption2": "2 - 3 byte", + "repeater_pathHashModeOption3": "3 - 4 byte", + "appSettings_batteryLipoHv": "LiPo HV (3,0-4,35 V)", + "channels_regionSetTo": "Regione: {region}", + "channels_regionNotSet": "Regione: nessuna", + "channels_regionSelect_Title": "Scegli una regione", + "channels_clearRegion": "Zona chiara", + "chat_sendImageLora": "Invia immagine tramite MeshCore", + "chat_imagePickFailed": "Non sono riuscito ad aprire quell'immagine", + "chat_receivedGif": "Ricevuto un GIF", + "repeater_keySettings": "Cambia le Chiavi di Identità", + "repeater_keySettingsSubtitle": "Cambia la coppia di chiavi pubblica/privata", + "repeater_prvKey": "Chiave privata", + "repeater_prvKeyHelper": "Una nuova chiave privata per il ripetitore, una stringa esadecimale di 128 caratteri.", + "repeater_generatePrvKey": "Genera una coppia di chiavi casuale", + "repeater_stopGeneratingPrvKey": "Interrompi la ricerca della coppia di chiavi", + "repeater_pubKey": "Chiave pubblica", + "repeater_pubKeyHelper": "Questa è la chiave pubblica che accompagna la chiave privata generata. Non è possibile impostarla direttamente.", + "repeater_pubKeyPrefix": "Prefisso desiderato", + "repeater_pubKeyPrefixHelper": "Trova una chiave pubblica che inizia con queste cifre esadecimali. Tentativi necessari previsti: {tries}.", + "imageMessages_enableTitle": "Messaggi con immagini", + "imageMessages_enableSubtitle": "Invia le immagini tramite la mesh. È necessario scaricare il modello dell'immagine una tantum.", + "imageMessages_modelSectionTitle": "Modello di immagine", + "imageMessages_downloadModel": "Scarica", + "imageMessages_cancelDownload": "Annullare", + "imageMessages_removeModel": "Rimuovi il modello", + "imageMessages_modelReady": "Pronto", + "imageMessages_modelNotPublished": "Non pubblicato ancora — questa versione non può scaricarlo.", + "imageMessages_downloadFailed": "Il modello di immagine non può essere scaricato.", + "imageMessages_autoProcessTitle": "Elabora automaticamente le immagini", + "imageMessages_autoProcessSubtitle": "Ricostruisci ogni immagine non appena arriva. Utilizza circa 2 GB di memoria per un secondo ogni volta; disattiva la ricostruzione con un semplice tocco.", + "imageSend_title": "Invia immagine", + "imageSend_cropNote": "Ridimensionato a 512 × 512 · rapporto d'aspetto non conservato", + "imageSend_originalSize": "Traduzione:\n\nOriginal text:\n\nPlease translate the following English text into Italian:\n\nOriginal text:\n\n(No original English text provided)", + "imageSend_onAirSize": "In onda", + "imageSend_quality": "Qualità", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Alto", + "imageSend_packetsLabel": "Pacchetti", + "imageSend_airtimeLabel": "Tempo in onda", + "imageSend_sizeLabel": "Carico utile", + "imageSend_packetsCount": "{count} {count, plural, =1{pacchetto} other{pacchetti}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Impostazioni radio sconosciute", + "imageSend_radioUnknownBody": "Collegati a un dispositivo in modo che si possa calcolare l'orario di trasmissione.", + "imageSend_longSendTitle": "Lunga trasmissione", + "imageSend_longSendBody": "Questo manterrà il canale per circa {duration}.", + "imageSend_floodNote": "Instradamento flood: ogni ripetitore nel raggio ritrasmette ogni pacchetto, quindi il canale rimane occupato più a lungo.", + "imageSend_parityTitle": "Pacchetto di recupero", + "imageSend_paritySubtitle": "Un pacchetto aggiuntivo. I messaggi di gruppo non vengono riconosciuti, quindi questo permette al destinatario di ricostruire l'immagine se un singolo pacchetto viene perso.", + "imageSend_send": "Invia", + "imageSend_cancel": "Annullare", + "imageSend_encodeFailed": "Questa immagine non può essere codificata.", + "imageSend_codecDownloading": "Il modello di immagine sta ancora scaricando.", + "imageSend_codecUnavailable": "L'invio di immagini non è disponibile su questo dispositivo.", + "imageSend_codecDisabled": "I messaggi immagine sono disattivati nelle impostazioni.", + "imageSend_deviceUnsupported": "Questa radio non può inviare pacchetti di immagini. Collegare un dispositivo con firmware companion versione 13 o successiva.", + "imageSend_directMessagesUnsupported": "Le immagini viaggiano come dati di gruppo, quindi possono essere inviate solo a un canale — non tramite messaggio diretto.", + "imageSend_tooLarge": "Quella immagine è stata codificata in un numero di pacchetti superiore a quello consentito dal formato mesh.", + "imageSend_sentConfirmation": "Immagine inviata come {count} {count, plural, =1{pacchetto} other{pacchetti}}.", + "imageSend_sendFailed": "L'immagine non può essere inviata: {error}", + "imageSend_sendingProgress": "Invio immagine — pacchetto {sent} di {total}", + "receivedImage_senderPrefix": "Nodo {prefix}", + "receivedImage_incoming": "{received} di {total} pacchetti", + "receivedImage_queued": "In attesa di decodificare", + "receivedImage_tapToDecode": "Tocca per decodificare", + "receivedImage_decoding": "Ricostruire… circa 1 s", + "receivedImage_incomplete": "Immagine incompleta — {received} su {total} pacchetti ricevuti", + "receivedImage_corrupt": "L'immagine non potrebbe essere ricostruita", + "receivedImage_decoderMissing": "Immagine ricevuta — decodifica dell'immagine non funzionante", + "receivedImage_evicted": "Immagine non più memorizzata", + "receivedImage_retry": "Prova ancora", + "receivedImage_decodeAgain": "Decodifica di nuovo", + "receivedImage_openSettings": "Imposta", + "receivedImage_tapToProcess": "Premi per elaborare", + "receivedImage_awaiting": "{bytes} byte · {packets} {packets, plural, =1{pacchetto} other{pacchetti}}", + "imageSend_secondsValue": "{seconds} secondi", + "imageSend_minutesSecondsValue": "{minutes} min {seconds} s", + "channels_noFreeSlots": "Tutti gli slot dei canali sono in uso", + "chat_longMessageRetryNote": "Oltre 158 byte: inviato al massimo {count} volte", + "reaction_report": "Reazioni con Emoji", + "repeater_bridgeNote": "Disponibile solo su firmware compilato con un bridge (RS232 o ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Mostra il numero massimo di salti per gli annunci flood.", + "repeater_cliHelpGetFloodMaxUnscoped": "Mostra il numero massimo di salti per i pacchetti flood senza ambito regionale.", + "repeater_cliHelpGetRadioFemRxGain": "Mostra se il guadagno RX del modulo frontend LoRa è attivo.", + "repeater_cliHelpGetRadioFemTxGain": "Mostra se il guadagno TX del modulo frontend LoRa è attivo.", + "repeater_cliHelpRegionDef": "Definisce una catena di regioni in un solo comando: ogni nome viene aggiunto sotto il precedente; \"name,parent\" aggiunge il nome e continua sotto il padre indicato. Risponde con l'elenco delle regioni.", + "repeater_cliHelpSetFloodMaxAdvert": "Imposta il numero massimo di salti per l'inoltro degli annunci flood (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Imposta il numero massimo di salti per l'inoltro dei pacchetti flood privi di ambito regionale (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Attiva o disattiva il guadagno RX (LNA) del modulo frontend LoRa. Le schede prive di questo modulo rispondono \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Attiva o disattiva il guadagno TX (PA) del modulo frontend LoRa. Le schede prive di questo modulo rispondono \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Modalità di caricamento regioni: invia un nome di regione per riga, indentato con spazi sotto la sua regione padre (aggiungi F dopo il nome per consentire il flood). Le righe non ricevono risposta. Invia una riga vuota per terminare, poi \"region save\" per salvare il risultato.", + "repeater_cliRegionLoadEnd": "(fine caricamento regioni)", + "repeater_cliRegionLoadHint": "Riga di regione, o vuota per terminare", + "repeater_frequencyInvalid": "Frequenza non valida (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Errori di ricezione", + "repeater_txPowerRangeHelper": "Da -9 a 30 dBm", + "room_postsPushed": "Post Inviati", + "room_postsStored": "Post", + "settings_radioSettingsNotApplied": "La radio non ha applicato queste impostazioni", + "urlImage_enable": "Abilita immagini URL", + "urlImage_possible": "Possibile immagine URL; abilitala nelle Impostazioni.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 1c8b728f..d965909b 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -28,11 +28,11 @@ "common_enable": "有効にする", "common_disable": "無効にする", "common_undo": "元に戻す", - "messageStatus_sent": "送信済み", - "messageStatus_delivered": "配信済み", - "messageStatus_pending": "送信中", - "messageStatus_failed": "送信に失敗", - "messageStatus_repeated": "重複受信", + "messageStatus_sent": "送信", + "messageStatus_delivered": "配達", + "messageStatus_pending": "送信", + "messageStatus_failed": "送信できませんでした", + "messageStatus_repeated": "何度も聞いた", "common_autoRefresh": "自動更新", "common_interval": "間隔", "common_reboot": "再起動", @@ -167,19 +167,21 @@ "settings_locationIntervalInvalid": "間隔は少なくとも60秒で、86400秒未満でなければなりません。", "settings_latitude": "緯度", "settings_longitude": "経度", + "settings_autoZeroHopAdvertOnGpsUpdate": "GPS更新時にゼロホップアドバートを自動送信", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "GPS位置が変化したときにゼロホップアドバートを送信します(アドバートへの位置情報の含有が必要)。", "settings_contactSettings": "連絡先設定", "settings_contactSettingsSubtitle": "連絡先の追加方法に関する設定", "settings_privacyMode": "プライバシーモード", - "settings_privacyModeSubtitle": "広告に名前や位置を表示しない", - "settings_privacyModeToggle": "プライバシーモードを有効にすると、広告に表示される名前と位置を非表示にします。", + "settings_privacyModeSubtitle": "アドバートに名前や位置を表示しない", + "settings_privacyModeToggle": "プライバシーモードを有効にすると、アドバートに表示される名前と位置を非表示にします。", "settings_privacyModeEnabled": "プライバシーモードが有効になっています", "settings_privacyModeDisabled": "プライバシーモードは無効です", "settings_actions": "操作", "settings_deleteAllPaths": "すべての経路を削除", "settings_deleteAllPathsSubtitle": "連絡先からすべての経路データを消去します。", - "settings_sendAdvertisement": "広告を送信", + "settings_sendAdvertisement": "アドバートを送信", "settings_sendAdvertisementSubtitle": "現在の存在を送信します", - "settings_advertisementSent": "広告を送信しました", + "settings_advertisementSent": "アドバートを送信しました", "settings_syncTime": "時刻を同期", "settings_syncTimeSubtitle": "デバイスの時刻をスマートフォンに合わせます", "settings_timeSynchronized": "時刻を同期しました", @@ -260,7 +262,7 @@ "appSettings_enableMessageTracingSubtitle": "メッセージの詳細な経路とタイミングのメタデータを表示します", "appSettings_notifications": "通知", "appSettings_enableNotifications": "通知を有効にする", - "appSettings_enableNotificationsSubtitle": "メッセージや広告の通知を受け取ります", + "appSettings_enableNotificationsSubtitle": "メッセージやアドバートの通知を受け取ります", "appSettings_notificationPermissionDenied": "通知の許可が拒否されました", "appSettings_notificationsEnabled": "通知機能が有効になっています", "appSettings_notificationsDisabled": "通知が無効化されています", @@ -268,7 +270,7 @@ "appSettings_messageNotificationsSubtitle": "新しいメッセージを受信した際に、通知を表示する", "appSettings_channelMessageNotifications": "チャネルメッセージの通知", "appSettings_channelMessageNotificationsSubtitle": "チャンネルからのメッセージを受信した際に、通知を表示する", - "appSettings_advertisementNotifications": "広告通知", + "appSettings_advertisementNotifications": "アドバート通知", "appSettings_advertisementNotificationsSubtitle": "新しいノードが発見された場合に通知を表示する", "appSettings_messaging": "メッセージング", "appSettings_clearPathOnMaxRetry": "最大再試行時に経路を消去", @@ -338,6 +340,19 @@ "appSettings_last6Hours": "過去6時間", "appSettings_last24Hours": "過去24時間", "appSettings_lastWeek": "過去1週間", + "appSettings_rasterTileSource": "ラスタタイルのソース", + "appSettings_stadiaEndpoint": "Stadia エンドポイント", + "appSettings_stadiaApiKey": "Stadia API キー", + "appSettings_stadiaApiKeyRequired": "Stadia Maps の利用に必要です", + "appSettings_stadiaApiKeyConfigured": "設定済み: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Stadia Maps の API キーを入力してください。このアプリはラスタタイルの取得に使用します。", "appSettings_offlineMapCache": "オフライン地図キャッシュ", "appSettings_unitsTitle": "単位", "appSettings_unitsMetric": "メートル法 (m / km)", @@ -361,7 +376,7 @@ "appSettings_appDebugLoggingDisabled": "アプリのデバッグログは無効です", "contacts_title": "連絡先", "contacts_noContacts": "まだ連絡先はありません", - "contacts_contactsWillAppear": "デバイスが広告を送信すると連絡先が表示されます", + "contacts_contactsWillAppear": "デバイスがアドバートを送信すると連絡先が表示されます", "contacts_unread": "未読", "contacts_searchContactsNoNumber": "連絡先を検索...", "contacts_searchContacts": "連絡先を検索... {number} 件の {str}", @@ -660,6 +675,7 @@ } } }, + "chat_selectSendAction": "送信アクションを選択", "chat_sendGif": "GIF を送信", "chat_reply": "返信", "chat_addReaction": "リアクションを追加", @@ -970,6 +986,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1093,7 +1159,7 @@ } } }, - "path_tooLong": "経路が長すぎる。最大64回のジャンプのみ許可。", + "path_tooLong": "経路が長すぎる。最大64回のホップのみ許可。", "path_setPath": "パスを設定", "repeater_management": "リピータ管理", "room_management": "ルームサーバーの管理", @@ -1230,9 +1296,9 @@ "repeater_guestAccess": "ゲストへのアクセス", "repeater_guestAccessSubtitle": "ゲストへの読み取り専用アクセスを許可する", "repeater_privacyMode": "プライバシーモード", - "repeater_privacyModeSubtitle": "広告に名前/場所を記載しない", - "repeater_advertisementSettings": "広告設定", - "repeater_localAdvertInterval": "地域広告掲載期間", + "repeater_privacyModeSubtitle": "アドバートに名前/場所を記載しない", + "repeater_advertisementSettings": "アドバート設定", + "repeater_localAdvertInterval": "地域アドバート掲載期間", "repeater_localAdvertIntervalMinutes": "{minutes} 分", "@repeater_localAdvertIntervalMinutes": { "placeholders": { @@ -1241,7 +1307,7 @@ } } }, - "repeater_floodAdvertInterval": "フラッドに関する広告の表示間隔", + "repeater_floodAdvertInterval": "フラッドに関するアドバートの表示間隔", "repeater_floodAdvertIntervalHours": "{hours} 時間", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1250,7 +1316,7 @@ } } }, - "repeater_encryptedAdvertInterval": "暗号化された広告表示間", + "repeater_encryptedAdvertInterval": "暗号化されたアドバート表示間", "repeater_dangerZone": "危険区域", "repeater_rebootRepeater": "リピータを再起動する", "repeater_rebootRepeaterSubtitle": "リピータデバイスを再起動する", @@ -1321,10 +1387,10 @@ "repeater_agcResetInterval": "AGCのリセット間隔", "repeater_agcResetIntervalHelper": "ラジオの自動ゲイン制御をリセットする頻度について:ゲインが固定状態になった場合に、回復するために、何度リセットするかを設定します。4の倍数でリセットする場合、0を設定すると、定期的なリセットは停止します。", "repeater_actionsTitle": "操作", - "repeater_sendAdvert": "フラッド広告を送信", - "repeater_sendAdvertSubtitle": "ネットワーク全体にフラッド広告をブロードキャストします", - "repeater_sendAdvertZeroHop": "ゼロホップ広告を送信", - "repeater_sendAdvertZeroHopSubtitle": "1 ホップ広告を送信します(リピータなし)", + "repeater_sendAdvert": "フラッドアドバートを送信", + "repeater_sendAdvertSubtitle": "ネットワーク全体にフラッドアドバートをブロードキャストします", + "repeater_sendAdvertZeroHop": "ゼロホップアドバートを送信", + "repeater_sendAdvertZeroHopSubtitle": "1 ホップアドバートを送信します(リピータなし)", "repeater_clockSync": "時刻を同期", "repeater_clockSyncSubtitle": "スマートフォンの時刻をデバイスに設定します", "repeater_actionSucceeded": "{action} が成功しました", @@ -1409,9 +1475,9 @@ "repeater_cliQuickGetTx": "TX を取得", "repeater_cliQuickNeighbors": "近隣", "repeater_cliQuickVersion": "バージョン", - "repeater_cliQuickAdvertise": "広告送信", + "repeater_cliQuickAdvertise": "アドバート送信", "repeater_cliQuickClock": "時刻", - "repeater_cliHelpAdvert": "広告用資料を送る", + "repeater_cliHelpAdvert": "アドバートパケットを送信します", "repeater_cliHelpReboot": "デバイスを再起動します。(注:通常は「タイムアウト」が表示されますが、これは正常です)", "repeater_cliHelpClock": "各デバイスの時計で現在の時刻を表示します。", "repeater_cliHelpPassword": "デバイス用の新しい管理者パスワードを設定します。", @@ -1425,15 +1491,15 @@ "repeater_cliHelpSetIntThresh": "干渉閾値を設定します(dB単位)。デフォルト値は14です。0に設定すると、チャンネル間の干渉を検出する機能を無効にします。", "repeater_cliHelpSetAgcResetInterval": "オートゲインコントローラーのリセット間隔を設定します。 0 に設定すると無効化されます。", "repeater_cliHelpSetMultiAcks": "「ダブルACK」機能の有効化または無効化を可能にします。", - "repeater_cliHelpSetAdvertInterval": "ローカル(ホップなし)の広告パケットを送信する間隔を分単位で設定します。 0 に設定すると、機能を無効にします。", - "repeater_cliHelpSetFloodAdvertInterval": "フラッド広告の送信間隔を時間単位で設定します。0に設定すると、送信を停止します。", + "repeater_cliHelpSetAdvertInterval": "ローカル(ホップなし)のアドバートパケットを送信する間隔を分単位で設定します。 0 に設定すると、機能を無効にします。", + "repeater_cliHelpSetFloodAdvertInterval": "フラッドアドバートの送信間隔を時間単位で設定します。0に設定すると、送信を停止します。", "repeater_cliHelpSetGuestPassword": "ゲストのパスワードを設定/更新します。(繰り返し利用の場合、ゲストのログインは「統計情報を取得」のリクエストを送信できます)", - "repeater_cliHelpSetName": "広告の名前を設定します。", - "repeater_cliHelpSetLat": "広告表示の地図の緯度を設定します。(度分秒表記)", - "repeater_cliHelpSetLon": "広告表示の地図の経度を設定します。(度数、分)", + "repeater_cliHelpSetName": "アドバートの名前を設定します。", + "repeater_cliHelpSetLat": "アドバート表示の地図の緯度を設定します。(度分秒表記)", + "repeater_cliHelpSetLon": "アドバート表示の地図の経度を設定します。(度数、分)", "repeater_cliHelpSetRadio": "完全に新しいラジオパラメータを設定し、設定として保存します。適用するには、「再起動」コマンドが必要です。", "repeater_cliHelpSetRxDelay": "(実験用)遅延時間を設定するためのベース(1以上の値に設定する必要)\n受信パケットに対して、信号強度/スコアに基づいてわずかな遅延を適用します。 0に設定すると無効化されます。", - "repeater_cliHelpSetTxDelay": "時間経過に応じた「フラッシュモード」パケットの送信遅延を設定します。この遅延は、ランダムなスロットシステムと組み合わせて使用され、パケットの衝突を減らすことを目的としています。", + "repeater_cliHelpSetTxDelay": "時間経過に応じた「フラッドモード」パケットの送信遅延を設定します。この遅延は、ランダムなスロットシステムと組み合わせて使用され、パケットの衝突を減らすことを目的としています。", "repeater_cliHelpSetDirectTxDelay": "txdelayと同様ですが、ダイレクトモードのパケット転送にランダムな遅延を適用する場合に使用します。", "repeater_cliHelpSetBridgeEnabled": "ブリッジを有効化/無効化", "repeater_cliHelpSetBridgeDelay": "パケットを再送信する前に、遅延を設定する。", @@ -1447,7 +1513,7 @@ "repeater_cliHelpLogStart": "パケットのログ記録を開始し、ファイルシステムに保存する。", "repeater_cliHelpLogStop": "ファイルシステムへのパケットログの記録を停止する。", "repeater_cliHelpLogErase": "ファイルシステムからパケットログを削除する。", - "repeater_cliHelpNeighbors": "ゼロホップ広告を通じて受信した他のリピータノードの一覧を表示します。各行は、IDプレフィックス(16進数)、タイムスタンプ、SNR(シグナル強度)の情報を4つ含みます。", + "repeater_cliHelpNeighbors": "ゼロホップアドバートを通じて受信した他のリピータノードの一覧を表示します。各行は、IDプレフィックス(16進数)、タイムスタンプ、SNR(シグナル強度)の情報を4つ含みます。", "repeater_cliHelpNeighborRemove": "隣接リストから、最初に一致するエントリ(pubkeyプレフィックス(16進数)で特定)を削除します。", "repeater_cliHelpRegion": "(特定のシリーズのみ)定義されたすべての地域と、現在のフラッド許可状況を一覧表示します。", "repeater_cliHelpRegionLoad": "注:これは特殊な複数コマンドの呼び出しです。その後の各コマンドは、地域名であり(スペースを使用して親階層を示し、少なくとも1つのスペースが必要です)、空行/コマンドで終了します。", @@ -1463,8 +1529,8 @@ "repeater_cliHelpGpsOnOff": "GPS の電源状態を切り替えます。", "repeater_cliHelpGpsSync": "ノードの時刻をGPSクロックと同期する。", "repeater_cliHelpGpsSetLoc": "ノードの位置をGPS座標に設定し、設定を保存する。", - "repeater_cliHelpGpsAdvert": "ノードの広告設定における場所情報の指定:\n- none: 広告に場所情報を含まない\n- share: GPS位置情報を共有 (SensorManagerから取得)\n- prefs: プリファレンスに保存された場所情報を広告", - "repeater_cliHelpGpsAdvertSet": "場所に関する広告設定を行います。", + "repeater_cliHelpGpsAdvert": "ノードのアドバート設定における場所情報の指定:\n- none: アドバートに場所情報を含まない\n- share: GPS位置情報を共有 (SensorManagerから取得)\n- prefs: プリファレンスに保存された場所情報をアドバートする", + "repeater_cliHelpGpsAdvertSet": "場所に関するアドバート設定を行います。", "repeater_commandsListTitle": "コマンド一覧", "repeater_commandsListNote": "注:さまざまな「set ...」コマンドには、「get ...」コマンドも存在します。", "repeater_general": "一般的な", @@ -2088,16 +2154,16 @@ "contacts_invalidAdvertFormat": "無効な連絡先情報", "contacts_contactImported": "連絡先が登録されました。", "contacts_contactImportFailed": "連絡先のインポートに失敗しました。", - "contacts_zeroHopAdvert": "ゼロホップ広告", - "contacts_floodAdvert": "フラッドに関する広告", - "contacts_copyAdvertToClipboard": "広告をクリップボードにコピー", + "contacts_zeroHopAdvert": "ゼロホップアドバート", + "contacts_floodAdvert": "フラッドアドバート", + "contacts_copyAdvertToClipboard": "アドバートをクリップボードにコピー", "contacts_addContactFromClipboard": "クリップボードから連絡先を追加する", "contacts_ShareContact": "連絡先をクリップボードにコピー", - "contacts_ShareContactZeroHop": "広告を通じて連絡先を共有する", - "contacts_zeroHopContactAdvertSent": "広告を通じて連絡先を得た。", + "contacts_ShareContactZeroHop": "アドバートを通じて連絡先を共有する", + "contacts_zeroHopContactAdvertSent": "アドバートを通じて連絡先を得た。", "contacts_zeroHopContactAdvertFailed": "連絡を送信できませんでした。", - "contacts_contactAdvertCopied": "広告がクリップボードにコピーされました。", - "contacts_contactAdvertCopyFailed": "広告のコピーがクリップボードにコピーできませんでした。", + "contacts_contactAdvertCopied": "アドバートがクリップボードにコピーされました。", + "contacts_contactAdvertCopyFailed": "アドバートのコピーがクリップボードにコピーできませんでした。", "notification_activityTitle": "メッシュコアの活動", "notification_messagesCount": "{count} {count, plural, =1{message} other{messages}}", "@notification_messagesCount": { @@ -2243,8 +2309,8 @@ "settings_telemetryBaseMode": "テレメトリ基本モード", "settings_telemetryLocationMode": "テレメトリ位置特定モード", "settings_telemetryEnvironmentMode": "テレメトリ環境モード", - "settings_advertLocation": "広告掲載場所", - "settings_advertLocationSubtitle": "広告に場所を記載してください。", + "settings_advertLocation": "アドバート位置", + "settings_advertLocationSubtitle": "アドバートに位置情報を含めてください。", "settings_telemetryModeUpdated": "テレメトリモードが更新されました", "contact_info": "連絡先", "contact_settings": "連絡設定", @@ -2334,7 +2400,7 @@ "repeater_sensors": "センサー", "repeater_cliHelpPowerOff": "デバイスをシャットダウンします。(応答は期待されていません)", "repeater_cliHelpClkReboot": "時計を既知の基準時点にリセットし、デバイスを再起動します。", - "repeater_cliHelpAdvertZeroHop": "近隣のデバイスのみに、ゼロホップの広告を送信します。", + "repeater_cliHelpAdvertZeroHop": "近隣のデバイスのみに、ゼロホップのアドバートを送信します。", "repeater_cliHelpStartOta": "サポートされているボードに対して、無線でファームウェアのアップデートを開始します。", "repeater_cliHelpTime": "デバイスのクロックを、指定されたUnixエポックの秒数に設定します。クロックは逆方向に進むことはできません。", "repeater_cliHelpBoard": "製造元の名前/ハードウェア識別子を表示します。", @@ -2345,7 +2411,7 @@ "repeater_cliHelpSetDutyCycle": "送信可能な最大デューティサイクルをパーセントで設定します(1〜100)。内部で、空き時間の要素を調整します。", "repeater_cliHelpSetPrvKey": "(シリアル番号のみ)デバイスのプライベートキーを置き換えます。適用には再起動が必要です。新しいパブリックキーを生成します。", "repeater_cliHelpSetRadioRxGain": "(SX126xのみ)高電流での使用時に、感度を向上させるために、増幅されたRXのゲインを切り替えることができます。", - "repeater_cliHelpSetOwnerInfo": "広告に記載されている所有者連絡先情報を設定します。改行には'|'を使用してください。", + "repeater_cliHelpSetOwnerInfo": "アドバートに記載されている所有者連絡先情報を設定します。改行には'|'を使用してください。", "repeater_cliHelpSetPathHashMode": "パスハッシュモードを設定します。 0 = 従来のモード、1 = 標準モード、2 = 厳格モード。ルーティングパスのマッチング方法に影響します。", "repeater_cliHelpSetLoopDetect": "ルーティングループ検出の感度を設定します:オフ、最小、中程度、または厳格。", "repeater_cliHelpSetFreq": "(シリアル設定のみ)特定の周波数のみを素早く設定できます。再起動が必要です。「ラジオ設定」を使用すると、ラジオのすべてのパラメータを設定できます。", @@ -2365,8 +2431,8 @@ "repeater_cliHelpGetAgcResetInterval": "AGCのリセット間隔を秒単位で表示します。", "repeater_cliHelpGetMultiAcks": "ダブルACKモードが有効 (1) か無効 (0) かを示す。", "repeater_cliHelpGetAllowReadOnly": "ゲストによる読み取り専用アクセスが許可されているかどうかを示す。", - "repeater_cliHelpGetAdvertInterval": "ローカル広告の時間を分単位で表示します。", - "repeater_cliHelpGetFloodAdvertInterval": "フラッドに関する広告の放送時間を時間単位で表示します。", + "repeater_cliHelpGetAdvertInterval": "ローカルアドバートの時間を分単位で表示します。", + "repeater_cliHelpGetFloodAdvertInterval": "フラッドに関するアドバートの放送時間を時間単位で表示します。", "repeater_cliHelpGetGuestPassword": "設定されたゲストパスワードを表示します。", "repeater_cliHelpGetLat": "設定された緯度を表示します。", "repeater_cliHelpGetLon": "設定された経度を表示します。", @@ -2532,13 +2598,7 @@ } } }, - "messageStatus_delivered": "配達", - "common_undo": "元に戻す", - "messageStatus_pending": "送信", - "messageStatus_sent": "送信", - "messageStatus_failed": "送信できませんでした", "contacts_moreOptions": "さらに多くの選択肢", - "messageStatus_repeated": "何度も聞いた", "contacts_searchOpen": "連絡先を検索する", "contacts_searchClose": "検索を終了", "routing_modeFlood": "フラッド", @@ -2680,5 +2740,260 @@ "pathMap_noLocation": "位置情報なし", "pathMap_followPacket": "パケットを追跡", "pathMap_unfollowPacket": "パケットの追跡を解除", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "地域", + "settings_regionSettingsSubtitle": "保存された領域の管理", + "settings_regionManagement_screenTitle": "地域管理", + "settings_regionNameHint": "地域名を入力してください", + "settings_regionAddRegion": "地域を追加", + "settings_regionFetchRegions": "リピーターからのフェッチ地域", + "settings_regionFetchRegionsFail": "地域は見つかりませんでした", + "settings_regionFetchRegionsAlreadyExists": "この地域はすでに追加されています。", + "settings_regionName": "地域名", + "settings_regionDeleted": "地域が削除されました", + "settings_deleteRegion": "地域を削除", + "settings_deleteRegionConfirm": "{region} を地域リストから削除しますか?", + "settings_infoHardware": "ハードウェア", + "settings_infoFirmware": "ファームウェア", + "repeater_pathHashModeOption0": "0 - 1バイト", + "repeater_pathHashModeOption1": "1〜2バイト", + "repeater_pathHashModeOption2": "2〜3バイト", + "repeater_pathHashModeOption3": "3〜4バイト", + "appSettings_batteryLipoHv": "リポバッテリー HV(3.0〜4.35V)", + "channels_regionSetTo": "地域:{region}", + "channels_regionNotSet": "地域:なし", + "channels_regionSelect_Title": "地域を選択する", + "channels_clearRegion": "クリアな地域", + "chat_sendImageLora": "MeshCore経由で画像を送信", + "chat_imagePickFailed": "その画像を開けませんでした", + "chat_receivedGif": "GIFを受け取りました", + "repeater_keySettings": "アイデンティティキーの変更", + "repeater_keySettingsSubtitle": "公開鍵/秘密鍵を変更する", + "repeater_prvKey": "プライベートキー", + "repeater_prvKeyHelper": "リピーター用の新しいプライベートキー。128文字の16進文字列です。", + "repeater_generatePrvKey": "ランダムな鍵ペアを生成する", + "repeater_stopGeneratingPrvKey": "キーペアの検索を中断", + "repeater_pubKey": "公開鍵", + "repeater_pubKeyHelper": "これは生成された秘密鍵に対応する公開鍵です。直接設定することはできません。", + "repeater_pubKeyPrefix": "希望する接頭辞", + "repeater_pubKeyPrefixHelper": "これらの16進数で始まる公開鍵を見つけてください。予想される試行回数: {tries}。", + "imageMessages_enableTitle": "画像メッセージを有効にする", + "imageMessages_enableSubtitle": "メッシュ経由で画像を送信してください。画像モデルを一度限りのダウンロードが必要です。", + "imageMessages_modelSectionTitle": "画像モデル", + "imageMessages_downloadModel": "ダウンロード", + "imageMessages_cancelDownload": "キャンセル", + "imageMessages_removeModel": "モデルを削除", + "imageMessages_modelReady": "準備完了", + "imageMessages_modelNotPublished": "まだ公開されていません — このビルドではダウンロードできません。", + "imageMessages_downloadFailed": "画像モデルがダウンロードできませんでした。", + "imageMessages_autoProcessTitle": "画像を自動的に処理する", + "imageMessages_autoProcessSubtitle": "画像が届き次第、すぐに再構築してください。1回あたり約2GBのメモリを使用します。タップで再構築を解除できます。", + "imageSend_title": "画像を送信", + "imageSend_cropNote": "512 × 512にリサイズされました。アスペクト比は保持されませんでした。", + "imageSend_originalSize": "原文:\nThe early morning light filtered through the curtains, casting a soft glow on the room.\n\n翻訳:\n早朝の光がカーテンをすり抜け、部屋に柔らかな光を投げかけていた。", + "imageSend_onAirSize": "放送中", + "imageSend_quality": "品質", + "imageSend_qualityStandard": "標準", + "imageSend_qualityHigh": "ハイ", + "imageSend_packetsLabel": "パケット", + "imageSend_airtimeLabel": "放送時間", + "imageSend_sizeLabel": "ペイロード", + "imageSend_packetsCount": "{count} {count, plural, =1{パケット} other{パケット}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "ラジオの設定が不明です", + "imageSend_radioUnknownBody": "放送時間の計算ができるように、デバイスに接続してください。", + "imageSend_longSendTitle": "長距離伝送", + "imageSend_longSendBody": "このチャンネルは約 {duration} 間保持されます。", + "imageSend_floodNote": "フラッドルーティング:範囲内の各リピーターが各パケットを再送信するため、チャネルはこれよりも長く占有されたままになります。", + "imageSend_parityTitle": "回復パケット", + "imageSend_paritySubtitle": "追加のパケットが1つあります。グループメッセージは確認されないため、1つのパケットが失われても受信者が画像を再構築できます。", + "imageSend_send": "送る", + "imageSend_cancel": "キャンセル", + "imageSend_encodeFailed": "この画像はエンコードできませんでした。", + "imageSend_codecDownloading": "画像モデルはまだダウンロード中です。", + "imageSend_codecUnavailable": "このデバイスでは画像送信が利用できません。", + "imageSend_codecDisabled": "設定で画像メッセージはオフになっています。", + "imageSend_deviceUnsupported": "このラジオは画像パケットを送信できません。コンパニオン ファームウェア 13 以降を実行しているデバイスを接続してください。", + "imageSend_directMessagesUnsupported": "画像はグループデータとして送信されるため、ダイレクトメッセージではなくチャンネルに送ることができます。", + "imageSend_tooLarge": "その画像は、メッシュ形式が許容するよりも多くのパケットにエンコードされています。", + "imageSend_sentConfirmation": "{count} {count, plural, =1{パケット} other{パケット}}として画像を送信しました。", + "imageSend_sendFailed": "画像を送信できませんでした:{error}", + "imageSend_sendingProgress": "画像送信 — パケット {sent} 件、合計 {total} 件", + "receivedImage_senderPrefix": "ノード {prefix}", + "receivedImage_incoming": "{total} パケット中 {received} パケット", + "receivedImage_queued": "復号を待っている", + "receivedImage_tapToDecode": "デコードするにはタップしてください。", + "receivedImage_decoding": "再構築… 約1秒", + "receivedImage_incomplete": "画像が不完全です — {total} パケット中 {received} パケットが到着しました", + "receivedImage_corrupt": "画像を再構成することはできませんでした", + "receivedImage_decoderMissing": "画像を受信しました — 画像のデコードが失敗しました", + "receivedImage_evicted": "画像はもう保存されていません", + "receivedImage_retry": "もう一度試してください", + "receivedImage_decodeAgain": "もう一度デコードしてください", + "receivedImage_openSettings": "設定する", + "receivedImage_tapToProcess": "処理するにはタップしてください", + "receivedImage_awaiting": "{bytes} バイト・{packets} {packets, plural, =1{パケット} other{パケット}}", + "imageSend_secondsValue": "{seconds}秒", + "imageSend_minutesSecondsValue": "{minutes}分 {seconds}秒", + "channels_noFreeSlots": "すべてのチャンネルスロットが使用中です", + "chat_longMessageRetryNote": "158バイトを超える場合:最大 {count} 回まで送信されます", + "reaction_report": "絵文字リアクション", + "repeater_bridgeNote": "RS232またはESP-NOWのブリッジ機能を備えたファームウェアでのみ利用可能です。", + "repeater_cliHelpGetFloodMaxAdvert": "フラッドアドバートの最大ホップ数を表示します。", + "repeater_cliHelpGetFloodMaxUnscoped": "地域スコープのないフラッドパケットの最大ホップ数を表示します。", + "repeater_cliHelpGetRadioFemRxGain": "LoRaフロントエンドモジュールのRXゲインが有効になっているかどうかを表示します。", + "repeater_cliHelpGetRadioFemTxGain": "LoRaフロントエンドモジュールのTXゲインが有効になっているかどうかを表示します。", + "repeater_cliHelpRegionDef": "1つのコマンドで地域のチェーンを定義します。各名前は直前の名前の下に追加されます。「name,parent」を指定すると、その名前を追加した後、指定した親の下に続けます。地域リストを返信します。", + "repeater_cliHelpSetFloodMaxAdvert": "フラッドアドバートを転送する際の最大ホップ数を設定します(0-64)。", + "repeater_cliHelpSetFloodMaxUnscoped": "地域スコープを持たないフラッドパケットを転送する際の最大ホップ数を設定します(0-64)。", + "repeater_cliHelpSetRadioFemRxGain": "LoRaフロントエンドモジュールのRXゲイン(LNA)の有効/無効を切り替えます。対応していない基板は「Error: unsupported」と返信します。", + "repeater_cliHelpSetRadioFemTxGain": "LoRaフロントエンドモジュールのTXゲイン(PA)の有効/無効を切り替えます。対応していない基板は「Error: unsupported」と返信します。", + "repeater_cliRegionLoadActive": "地域読み込みモード:1行に1つの地域名を送信し、親の下にスペースでインデントします(フラッドを許可する場合は名前の後にFを追加)。各行に返信はありません。空行を送信して終了し、その後「region save」を送信すると結果が保存されます。", + "repeater_cliRegionLoadEnd": "(地域読み込み終了)", + "repeater_cliRegionLoadHint": "地域行、または空欄で終了", + "repeater_frequencyInvalid": "無効な周波数 (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "受信エラー", + "repeater_txPowerRangeHelper": "-9~30 dBm", + "room_postsPushed": "プッシュされた投稿", + "room_postsStored": "投稿", + "settings_publicKeyCopied": "公開鍵がコピーされました", + "settings_radioSettingsNotApplied": "ラジオがこれらの設定を適用しませんでした", + "urlImage_enable": "URL画像を有効にする", + "urlImage_possible": "URL画像の可能性があります。設定で有効にしてください。", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 6ed6f9a4..de605c47 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -161,19 +161,21 @@ "settings_locationIntervalInvalid": "간격은 최소 60초 이상, 86400초 미만이어야 합니다.", "settings_latitude": "위도", "settings_longitude": "경도", + "settings_autoZeroHopAdvertOnGpsUpdate": "GPS 업데이트 시 제로 홉 어드버트 자동 전송", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "GPS 위치가 변경되면 제로 홉 어드버트를 전송합니다(어드버트에 위치 포함 필요).", "settings_contactSettings": "연락처 설정", "settings_contactSettingsSubtitle": "연락처 추가 방식 설정", "settings_privacyMode": "개인 정보 보호 모드", - "settings_privacyModeSubtitle": "광고에 이름/위치 정보 숨기기", - "settings_privacyModeToggle": "광고에 자신의 이름과 위치를 숨기기 위해 개인 정보 보호 모드를 켜거나 끄십시오.", + "settings_privacyModeSubtitle": "어드버트에 이름/위치 정보 숨기기", + "settings_privacyModeToggle": "어드버트에 자신의 이름과 위치를 숨기기 위해 개인 정보 보호 모드를 켜거나 끄십시오.", "settings_privacyModeEnabled": "개인 정보 보호 모드 활성화", "settings_privacyModeDisabled": "개인 정보 보호 모드 비활성화", "settings_actions": "행동", "settings_deleteAllPaths": "모든 경로 삭제", "settings_deleteAllPathsSubtitle": "연락처의 모든 경로 데이터를 지웁니다.", - "settings_sendAdvertisement": "광고 전송", + "settings_sendAdvertisement": "어드버트 전송", "settings_sendAdvertisementSubtitle": "현재 존재를 방송합니다.", - "settings_advertisementSent": "광고가 전송되었습니다.", + "settings_advertisementSent": "어드버트가 전송되었습니다.", "settings_syncTime": "시간 동기화", "settings_syncTimeSubtitle": "장치 시계를 휴대폰 시간으로 설정", "settings_timeSynchronized": "시간이 동기화되었습니다.", @@ -254,7 +256,7 @@ "appSettings_enableMessageTracingSubtitle": "메시지에 대한 상세한 경로 및 시간 정보를 표시", "appSettings_notifications": "알림", "appSettings_enableNotifications": "알림 활성화", - "appSettings_enableNotificationsSubtitle": "메시지와 광고에 대한 알림을 받으세요.", + "appSettings_enableNotificationsSubtitle": "메시지와 어드버트에 대한 알림을 받으세요.", "appSettings_notificationPermissionDenied": "알림 권한 거부", "appSettings_notificationsEnabled": "알림 사용", "appSettings_notificationsDisabled": "알림 사용 안 함", @@ -262,7 +264,7 @@ "appSettings_messageNotificationsSubtitle": "새로운 메시지를 받을 때 알림 표시", "appSettings_channelMessageNotifications": "채널 메시지 알림", "appSettings_channelMessageNotificationsSubtitle": "채널 메시지를 수신할 때 알림 표시", - "appSettings_advertisementNotifications": "광고 알림", + "appSettings_advertisementNotifications": "어드버트 알림", "appSettings_advertisementNotificationsSubtitle": "새 노드가 발견되었을 때 알림 표시", "appSettings_messaging": "메시징", "appSettings_clearPathOnMaxRetry": "최대 재시도 시 경로 지우기", @@ -270,7 +272,7 @@ "appSettings_pathsWillBeCleared": "5번 실패하면 해당 경로를 지웁니다.", "appSettings_pathsWillNotBeCleared": "경로를 자동으로 지우지 않습니다.", "appSettings_autoRouteRotation": "자동 경로 순환", - "appSettings_autoRouteRotationSubtitle": "최적 경로와 플러드 모드 사이를 전환합니다.", + "appSettings_autoRouteRotationSubtitle": "최적 경로와 플러딩 모드 사이를 전환합니다.", "appSettings_autoRouteRotationEnabled": "자동 경로 순환 기능 활성화", "appSettings_autoRouteRotationDisabled": "자동 경로 순환 기능 비활성화", "appSettings_maxRouteWeight": "최대 경로 가중치", @@ -332,6 +334,19 @@ "appSettings_last6Hours": "지난 6시간", "appSettings_last24Hours": "지난 24시간", "appSettings_lastWeek": "지난 주", + "appSettings_rasterTileSource": "래스터 타일 소스", + "appSettings_stadiaEndpoint": "Stadia 엔드포인트", + "appSettings_stadiaApiKey": "Stadia API 키", + "appSettings_stadiaApiKeyRequired": "Stadia Maps를 사용하려면 필요합니다", + "appSettings_stadiaApiKeyConfigured": "설정됨: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Stadia Maps API 키를 입력하세요. 이 앱은 래스터 타일 요청에 이 키를 사용합니다.", "appSettings_offlineMapCache": "오프라인 지도 캐시", "appSettings_unitsTitle": "단위", "appSettings_unitsMetric": "미터법 (m / km)", @@ -355,7 +370,7 @@ "appSettings_appDebugLoggingDisabled": "앱 디버깅 로깅 비활성화", "contacts_title": "연락처", "contacts_noContacts": "아직 연락처는 없습니다.", - "contacts_contactsWillAppear": "장치가 광고를 할 때, 연락처 정보가 표시됩니다.", + "contacts_contactsWillAppear": "장치가 어드버트를 전송하면 연락처 정보가 표시됩니다.", "contacts_unread": "읽지 않음", "contacts_searchContactsNoNumber": "연락처 검색...", "contacts_searchContacts": "{number} {str} 연락처 검색...", @@ -642,6 +657,7 @@ } } }, + "chat_selectSendAction": "전송 작업 선택", "chat_sendGif": "GIF 보내기", "chat_reply": "답변", "chat_addReaction": "댓글 추가", @@ -735,10 +751,10 @@ "chat_ShowAllPaths": "모든 경로 표시", "chat_routingMode": "라우팅 방식", "chat_autoUseSavedPath": "자동 (저장된 경로 사용)", - "chat_forceFloodMode": "플러드 모드 활성화", + "chat_forceFloodMode": "플러딩 모드 활성화", "chat_recentAckPaths": "최근 사용한 ACK 경로 (사용하려면 탭):", "chat_pathHistoryFull": "이력 기록은 이미 가득 차 있습니다. 항목을 삭제하여 새로운 항목을 추가할 수 있습니다.", - "chat_hopSingular": "점프", + "chat_hopSingular": "홉", "chat_hopPlural": "홉", "chat_hopsCount": "{count} {count, plural, =1{홉} other{홉}}", "@chat_hopsCount": { @@ -758,7 +774,7 @@ "chat_clearPathSubtitle": "다음 전송 시 강제로 새 경로를 찾습니다.", "chat_pathCleared": "경로가 확보되었습니다. 다음 메시지는 경로를 다시 찾을 것입니다.", "chat_floodModeSubtitle": "앱 바의 라우팅 스위치를 사용하세요.", - "chat_floodModeEnabled": "플러드 모드가 활성화되었습니다. 앱 바의 경로 아이콘으로 다시 전환할 수 있습니다.", + "chat_floodModeEnabled": "플러딩 모드가 활성화되었습니다. 앱 바의 경로 아이콘으로 다시 전환할 수 있습니다.", "chat_fullPath": "전체 경로", "chat_pathDetailsNotAvailable": "경로 정보는 아직 제공되지 않습니다. 메시지를 보내어 다시 시도해 보세요.", "chat_pathSetHops": "경로 설정: {hopCount} {hopCount, plural, =1{홉} other{홉}} - {status}", @@ -779,7 +795,7 @@ "chat_path": "경로", "chat_publicKey": "공개 키", "chat_compressOutgoingMessages": "전송되는 메시지 압축", - "chat_floodForced": "플러드 (강제)", + "chat_floodForced": "플러딩 (강제)", "chat_directForced": "직접 (강제)", "chat_hopsForced": "{count}홉 (강제)", "@chat_hopsForced": { @@ -789,7 +805,7 @@ } } }, - "chat_floodAuto": "플러드 (자동)", + "chat_floodAuto": "플러딩 (자동)", "chat_direct": "직접", "chat_poiShared": "공유된 POI", "chat_unread": "읽지 않음: {count}", @@ -952,6 +968,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1017,7 +1083,7 @@ "login_routing": "라우팅", "login_routingMode": "라우팅 모드", "login_autoUseSavedPath": "자동 (저장된 경로 사용)", - "login_forceFloodMode": "강수 모드 활성화", + "login_forceFloodMode": "플러딩 모드 강제 활성화", "login_managePaths": "경로 관리", "login_login": "로그인", "login_attempt": "시도 {current}/{max}", @@ -1093,7 +1159,7 @@ "repeater_statusTitle": "반복 장치 상태", "repeater_routingMode": "라우팅 방식", "repeater_autoUseSavedPath": "자동 (저장된 경로 사용)", - "repeater_forceFloodMode": "강수 모드 활성화", + "repeater_forceFloodMode": "플러딩 모드 강제 활성화", "repeater_pathManagement": "경로 관리", "repeater_refresh": "새롭게", "repeater_statusRequestTimeout": "상태 확인 요청이 시간 초과되었습니다.", @@ -1138,7 +1204,7 @@ } } }, - "repeater_packetTxTotal": "총: {total}, 홍수: {flood}, 직접: {direct}", + "repeater_packetTxTotal": "총: {total}, 플러딩: {flood}, 직접: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -1152,7 +1218,7 @@ } } }, - "repeater_packetRxTotal": "총: {total}, 홍수: {flood}, 직접: {direct}", + "repeater_packetRxTotal": "총: {total}, 플러딩: {flood}, 직접: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -1166,7 +1232,7 @@ } } }, - "repeater_duplicatesFloodDirect": "홍수: {flood}, 직접: {direct}", + "repeater_duplicatesFloodDirect": "플러딩: {flood}, 직접: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1212,9 +1278,9 @@ "repeater_guestAccess": "게스트 접근", "repeater_guestAccessSubtitle": "게스트의 읽기 전용 접근 권한 허용", "repeater_privacyMode": "개인 정보 보호 모드", - "repeater_privacyModeSubtitle": "광고에 이름/위치 정보 숨기기", - "repeater_advertisementSettings": "광고 설정", - "repeater_localAdvertInterval": "지역 광고 시간 간격", + "repeater_privacyModeSubtitle": "어드버트에 이름/위치 정보 숨기기", + "repeater_advertisementSettings": "어드버트 설정", + "repeater_localAdvertInterval": "지역 어드버트 시간 간격", "repeater_localAdvertIntervalMinutes": "{minutes} 분", "@repeater_localAdvertIntervalMinutes": { "placeholders": { @@ -1223,7 +1289,7 @@ } } }, - "repeater_floodAdvertInterval": "홍수 광고 간격", + "repeater_floodAdvertInterval": "플러딩 어드버트 간격", "repeater_floodAdvertIntervalHours": "{hours} 시간", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1232,7 +1298,7 @@ } } }, - "repeater_encryptedAdvertInterval": "암호화된 광고 간격", + "repeater_encryptedAdvertInterval": "암호화된 어드버트 간격", "repeater_dangerZone": "위험 구역", "repeater_rebootRepeater": "리부트 반복", "repeater_rebootRepeaterSubtitle": "리피터 장치를 재시작하세요.", @@ -1293,9 +1359,9 @@ "repeater_advancedSettings": "고급", "repeater_advancedSettingsSubtitle": "숙련된 운영자를 위한 조절 노브", "repeater_pathHashMode": "패스 해시 모드", - "repeater_pathHashModeHelper": "이 리피터의 ID를 플러드 경로/루프 감지 태그에 인코딩하는 데 사용되는 바이트 수: 0=1 바이트 (256개의 ID, 최대 64개의 홉), 1=2 바이트 (65,000개의 ID, 최대 32개의 홉), 2=3 바이트 (16백만 개의 ID, 최대 21개의 홉). v1.13 및 이전 버전의 펌웨어는 다중 바이트 경로를 지원하지 않으며, 네트워크가 v1.14 이상으로 업그레이드되면 한 번만 감지합니다.", - "repeater_txDelay": "플러드 TX 지연", - "repeater_txDelayHelper": "홍수 시 교통량에 맞춰 재전송 간격을 설정합니다. 이는 패킷의 전송 시간을 곱한 값 (0-2, 기본값 0.5)으로 설정합니다. 값이 클수록 충돌이 줄어들지만 전송 속도가 느려집니다.", + "repeater_pathHashModeHelper": "이 리피터의 ID를 플러딩 경로/루프 감지 태그에 인코딩하는 데 사용되는 바이트 수입니다. 0=1바이트(256개 ID, 최대 64홉), 1=2바이트(65,000개 ID, 최대 32홉), 2=3바이트(1,600만 개 ID, 최대 21홉). v1.14 이전 펌웨어는 항상 1바이트 경로를 사용했으며, v1.14 이상은 2바이트 또는 3바이트 경로로 설정할 수 있습니다.", + "repeater_txDelay": "플러딩 TX 지연", + "repeater_txDelayHelper": "플러딩 시 교통량에 맞춰 재전송 간격을 설정합니다. 이는 패킷의 전송 시간을 곱한 값 (0-2, 기본값 0.5)으로 설정합니다. 값이 클수록 충돌이 줄어들지만 전송 속도가 느려집니다.", "repeater_directTxDelay": "직접적인 TX 지연", "repeater_directTxDelayHelper": "직접 (대량 전송이 아닌) 트래픽에 대한 재전송 간격을, 패킷의 전송 시간을 곱하여 설정 (0-2, 기본값 0.3).", "repeater_intThresh": "간섭 허용치", @@ -1303,10 +1369,10 @@ "repeater_agcResetInterval": "AGC 재설정 간격", "repeater_agcResetIntervalHelper": "자동 게인 제어를 재설정하여 신호가 불안정해졌을 때 원래 상태로 복구하는 빈도를 설정하는 방법은 다음과 같습니다. 4의 배수 단위로 설정하면 주기적인 재설정이 수행됩니다. 0을 설정하면 주기적인 재설정이 수행되지 않습니다.", "repeater_actionsTitle": "행동", - "repeater_sendAdvert": "홍수 관련 광고 전송", - "repeater_sendAdvertSubtitle": "네트워크를 통해 홍수 광고를 방송", - "repeater_sendAdvertZeroHop": "제로 홉 광고 전송", - "repeater_sendAdvertZeroHopSubtitle": "단일 중계 (중계 없이) 광고를 송출", + "repeater_sendAdvert": "플러딩 관련 어드버트 전송", + "repeater_sendAdvertSubtitle": "네트워크를 통해 플러딩 어드버트를 방송", + "repeater_sendAdvertZeroHop": "제로 홉 어드버트 전송", + "repeater_sendAdvertZeroHopSubtitle": "1홉 어드버트를 전송합니다 (중계 없음).", "repeater_clockSync": "현재 시계 동기화", "repeater_clockSyncSubtitle": "스마트폰의 시간을 리피터로 설정", "repeater_actionSucceeded": "{action}이 성공적으로 완료되었습니다.", @@ -1391,9 +1457,9 @@ "repeater_cliQuickGetTx": "TX 획득", "repeater_cliQuickNeighbors": "이웃", "repeater_cliQuickVersion": "버전", - "repeater_cliQuickAdvertise": "광고", + "repeater_cliQuickAdvertise": "어드버트", "repeater_cliQuickClock": "시계", - "repeater_cliHelpAdvert": "광고 패킷을 발송", + "repeater_cliHelpAdvert": "어드버트 패킷을 발송", "repeater_cliHelpReboot": "장치를 재부팅합니다. (참고: '시간 초과' 오류가 발생할 수 있으며, 이는 정상적인 현상입니다)", "repeater_cliHelpClock": "각 기기의 시계에 표시되는 현재 시간", "repeater_cliHelpPassword": "장치에 새로운 관리자 비밀번호를 설정합니다.", @@ -1403,16 +1469,16 @@ "repeater_cliHelpSetTx": "LoRa 전송 전력을 dBm 단위로 설정합니다. (설정을 적용하려면 재부팅 필요)", "repeater_cliHelpSetRepeat": "이 노드에 대한 리피터 역할을 활성화하거나 비활성화합니다.", "repeater_cliHelpSetAllowReadOnly": "(방 서버) '켜짐' 상태인 경우, 빈 비밀번호로 로그인할 수 있지만, 방에 게시할 수는 없습니다 (단, 읽기만 가능).", - "repeater_cliHelpSetFloodMax": "들어오는 플러드 패킷의 최대 홉 수를 설정합니다 (최대 홉 수보다 크거나 같으면 패킷은 전달되지 않습니다).", + "repeater_cliHelpSetFloodMax": "들어오는 플러딩 패킷의 최대 홉 수를 설정합니다 (최대 홉 수보다 크거나 같으면 패킷은 전달되지 않습니다).", "repeater_cliHelpSetIntThresh": "간섭 임계값을 설정합니다 (dB 단위). 기본값은 14입니다. 0으로 설정하면 채널 간섭 감지 기능을 비활성화합니다.", "repeater_cliHelpSetAgcResetInterval": "자동 게인 제어기를 재설정하는 간격을 설정합니다. 0으로 설정하면 비활성화됩니다.", "repeater_cliHelpSetMultiAcks": "'더블 ACK' 기능을 활성화하거나 비활성화할 수 있습니다.", - "repeater_cliHelpSetAdvertInterval": "로컬 (제로 홉) 광고 패킷을 전송하는 간격 (분 단위)을 설정합니다. 0으로 설정하면 비활성화됩니다.", - "repeater_cliHelpSetFloodAdvertInterval": "시간 단위로 광고 패킷을 전송하는 간격을 설정합니다. 0으로 설정하면 비활성화됩니다.", + "repeater_cliHelpSetAdvertInterval": "로컬 (제로 홉) 어드버트 패킷을 전송하는 간격 (분 단위)을 설정합니다. 0으로 설정하면 비활성화됩니다.", + "repeater_cliHelpSetFloodAdvertInterval": "시간 단위로 어드버트 패킷을 전송하는 간격을 설정합니다. 0으로 설정하면 비활성화됩니다.", "repeater_cliHelpSetGuestPassword": "게스트 비밀번호를 설정하거나 업데이트합니다. (반복 사용자, 게스트 로그인 시 \"통계 가져오기\" 요청을 보낼 수 있음)", - "repeater_cliHelpSetName": "광고 이름을 설정합니다.", - "repeater_cliHelpSetLat": "광고 지도의 위도를 설정합니다. (십진법 단위)", - "repeater_cliHelpSetLon": "광고 지도의 경도를 설정합니다. (십진도)", + "repeater_cliHelpSetName": "어드버트 이름을 설정합니다.", + "repeater_cliHelpSetLat": "어드버트 지도의 위도를 설정합니다. (십진법 단위)", + "repeater_cliHelpSetLon": "어드버트 지도의 경도를 설정합니다. (십진도)", "repeater_cliHelpSetRadio": "완전히 새로운 라디오 파라미터를 설정하고, 선호 사항에 저장합니다. 적용하려면 \"재부팅\" 명령이 필요합니다.", "repeater_cliHelpSetRxDelay": "(실험용) 기본 설정 (최소 1이어야 함)으로, 수신된 패킷에 약간의 지연을 적용하며, 신호 강도/점수를 기준으로 설정합니다. 0으로 설정하면 비활성화됩니다.", "repeater_cliHelpSetTxDelay": "공통 패킷의 전송 지연 시간을 설정하며, 시간-공기 시간과 무작위 슬롯 시스템을 곱하여 충돌 가능성을 줄입니다.", @@ -1429,9 +1495,9 @@ "repeater_cliHelpLogStart": "패킷 로깅을 파일 시스템으로 시작합니다.", "repeater_cliHelpLogStop": "패킷 로깅을 파일 시스템으로 저장하는 것을 중단합니다.", "repeater_cliHelpLogErase": "파일 시스템에서 패킷 로그를 삭제합니다.", - "repeater_cliHelpNeighbors": "제로 홉 광고를 통해 수신된 다른 리피터 노드 목록을 보여줍니다. 각 줄은 ID-프리픽스-16진수:타임스탬프:SNR-횟수-4 형식입니다.", + "repeater_cliHelpNeighbors": "제로 홉 어드버트를 통해 수신된 다른 리피터 노드 목록을 보여줍니다. 각 줄은 ID-프리픽스-16진수:타임스탬프:SNR-횟수-4 형식입니다.", "repeater_cliHelpNeighborRemove": "이 함수는 지정된 pubkey 접두사(16진수)와 일치하는 첫 번째 항목을 이웃 목록에서 제거합니다.", - "repeater_cliHelpRegion": "(단일 시리즈) 정의된 모든 지역과 현재 홍수 허가 정보를 나열합니다.", + "repeater_cliHelpRegion": "(단일 시리즈) 정의된 모든 지역과 현재 플러딩 허가 정보를 나열합니다.", "repeater_cliHelpRegionLoad": "참고: 이는 여러 명령을 한 번에 실행하는 특별한 방식입니다. 각 후속 명령은 영역 이름이며 (부모 계층 구조를 나타내기 위해 공백으로 들여쓰기하며, 최소 1개의 공백을 사용) 공백으로 끝나는 줄 또는 명령을 보내어 종료합니다.", "repeater_cliHelpRegionGet": "주어진 이름 접두사(또는 전역 검색을 위한 \"\\*\" 사용)를 사용하여 특정 지역을 검색합니다. 결과를 \"-> 지역 이름 (상위 지역 이름) 'F'\" 형태로 반환합니다.", "repeater_cliHelpRegionPut": "주어진 이름으로 지역 정의를 추가하거나 업데이트합니다.", @@ -1445,8 +1511,8 @@ "repeater_cliHelpGpsOnOff": "GPS 전원 상태를 켜고 끄는 기능.", "repeater_cliHelpGpsSync": "노드 시간을 GPS 시계와 동기화합니다.", "repeater_cliHelpGpsSetLoc": "노드의 위치를 GPS 좌표로 설정하고, 설정을 저장합니다.", - "repeater_cliHelpGpsAdvert": "노드의 위치 광고 설정:\n- none: 광고에 위치 정보를 포함하지 않음\n- share: GPS 위치 정보를 공유 (SensorManager에서 가져옴)\n- prefs: 설정에 저장된 위치를 광고", - "repeater_cliHelpGpsAdvertSet": "위치 기반 광고 설정 구성", + "repeater_cliHelpGpsAdvert": "노드의 위치 어드버트 설정:\n- none: 어드버트에 위치 정보를 포함하지 않음\n- share: GPS 위치 정보를 공유 (SensorManager에서 가져옴)\n- prefs: 설정에 저장된 위치를 어드버트에 포함", + "repeater_cliHelpGpsAdvertSet": "위치 기반 어드버트 설정 구성", "repeater_commandsListTitle": "명령 목록", "repeater_commandsListNote": "참고: 다양한 \"set...\" 명령과 함께 \"get...\" 명령도 존재합니다.", "repeater_general": "일반", @@ -1631,7 +1697,7 @@ } }, "channelPath_unknownPath": "알 수 없음", - "channelPath_floodPath": "홍수", + "channelPath_floodPath": "플러딩", "channelPath_directPath": "직접", "channelPath_observedZeroOf": "{total} 중 0개", "@channelPath_observedZeroOf": { @@ -1993,16 +2059,16 @@ "contacts_invalidAdvertFormat": "유효하지 않은 연락 정보", "contacts_contactImported": "연락이 수신되었습니다.", "contacts_contactImportFailed": "연락처를 가져오지 못했습니다.", - "contacts_zeroHopAdvert": "제로 홉 광고", - "contacts_floodAdvert": "홍수 광고", - "contacts_copyAdvertToClipboard": "광고 텍스트를 클립보드에 복사", + "contacts_zeroHopAdvert": "제로 홉 어드버트", + "contacts_floodAdvert": "플러딩 어드버트", + "contacts_copyAdvertToClipboard": "어드버트 텍스트를 클립보드에 복사", "contacts_addContactFromClipboard": "복사본에서 연락처 추가", "contacts_ShareContact": "연락처를 복사", - "contacts_ShareContactZeroHop": "광고를 통해 연락처 공유", - "contacts_zeroHopContactAdvertSent": "광고를 통해 연락처를 받았습니다.", + "contacts_ShareContactZeroHop": "어드버트를 통해 연락처 공유", + "contacts_zeroHopContactAdvertSent": "어드버트를 통해 연락처를 받았습니다.", "contacts_zeroHopContactAdvertFailed": "연락처 전송에 실패했습니다.", - "contacts_contactAdvertCopied": "광고 내용이 복사되었습니다.", - "contacts_contactAdvertCopyFailed": "광고를 클립보드에 복사하는 데 실패했습니다.", + "contacts_contactAdvertCopied": "어드버트 내용이 복사되었습니다.", + "contacts_contactAdvertCopyFailed": "어드버트를 클립보드에 복사하는 데 실패했습니다.", "notification_activityTitle": "메쉬코어 활동", "notification_messagesCount": "{count} {count, plural, =1{메시지} other{메시지들}}", "@notification_messagesCount": { @@ -2148,8 +2214,8 @@ "settings_telemetryBaseMode": "원격 모니터링 기본 설정", "settings_telemetryLocationMode": "텔레메트리 위치 모드", "settings_telemetryEnvironmentMode": "텔레메트리 환경 모드", - "settings_advertLocation": "광고 위치", - "settings_advertLocationSubtitle": "광고에 위치 정보를 포함하세요.", + "settings_advertLocation": "어드버트 위치", + "settings_advertLocationSubtitle": "어드버트에 위치 정보를 포함하세요.", "settings_telemetryModeUpdated": "텔레메트리 모드 업데이트 완료", "contact_info": "연락처", "contact_settings": "연락처 설정", @@ -2239,7 +2305,7 @@ "repeater_sensors": "센서", "repeater_cliHelpPowerOff": "장치를 끄는 기능 (응답이 없을 것으로 예상)", "repeater_cliHelpClkReboot": "시계를 알려진 시점으로 재설정하고 장치를 재부팅합니다.", - "repeater_cliHelpAdvertZeroHop": "직접적인 연결 없이 이웃에게만 광고를 전송합니다.", + "repeater_cliHelpAdvertZeroHop": "직접적인 연결 없이 이웃에게만 어드버트를 전송합니다.", "repeater_cliHelpStartOta": "지원되는 보드에서 무선으로 펌웨어 업데이트를 시작합니다.", "repeater_cliHelpTime": "장치를 주어진 유닉스 에포크 초부터 시간으로 설정합니다. 시간은 이전으로 이동할 수 없습니다.", "repeater_cliHelpBoard": "제조사/하드웨어 식별 정보를 표시합니다.", @@ -2250,7 +2316,7 @@ "repeater_cliHelpSetDutyCycle": "최대 허용 전송 주기(백분율)를 설정합니다(1~100%). 내부적으로 통신 시간을 조정합니다.", "repeater_cliHelpSetPrvKey": "(시리얼 키만 해당) 장치 식별용 개인 키를 대체합니다. 적용하려면 재부팅이 필요합니다. 새로운 공개 키를 생성합니다.", "repeater_cliHelpSetRadioRxGain": "(SX126x 전용) 더 높은 전류를 사용할 때 더 나은 감도를 위해 증폭된 RX 감쇠 기능을 전환합니다.", - "repeater_cliHelpSetOwnerInfo": "광고에 포함된 소유자 연락처 정보를 지정합니다. 줄 바꿈을 위해 '|' 문자를 사용합니다.", + "repeater_cliHelpSetOwnerInfo": "어드버트에 포함된 소유자 연락처 정보를 지정합니다. 줄 바꿈을 위해 '|' 문자를 사용합니다.", "repeater_cliHelpSetPathHashMode": "경로 해시 모드를 설정합니다. 0 = 고전 방식, 1 = 표준 방식, 2 = 엄격한 방식. 경로 매칭 방식에 영향을 미칩니다.", "repeater_cliHelpSetLoopDetect": "라우팅 루프 감지 감도 설정: 끄기, 최소, 중간, 또는 엄격", "repeater_cliHelpSetFreq": "(단일 기능) 특정 주파수만 빠르게 설정합니다. 재부팅이 필요합니다. 전체 라디오 파라미터 설정에는 \"라디오 설정\" 기능을 사용하는 것이 좋습니다.", @@ -2270,15 +2336,15 @@ "repeater_cliHelpGetAgcResetInterval": "AGC 재설정 간격을 초 단위로 표시합니다.", "repeater_cliHelpGetMultiAcks": "더블 ACK 모드가 활성화되어 있는지 (1) 또는 비활성화되어 있는지 (0)를 표시합니다.", "repeater_cliHelpGetAllowReadOnly": "게스트의 읽기 전용 액세스가 허용되는지 여부를 표시합니다.", - "repeater_cliHelpGetAdvertInterval": "지역 광고 시간 간격을 분 단위로 표시합니다.", - "repeater_cliHelpGetFloodAdvertInterval": "홍수 광고 시간 간격을 시간 단위로 표시합니다.", + "repeater_cliHelpGetAdvertInterval": "지역 어드버트 시간 간격을 분 단위로 표시합니다.", + "repeater_cliHelpGetFloodAdvertInterval": "플러딩 어드버트 시간 간격을 시간 단위로 표시합니다.", "repeater_cliHelpGetGuestPassword": "구성된 게스트 비밀번호를 표시합니다.", "repeater_cliHelpGetLat": "설정된 위도를 보여줍니다.", "repeater_cliHelpGetLon": "설정된 경도를 보여줍니다.", "repeater_cliHelpGetRxDelay": "Rxdelay 기본 값을 표시합니다.", - "repeater_cliHelpGetTxDelay": "홍수 모드에서의 전송 지연 계수를 보여줍니다.", + "repeater_cliHelpGetTxDelay": "플러딩 모드에서의 전송 지연 계수를 보여줍니다.", "repeater_cliHelpGetDirectTxDelay": "직렬 모드에서의 딜레이 계수를 보여줍니다.", - "repeater_cliHelpGetFloodMax": "최대 홍수 발생 횟수를 보여줍니다.", + "repeater_cliHelpGetFloodMax": "최대 플러딩 홉 수를 보여줍니다.", "repeater_cliHelpGetOwnerInfo": "소유주 연락처 정보를 표시합니다.", "repeater_cliHelpGetPathHashMode": "경로 해시 모드 (0/1/2)를 표시합니다.", "repeater_cliHelpGetLoopDetect": "루프 탐지 감도를 보여줍니다.", @@ -2300,8 +2366,8 @@ "repeater_cliHelpSensorList": "사용자 정의 센서 설정 목록을, 선택적으로 지정된 시작 인덱스부터 페이지 나누어 표시합니다.", "repeater_cliHelpRegionDefault": "현재 기본 지역 범위를 보여줍니다.", "repeater_cliHelpRegionDefaultSet": "기본 지역 범위를 설정합니다. \"\"을 사용하여 초기화합니다.", - "repeater_cliHelpRegionListAllowed": "홍수 피해 차량 통행이 가능한 지역 목록", - "repeater_cliHelpRegionListDenied": "홍수 발생 시 통행 금지 지역 목록", + "repeater_cliHelpRegionListAllowed": "플러딩 트래픽이 허용되는 지역 목록", + "repeater_cliHelpRegionListDenied": "플러딩 트래픽이 금지되는 지역 목록", "repeater_cliHelpStatsPackets": "(전송 속도만 표시) 패킷 수준의 통계 정보를 보여줍니다.", "repeater_cliHelpStatsRadio": "(특정 시리즈만 해당) 라디오 통계 정보를 표시합니다.", "repeater_cliHelpStatsCore": "(시리얼 번호만 표시) 핵심 펌웨어 통계 정보를 보여줍니다.", @@ -2430,13 +2496,10 @@ } } }, - "messageStatus_pending": "발송", - "messageStatus_sent": "발송", - "messageStatus_delivered": "배송 완료", - "common_undo": "되돌리기", "messageStatus_pending": "전송 중", "messageStatus_sent": "전송됨", "messageStatus_delivered": "전달됨", + "common_undo": "되돌리기", "messageStatus_failed": "전송 실패", "messageStatus_repeated": "반복 수신됨", "contacts_searchOpen": "연락처 검색", @@ -2444,9 +2507,9 @@ "contacts_searchClose": "검색 닫기", "routing_title": "라우팅", "routing_modeAuto": "자동", - "routing_modeFlood": "플러드", + "routing_modeFlood": "플러딩", "routing_modeManual": "수동", - "routing_modeAutoHint": "가장 잘 알려진 경로를 자동으로 선택하고, 경로가 없으면 플러드로 전환합니다.", + "routing_modeAutoHint": "가장 잘 알려진 경로를 자동으로 선택하고, 경로가 없으면 플러딩으로 전환합니다.", "routing_modeFloodHint": "모든 중계기를 통해 방송합니다. 가장 안정적이지만 송신 시간을 더 많이 사용합니다.", "routing_modeManualHint": "항상 지정한 정확한 경로를 따릅니다.", "routing_currentRoute": "현재 경로", @@ -2462,11 +2525,11 @@ "routing_qualityGood": "좋음", "routing_qualityFair": "보통", "routing_qualityWorked": "작동함", - "routing_qualityFlood": "플러드로 수신됨", + "routing_qualityFlood": "플러딩으로 수신됨", "routing_qualityUntested": "미검증", "routing_lastWorked": "{when}에 작동", "routing_neverWorked": "아직 작동한 적 없음", - "routing_floodDelivery": "플러드 전송", + "routing_floodDelivery": "플러딩 전송", "pathEditor_title": "경로 만들기", "pathEditor_hopCounter": "64개 중 {count} 홉", "pathEditor_noHops": "아직 홉이 추가되지 않았습니다. 아래 탭을 사용해 순서대로 추가하거나, 홉 없이 바로 보내려면 \"홉 없음\"으로 저장하세요.", @@ -2677,5 +2740,260 @@ "type": "String" } } + }, + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "지역", + "settings_regionSettingsSubtitle": "저장된 지역 관리", + "settings_regionManagement_screenTitle": "지역 관리", + "settings_regionNameHint": "지역 이름 입력", + "settings_regionAddRegion": "지역 추가", + "settings_regionFetchRegions": "리피터에서 지역을 가져옵니다.", + "settings_regionFetchRegionsFail": "어떤 지역도 발견되지 않았습니다.", + "settings_regionFetchRegionsAlreadyExists": "이 지역은 이미 추가되었습니다.", + "settings_regionName": "지역 이름", + "settings_regionDeleted": "지역 삭제", + "settings_deleteRegion": "지역 삭제", + "settings_deleteRegionConfirm": "\"{region}\"을(를) 지역 목록에서 삭제하시겠습니까?", + "settings_infoHardware": "하드웨어", + "settings_infoFirmware": "펌웨어", + "repeater_pathHashModeOption0": "0 - 1 바이트", + "repeater_pathHashModeOption1": "1~2 바이트", + "repeater_pathHashModeOption2": "2 - 3 바이트", + "repeater_pathHashModeOption3": "3 - 4 바이트", + "appSettings_batteryLipoHv": "리포 HV (3.0-4.35V)", + "channels_regionSetTo": "지역: {region}", + "channels_regionNotSet": "지역: 없음", + "channels_regionSelect_Title": "지역을 선택하세요", + "channels_clearRegion": "명확한 지역", + "chat_sendImageLora": "MeshCore를 통해 이미지 보내기", + "chat_imagePickFailed": "그 이미지를 열 수 없었어요.", + "chat_receivedGif": "GIF를 받았습니다", + "repeater_keySettings": "신원 키 변경", + "repeater_keySettingsSubtitle": "공개/비공개 키 쌍을 변경하세요", + "repeater_prvKey": "개인 키", + "repeater_prvKeyHelper": "리피터의 새로운 개인 키로, 128자리의 16진수 문자열입니다.", + "repeater_generatePrvKey": "임의의 키 쌍을 생성하세요.", + "repeater_stopGeneratingPrvKey": "키페어 검색 중단", + "repeater_pubKey": "공개 키", + "repeater_pubKeyHelper": "이것은 생성된 개인 키와 함께 사용되는 공개 키입니다. 직접 설정할 수 없습니다.", + "repeater_pubKeyPrefix": "원하는 접두사", + "repeater_pubKeyPrefixHelper": "이러한 16진수로 시작하는 공개 키를 찾으세요. 필요한 시도 횟수: {tries}.", + "imageMessages_enableTitle": "이미지 메시지 활성화", + "imageMessages_enableSubtitle": "메시를 통해 이미지를 전송하세요. 일회성 이미지 모델 다운로드가 필요합니다.", + "imageMessages_modelSectionTitle": "이미지 모델", + "imageMessages_downloadModel": "다운로드", + "imageMessages_cancelDownload": "취소", + "imageMessages_removeModel": "모델 제거", + "imageMessages_modelReady": "준비 완료", + "imageMessages_modelNotPublished": "아직 출판되지 않았습니다 — 이 빌드로는 다운로드할 수 없습니다.", + "imageMessages_downloadFailed": "이미지 모델을 다운로드할 수 없었습니다.", + "imageMessages_autoProcessTitle": "자동으로 프로세스 이미지를 처리합니다.", + "imageMessages_autoProcessSubtitle": "이미지가 도착하는 즉시 재구성하세요. 매번 2GB의 메모리를 사용하며, 탭으로 재구성을 원할 경우 해제하세요.", + "imageSend_title": "이미지를 보내세요", + "imageSend_cropNote": "512 × 512로 크기가 조정되었으며, 종횡비는 유지되지 않았습니다.", + "imageSend_originalSize": "원문 없음", + "imageSend_onAirSize": "방송 중", + "imageSend_quality": "품질", + "imageSend_qualityStandard": "표준", + "imageSend_qualityHigh": "높다", + "imageSend_packetsLabel": "패킷", + "imageSend_airtimeLabel": "방송 시간", + "imageSend_sizeLabel": "페이로드", + "imageSend_packetsCount": "{count} {count, plural, =1{패킷} other{패킷}}", + "imageSend_range": "{min}~{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "라디오 설정 정보 없음", + "imageSend_radioUnknownBody": "방송 시간을 계산할 수 있도록 기기와 연결하세요.", + "imageSend_longSendTitle": "장거리 송신", + "imageSend_longSendBody": "이것은 약 {duration} 동안 채널을 유지할 것입니다.", + "imageSend_floodNote": "플러딩 라우팅: 범위 내의 모든 리피터가 각 패킷을 재전송하므로, 채널이 이보다 더 오래 점유 상태를 유지합니다.", + "imageSend_parityTitle": "회복 패킷", + "imageSend_paritySubtitle": "추가 한 개의 패킷입니다. 그룹 메시지는 확인되지 않으므로, 하나의 패킷이 손실되었을 경우 수신자가 이미지를 다시 구성할 수 있습니다.", + "imageSend_send": "보내다", + "imageSend_cancel": "취소", + "imageSend_encodeFailed": "이 이미지는 인코딩할 수 없습니다.", + "imageSend_codecDownloading": "이미지 모델이 아직 다운로드 중입니다.", + "imageSend_codecUnavailable": "이 기기에서는 이미지 전송이 불가능합니다.", + "imageSend_codecDisabled": "설정에서 이미지 메시지가 꺼져 있습니다.", + "imageSend_deviceUnsupported": "이 라디오는 이미지 패킷을 전송할 수 없습니다. 컴패니언 펌웨어 13 이상을 실행하는 장치를 연결해 주세요.", + "imageSend_directMessagesUnsupported": "이미지는 그룹 데이터로 전송되므로, 직접 메시지가 아닌 채널로만 보낼 수 있습니다.", + "imageSend_tooLarge": "그 이미지는 메시 형식이 허용하는 것보다 더 많은 패킷으로 인코딩되었습니다.", + "imageSend_sentConfirmation": "이미지가 {count} {count, plural, =1{패킷} other{패킷}}로 전송되었습니다.", + "imageSend_sendFailed": "이미지를 보낼 수 없습니다: {error}", + "imageSend_sendingProgress": "이미지 전송 — {sent}개의 {total} 패킷", + "receivedImage_senderPrefix": "노드 {prefix}", + "receivedImage_incoming": "{total}개 패킷 중 {received}개", + "receivedImage_queued": "해독을 기다리는 중입니다.", + "receivedImage_tapToDecode": "해독하려면 탭을 누르세요.", + "receivedImage_decoding": "재구성하는… 약 1초 정도", + "receivedImage_incomplete": "이미지 불완전 — {total}개 중 {received}개 패킷 수신됨", + "receivedImage_corrupt": "이미지는 재구성될 수 없습니다.", + "receivedImage_decoderMissing": "수신된 이미지 — 이미지 해독이 되지 않았습니다", + "receivedImage_evicted": "이미지는 더 이상 저장되지 않았습니다.", + "receivedImage_retry": "다시 시도해 보세요", + "receivedImage_decodeAgain": "다시 해독하다", + "receivedImage_openSettings": "설정하다", + "receivedImage_tapToProcess": "처리하려면 탭을 누르세요.", + "receivedImage_awaiting": "{bytes} 바이트 · {packets} {packets, plural, =1{패킷} other{패킷}}", + "imageSend_secondsValue": "{seconds} 초", + "imageSend_minutesSecondsValue": "{minutes}분 {seconds}초", + "channels_noFreeSlots": "모든 채널 슬롯이 사용 중입니다", + "chat_longMessageRetryNote": "158바이트 초과 시: 최대 {count}회 전송됩니다", + "reaction_report": "이모지 반응", + "repeater_bridgeNote": "RS232 또는 ESP-NOW 브리지 기능이 포함된 펌웨어에서만 사용할 수 있습니다.", + "repeater_cliHelpGetFloodMaxAdvert": "플러딩 어드버트의 최대 홉 수를 표시합니다.", + "repeater_cliHelpGetFloodMaxUnscoped": "지역 범위가 없는 플러딩 패킷의 최대 홉 수를 표시합니다.", + "repeater_cliHelpGetRadioFemRxGain": "LoRa 프런트엔드 모듈의 RX 게인이 켜져 있는지 표시합니다.", + "repeater_cliHelpGetRadioFemTxGain": "LoRa 프런트엔드 모듈의 TX 게인이 켜져 있는지 표시합니다.", + "repeater_cliHelpRegionDef": "하나의 명령으로 지역 체인을 정의합니다. 각 이름은 이전 이름 아래에 추가됩니다. \"name,parent\"를 사용하면 해당 이름을 추가한 뒤 지정한 상위 지역 아래로 이어집니다. 지역 목록으로 응답합니다.", + "repeater_cliHelpSetFloodMaxAdvert": "플러딩 어드버트를 전달할 때의 최대 홉 수를 설정합니다(0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "지역 범위가 없는 플러딩 패킷을 전달할 때의 최대 홉 수를 설정합니다(0-64).", + "repeater_cliHelpSetRadioFemRxGain": "LoRa 프런트엔드 모듈의 RX 게인(LNA)을 전환합니다. 이 기능이 없는 보드는 \"Error: unsupported\"로 응답합니다.", + "repeater_cliHelpSetRadioFemTxGain": "LoRa 프런트엔드 모듈의 TX 게인(PA)을 전환합니다. 이 기능이 없는 보드는 \"Error: unsupported\"로 응답합니다.", + "repeater_cliRegionLoadActive": "지역 로드 모드: 한 줄에 지역 이름 하나씩 보내고, 상위 지역 아래에 공백으로 들여씁니다 (플러딩을 허용하려면 이름 뒤에 F를 추가). 각 줄에는 응답이 없습니다. 빈 줄을 보내 완료한 뒤 \"region save\"를 보내면 결과가 저장됩니다.", + "repeater_cliRegionLoadEnd": "(지역 로드 종료)", + "repeater_cliRegionLoadHint": "지역 줄, 또는 완료하려면 비워 두기", + "repeater_frequencyInvalid": "유효하지 않은 주파수 (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "수신 오류", + "repeater_txPowerRangeHelper": "-9~30 dBm", + "room_postsPushed": "푸시된 게시물", + "room_postsStored": "게시물", + "settings_publicKeyCopied": "공개 키가 복사되었습니다", + "settings_radioSettingsNotApplied": "라디오가 이 설정을 적용하지 않았습니다", + "urlImage_enable": "URL 이미지 활성화", + "urlImage_possible": "URL 이미지일 수 있습니다. 설정에서 활성화하세요.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } } } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 08d7a0b6..51014ffb 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -313,7 +313,7 @@ abstract class AppLocalizations { /// No description provided for @messageStatus_delivered. /// /// In en, this message translates to: - /// **'Delivered'** + /// **'Delivered. The contact confirmed they got it.'** String get messageStatus_delivered; /// No description provided for @messageStatus_pending. @@ -334,6 +334,54 @@ abstract class AppLocalizations { /// **'Heard repeated'** String get messageStatus_repeated; + /// No description provided for @messageStatus_failedChannel. + /// + /// In en, this message translates to: + /// **'Your radio couldn\'t send this message.'** + String get messageStatus_failedChannel; + + /// No description provided for @messageStatus_resending. + /// + /// In en, this message translates to: + /// **'Not heard through enough repeaters yet. Resent {resends} of {maxResends} times.'** + String messageStatus_resending(int resends, int maxResends); + + /// No description provided for @messageStatus_hopsNotReached. + /// + /// In en, this message translates to: + /// **'Sent, but only heard back through {hops} of {required} repeaters. It may still have gone further than your radio can hear.'** + String messageStatus_hopsNotReached(int hops, int required); + + /// No description provided for @messageStatus_sentChannel. + /// + /// In en, this message translates to: + /// **'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'** + String get messageStatus_sentChannel; + + /// No description provided for @messageStatus_sentDirect. + /// + /// In en, this message translates to: + /// **'Sent. Waiting for the contact to confirm.'** + String get messageStatus_sentDirect; + + /// No description provided for @messageStatus_heardRepeatedCount. + /// + /// In en, this message translates to: + /// **'Heard repeated {count, plural, =1{once} other{{count} times}}. Nearby repeaters passed it on.'** + String messageStatus_heardRepeatedCount(int count); + + /// No description provided for @urlImage_enable. + /// + /// In en, this message translates to: + /// **'Enable URL images'** + String get urlImage_enable; + + /// No description provided for @urlImage_possible. + /// + /// In en, this message translates to: + /// **'Possible URL image; enable it in Settings.'** + String get urlImage_possible; + /// No description provided for @common_reboot. /// /// In en, this message translates to: @@ -784,6 +832,12 @@ abstract class AppLocalizations { /// **'Radio settings updated'** String get settings_radioSettingsUpdated; + /// No description provided for @settings_radioSettingsNotApplied. + /// + /// In en, this message translates to: + /// **'The radio did not apply these settings'** + String get settings_radioSettingsNotApplied; + /// No description provided for @settings_regionSettings. /// /// In en, this message translates to: @@ -793,9 +847,39 @@ abstract class AppLocalizations { /// No description provided for @settings_regionSettingsSubtitle. /// /// In en, this message translates to: - /// **'Manage stored regions'** + /// **'Limit channel floods to an area'** String get settings_regionSettingsSubtitle; + /// No description provided for @settings_regionEmptyExplanation. + /// + /// In en, this message translates to: + /// **'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'** + String get settings_regionEmptyExplanation; + + /// No description provided for @settings_regionFetchFromRepeaters. + /// + /// In en, this message translates to: + /// **'Fetch from repeaters'** + String get settings_regionFetchFromRepeaters; + + /// No description provided for @settings_regionDefault. + /// + /// In en, this message translates to: + /// **'Default region'** + String get settings_regionDefault; + + /// No description provided for @settings_regionDefaultSubtitle. + /// + /// In en, this message translates to: + /// **'Used by channels without their own region'** + String get settings_regionDefaultSubtitle; + + /// No description provided for @settings_regionDefaultNone. + /// + /// In en, this message translates to: + /// **'None'** + String get settings_regionDefaultNone; + /// No description provided for @settings_regionManagement_screenTitle. /// /// In en, this message translates to: @@ -991,7 +1075,7 @@ abstract class AppLocalizations { /// No description provided for @settings_allowByContact. /// /// In en, this message translates to: - /// **'Allow by contact flags'** + /// **'Only contacts I allow'** String get settings_allowByContact; /// No description provided for @settings_allowAll. @@ -1003,21 +1087,27 @@ abstract class AppLocalizations { /// No description provided for @settings_telemetryBaseMode. /// /// In en, this message translates to: - /// **'Telemetry Base Mode'** + /// **'Who can request battery and status'** String get settings_telemetryBaseMode; /// No description provided for @settings_telemetryLocationMode. /// /// In en, this message translates to: - /// **'Telemetry Location Mode'** + /// **'Who can request my location'** String get settings_telemetryLocationMode; /// No description provided for @settings_telemetryEnvironmentMode. /// /// In en, this message translates to: - /// **'Telemetry Environment Mode'** + /// **'Who can request sensor data'** String get settings_telemetryEnvironmentMode; + /// No description provided for @settings_telemetryPerContactHint. + /// + /// In en, this message translates to: + /// **'To allow a contact, open their chat and choose Contact Settings from the menu.'** + String get settings_telemetryPerContactHint; + /// No description provided for @settings_advertLocation. /// /// In en, this message translates to: @@ -1030,12 +1120,30 @@ abstract class AppLocalizations { /// **'Include location in advert.'** String get settings_advertLocationSubtitle; + /// No description provided for @settings_autoZeroHopAdvertOnGpsUpdate. + /// + /// In en, this message translates to: + /// **'Auto Zero-Hop Advert On GPS Update'** + String get settings_autoZeroHopAdvertOnGpsUpdate; + + /// No description provided for @settings_autoZeroHopAdvertOnGpsUpdateSubtitle. + /// + /// In en, this message translates to: + /// **'App setting: when your GPS position changes, automatically advertise your new location to nearby nodes only (requires Advert Location).'** + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle; + /// No description provided for @settings_multiAck. /// /// In en, this message translates to: /// **'Multi-ACKs'** String get settings_multiAck; + /// No description provided for @settings_multiAckSubtitle. + /// + /// In en, this message translates to: + /// **'Send extra ACKs for better delivery; uses more airtime'** + String get settings_multiAckSubtitle; + /// No description provided for @settings_telemetryModeUpdated. /// /// In en, this message translates to: @@ -1216,6 +1324,12 @@ abstract class AppLocalizations { /// **'Public Key'** String get settings_infoPublicKey; + /// No description provided for @settings_publicKeyCopied. + /// + /// In en, this message translates to: + /// **'Public key copied'** + String get settings_publicKeyCopied; + /// No description provided for @settings_infoContactsCount. /// /// In en, this message translates to: @@ -1228,12 +1342,36 @@ abstract class AppLocalizations { /// **'Channel Count'** String get settings_infoChannelCount; + /// No description provided for @settings_infoHardware. + /// + /// In en, this message translates to: + /// **'Hardware'** + String get settings_infoHardware; + + /// No description provided for @settings_infoFirmware. + /// + /// In en, this message translates to: + /// **'Firmware'** + String get settings_infoFirmware; + /// No description provided for @settings_presets. /// /// In en, this message translates to: /// **'Presets'** String get settings_presets; + /// No description provided for @settings_presetCustom. + /// + /// In en, this message translates to: + /// **'Custom'** + String get settings_presetCustom; + + /// No description provided for @settings_radioMatchWarning. + /// + /// In en, this message translates to: + /// **'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'** + String get settings_radioMatchWarning; + /// No description provided for @settings_frequency. /// /// In en, this message translates to: @@ -1243,13 +1381,13 @@ abstract class AppLocalizations { /// No description provided for @settings_frequencyHelper. /// /// In en, this message translates to: - /// **'300.0 - 2500.0'** + /// **'150.0 - 2500.0'** String get settings_frequencyHelper; /// No description provided for @settings_frequencyInvalid. /// /// In en, this message translates to: - /// **'Invalid frequency (300-2500 MHz)'** + /// **'Invalid frequency (150-2500 MHz)'** String get settings_frequencyInvalid; /// No description provided for @settings_bandwidth. @@ -1276,16 +1414,16 @@ abstract class AppLocalizations { /// **'TX Power (dBm)'** String get settings_txPower; - /// No description provided for @settings_txPowerHelper. + /// No description provided for @settings_txPowerRangeHelper. /// /// In en, this message translates to: - /// **'0 - 22'** - String get settings_txPowerHelper; + /// **'{min} to {max} dBm'** + String settings_txPowerRangeHelper(int min, int max); /// No description provided for @settings_txPowerInvalid. /// /// In en, this message translates to: - /// **'Invalid TX power (0-22 dBm)'** + /// **'Invalid TX power'** String get settings_txPowerInvalid; /// No description provided for @settings_clientRepeat. @@ -1294,6 +1432,12 @@ abstract class AppLocalizations { /// **'Off-Grid Repeat'** String get settings_clientRepeat; + /// No description provided for @settings_clientRepeatFrequencyNote. + /// + /// In en, this message translates to: + /// **'Frequency set to {freq} MHz for off-grid repeat'** + String settings_clientRepeatFrequencyNote(String freq); + /// No description provided for @settings_clientRepeatSubtitle. /// /// In en, this message translates to: @@ -1303,7 +1447,7 @@ abstract class AppLocalizations { /// No description provided for @settings_clientRepeatFreqWarning. /// /// In en, this message translates to: - /// **'Off-grid repeat requires 433, 869, or 918 MHz frequency'** + /// **'Off-grid repeat requires 433, 869.495, or 918 MHz frequency'** String get settings_clientRepeatFreqWarning; /// No description provided for @settings_error. @@ -1450,16 +1594,76 @@ abstract class AppLocalizations { /// **'Українська'** String get appSettings_languageUk; + /// No description provided for @repeater_pathHashModeOption0. + /// + /// In en, this message translates to: + /// **'1 byte'** + String get repeater_pathHashModeOption0; + + /// No description provided for @repeater_pathHashModeOption1. + /// + /// In en, this message translates to: + /// **'2 bytes'** + String get repeater_pathHashModeOption1; + + /// No description provided for @repeater_pathHashModeOption2. + /// + /// In en, this message translates to: + /// **'3 bytes'** + String get repeater_pathHashModeOption2; + + /// No description provided for @repeater_pathHashModeOption3. + /// + /// In en, this message translates to: + /// **'4 bytes'** + String get repeater_pathHashModeOption3; + + /// No description provided for @settings_pathHashModeHelper. + /// + /// In en, this message translates to: + /// **'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'** + String get settings_pathHashModeHelper; + + /// No description provided for @settings_requiresFirmware. + /// + /// In en, this message translates to: + /// **'Requires firmware {version} or newer'** + String settings_requiresFirmware(String version); + + /// No description provided for @appSettings_channelMinHops. + /// + /// In en, this message translates to: + /// **'Resend channel messages until they travel far enough'** + String get appSettings_channelMinHops; + + /// No description provided for @appSettings_channelMinHopsSubtitle. + /// + /// In en, this message translates to: + /// **'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'** + String get appSettings_channelMinHopsSubtitle; + + /// No description provided for @appSettings_channelMinHopsCount. + /// + /// In en, this message translates to: + /// **'Required hops: {count}'** + String appSettings_channelMinHopsCount(int count); + + /// No description provided for @appSettings_channelMinHopsRetries. + /// + /// In en, this message translates to: + /// **'Resend up to {count, plural, =1{1 time} other{{count} times}}'** + String appSettings_channelMinHopsRetries(int count); + /// No description provided for @appSettings_enableMessageTracing. /// /// In en, this message translates to: - /// **'Enable Message Tracing'** + /// **'Show full repeater path in messages'** String get appSettings_enableMessageTracing; /// No description provided for @appSettings_enableMessageTracingSubtitle. /// /// In en, this message translates to: - /// **'Show detailed routing and timing metadata for messages'** + /// **'Also show repeat counts and trip times. Long-press a message and choose Path for full details.'** String get appSettings_enableMessageTracingSubtitle; /// No description provided for @appSettings_notifications. @@ -1510,6 +1714,18 @@ abstract class AppLocalizations { /// **'Show notification when receiving new messages'** String get appSettings_messageNotificationsSubtitle; + /// No description provided for @appSettings_batteryOptimization. + /// + /// In en, this message translates to: + /// **'Background Activity'** + String get appSettings_batteryOptimization; + + /// No description provided for @appSettings_batteryOptimizationSubtitle. + /// + /// In en, this message translates to: + /// **'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'** + String get appSettings_batteryOptimizationSubtitle; + /// No description provided for @appSettings_channelMessageNotifications. /// /// In en, this message translates to: @@ -1690,6 +1906,12 @@ abstract class AppLocalizations { /// **'LiPo (3.0-4.2V)'** String get appSettings_batteryLipo; + /// No description provided for @appSettings_batteryLipoHv. + /// + /// In en, this message translates to: + /// **'LiPo HV (3.0-4.35V)'** + String get appSettings_batteryLipoHv; + /// No description provided for @appSettings_mapDisplay. /// /// In en, this message translates to: @@ -1792,6 +2014,42 @@ abstract class AppLocalizations { /// **'Last week'** String get appSettings_lastWeek; + /// No description provided for @appSettings_rasterTileSource. + /// + /// In en, this message translates to: + /// **'Raster Tile Source'** + String get appSettings_rasterTileSource; + + /// No description provided for @appSettings_stadiaEndpoint. + /// + /// In en, this message translates to: + /// **'Stadia Endpoint'** + String get appSettings_stadiaEndpoint; + + /// No description provided for @appSettings_stadiaApiKey. + /// + /// In en, this message translates to: + /// **'Stadia API Key'** + String get appSettings_stadiaApiKey; + + /// No description provided for @appSettings_stadiaApiKeyRequired. + /// + /// In en, this message translates to: + /// **'Required for Stadia Maps usage'** + String get appSettings_stadiaApiKeyRequired; + + /// No description provided for @appSettings_stadiaApiKeyConfigured. + /// + /// In en, this message translates to: + /// **'Configured: {maskedKey}'** + String appSettings_stadiaApiKeyConfigured(String maskedKey); + + /// No description provided for @appSettings_stadiaApiKeyDialogDescription. + /// + /// In en, this message translates to: + /// **'Enter your Stadia Maps API key. This app uses it for raster tile requests.'** + String get appSettings_stadiaApiKeyDialogDescription; + /// No description provided for @appSettings_offlineMapCache. /// /// In en, this message translates to: @@ -1942,6 +2200,42 @@ abstract class AppLocalizations { /// **'Remove {contactName} from contacts?'** String contacts_removeConfirm(String contactName); + /// No description provided for @contacts_removeFromContacts. + /// + /// In en, this message translates to: + /// **'Remove from contacts'** + String get contacts_removeFromContacts; + + /// No description provided for @contacts_removeFromContactsConfirm. + /// + /// In en, this message translates to: + /// **'{contactName} will move to Discovered contacts. Chat history will be deleted.'** + String contacts_removeFromContactsConfirm(String contactName); + + /// No description provided for @contacts_keepChatHistory. + /// + /// In en, this message translates to: + /// **'Keep chat history'** + String get contacts_keepChatHistory; + + /// No description provided for @contacts_remove. + /// + /// In en, this message translates to: + /// **'Remove'** + String get contacts_remove; + + /// No description provided for @contacts_discoveredNearby. + /// + /// In en, this message translates to: + /// **'Discovered nearby ({count})'** + String contacts_discoveredNearby(int count); + + /// No description provided for @contacts_noContactsDiscoveredHint. + /// + /// In en, this message translates to: + /// **'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'** + String get contacts_noContactsDiscoveredHint; + /// No description provided for @contacts_manageRepeater. /// /// In en, this message translates to: @@ -2206,6 +2500,30 @@ abstract class AppLocalizations { /// **'Private'** String get channels_private; + /// No description provided for @channels_hashtag. + /// + /// In en, this message translates to: + /// **'Hashtag'** + String get channels_hashtag; + + /// No description provided for @channels_addSectionJoin. + /// + /// In en, this message translates to: + /// **'Join existing'** + String get channels_addSectionJoin; + + /// No description provided for @channels_addSectionCreate. + /// + /// In en, this message translates to: + /// **'Create new'** + String get channels_addSectionCreate; + + /// No description provided for @channels_dragToReorder. + /// + /// In en, this message translates to: + /// **'Drag to reorder'** + String get channels_dragToReorder; + /// No description provided for @channels_editChannel. /// /// In en, this message translates to: @@ -2428,6 +2746,12 @@ abstract class AppLocalizations { /// **'Public channel added'** String get channels_publicChannelAdded; + /// No description provided for @channels_noFreeSlots. + /// + /// In en, this message translates to: + /// **'All channel slots are in use'** + String get channels_noFreeSlots; + /// No description provided for @channels_sortBy. /// /// In en, this message translates to: @@ -2554,6 +2878,30 @@ abstract class AppLocalizations { /// **'Clear region'** String get channels_clearRegion; + /// No description provided for @channels_regionDefaultSuffix. + /// + /// In en, this message translates to: + /// **'(default)'** + String get channels_regionDefaultSuffix; + + /// No description provided for @channels_regionSelectExplanation. + /// + /// In en, this message translates to: + /// **'Flood messages on this channel will only be forwarded by repeaters in the selected region.'** + String get channels_regionSelectExplanation; + + /// No description provided for @channels_regionEmpty. + /// + /// In en, this message translates to: + /// **'No regions yet.'** + String get channels_regionEmpty; + + /// No description provided for @channels_manageRegions. + /// + /// In en, this message translates to: + /// **'Manage regions'** + String get channels_manageRegions; + /// No description provided for @chat_noMessages. /// /// In en, this message translates to: @@ -2638,12 +2986,48 @@ abstract class AppLocalizations { /// **'Retry {current}/{max}'** String chat_retryCount(int current, int max); + /// No description provided for @chat_selectSendAction. + /// + /// In en, this message translates to: + /// **'Select send action'** + String get chat_selectSendAction; + /// No description provided for @chat_sendGif. /// /// In en, this message translates to: /// **'Send GIF'** String get chat_sendGif; + /// No description provided for @chat_removeGif. + /// + /// In en, this message translates to: + /// **'Remove GIF'** + String get chat_removeGif; + + /// No description provided for @chat_cancelReply. + /// + /// In en, this message translates to: + /// **'Cancel reply'** + String get chat_cancelReply; + + /// No description provided for @chat_sendImageLora. + /// + /// In en, this message translates to: + /// **'Send low-res image over radio'** + String get chat_sendImageLora; + + /// Shown when picking or reading a photo to send fails + /// + /// In en, this message translates to: + /// **'Couldn\'t open that image'** + String get chat_imagePickFailed; + + /// No description provided for @chat_receivedGif. + /// + /// In en, this message translates to: + /// **'Received a GIF'** + String get chat_receivedGif; + /// No description provided for @chat_reply. /// /// In en, this message translates to: @@ -2662,6 +3046,12 @@ abstract class AppLocalizations { /// **'Me'** String get chat_me; + /// No description provided for @reaction_report. + /// + /// In en, this message translates to: + /// **'Emoji Reactions'** + String get reaction_report; + /// No description provided for @emojiCategorySmileys. /// /// In en, this message translates to: @@ -3154,6 +3544,12 @@ abstract class AppLocalizations { /// **'Path'** String get chat_path; + /// No description provided for @chat_viewPathOnMap. + /// + /// In en, this message translates to: + /// **'View path on map'** + String get chat_viewPathOnMap; + /// No description provided for @chat_publicKey. /// /// In en, this message translates to: @@ -3220,6 +3616,18 @@ abstract class AppLocalizations { /// **'New messages'** String get chat_newMessages; + /// No description provided for @chat_today. + /// + /// In en, this message translates to: + /// **'Today'** + String get chat_today; + + /// No description provided for @chat_yesterday. + /// + /// In en, this message translates to: + /// **'Yesterday'** + String get chat_yesterday; + /// No description provided for @chat_openLink. /// /// In en, this message translates to: @@ -3304,6 +3712,12 @@ abstract class AppLocalizations { /// **'Center on node'** String get map_centerOnNode; + /// No description provided for @map_centerOnMe. + /// + /// In en, this message translates to: + /// **'Center on my location'** + String get map_centerOnMe; + /// No description provided for @map_details. /// /// In en, this message translates to: @@ -3340,6 +3754,12 @@ abstract class AppLocalizations { /// **'No nodes with location data'** String get map_noNodesWithLocation; + /// No description provided for @map_noNodesLocationHint. + /// + /// In en, this message translates to: + /// **'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'** + String get map_noNodesLocationHint; + /// No description provided for @map_nodesNeedGps. /// /// In en, this message translates to: @@ -3604,6 +4024,24 @@ abstract class AppLocalizations { /// **'Show guessed node locations'** String get map_showGuessedLocations; + /// No description provided for @map_clusterNodes. + /// + /// In en, this message translates to: + /// **'Group nearby nodes'** + String get map_clusterNodes; + + /// No description provided for @map_groupChip. + /// + /// In en, this message translates to: + /// **'Group'** + String get map_groupChip; + + /// No description provided for @map_clusterNodesSubtitle. + /// + /// In en, this message translates to: + /// **'When zoomed out, show nearby nodes as one numbered circle'** + String get map_clusterNodesSubtitle; + /// No description provided for @map_showDiscoveryContacts. /// /// In en, this message translates to: @@ -3646,6 +4084,12 @@ abstract class AppLocalizations { /// **'Manage Repeater'** String get map_manageRepeater; + /// No description provided for @map_manageServer. + /// + /// In en, this message translates to: + /// **'Manage Server'** + String get map_manageServer; + /// No description provided for @map_tapToAdd. /// /// In en, this message translates to: @@ -3796,6 +4240,54 @@ abstract class AppLocalizations { /// **'Failed downloads: {count}'** String mapCache_failedDownloads(int count); + /// No description provided for @mapCache_cachedTilesLabel. + /// + /// In en, this message translates to: + /// **'Cached tiles'** + String get mapCache_cachedTilesLabel; + + /// No description provided for @mapCache_cachedTileSummaryLabel. + /// + /// In en, this message translates to: + /// **'Cached tile summary'** + String get mapCache_cachedTileSummaryLabel; + + /// No description provided for @mapCache_bulkDownloadDisabledForSource. + /// + /// In en, this message translates to: + /// **'Offline bulk downloads are disabled for {source}.'** + String mapCache_bulkDownloadDisabledForSource(String source); + + /// No description provided for @mapCache_bulkDownloadDisabledInConfig. + /// + /// In en, this message translates to: + /// **'Offline bulk downloads are disabled for {source} in this app configuration.'** + String mapCache_bulkDownloadDisabledInConfig(String source); + + /// No description provided for @mapCache_summarySource. + /// + /// In en, this message translates to: + /// **'Source: {source}'** + String mapCache_summarySource(String source); + + /// No description provided for @mapCache_summaryCachedTilesForSource. + /// + /// In en, this message translates to: + /// **'Cached tiles for source: {count}'** + String mapCache_summaryCachedTilesForSource(int count); + + /// No description provided for @mapCache_summaryCachedInSelection. + /// + /// In en, this message translates to: + /// **'Cached in selected area/zoom: {count}'** + String mapCache_summaryCachedInSelection(int count); + + /// No description provided for @mapCache_summaryApproxCacheSize. + /// + /// In en, this message translates to: + /// **'Approx cache size: {size}'** + String mapCache_summaryApproxCacheSize(String size); + /// No description provided for @mapCache_boundsLabel. /// /// In en, this message translates to: @@ -3927,6 +4419,18 @@ abstract class AppLocalizations { /// **'Enter password'** String get login_enterPassword; + /// No description provided for @login_showPassword. + /// + /// In en, this message translates to: + /// **'Show password'** + String get login_showPassword; + + /// No description provided for @login_hidePassword. + /// + /// In en, this message translates to: + /// **'Hide password'** + String get login_hidePassword; + /// No description provided for @login_savePassword. /// /// In en, this message translates to: @@ -3942,7 +4446,7 @@ abstract class AppLocalizations { /// No description provided for @login_repeaterDescription. /// /// In en, this message translates to: - /// **'Enter the repeater password for guest or admin access.'** + /// **'The admin password unlocks settings and the CLI. A guest password (or blank) shows status only.'** String get login_repeaterDescription; /// No description provided for @login_roomDescription. @@ -3951,6 +4455,12 @@ abstract class AppLocalizations { /// **'Enter the room password for guest or admin access.'** String get login_roomDescription; + /// No description provided for @login_advanced. + /// + /// In en, this message translates to: + /// **'Advanced'** + String get login_advanced; + /// No description provided for @login_routing. /// /// In en, this message translates to: @@ -4017,6 +4527,12 @@ abstract class AppLocalizations { /// **'Clear'** String get common_clear; + /// No description provided for @common_clearSearch. + /// + /// In en, this message translates to: + /// **'Clear search'** + String get common_clearSearch; + /// No description provided for @path_currentPathLabel. /// /// In en, this message translates to: @@ -4065,6 +4581,18 @@ abstract class AppLocalizations { /// **'Guest Tools'** String get repeater_guestTools; + /// No description provided for @repeater_roleAdmin. + /// + /// In en, this message translates to: + /// **'ADMIN'** + String get repeater_roleAdmin; + + /// No description provided for @repeater_roleGuest. + /// + /// In en, this message translates to: + /// **'GUEST'** + String get repeater_roleGuest; + /// No description provided for @repeater_status. /// /// In en, this message translates to: @@ -4739,15 +5267,75 @@ abstract class AppLocalizations { /// No description provided for @repeater_pathHashMode. /// /// In en, this message translates to: - /// **'Path hash mode'** + /// **'Node ID size in paths'** String get repeater_pathHashMode; /// No description provided for @repeater_pathHashModeHelper. /// /// In en, this message translates to: - /// **'Bytes used to encode this repeater\'s ID in flood path/loop-detect tags. 0=1 byte (256 IDs, up to 64 hops), 1=2 bytes (65K IDs, up to 32 hops), 2=3 bytes (16M IDs, up to 21 hops). v1.13 and older firmware drops multi-byte paths — only raise once your network is on v1.14+.'** + /// **'Size of this repeater\'s ID in the paths of adverts it sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Does not affect forwarding; v1.14+ repeaters forward all sizes, but older firmware drops packets with 2- or 3-byte IDs.'** String get repeater_pathHashModeHelper; + /// No description provided for @repeater_keySettings. + /// + /// In en, this message translates to: + /// **'Change Identity Keys'** + String get repeater_keySettings; + + /// No description provided for @repeater_keySettingsSubtitle. + /// + /// In en, this message translates to: + /// **'Change the public/private keypair'** + String get repeater_keySettingsSubtitle; + + /// No description provided for @repeater_prvKey. + /// + /// In en, this message translates to: + /// **'Private key'** + String get repeater_prvKey; + + /// No description provided for @repeater_prvKeyHelper. + /// + /// In en, this message translates to: + /// **'A new private key for the repeater, a 128-character hex string.'** + String get repeater_prvKeyHelper; + + /// No description provided for @repeater_generatePrvKey. + /// + /// In en, this message translates to: + /// **'Generate a random keypair'** + String get repeater_generatePrvKey; + + /// No description provided for @repeater_stopGeneratingPrvKey. + /// + /// In en, this message translates to: + /// **'Interrupt search for keypair'** + String get repeater_stopGeneratingPrvKey; + + /// No description provided for @repeater_pubKey. + /// + /// In en, this message translates to: + /// **'Public key'** + String get repeater_pubKey; + + /// No description provided for @repeater_pubKeyHelper. + /// + /// In en, this message translates to: + /// **'This is the public key that goes with the generated private key. You can\'t set this directly.'** + String get repeater_pubKeyHelper; + + /// No description provided for @repeater_pubKeyPrefix. + /// + /// In en, this message translates to: + /// **'Desired prefix'** + String get repeater_pubKeyPrefix; + + /// No description provided for @repeater_pubKeyPrefixHelper. + /// + /// In en, this message translates to: + /// **'Find a public key that starts with these hex digits. Expected tries needed: {tries}.'** + String repeater_pubKeyPrefixHelper(int tries); + /// No description provided for @repeater_txDelay. /// /// In en, this message translates to: @@ -4904,6 +5492,24 @@ abstract class AppLocalizations { /// **'Refresh Privacy Mode'** String get repeater_refreshPrivacyMode; + /// No description provided for @repeater_refreshAll. + /// + /// In en, this message translates to: + /// **'Refresh all'** + String get repeater_refreshAll; + + /// No description provided for @repeater_settingsNotLoaded. + /// + /// In en, this message translates to: + /// **'Settings haven\'t been loaded from this repeater yet.'** + String get repeater_settingsNotLoaded; + + /// No description provided for @repeater_settingsLoadIncomplete. + /// + /// In en, this message translates to: + /// **'Some settings could not be loaded. Use the refresh buttons to retry.'** + String get repeater_settingsLoadIncomplete; + /// No description provided for @repeater_refreshed. /// /// In en, this message translates to: @@ -5378,6 +5984,120 @@ abstract class AppLocalizations { /// **'NOTE: for the various \"set ...\" commands, there is also a \"get ...\" command.'** String get repeater_commandsListNote; + /// No description provided for @repeater_frequencyRangeHelper. + /// + /// In en, this message translates to: + /// **'150-2500 MHz'** + String get repeater_frequencyRangeHelper; + + /// No description provided for @repeater_frequencyInvalid. + /// + /// In en, this message translates to: + /// **'Invalid frequency (150-2500 MHz)'** + String get repeater_frequencyInvalid; + + /// No description provided for @repeater_txPowerRangeHelper. + /// + /// In en, this message translates to: + /// **'-9 to 30 dBm'** + String get repeater_txPowerRangeHelper; + + /// No description provided for @repeater_recvErrors. + /// + /// In en, this message translates to: + /// **'Receive Errors'** + String get repeater_recvErrors; + + /// No description provided for @room_postsStored. + /// + /// In en, this message translates to: + /// **'Posts'** + String get room_postsStored; + + /// No description provided for @room_postsPushed. + /// + /// In en, this message translates to: + /// **'Posts Pushed'** + String get room_postsPushed; + + /// No description provided for @repeater_cliRegionLoadActive. + /// + /// In en, this message translates to: + /// **'Region load mode: send one region name per line, indented with spaces under its parent (add F after the name to allow flood). Lines get no reply. Send an empty line to finish, then \"region save\" to keep the result.'** + String get repeater_cliRegionLoadActive; + + /// No description provided for @repeater_cliRegionLoadHint. + /// + /// In en, this message translates to: + /// **'Region line, or empty to finish'** + String get repeater_cliRegionLoadHint; + + /// No description provided for @repeater_cliRegionLoadEnd. + /// + /// In en, this message translates to: + /// **'(end of region load)'** + String get repeater_cliRegionLoadEnd; + + /// No description provided for @repeater_cliHelpRegionDef. + /// + /// In en, this message translates to: + /// **'Defines a chain of regions in one command: each name is added under the previous one; \"name,parent\" adds the name, then continues under the given parent. Replies with the region list.'** + String get repeater_cliHelpRegionDef; + + /// No description provided for @repeater_cliHelpSetFloodMaxUnscoped. + /// + /// In en, this message translates to: + /// **'Sets the maximum hop count for forwarding flood packets that have no region scope (0-64).'** + String get repeater_cliHelpSetFloodMaxUnscoped; + + /// No description provided for @repeater_cliHelpSetFloodMaxAdvert. + /// + /// In en, this message translates to: + /// **'Sets the maximum hop count for forwarding flood adverts (0-64).'** + String get repeater_cliHelpSetFloodMaxAdvert; + + /// No description provided for @repeater_cliHelpGetFloodMaxUnscoped. + /// + /// In en, this message translates to: + /// **'Shows the maximum hop count for unscoped flood packets.'** + String get repeater_cliHelpGetFloodMaxUnscoped; + + /// No description provided for @repeater_cliHelpGetFloodMaxAdvert. + /// + /// In en, this message translates to: + /// **'Shows the maximum hop count for flood adverts.'** + String get repeater_cliHelpGetFloodMaxAdvert; + + /// No description provided for @repeater_cliHelpSetRadioFemRxGain. + /// + /// In en, this message translates to: + /// **'Toggles the LoRa front-end module\'s RX gain (LNA). Boards without one reply \"Error: unsupported\".'** + String get repeater_cliHelpSetRadioFemRxGain; + + /// No description provided for @repeater_cliHelpSetRadioFemTxGain. + /// + /// In en, this message translates to: + /// **'Toggles the LoRa front-end module\'s TX gain (PA). Boards without one reply \"Error: unsupported\".'** + String get repeater_cliHelpSetRadioFemTxGain; + + /// No description provided for @repeater_cliHelpGetRadioFemRxGain. + /// + /// In en, this message translates to: + /// **'Shows whether the LoRa front-end module\'s RX gain is on.'** + String get repeater_cliHelpGetRadioFemRxGain; + + /// No description provided for @repeater_cliHelpGetRadioFemTxGain. + /// + /// In en, this message translates to: + /// **'Shows whether the LoRa front-end module\'s TX gain is on.'** + String get repeater_cliHelpGetRadioFemTxGain; + + /// No description provided for @repeater_bridgeNote. + /// + /// In en, this message translates to: + /// **'Only available on firmware built with a bridge (RS232 or ESP-NOW).'** + String get repeater_bridgeNote; + /// No description provided for @repeater_general. /// /// In en, this message translates to: @@ -5519,7 +6239,7 @@ abstract class AppLocalizations { /// No description provided for @repeater_cliHelpSetPrvKey. /// /// In en, this message translates to: - /// **'(Serial only) Replaces the device identity private key. Reboot required to apply. Generates a new public key.'** + /// **'Replaces the device identity private key. Reboot required to apply. Generates a new public key.'** String get repeater_cliHelpSetPrvKey; /// No description provided for @repeater_cliHelpSetRadioRxGain. @@ -5537,7 +6257,7 @@ abstract class AppLocalizations { /// No description provided for @repeater_cliHelpSetPathHashMode. /// /// In en, this message translates to: - /// **'Sets the path-hash mode. 0 = legacy, 1 = standard, 2 = strict. Affects how routing paths are matched.'** + /// **'Sets the node ID size used in this repeater\'s adverts: 0 = 1 byte (up to 64 hops), 1 = 2 bytes (up to 32 hops), 2 = 3 bytes (up to 21 hops). 3 is reserved. Does not affect which sizes are forwarded. Requires firmware v1.14+.'** String get repeater_cliHelpSetPathHashMode; /// No description provided for @repeater_cliHelpSetLoopDetect. @@ -5711,7 +6431,7 @@ abstract class AppLocalizations { /// No description provided for @repeater_cliHelpGetPathHashMode. /// /// In en, this message translates to: - /// **'Shows the path-hash mode (0/1/2).'** + /// **'Shows the node ID size mode used in adverts (0 = 1 byte, 1 = 2 bytes, 2 = 3 bytes).'** String get repeater_cliHelpGetPathHashMode; /// No description provided for @repeater_cliHelpGetLoopDetect. @@ -7126,6 +7846,36 @@ abstract class AppLocalizations { /// **'Add Contact from Clipboard'** String get contacts_addContactFromClipboard; + /// No description provided for @contacts_scanQrCode. + /// + /// In en, this message translates to: + /// **'Scan QR Code'** + String get contacts_scanQrCode; + + /// No description provided for @contacts_scanQrInstructions. + /// + /// In en, this message translates to: + /// **'Point the camera at a MeshCore contact QR code'** + String get contacts_scanQrInstructions; + + /// No description provided for @contacts_qrFromGallery. + /// + /// In en, this message translates to: + /// **'Scan QR from Gallery'** + String get contacts_qrFromGallery; + + /// No description provided for @contacts_noQrCodeFound. + /// + /// In en, this message translates to: + /// **'No QR code found in the selected image.'** + String get contacts_noQrCodeFound; + + /// No description provided for @contacts_qrGalleryFailed. + /// + /// In en, this message translates to: + /// **'Could not open the gallery.'** + String get contacts_qrGalleryFailed; + /// No description provided for @contacts_ShareContact. /// /// In en, this message translates to: @@ -7300,6 +8050,12 @@ abstract class AppLocalizations { /// **'Last seen'** String get snrIndicator_lastSeen; + /// No description provided for @snrIndicator_nearByRepeatersDescription. + /// + /// In en, this message translates to: + /// **'Repeaters your radio heard directly, most recently heard first.'** + String get snrIndicator_nearByRepeatersDescription; + /// No description provided for @contactsSettings_title. /// /// In en, this message translates to: @@ -7480,6 +8236,18 @@ abstract class AppLocalizations { /// **'Radio stats'** String get radioStats_screenTitle; + /// No description provided for @radioStats_sectionSignal. + /// + /// In en, this message translates to: + /// **'Signal'** + String get radioStats_sectionSignal; + + /// No description provided for @radioStats_sectionAirtime. + /// + /// In en, this message translates to: + /// **'Airtime'** + String get radioStats_sectionAirtime; + /// No description provided for @radioStats_notConnected. /// /// In en, this message translates to: @@ -7564,6 +8332,72 @@ abstract class AppLocalizations { /// **'Translation'** String get translation_title; + /// No description provided for @imageMessages_enableTitle. + /// + /// In en, this message translates to: + /// **'Enable image messages'** + String get imageMessages_enableTitle; + + /// No description provided for @imageMessages_enableSubtitle. + /// + /// In en, this message translates to: + /// **'Send images over the mesh. Requires a one-time image model download.'** + String get imageMessages_enableSubtitle; + + /// No description provided for @imageMessages_modelSectionTitle. + /// + /// In en, this message translates to: + /// **'Image model'** + String get imageMessages_modelSectionTitle; + + /// No description provided for @imageMessages_downloadModel. + /// + /// In en, this message translates to: + /// **'Download'** + String get imageMessages_downloadModel; + + /// No description provided for @imageMessages_cancelDownload. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get imageMessages_cancelDownload; + + /// No description provided for @imageMessages_removeModel. + /// + /// In en, this message translates to: + /// **'Remove model'** + String get imageMessages_removeModel; + + /// No description provided for @imageMessages_modelReady. + /// + /// In en, this message translates to: + /// **'Ready'** + String get imageMessages_modelReady; + + /// No description provided for @imageMessages_modelNotPublished. + /// + /// In en, this message translates to: + /// **'Not published yet — this build cannot download it.'** + String get imageMessages_modelNotPublished; + + /// No description provided for @imageMessages_downloadFailed. + /// + /// In en, this message translates to: + /// **'The image model could not be downloaded.'** + String get imageMessages_downloadFailed; + + /// No description provided for @imageMessages_autoProcessTitle. + /// + /// In en, this message translates to: + /// **'Process images automatically'** + String get imageMessages_autoProcessTitle; + + /// No description provided for @imageMessages_autoProcessSubtitle. + /// + /// In en, this message translates to: + /// **'Reconstruct every image as soon as it arrives. Uses about 2 GB of memory for a second each time; leave off to reconstruct with a tap instead.'** + String get imageMessages_autoProcessSubtitle; + /// No description provided for @translation_enableTitle. /// /// In en, this message translates to: @@ -8031,6 +8865,366 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Unlock view from packet'** String get pathMap_unfollowPacket; + + /// No description provided for @imageSend_title. + /// + /// In en, this message translates to: + /// **'Send image'** + String get imageSend_title; + + /// No description provided for @imageSend_cropNote. + /// + /// In en, this message translates to: + /// **'Resized to 512 × 512 · aspect ratio not preserved'** + String get imageSend_cropNote; + + /// No description provided for @imageSend_lossyNote. + /// + /// In en, this message translates to: + /// **'Compressed to about {bytes} bytes. The receiver\'s model reconstructs it, so details will differ.'** + String imageSend_lossyNote(int bytes); + + /// No description provided for @imageSend_viewOriginal. + /// + /// In en, this message translates to: + /// **'Original'** + String get imageSend_viewOriginal; + + /// No description provided for @imageSend_viewReconstruction. + /// + /// In en, this message translates to: + /// **'What recipients see'** + String get imageSend_viewReconstruction; + + /// No description provided for @imageSend_reconstructionUnavailable. + /// + /// In en, this message translates to: + /// **'This device can\'t preview the reconstruction.'** + String get imageSend_reconstructionUnavailable; + + /// No description provided for @imageSend_modelNotDownloaded. + /// + /// In en, this message translates to: + /// **'The image model isn\'t downloaded yet. Download it in Settings to send images.'** + String get imageSend_modelNotDownloaded; + + /// No description provided for @imageSend_originalSize. + /// + /// In en, this message translates to: + /// **'Original'** + String get imageSend_originalSize; + + /// No description provided for @imageSend_onAirSize. + /// + /// In en, this message translates to: + /// **'On air'** + String get imageSend_onAirSize; + + /// No description provided for @imageSend_quality. + /// + /// In en, this message translates to: + /// **'Quality'** + String get imageSend_quality; + + /// No description provided for @imageSend_qualityStandard. + /// + /// In en, this message translates to: + /// **'Standard'** + String get imageSend_qualityStandard; + + /// No description provided for @imageSend_qualityHigh. + /// + /// In en, this message translates to: + /// **'High'** + String get imageSend_qualityHigh; + + /// No description provided for @imageSend_packetsLabel. + /// + /// In en, this message translates to: + /// **'Packets'** + String get imageSend_packetsLabel; + + /// No description provided for @imageSend_airtimeLabel. + /// + /// In en, this message translates to: + /// **'Time on air'** + String get imageSend_airtimeLabel; + + /// No description provided for @imageSend_sizeLabel. + /// + /// In en, this message translates to: + /// **'Payload'** + String get imageSend_sizeLabel; + + /// No description provided for @imageSend_packetsCount. + /// + /// In en, this message translates to: + /// **'{count} {count, plural, =1{packet} other{packets}}'** + String imageSend_packetsCount(int count); + + /// No description provided for @imageSend_range. + /// + /// In en, this message translates to: + /// **'{min}–{max}'** + String imageSend_range(String min, String max); + + /// No description provided for @imageSend_unknownValue. + /// + /// In en, this message translates to: + /// **'—'** + String get imageSend_unknownValue; + + /// No description provided for @imageSend_radioUnknownTitle. + /// + /// In en, this message translates to: + /// **'Radio settings unknown'** + String get imageSend_radioUnknownTitle; + + /// No description provided for @imageSend_radioUnknownBody. + /// + /// In en, this message translates to: + /// **'Connect to a device so the time on air can be calculated.'** + String get imageSend_radioUnknownBody; + + /// No description provided for @imageSend_longSendTitle. + /// + /// In en, this message translates to: + /// **'Long transmission'** + String get imageSend_longSendTitle; + + /// No description provided for @imageSend_longSendBody. + /// + /// In en, this message translates to: + /// **'This will hold the channel for about {duration}.'** + String imageSend_longSendBody(String duration); + + /// No description provided for @imageSend_floodNote. + /// + /// In en, this message translates to: + /// **'Flood routing: every repeater in range retransmits each packet, so the channel stays busy longer than this.'** + String get imageSend_floodNote; + + /// No description provided for @imageSend_parityTitle. + /// + /// In en, this message translates to: + /// **'Add recovery packet'** + String get imageSend_parityTitle; + + /// No description provided for @imageSend_paritySubtitle. + /// + /// In en, this message translates to: + /// **'One extra packet. Group messages are not acknowledged, so this lets the receiver rebuild the image if a single packet is lost.'** + String get imageSend_paritySubtitle; + + /// No description provided for @imageSend_send. + /// + /// In en, this message translates to: + /// **'Send'** + String get imageSend_send; + + /// No description provided for @imageSend_cancel. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get imageSend_cancel; + + /// No description provided for @imageSend_encodeFailed. + /// + /// In en, this message translates to: + /// **'This image could not be encoded.'** + String get imageSend_encodeFailed; + + /// No description provided for @imageSend_codecDownloading. + /// + /// In en, this message translates to: + /// **'The image model is still downloading.'** + String get imageSend_codecDownloading; + + /// No description provided for @imageSend_codecUnavailable. + /// + /// In en, this message translates to: + /// **'Image sending is not available on this device.'** + String get imageSend_codecUnavailable; + + /// No description provided for @imageSend_codecDisabled. + /// + /// In en, this message translates to: + /// **'Image messages are turned off in settings.'** + String get imageSend_codecDisabled; + + /// No description provided for @imageSend_deviceUnsupported. + /// + /// In en, this message translates to: + /// **'This radio cannot send image packets. Connect a device running companion firmware 13 or newer.'** + String get imageSend_deviceUnsupported; + + /// No description provided for @imageSend_directMessagesUnsupported. + /// + /// In en, this message translates to: + /// **'Images travel as group data, so they can only be sent to a channel — not in a direct message.'** + String get imageSend_directMessagesUnsupported; + + /// No description provided for @imageSend_tooLarge. + /// + /// In en, this message translates to: + /// **'That image encoded to more packets than the mesh format allows.'** + String get imageSend_tooLarge; + + /// No description provided for @imageSend_sentConfirmation. + /// + /// In en, this message translates to: + /// **'Image sent as {count} {count, plural, =1{packet} other{packets}}.'** + String imageSend_sentConfirmation(int count); + + /// No description provided for @imageSend_sendFailed. + /// + /// In en, this message translates to: + /// **'The image could not be sent: {error}'** + String imageSend_sendFailed(String error); + + /// No description provided for @imageSend_sendingProgress. + /// + /// In en, this message translates to: + /// **'Sending image — packet {sent} of {total}'** + String imageSend_sendingProgress(int sent, int total); + + /// No description provided for @receivedImage_senderPrefix. + /// + /// In en, this message translates to: + /// **'Node {prefix}'** + String receivedImage_senderPrefix(String prefix); + + /// No description provided for @receivedImage_incoming. + /// + /// In en, this message translates to: + /// **'{received} of {total} packets'** + String receivedImage_incoming(int received, int total); + + /// No description provided for @receivedImage_queued. + /// + /// In en, this message translates to: + /// **'Waiting to decode'** + String get receivedImage_queued; + + /// No description provided for @receivedImage_tapToDecode. + /// + /// In en, this message translates to: + /// **'Tap to decode'** + String get receivedImage_tapToDecode; + + /// No description provided for @receivedImage_decoding. + /// + /// In en, this message translates to: + /// **'Reconstructing… about 1 s'** + String get receivedImage_decoding; + + /// No description provided for @receivedImage_incomplete. + /// + /// In en, this message translates to: + /// **'Image incomplete — {received} of {total} packets arrived'** + String receivedImage_incomplete(int received, int total); + + /// No description provided for @receivedImage_corrupt. + /// + /// In en, this message translates to: + /// **'Image could not be reconstructed'** + String get receivedImage_corrupt; + + /// No description provided for @receivedImage_decoderMissing. + /// + /// In en, this message translates to: + /// **'Image received — image decoding is off'** + String get receivedImage_decoderMissing; + + /// No description provided for @receivedImage_evicted. + /// + /// In en, this message translates to: + /// **'Image no longer stored'** + String get receivedImage_evicted; + + /// No description provided for @receivedImage_retry. + /// + /// In en, this message translates to: + /// **'Try again'** + String get receivedImage_retry; + + /// No description provided for @receivedImage_decodeAgain. + /// + /// In en, this message translates to: + /// **'Decode again'** + String get receivedImage_decodeAgain; + + /// No description provided for @receivedImage_openSettings. + /// + /// In en, this message translates to: + /// **'Set up'** + String get receivedImage_openSettings; + + /// No description provided for @receivedImage_tapToProcess. + /// + /// In en, this message translates to: + /// **'Tap to process'** + String get receivedImage_tapToProcess; + + /// No description provided for @receivedImage_save. + /// + /// In en, this message translates to: + /// **'Save image'** + String get receivedImage_save; + + /// No description provided for @receivedImage_shareCaption. + /// + /// In en, this message translates to: + /// **'AI-reconstructed from {bytes} bytes; fine detail is generated, not transmitted.'** + String receivedImage_shareCaption(int bytes); + + /// No description provided for @receivedImage_packetInfo. + /// + /// In en, this message translates to: + /// **'Packet info'** + String get receivedImage_packetInfo; + + /// No description provided for @receivedImage_parityRecovered. + /// + /// In en, this message translates to: + /// **'One packet was rebuilt from the recovery packet.'** + String get receivedImage_parityRecovered; + + /// No description provided for @receivedImage_decodeTime. + /// + /// In en, this message translates to: + /// **'Reconstructed in {ms} ms'** + String receivedImage_decodeTime(int ms); + + /// No description provided for @receivedImage_saveFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t save the image'** + String get receivedImage_saveFailed; + + /// No description provided for @receivedImage_awaiting. + /// + /// In en, this message translates to: + /// **'{bytes} bytes · {packets} {packets, plural, =1{packet} other{packets}}'** + String receivedImage_awaiting(int bytes, int packets); + + /// No description provided for @imageSend_secondsValue. + /// + /// In en, this message translates to: + /// **'{seconds} s'** + String imageSend_secondsValue(String seconds); + + /// No description provided for @imageSend_minutesSecondsValue. + /// + /// In en, this message translates to: + /// **'{minutes} m {seconds} s'** + String imageSend_minutesSecondsValue(String minutes, String seconds); + + /// Shown under the DM composer when the message is too long for the firmware's later retry attempts + /// + /// In en, this message translates to: + /// **'Over 158 bytes: sent at most {count} times'** + String chat_longMessageRetryNote(int count); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 1404277c..49e34352 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -110,6 +110,46 @@ class AppLocalizationsBg extends AppLocalizations { @override String get messageStatus_repeated => 'Повторно чуто'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Активиране на URL изображения'; + + @override + String get urlImage_possible => + 'Възможно изображение от URL; активирайте го в Настройки.'; + @override String get common_reboot => 'Рестартирай'; @@ -368,42 +408,65 @@ class AppLocalizationsBg extends AppLocalizations { 'Радио настройките са актуализирани'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Радиото не приложи тези настройки'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Региони'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Управляне на хранилищни региони'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Регионално управление'; + + @override + String get settings_regionNameHint => 'Възразна название на региона'; + + @override + String get settings_regionAddRegion => 'Добавете регион'; + + @override + String get settings_regionFetchRegions => 'Извън рептерите от региони'; + + @override + String get settings_regionFetchRegionsFail => + 'Не бъде открити никако региони'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Тата регион е уже добавена'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Регионноименоване'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Регион отстранен'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Удаляне на регион'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Състрясна: отпиште \"$region\" от списка региони?'; } @override @@ -454,11 +517,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get settings_privacyModeSubtitle => - 'Скриване на име/местоположение в рекламите'; + 'Скриване на име/местоположение в обявите'; @override String get settings_privacyModeToggle => - 'Активирайте режим на поверителност, за да скриете името и местоположението си в рекламите.'; + 'Активирайте режим на поверителност, за да скриете името и местоположението си в обявите.'; @override String get settings_privacyModeEnabled => @@ -499,6 +562,10 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Режим на средата на телеметрията'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Място на обявата'; @@ -506,9 +573,21 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_advertLocationSubtitle => 'Включи местоположение в обявата'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Автоматична zero-hop обява при GPS обновяване'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Когато GPS местоположението се промени, изпрати zero-hop обява (изисква местоположение в обявата).'; + @override String get settings_multiAck => 'Множество ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Режим на телеметрията е обновен'; @@ -523,13 +602,13 @@ class AppLocalizationsBg extends AppLocalizations { 'Изчисти всички данни за пътищата от контактите.'; @override - String get settings_sendAdvertisement => 'Изпрати реклама'; + String get settings_sendAdvertisement => 'Изпрати обява'; @override String get settings_sendAdvertisementSubtitle => 'Излъчи присъствието сега'; @override - String get settings_advertisementSent => 'Рекламата е изпратена'; + String get settings_advertisementSent => 'Обявата е изпратена'; @override String get settings_syncTime => 'Време за синхронизация'; @@ -612,15 +691,32 @@ class AppLocalizationsBg extends AppLocalizations { @override String get settings_infoPublicKey => 'Публичен ключ'; + @override + String get settings_publicKeyCopied => 'Публичният ключ е копиран'; + @override String get settings_infoContactsCount => 'Брой контакти'; @override String get settings_infoChannelCount => 'Брой канали'; + @override + String get settings_infoHardware => 'Оборудование'; + + @override + String get settings_infoFirmware => + 'Програмно-оборонни системни программи (фirmware)'; + @override String get settings_presets => 'Предварителни настройки'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Честота (MHz)'; @@ -643,7 +739,9 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_txPower => 'TX мощност (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Невалидна мощност на TX (0-22 dBm)'; @@ -651,6 +749,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get settings_clientRepeat => 'Клиентско повторение'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Позволете на това устройство да предава пакети към мрежата за други устройства.'; @@ -733,6 +836,51 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_languageUk => 'Украински'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 байт'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 байта'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 байта'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 байта'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Разрешаване на проследяване на съобщения'; @@ -749,7 +897,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_enableNotificationsSubtitle => - 'Получавайте известия за съобщения и реклами'; + 'Получавайте известия за съобщения и обяви'; @override String get appSettings_notificationPermissionDenied => @@ -768,6 +916,13 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Показвай известие при получаване на нови съобщения'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Известия за канални съобщения'; @@ -777,7 +932,7 @@ class AppLocalizationsBg extends AppLocalizations { 'Показвай известие при получаване на съобщения от канали'; @override - String get appSettings_advertisementNotifications => 'Уведомления за реклами'; + String get appSettings_advertisementNotifications => 'Уведомления за обяви'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -808,7 +963,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Превключвайте между най-добрите пътища и режим на наводняване'; + 'Превключвайте между най-добрите пътища и режим Flood'; @override String get appSettings_autoRouteRotationEnabled => @@ -882,6 +1037,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_batteryLipo => 'Литиев полимер (3.0-4.2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo ВЗГ (3,0-4,35 В)'; + @override String get appSettings_mapDisplay => 'Карта за показване'; @@ -939,6 +1097,28 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_lastWeek => 'Миналата седмица'; + @override + String get appSettings_rasterTileSource => 'Източник на растерни плочки'; + + @override + String get appSettings_stadiaEndpoint => 'Крайна точка на Stadia'; + + @override + String get appSettings_stadiaApiKey => 'API ключ за Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Задължително за използване на Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Конфигурирано: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Въведете своя API ключ за Stadia Maps. Приложението го използва за заявки за растерни плочки.'; + @override String get appSettings_offlineMapCache => 'Кеш на офлайн карти'; @@ -986,7 +1166,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_contactsWillAppear => - 'Контактите ще се появят, когато устройствата рекламират.'; + 'Контактите ще се появят, когато устройствата изпратят обява.'; @override String get contacts_unread => 'Непрочетено'; @@ -1033,6 +1213,29 @@ class AppLocalizationsBg extends AppLocalizations { return 'Изтрий $contactName от контактите?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Управление на повторителя'; @@ -1183,6 +1386,18 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_private => 'Частен'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Редактирай канал'; @@ -1315,6 +1530,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публичен канал добавен'; + @override + String get channels_noFreeSlots => 'Няма свободни канални места'; + @override String get channels_sortBy => 'Сортирай по'; @@ -1371,17 +1589,30 @@ class AppLocalizationsBg extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Регион: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Регион: ние'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Выберете регион'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Чиста зона'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Няма съобщения.'; @@ -1435,9 +1666,27 @@ class AppLocalizationsBg extends AppLocalizations { return 'Опитай отново $current/$max'; } + @override + String get chat_selectSendAction => 'Изберете действие за изпращане'; + @override String get chat_sendGif => 'Изпрати GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Изпращане на изображение чрез MeshCore'; + + @override + String get chat_imagePickFailed => 'Не мог да откривам та изображин'; + + @override + String get chat_receivedGif => 'Получил GIF'; + @override String get chat_reply => 'Отговори'; @@ -1447,6 +1696,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_me => 'Аз'; + @override + String get reaction_report => 'Емоджи реакции'; + @override String get emojiCategorySmileys => 'Емотикони'; @@ -1594,14 +1846,14 @@ class AppLocalizationsBg extends AppLocalizations { String get routing_modeAuto => 'Автоматично'; @override - String get routing_modeFlood => 'Наводняване'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Ръчно'; @override String get routing_modeAutoHint => - 'Автоматично избира най-добрия известен път, а при липса на информация използва стратегия за наводняване.'; + 'Автоматично избира най-добрия известен път, а при липса на такъв използва режим Flood.'; @override String get routing_modeFloodHint => @@ -1653,7 +1905,7 @@ class AppLocalizationsBg extends AppLocalizations { String get routing_qualityWorked => 'Работил'; @override - String get routing_qualityFlood => 'Получено чрез наводняване'; + String get routing_qualityFlood => 'Получено чрез Flood'; @override String get routing_qualityUntested => 'Нетестирано'; @@ -1672,7 +1924,7 @@ class AppLocalizationsBg extends AppLocalizations { } @override - String get routing_floodDelivery => 'Доставка при наводняване'; + String get routing_floodDelivery => 'Доставка чрез Flood'; @override String get pathEditor_title => 'Създаване на път'; @@ -1736,6 +1988,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_path => 'Път'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Публичен ключ'; @@ -1744,7 +1999,7 @@ class AppLocalizationsBg extends AppLocalizations { 'Компресиране на изходящи съобщения'; @override - String get chat_floodForced => 'Наводняване (принудително)'; + String get chat_floodForced => 'Flood (принудително)'; @override String get chat_directForced => 'Директно (принудително)'; @@ -1755,7 +2010,7 @@ class AppLocalizationsBg extends AppLocalizations { } @override - String get chat_floodAuto => 'Наводняване (автоматично)'; + String get chat_floodAuto => 'Flood (автоматично)'; @override String get chat_direct => 'Директно'; @@ -1774,6 +2029,12 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_newMessages => 'Нови съобщения'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Отворете връзката?'; @@ -1819,6 +2080,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get map_centerOnNode => 'Центрирай върху възела'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Подробности'; @@ -1837,6 +2101,10 @@ class AppLocalizationsBg extends AppLocalizations { @override String get map_noNodesWithLocation => 'Няма възли с данни за местоположение.'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Възлите трябва да споделят GPS координатите си,\nза да се появят на картата.'; @@ -1979,6 +2247,16 @@ class AppLocalizationsBg extends AppLocalizations { String get map_showGuessedLocations => 'Покажете местоположенията на предположените възли.'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Покажи контакти за откриване'; @@ -2000,6 +2278,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get map_manageRepeater => 'Управление на повторителя'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Докоснете възлите, за да ги добавите към пътя.'; @@ -2090,6 +2371,42 @@ class AppLocalizationsBg extends AppLocalizations { return 'Неуспешни изтегляния: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2167,6 +2484,12 @@ class AppLocalizationsBg extends AppLocalizations { @override String get login_enterPassword => 'Въведете парола'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Запази паролата'; @@ -2182,6 +2505,9 @@ class AppLocalizationsBg extends AppLocalizations { String get login_roomDescription => 'Въведете паролата на стаята, за да получите достъп до настройките и статуса.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Маршрутизиране'; @@ -2192,7 +2518,7 @@ class AppLocalizationsBg extends AppLocalizations { String get login_autoUseSavedPath => 'Автоматично (използвай запазения път)'; @override - String get login_forceFloodMode => 'Принуди режим на наводняване'; + String get login_forceFloodMode => 'Принуди режим Flood'; @override String get login_managePaths => 'Управление на пътищата'; @@ -2220,6 +2546,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get common_clear => 'Изчисти'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Текущ път'; @@ -2245,6 +2574,12 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_guestTools => 'Инструменти за гости'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Статус'; @@ -2368,17 +2703,17 @@ class AppLocalizationsBg extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Общо: $total, Наводнение: $flood, Директно: $direct'; + return 'Общо: $total, Flood: $flood, Директно: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Общо: $total, Наводнение: $flood, Директно: $direct'; + return 'Общо: $total, Flood: $flood, Директно: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Поливане: $flood, Директен: $direct'; + return 'Flood: $flood, Директен: $direct'; } @override @@ -2472,13 +2807,13 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_privacyModeSubtitle => - 'Скриване на име/местоположение в рекламите'; + 'Скриване на име/местоположение в обявите'; @override - String get repeater_advertisementSettings => 'Настройки на рекламите'; + String get repeater_advertisementSettings => 'Настройки на обявите'; @override - String get repeater_localAdvertInterval => 'Интервал на местната реклама'; + String get repeater_localAdvertInterval => 'Интервал на локалната обява'; @override String repeater_localAdvertIntervalMinutes(int minutes) { @@ -2486,8 +2821,7 @@ class AppLocalizationsBg extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => - 'Интервал на рекламата за наводняване'; + String get repeater_floodAdvertInterval => 'Интервал на Flood обявата'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2496,7 +2830,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_encryptedAdvertInterval => - 'Криптиран интервал на рекламата'; + 'Криптиран интервал на обявата'; @override String get repeater_dangerZone => 'Опасна зона'; @@ -2619,11 +2953,11 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_refreshOwnerInfo => 'Обновете информацията за оператора'; @override - String get repeater_floodMax => 'Максимален брой хопове при наводняване'; + String get repeater_floodMax => 'Максимален брой скокове при Flood'; @override String get repeater_floodMaxHelper => - 'Максималният брой хопове, които един пакет може да премине (0-64)'; + 'Максималният брой скокове, които един пакет може да премине (0-64)'; @override String get repeater_advancedSettings => 'Разширени настройки'; @@ -2639,12 +2973,48 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_pathHashModeHelper => 'Байтовете, използвани за кодиране на идентификатора на този повторител в таговете за откриване на потоци/цикли, са: 0=1 байт (256 идентификатора, до 64 скока), 1=2 байта (65 000 идентификатора, до 32 скока), 2=3 байта (16 милиона идентификатора, до 21 скока). Версиите 1.13 и по-старите фърмуери използват многобайтови пътища - само след като мрежата е актуализирана до версия 1.14 или по-нова.'; + @override + String get repeater_keySettings => 'Изменяне на идентичности ключа'; + + @override + String get repeater_keySettingsSubtitle => + 'Замени ключовият пар от публични/частни'; + + @override + String get repeater_prvKey => 'Частни ключ'; + + @override + String get repeater_prvKeyHelper => + 'Нова приватна ключ на повторчето, 128-символовна шестнадатерична строка.'; + + @override + String get repeater_generatePrvKey => 'Генериране на случайна ключи'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Прервана поискна на ключова парта'; + + @override + String get repeater_pubKey => 'Публична ключ'; + + @override + String get repeater_pubKeyHelper => + 'Та е публичната ключ, която се свързува с генериранта приватна ключ. Трябва да не настройте тоа напрямо.'; + + @override + String get repeater_pubKeyPrefix => 'Желата префикс'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Наискате публична ключ, който почева с този шестнадатницил. Ожидавани проби: $tries.'; + } + @override String get repeater_txDelay => 'Забавяне на Flood TX'; @override String get repeater_txDelayHelper => - 'Разстоянието между пакетите при наводняване като множител на времето за пренос на пакета (0-2, по подразбиране 0.5). По-висока стойност означава по-малко сблъсъци, но по-бавно предаване.'; + 'Разстоянието между пакетите при Flood трафик като множител на времето за пренос на пакета (0-2, по подразбиране 0.5). По-висока стойност означава по-малко сблъсъци, но по-бавно предаване.'; @override String get repeater_directTxDelay => 'Забавяне на директното предаване'; @@ -2671,18 +3041,18 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_actionsTitle => 'Действия'; @override - String get repeater_sendAdvert => 'Изпрати реклама за наводняване'; + String get repeater_sendAdvert => 'Изпрати Flood обява'; @override String get repeater_sendAdvertSubtitle => - 'Публикувай реклама за наводняване в мрежата.'; + 'Разпространи Flood обява в мрежата.'; @override - String get repeater_sendAdvertZeroHop => 'Изпрати реклама без хопове'; + String get repeater_sendAdvertZeroHop => 'Изпрати обява с нулев скок'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Публикувай реклама, която достига до целевата аудитория само чрез директно разпространение.'; + 'Разпространи обява само с един скок (без повторители).'; @override String get repeater_clockSync => 'Синхронизирай часовника сега'; @@ -2734,6 +3104,17 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Обнови режима на поверителност'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label е обновено'; @@ -2799,7 +3180,7 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_cliQuickVersion => 'Версия'; @override - String get repeater_cliQuickAdvertise => 'Рекламирай'; + String get repeater_cliQuickAdvertise => 'Обяви'; @override String get repeater_cliQuickClock => 'Часовник'; @@ -2811,7 +3192,7 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_cliQuickDiscovery => 'Открий Съседи'; @override - String get repeater_cliHelpAdvert => 'Изпраща рекламен пакет'; + String get repeater_cliHelpAdvert => 'Изпраща пакет за обява'; @override String get repeater_cliHelpReboot => @@ -2850,7 +3231,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Задава максималния брой хопове на входящ пакет за заливване (ако >= max, пакетът не се предава).'; + 'Задава максималния брой скокове на входящ Flood пакет (ако >= max, пакетът не се предава).'; @override String get repeater_cliHelpSetIntThresh => @@ -2866,11 +3247,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - 'Задава интервала на таймера в минути за изпращане на локален (безпроблемен) рекламен пакет. Задайте на 0, за да го деактивирате.'; + 'Задава интервала на таймера в минути за изпращане на локален (нулев скок) пакет за обява. Задайте на 0, за да го деактивирате.'; @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Задава интервала на таймера в часове за изпращане на пакет с реклама за наводнение. Задайте на 0, за да го деактивирате.'; + 'Задава интервала на таймера в часове за изпращане на Flood пакет за обява. Задайте на 0, за да го деактивирате.'; @override String get repeater_cliHelpSetGuestPassword => @@ -2881,11 +3262,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpSetLat => - 'Задава географска ширина на картата с реклами (в десетими градуси).'; + 'Задава географска ширина на картата за обявата (в десетични градуси).'; @override String get repeater_cliHelpSetLon => - 'Задава обхвата на дължина на картата на рекламата. (десетими градуса)'; + 'Задава географска дължина на картата за обявата. (десетични градуси)'; @override String get repeater_cliHelpSetRadio => @@ -2897,7 +3278,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - 'Задава фактор, умножен по времето на въздух за пакет в режим на наводнение и с рандомизирана система за слотове, за да забави предаването му (за да намали вероятността от сблъсъци).'; + 'Задава фактор, умножен по времето на въздух за Flood пакет и с рандомизирана система за слотове, за да забави предаването му (за да намали вероятността от сблъсъци).'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2953,7 +3334,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - 'Показва списък с други възли на репитер, чути чрез нулев хоп реклами. Всяка линия е id-prefix-hex:timestamp:snr-times-4'; + 'Показва списък с други възли на повторител, чути чрез обяви с нулев скок. Всяка линия е id-prefix-hex:timestamp:snr-times-4'; @override String get repeater_cliHelpNeighborRemove => @@ -2961,7 +3342,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(сериен режим) Изброява всички дефинирани региони и текущите разрешения за наводнения.'; + '(сериен режим) Изброява всички дефинирани региони и текущите разрешения за Flood.'; @override String get repeater_cliHelpRegionLoad => @@ -3015,7 +3396,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - 'Предоставя конфигурацията на рекламата за местоположението на възела:\n- none: не включвайте местоположението в рекламите\n- share: споделяйте gps местоположението (от SensorManager)\n- prefs: рекламирайте местоположението, съхранено в предпочитанията'; + 'Предоставя конфигурацията на обявата за местоположението на възела:\n- none: не включвайте местоположението в обявите\n- share: споделяйте gps местоположението (от SensorManager)\n- prefs: обявявайте местоположението, съхранено в предпочитанията'; @override String get repeater_cliHelpGpsAdvertSet => @@ -3028,6 +3409,75 @@ class AppLocalizationsBg extends AppLocalizations { String get repeater_commandsListNote => 'ЗАБЕЛЕЖКА: за различните команди \"set ...\", също така съществува команда \"get ...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Невалидна честота (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => 'от -9 до 30 dBm'; + + @override + String get repeater_recvErrors => 'Грешки при приемане'; + + @override + String get room_postsStored => 'Публикации'; + + @override + String get room_postsPushed => 'Изпратени публикации'; + + @override + String get repeater_cliRegionLoadActive => + 'Режим на зареждане на региони: изпращайте по едно име на регион на ред, с отстъп от интервали под съответния родител (добавете F след името, за да разрешите flood). Редовете не получават отговор. Изпратете празен ред, за да завършите, след което изпратете „region save“, за да запазите резултата.'; + + @override + String get repeater_cliRegionLoadHint => + 'Ред за регион или празно за завършване'; + + @override + String get repeater_cliRegionLoadEnd => '(край на зареждането на региони)'; + + @override + String get repeater_cliHelpRegionDef => + 'Задава верига от региони с една команда: всяко име се добавя под предишното; „name,parent“ добавя името и продължава под указания родител. Връща списъка с региони.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Задава максималния брой скокове за препращане на flood пакети без определена регионална област (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Задава максималния брой скокове за препращане на flood обяви (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Показва максималния брой скокове за flood пакети без определена област.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Показва максималния брой скокове за flood обяви.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Превключва RX усилването (LNA) на LoRa предния модул. Платки без такъв отговарят с „Error: unsupported“.'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Превключва TX усилването (PA) на LoRa предния модул. Платки без такъв отговарят с „Error: unsupported“.'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Показва дали RX усилването на LoRa предния модул е включено.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Показва дали TX усилването на LoRa предния модул е включено.'; + + @override + String get repeater_bridgeNote => + 'Налично само за прошивка с мост (RS232 или ESP-NOW).'; + @override String get repeater_general => 'Общо'; @@ -3077,7 +3527,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Изпраща реклама, която достига само до съседни устройства (само до съседни мрежи).'; + 'Изпраща обява, която достига само до съседни устройства (само до съседни мрежи).'; @override String get repeater_cliHelpStartOta => @@ -3121,7 +3571,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpSetOwnerInfo => - 'Задава низовете с информация за контакт на собственика, които са включени в рекламите. Използвайте \'|\' за нови редове.'; + 'Задава низовете с информация за контакт на собственика, които са включени в обявите. Използвайте \'|\' за нови редове.'; @override String get repeater_cliHelpSetPathHashMode => @@ -3198,11 +3648,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Показва времето на рекламата в минути.'; + 'Показва интервала на обявата в минути.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Показва интервала на рекламата за навод в часове.'; + 'Показва интервала на Flood обявата в часове.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3220,7 +3670,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Показва коефициента за забавяне при режим на наводняване.'; + 'Показва коефициента за забавяне при режим Flood.'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3228,7 +3678,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Показва максималния брой на повторни наводнения.'; + 'Показва максималния брой скокове при Flood.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3316,11 +3766,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Списва регионите, които позволяват преминаване на превозни средства при наводнение.'; + 'Списва регионите, които разрешават Flood трафик.'; @override String get repeater_cliHelpRegionListDenied => - 'Списва региони, които забраняват движението по пътищата при наводнения.'; + 'Списва региони, които забраняват Flood трафик.'; @override String get repeater_cliHelpStatsPackets => @@ -3606,7 +4056,7 @@ class AppLocalizationsBg extends AppLocalizations { String get channelPath_unknownPath => 'Неизвестно'; @override - String get channelPath_floodPath => 'Поливане'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Директно'; @@ -3878,7 +4328,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Един или повече от хмелите липсва местоположение!'; + 'Един или повече от скоковете няма определено местоположение!'; @override String get pathTrace_clearTooltip => 'Изчисти пътя'; @@ -4092,10 +4542,10 @@ class AppLocalizationsBg extends AppLocalizations { 'Контактът не е успешно импортиран.'; @override - String get contacts_zeroHopAdvert => 'Реклама без скок'; + String get contacts_zeroHopAdvert => 'Обява без скок'; @override - String get contacts_floodAdvert => 'Реклама за наводняване'; + String get contacts_floodAdvert => 'Flood обява'; @override String get contacts_copyAdvertToClipboard => 'Копирай обявата в клипборда'; @@ -4103,6 +4553,23 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Добави контакт от клипборда'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Копирай контакт в клипборда'; @@ -4117,8 +4584,7 @@ class AppLocalizationsBg extends AppLocalizations { 'Неуспешно изпращане на контакт.'; @override - String get contacts_contactAdvertCopied => - 'Рекламата е копирана в клипборда.'; + String get contacts_contactAdvertCopied => 'Обявата е копирана в клипборда.'; @override String get contacts_contactAdvertCopyFailed => @@ -4228,6 +4694,10 @@ class AppLocalizationsBg extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Последно видян'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Настройки на контактите'; @@ -4334,6 +4804,12 @@ class AppLocalizationsBg extends AppLocalizations { String get radioStats_screenTitle => 'Статистически данни за радиопредаванията'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Свържете се с устройство, за да видите статистически данни за радиопредаване.'; @@ -4392,6 +4868,44 @@ class AppLocalizationsBg extends AppLocalizations { @override String get translation_title => 'Превод'; + @override + String get imageMessages_enableTitle => 'Абilitiraм изображените сообщения'; + + @override + String get imageMessages_enableSubtitle => + 'Изправате изображения чрез сетката. Треба е одноразовна загрузка модел на изображение.'; + + @override + String get imageMessages_modelSectionTitle => 'Изображени модель'; + + @override + String get imageMessages_downloadModel => 'Скачане'; + + @override + String get imageMessages_cancelDownload => 'Отмена'; + + @override + String get imageMessages_removeModel => 'Удалете модель'; + + @override + String get imageMessages_modelReady => 'Готов'; + + @override + String get imageMessages_modelNotPublished => + 'Еще не опубликовано — тази версия не може да скане.'; + + @override + String get imageMessages_downloadFailed => + 'Модел за изображение не може да бъде скачан.'; + + @override + String get imageMessages_autoProcessTitle => + 'Автоматически обрабатвате изображения'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Катализиране на всята изображение сразу по пришествие. Използване на около 2 ГБ на втора пъти; откажете от реконструкцията чаке при натискане.'; + @override String get translation_enableTitle => 'Активирайте превода'; @@ -4675,4 +5189,249 @@ class AppLocalizationsBg extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Спри проследяването на пакета'; + + @override + String get imageSend_title => 'Изпрати изображение'; + + @override + String get imageSend_cropNote => + 'Масштабиран до 512 × 512 · соотношение сторон не съхранясе'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Късно на използване на език:'; + + @override + String get imageSend_onAirSize => 'В ефир'; + + @override + String get imageSend_quality => 'Качество'; + + @override + String get imageSend_qualityStandard => 'Стандарт'; + + @override + String get imageSend_qualityHigh => 'Высок'; + + @override + String get imageSend_packetsLabel => 'Пакети'; + + @override + String get imageSend_airtimeLabel => 'Времето на изкъсване'; + + @override + String get imageSend_sizeLabel => 'Баланса'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакета', + one: 'пакет', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Настройки на радио неизвестни'; + + @override + String get imageSend_radioUnknownBody => + 'Усредете се с устройство, за да се отработа часът на изстъпане.'; + + @override + String get imageSend_longSendTitle => 'Долга пресилка'; + + @override + String imageSend_longSendBody(String duration) { + return 'Тази буде поддержива открит отряд на около $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood маршрутизация: всеки повторител в обхват препредава всеки пакет, затова каналът остава зает по-дълго от посоченото тук време.'; + + @override + String get imageSend_parityTitle => 'Возобновителен пакет'; + + @override + String get imageSend_paritySubtitle => + 'Едно дополително пакет. Групни извещания не принимаются, след това разбирателят едно пакетто, какщо е пропущен един пакет.'; + + @override + String get imageSend_send => 'Отправляй'; + + @override + String get imageSend_cancel => 'Отмена'; + + @override + String get imageSend_encodeFailed => + 'Тази изображение не може да бъде кодирано.'; + + @override + String get imageSend_codecDownloading => + 'Модел на изображение еще разгрузира.'; + + @override + String get imageSend_codecUnavailable => + 'Изглед отправа не е доступен на този устройство.'; + + @override + String get imageSend_codecDisabled => + 'Изображенията на извещенията е отключена в настройките.'; + + @override + String get imageSend_deviceUnsupported => + 'Та радиота не може да пресылава изображени пакети. Подключите устройство, който работи с компанионски прошивка 13 или новия.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Изображенията се превозводя се как групова информация, следато да се отправят единствено на канал — не в лична вестка.'; + + @override + String get imageSend_tooLarge => + 'Таата изображение е кодирано в по-числа пакети, отгоре както формат на сетта разрешава.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакета', + one: 'пакет', + ); + return 'Изображението е изпратено като $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Изображение не може да бъде отправено: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Отправка наизображение — пакет $sent от $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Узъдето $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received от $total пакета'; + } + + @override + String get receivedImage_queued => 'Ожидането за декодиране'; + + @override + String get receivedImage_tapToDecode => 'Натискнете за декодиране'; + + @override + String get receivedImage_decoding => 'Повторно… за приблизително 1 секунда'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Изображение неполно — $received от $total пакети отправили'; + } + + @override + String get receivedImage_corrupt => 'Изображение не може да бъде воссоздано'; + + @override + String get receivedImage_decoderMissing => + 'Получена изображение — разгадка на изображение е вреjan'; + + @override + String get receivedImage_evicted => 'Изображение не е хранитено'; + + @override + String get receivedImage_retry => 'Повтори'; + + @override + String get receivedImage_decodeAgain => 'Правилейте заново'; + + @override + String get receivedImage_openSettings => 'Настройте'; + + @override + String get receivedImage_tapToProcess => 'Натискнете за обработка'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'пакета', + one: 'пакет', + ); + return '$bytes байта · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds секунди'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes мин $seconds сек'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Над 158 байта: изпраща се най-много $count пъти'; + } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 9e061241..0c9c6a5d 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -110,6 +110,46 @@ class AppLocalizationsDe extends AppLocalizations { @override String get messageStatus_repeated => 'Mehrfach gehört'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'URL-Bilder anzeigen'; + + @override + String get urlImage_possible => + 'Mögliches URL-Bild; in den Einstellungen aktivieren.'; + @override String get common_reboot => 'Neustart'; @@ -369,6 +409,10 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_radioSettingsUpdated => 'Funkparameter aktualisiert'; + @override + String get settings_radioSettingsNotApplied => + 'Das Funkgerät hat diese Einstellungen nicht übernommen'; + @override String get settings_regionSettings => 'Regionen'; @@ -376,6 +420,23 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_regionSettingsSubtitle => 'Gespeicherte Regionen verwalten'; + @override + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; + + @override + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; + + @override + String get settings_regionDefault => 'Default region'; + + @override + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + @override String get settings_regionManagement_screenTitle => 'Regions-Verwaltung'; @@ -386,14 +447,15 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_regionAddRegion => 'Region hinzufügen'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionFetchRegions => 'Regionen von Wiederholern abrufen'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionFetchRegionsFail => + 'Es wurden keine Regionen gefunden.'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Diese Region wurde bereits hinzugefügt'; @override String get settings_regionName => 'Regions-Name'; @@ -499,6 +561,10 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_telemetryEnvironmentMode => 'Telemetrie-Umgebungsmodus'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Standort in Ankündigung'; @@ -506,9 +572,21 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_advertLocationSubtitle => 'Standort in die Ankündigung einschließen.'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatische Zero-Hop-Ankündigung bei GPS-Update'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Wenn sich der GPS-Standort ändert, eine Zero-Hop-Ankündigung senden (erfordert Standort in der Ankündigung).'; + @override String get settings_multiAck => 'Mehrfach-ACKs'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Telemetriemodus aktualisiert'; @@ -609,15 +687,31 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_infoPublicKey => 'Öffentlicher Schlüssel'; + @override + String get settings_publicKeyCopied => 'Öffentlicher Schlüssel kopiert'; + @override String get settings_infoContactsCount => 'Kontakte'; @override String get settings_infoChannelCount => 'Kanäle'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Voreinstellungen'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frequenz (MHz)'; @@ -640,7 +734,9 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_txPower => 'Sendeleistung (dBm)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Ungültige Sendeleistung (0-22 dBm)'; @@ -648,6 +744,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_clientRepeat => 'Weiterleitung ohne Netzstrom'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Dieses Gerät kann Mesh-Pakete für andere weiterleiten'; @@ -730,6 +831,51 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_languageUk => 'Ukrainisch'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 Byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 Bytes'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 Bytes'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 Bytes'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Nachrichtenverfolgung aktivieren'; @@ -767,6 +913,13 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Benachrichtigung anzeigen, wenn neue Direktnachrichten eingehen'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Kanalnachrichten-Benachrichtigungen'; @@ -879,6 +1032,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0–4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0–4,35 V)'; + @override String get appSettings_mapDisplay => 'Kartendarstellung'; @@ -936,6 +1092,28 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_lastWeek => 'Letzte Woche'; + @override + String get appSettings_rasterTileSource => 'Quelle für Rasterkacheln'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia-Endpunkt'; + + @override + String get appSettings_stadiaApiKey => 'Stadia-API-Schlüssel'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Für die Nutzung von Stadia Maps erforderlich'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Konfiguriert: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Geben Sie Ihren Stadia-Maps-API-Schlüssel ein. Die App verwendet ihn für Rasterkachel-Anfragen.'; + @override String get appSettings_offlineMapCache => 'Offline-Karten-Cache'; @@ -1030,6 +1208,29 @@ class AppLocalizationsDe extends AppLocalizations { return '$contactName aus den Kontakten entfernen?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Repeater verwalten'; @@ -1179,6 +1380,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_private => 'Privat'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Kanal bearbeiten'; @@ -1312,6 +1525,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_publicChannelAdded => 'Öffentlicher Kanal hinzugefügt'; + @override + String get channels_noFreeSlots => 'Alle Kanal-Slots sind belegt'; + @override String get channels_sortBy => 'Sortieren nach'; @@ -1383,6 +1599,19 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_clearRegion => 'Region zurücksetzen'; + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; + @override String get chat_noMessages => 'Noch keine Nachrichten.'; @@ -1436,9 +1665,27 @@ class AppLocalizationsDe extends AppLocalizations { return 'Wiederholen $current/$max'; } + @override + String get chat_selectSendAction => 'Sendeaktion auswählen'; + @override String get chat_sendGif => 'GIF senden'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Bild über MeshCore senden'; + + @override + String get chat_imagePickFailed => 'Konnte dieses Bild nicht öffnen.'; + + @override + String get chat_receivedGif => 'Erhalten eines GIF'; + @override String get chat_reply => 'Antworten'; @@ -1448,6 +1695,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_me => 'Ich'; + @override + String get reaction_report => 'Emoji-Reaktionen'; + @override String get emojiCategorySmileys => 'Emoticons'; @@ -1594,14 +1844,14 @@ class AppLocalizationsDe extends AppLocalizations { String get routing_modeAuto => 'Automatisch'; @override - String get routing_modeFlood => 'Flut'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Manuell'; @override String get routing_modeAutoHint => - 'Wählt automatisch den besten bekannten Pfad und wechselt auf Flut, wenn keiner bekannt ist.'; + 'Wählt automatisch den besten bekannten Pfad und wechselt in den Flood-Modus, wenn keiner bekannt ist.'; @override String get routing_modeFloodHint => @@ -1619,7 +1869,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get routing_noPathYet => - 'Noch kein Pfad gefunden. Die nächste Nachricht wird geflutet, bis eine Route entdeckt ist.'; + 'Noch kein Pfad gefunden. Die nächste Nachricht wird im Flood-Modus gesendet, bis eine Route entdeckt ist.'; @override String get routing_floodBroadcast => 'Über alle Repeater senden'; @@ -1641,13 +1891,13 @@ class AppLocalizationsDe extends AppLocalizations { String get routing_inUse => 'In Verwendung'; @override - String get routing_qualityStrong => 'Starker erster Hop'; + String get routing_qualityStrong => 'Starker erster Sprung'; @override - String get routing_qualityGood => 'Guter erster Hop'; + String get routing_qualityGood => 'Guter erster Sprung'; @override - String get routing_qualityFair => 'Ausreichender erster Hop'; + String get routing_qualityFair => 'Ausreichender erster Sprung'; @override String get routing_qualityWorked => 'Hat zugestellt'; @@ -1735,6 +1985,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_path => 'Pfad'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Öffentlicher Schlüssel'; @@ -1743,7 +1996,7 @@ class AppLocalizationsDe extends AppLocalizations { 'Komprimieren ausgehender Nachrichten'; @override - String get chat_floodForced => 'Geflutet (erzwungen)'; + String get chat_floodForced => 'Flood (erzwungen)'; @override String get chat_directForced => 'Direkt (erzwungen)'; @@ -1754,7 +2007,7 @@ class AppLocalizationsDe extends AppLocalizations { } @override - String get chat_floodAuto => 'Geflutet (automatisch)'; + String get chat_floodAuto => 'Flood (automatisch)'; @override String get chat_direct => 'Direkt'; @@ -1773,6 +2026,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_newMessages => 'Neue Nachrichten'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Link öffnen?'; @@ -1818,6 +2077,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get map_centerOnNode => 'Auf Knoten zentrieren'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Details'; @@ -1836,6 +2098,10 @@ class AppLocalizationsDe extends AppLocalizations { @override String get map_noNodesWithLocation => 'Keine Knoten mit Standortdaten'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Knoten müssen ihre GPS-Koordinaten teilen,\num auf der Karte zu erscheinen.'; @@ -1977,6 +2243,16 @@ class AppLocalizationsDe extends AppLocalizations { @override String get map_showGuessedLocations => 'Vermutete Knotenstandorte anzeigen'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Entdeckte Kontakte anzeigen'; @@ -1998,6 +2274,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get map_manageRepeater => 'Repeater verwalten'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Tippen Sie auf Knoten, um sie zum Pfad hinzuzufügen.'; @@ -2090,6 +2369,42 @@ class AppLocalizationsDe extends AppLocalizations { return 'Fehlgeschlagene Downloads: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2167,6 +2482,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get login_enterPassword => 'Passwort eingeben'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Passwort speichern'; @@ -2182,6 +2503,9 @@ class AppLocalizationsDe extends AppLocalizations { String get login_roomDescription => 'Geben Sie das Raumkennwort ein, um auf die Einstellungen und den Status zuzugreifen.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Routen'; @@ -2193,7 +2517,7 @@ class AppLocalizationsDe extends AppLocalizations { 'Automatisch (gespeicherten Pfad verwenden)'; @override - String get login_forceFloodMode => 'Flut-Modus erzwingen'; + String get login_forceFloodMode => 'Flood-Modus erzwingen'; @override String get login_managePaths => 'Pfadverwaltung'; @@ -2221,6 +2545,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get common_clear => 'Leeren'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Aktueller Pfad'; @@ -2246,6 +2573,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_guestTools => 'Gastwerkzeuge'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Status'; @@ -2270,7 +2603,8 @@ class AppLocalizationsDe extends AppLocalizations { String get repeater_neighbors => 'Nachbarn'; @override - String get repeater_neighborsSubtitle => 'Anzahl der Hop-Nachbarn anzeigen.'; + String get repeater_neighborsSubtitle => + 'Anzahl der Sprungnachbarn anzeigen.'; @override String get repeater_settings => 'Einstellungen'; @@ -2633,7 +2967,44 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Bytes, die zur Kodierung der ID dieses Repeaters in Flood-Pfad-/Schleifen-Erkennung-Tags verwendet werden. 0 = 1 Byte (256 IDs, bis zu 64 Hops), 1 = 2 Bytes (65.000 IDs, bis zu 32 Hops), 2 = 3 Bytes (16 Millionen IDs, bis zu 21 Hops). Firmware-Versionen 1.13 und älter verwenden mehrstellige Pfade – ab Version 1.14+ wird nur ein Pfad erstellt, sobald das Netzwerk aktiv ist.'; + 'Bytes, die zur Kodierung der ID dieses Repeaters in Flood-Pfad-/Schleifen-Erkennung-Tags verwendet werden. 0 = 1 Byte (256 IDs, bis zu 64 Sprüngen), 1 = 2 Bytes (65.000 IDs, bis zu 32 Sprüngen), 2 = 3 Bytes (16 Millionen IDs, bis zu 21 Sprüngen). Firmware-Versionen 1.13 und älter verwenden mehrstellige Pfade – ab Version 1.14+ wird nur ein Pfad erstellt, sobald das Netzwerk aktiv ist.'; + + @override + String get repeater_keySettings => 'Identitätsschlüssel ändern'; + + @override + String get repeater_keySettingsSubtitle => + 'Ändern Sie das öffentliche/private Schlüsselpaar'; + + @override + String get repeater_prvKey => 'Privatschlüssel'; + + @override + String get repeater_prvKeyHelper => + 'Ein neuer privater Schlüssel für den Repeater, eine 128-stellige Hexadezimalzeichenkette.'; + + @override + String get repeater_generatePrvKey => + 'Generiere ein zufälliges Schlüsselpaar'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Suchvorgang für Schlüsselpaar unterbrechen'; + + @override + String get repeater_pubKey => 'Öffentlicher Schlüssel'; + + @override + String get repeater_pubKeyHelper => + 'Dies ist der öffentliche Schlüssel, der zum generierten privaten Schlüssel gehört. Sie können dies nicht direkt festlegen.'; + + @override + String get repeater_pubKeyPrefix => 'Gewünschtes Präfix'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Suchen Sie einen öffentlichen Schlüssel, der mit diesen Hexadezimalziffern beginnt. Erwartete Versuche: $tries.'; + } @override String get repeater_txDelay => 'Flood-TX-Verzögerung'; @@ -2732,6 +3103,17 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Privatsphärenmodus aktualisieren'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label aktualisiert'; @@ -2868,14 +3250,14 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Legt das Timer-Intervall in Stunden für den Versand eines Flut-Ankündigungspacket fest. Auf 0 setzen, um es zu deaktivieren.'; + 'Legt das Timer-Intervall in Stunden für den Versand eines Flood-Ankündigungspaket fest. Auf 0 setzen, um es zu deaktivieren.'; @override String get repeater_cliHelpSetGuestPassword => 'Legt/aktualisiert das Gastpasswort fest. (für Repeater können Gast-Logins die \"Get Stats\"-Anfrage senden)'; @override - String get repeater_cliHelpSetName => 'Legt den Anzeigenamen fest.'; + String get repeater_cliHelpSetName => 'Legt den Ankündigungsnamen fest.'; @override String get repeater_cliHelpSetLat => @@ -2978,7 +3360,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpRegionAllowf => - 'Legt die \'Flut\'-Berechtigung für die angegebene Region fest. (\'\' für den globalen/legacy-Bereich)'; + 'Legt die \'Flood\'-Berechtigung für die angegebene Region fest. (\'\' für den globalen/legacy-Bereich)'; @override String get repeater_cliHelpRegionDenyf => @@ -3012,11 +3394,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - 'Gibt Konfiguration für die Standortanzeige des Knotens:\n- none: Standort nicht in Anzeigen einbeziehen\n- share: GPS-Standort teilen (von SensorManager)\n- prefs: Standort aus Einstellungen anzeigen'; + 'Gibt Konfiguration für die Standort-Ankündigung des Knotens:\n- none: Standort nicht in Ankündigungen einbeziehen\n- share: GPS-Standort teilen (von SensorManager)\n- prefs: Standort aus den Einstellungen ankündigen'; @override String get repeater_cliHelpGpsAdvertSet => - 'Legt die Standort-Anzeigekonfiguration fest.'; + 'Legt die Standort-Ankündigungskonfiguration fest.'; @override String get repeater_commandsListTitle => 'Befehlsliste'; @@ -3025,6 +3407,75 @@ class AppLocalizationsDe extends AppLocalizations { String get repeater_commandsListNote => 'ACHTUNG: Für die verschiedenen „set ...“-Befehle gibt es auch einen „get ...“-Befehl.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Ungültige Frequenz (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 bis 30 dBm'; + + @override + String get repeater_recvErrors => 'Empfangsfehler'; + + @override + String get room_postsStored => 'Beiträge'; + + @override + String get room_postsPushed => 'Gesendete Beiträge'; + + @override + String get repeater_cliRegionLoadActive => + 'Regions-Ladevorgang: Sende pro Zeile einen Regionsnamen, eingerückt mit Leerzeichen unter der übergeordneten Region (F nach dem Namen anhängen, um Flood zu erlauben). Zeilen erhalten keine Antwort. Sende eine Leerzeile zum Abschließen, dann \"region save\", um das Ergebnis zu speichern.'; + + @override + String get repeater_cliRegionLoadHint => + 'Regionszeile, oder leer zum Abschließen'; + + @override + String get repeater_cliRegionLoadEnd => '(Ende des Regions-Ladevorgangs)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definiert in einem Befehl eine Kette von Regionen: Jeder Name wird unter dem vorherigen hinzugefügt; \"name,parent\" fügt den Namen hinzu und setzt dann unter der angegebenen übergeordneten Region fort. Antwortet mit der Regionsliste.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Legt die maximale Hop-Anzahl für die Weiterleitung von Flood-Paketen ohne Region-Scope fest (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Legt die maximale Hop-Anzahl für die Weiterleitung von Flood-Ankündigungen fest (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Zeigt die maximale Hop-Anzahl für Flood-Pakete ohne Region-Scope an.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Zeigt die maximale Hop-Anzahl für Flood-Ankündigungen an.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Schaltet den RX-Gain (LNA) des LoRa-Frontend-Moduls um. Boards ohne dieses Modul antworten mit \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Schaltet den TX-Gain (PA) des LoRa-Frontend-Moduls um. Boards ohne dieses Modul antworten mit \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Zeigt, ob der RX-Gain des LoRa-Frontend-Moduls aktiviert ist.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Zeigt, ob der TX-Gain des LoRa-Frontend-Moduls aktiviert ist.'; + + @override + String get repeater_bridgeNote => + 'Nur verfügbar bei Firmware, die mit einer Bridge (RS232 oder ESP-NOW) gebaut wurde.'; + @override String get repeater_general => 'Allgemein'; @@ -3074,7 +3525,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Sendet eine Werbeanzeige, die nur an unmittelbare Nachbarn gesendet wird (ohne Zwischenstation).'; + 'Sendet eine Ankündigung, die nur an unmittelbare Nachbarn gesendet wird (ohne Zwischenstation).'; @override String get repeater_cliHelpStartOta => @@ -3197,11 +3648,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Zeigt die Dauer des lokalen Werbeintervalls in Minuten an.'; + 'Zeigt die Dauer des lokalen Ankündigungsintervalls in Minuten an.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Zeigt die Dauer der Werbeunterbrechung in Stunden an.'; + 'Zeigt die Dauer des Flood-Ankündigungsintervalls in Stunden an.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3219,7 +3670,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Zeigt den Faktor für die Übertragungsverzögerung im Notfallmodus an.'; + 'Zeigt den Faktor für die Übertragungsverzögerung im Flood-Modus an.'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3607,7 +4058,7 @@ class AppLocalizationsDe extends AppLocalizations { String get channelPath_unknownPath => 'Unbekannt'; @override - String get channelPath_floodPath => 'Geflutet'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Direkt'; @@ -4100,7 +4551,7 @@ class AppLocalizationsDe extends AppLocalizations { String get contacts_zeroHopAdvert => 'Zero-Hop-Ankündigung'; @override - String get contacts_floodAdvert => 'Flut-Ankündigung'; + String get contacts_floodAdvert => 'Flood-Ankündigung'; @override String get contacts_copyAdvertToClipboard => @@ -4110,15 +4561,32 @@ class AppLocalizationsDe extends AppLocalizations { String get contacts_addContactFromClipboard => 'Kontakt aus Zwischenablage hinzufügen'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Kontakt in die Zwischenablage kopieren'; @override - String get contacts_ShareContactZeroHop => 'Kontakt über Anzeige teilen'; + String get contacts_ShareContactZeroHop => 'Kontakt über Ankündigung teilen'; @override String get contacts_zeroHopContactAdvertSent => - 'Kontakt über Anzeige gesendet'; + 'Kontakt über Ankündigung gesendet'; @override String get contacts_zeroHopContactAdvertFailed => @@ -4126,7 +4594,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contacts_contactAdvertCopied => - 'Anzeige in die Zwischenablage kopiert.'; + 'Ankündigung in die Zwischenablage kopiert.'; @override String get contacts_contactAdvertCopyFailed => @@ -4236,6 +4704,10 @@ class AppLocalizationsDe extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Zuletzt gesehen'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Kontakteinstellungen'; @@ -4343,6 +4815,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get radioStats_screenTitle => 'Senderinformationen'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Verbinden Sie ein Gerät, um Radiostatistiken anzuzeigen.'; @@ -4401,6 +4879,43 @@ class AppLocalizationsDe extends AppLocalizations { @override String get translation_title => 'Übersetzung'; + @override + String get imageMessages_enableTitle => 'Bildnachrichten aktivieren'; + + @override + String get imageMessages_enableSubtitle => + 'Bilder über das Netzwerk senden. Einmaliges Herunterladen eines Bildmodells erforderlich.'; + + @override + String get imageMessages_modelSectionTitle => 'Bildmodell'; + + @override + String get imageMessages_downloadModel => 'Herunterladen'; + + @override + String get imageMessages_cancelDownload => 'Stornieren'; + + @override + String get imageMessages_removeModel => 'Modell entfernen'; + + @override + String get imageMessages_modelReady => 'Bereit'; + + @override + String get imageMessages_modelNotPublished => + 'Noch nicht veröffentlicht – dieser Build kann es nicht herunterladen.'; + + @override + String get imageMessages_downloadFailed => + 'Das Bildmodell konnte nicht heruntergeladen werden.'; + + @override + String get imageMessages_autoProcessTitle => 'Automatisch Bilder verarbeiten'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Rekonstruiere jedes Bild sofort nach dem Eintreffen. Verbraucht etwa 2 GB Arbeitsspeicher für jede zweite Wiederherstellung; deaktiviere die automatische Rekonstruktion mit einem Tippen.'; + @override String get translation_enableTitle => 'Aktivieren Sie die Übersetzung'; @@ -4688,4 +5203,251 @@ class AppLocalizationsDe extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Fixierung aufheben'; + + @override + String get imageSend_title => 'Bild senden'; + + @override + String get imageSend_cropNote => + 'Für 512 × 512 skaliert · Seitenverhältnis nicht erhalten'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + 'Originaltext:\n\nThe quick brown fox jumps over the lazy dog.\n\nÜbersetzung:\n\nDer schnelle braune Fuchs springt über den faulen Hund.'; + + @override + String get imageSend_onAirSize => 'On air'; + + @override + String get imageSend_quality => 'Qualität'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Hoch'; + + @override + String get imageSend_packetsLabel => 'Pakete'; + + @override + String get imageSend_airtimeLabel => 'Sendezeit'; + + @override + String get imageSend_sizeLabel => 'Nutzlast'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Pakete', + one: 'Paket', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Radioeinstellungen unbekannt'; + + @override + String get imageSend_radioUnknownBody => + 'Verbinden Sie das Gerät, damit die Sendezeit berechnet werden kann.'; + + @override + String get imageSend_longSendTitle => 'Lange Übertragung'; + + @override + String imageSend_longSendBody(String duration) { + return 'Dies hält den Kanal für etwa $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood-Weiterleitung: Jeder Repeater im Bereich leitet jedes Paket weiter, wodurch der Kanal länger als dieser Zeitraum beschäftigt bleibt.'; + + @override + String get imageSend_parityTitle => 'Wiederherstellungspaket'; + + @override + String get imageSend_paritySubtitle => + 'Ein zusätzliches Paket. Gruppen-Nachrichten werden nicht bestätigt, daher kann der Empfänger das Bild rekonstruieren, falls ein Paket verloren geht.'; + + @override + String get imageSend_send => 'Senden'; + + @override + String get imageSend_cancel => 'Stornieren'; + + @override + String get imageSend_encodeFailed => + 'Dieses Bild konnte nicht kodiert werden.'; + + @override + String get imageSend_codecDownloading => + 'Das Bildmodell wird noch heruntergeladen.'; + + @override + String get imageSend_codecUnavailable => + 'Bildversand ist auf diesem Gerät nicht verfügbar.'; + + @override + String get imageSend_codecDisabled => + 'Bildnachrichten sind in den Einstellungen deaktiviert.'; + + @override + String get imageSend_deviceUnsupported => + 'Dieses Radio kann keine Bildpakete senden. Verbinden Sie ein Gerät mit der Companion-Firmware-Version 13 oder neuer.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Bilder werden als Gruppendaten übertragen, daher können sie nur an einen Kanal gesendet werden – nicht per Direktnachricht.'; + + @override + String get imageSend_tooLarge => + 'Dieses Bild wurde in mehr Pakete kodiert, als das Mesh-Format zulässt.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Pakete', + one: 'Paket', + ); + return 'Bild gesendet als $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Das Bild konnte nicht gesendet werden: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Bildversand — Paket $sent von $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Kritisch: Diese Platzhalter $prefix beibehalten.'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received von $total Paketen'; + } + + @override + String get receivedImage_queued => 'Warten auf die Entschlüsselung'; + + @override + String get receivedImage_tapToDecode => 'Tippen Sie, um zu entschlüsseln'; + + @override + String get receivedImage_decoding => 'Rekonstruktion… ca. 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Bild unvollständig — $received von $total Paketen eingetroffen'; + } + + @override + String get receivedImage_corrupt => + 'Das Bild konnte nicht rekonstruiert werden.'; + + @override + String get receivedImage_decoderMissing => + 'Bild empfangen — Bilddekodierung fehlgeschlagen'; + + @override + String get receivedImage_evicted => 'Bild nicht mehr gespeichert'; + + @override + String get receivedImage_retry => 'Versuchen Sie es erneut'; + + @override + String get receivedImage_decodeAgain => 'Entschlüsseln Sie es erneut'; + + @override + String get receivedImage_openSettings => 'Einrichten'; + + @override + String get receivedImage_tapToProcess => 'Klicken Sie, um fortzufahren'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'Pakete', + one: 'Paket', + ); + return '$bytes Bytes · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds s'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes Min $seconds Sek'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Über 158 Byte: wird höchstens $count Mal gesendet'; + } } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 08f45442..bd873506 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -99,7 +99,8 @@ class AppLocalizationsEn extends AppLocalizations { String get messageStatus_sent => 'Sent'; @override - String get messageStatus_delivered => 'Delivered'; + String get messageStatus_delivered => + 'Delivered. The contact confirmed they got it.'; @override String get messageStatus_pending => 'Sending'; @@ -110,6 +111,45 @@ class AppLocalizationsEn extends AppLocalizations { @override String get messageStatus_repeated => 'Heard repeated'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Enable URL images'; + + @override + String get urlImage_possible => 'Possible URL image; enable it in Settings.'; + @override String get common_reboot => 'Reboot'; @@ -363,11 +403,33 @@ class AppLocalizationsEn extends AppLocalizations { @override String get settings_radioSettingsUpdated => 'Radio settings updated'; + @override + String get settings_radioSettingsNotApplied => + 'The radio did not apply these settings'; + @override String get settings_regionSettings => 'Regions'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettingsSubtitle => + 'Limit channel floods to an area'; + + @override + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; + + @override + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; + + @override + String get settings_regionDefault => 'Default region'; + + @override + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; @override String get settings_regionManagement_screenTitle => 'Region Management'; @@ -476,19 +538,23 @@ class AppLocalizationsEn extends AppLocalizations { String get settings_denyAll => 'Deny all'; @override - String get settings_allowByContact => 'Allow by contact flags'; + String get settings_allowByContact => 'Only contacts I allow'; @override String get settings_allowAll => 'Allow all'; @override - String get settings_telemetryBaseMode => 'Telemetry Base Mode'; + String get settings_telemetryBaseMode => 'Who can request battery and status'; @override - String get settings_telemetryLocationMode => 'Telemetry Location Mode'; + String get settings_telemetryLocationMode => 'Who can request my location'; @override - String get settings_telemetryEnvironmentMode => 'Telemetry Environment Mode'; + String get settings_telemetryEnvironmentMode => 'Who can request sensor data'; + + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; @override String get settings_advertLocation => 'Advert Location'; @@ -496,9 +562,21 @@ class AppLocalizationsEn extends AppLocalizations { @override String get settings_advertLocationSubtitle => 'Include location in advert.'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Auto Zero-Hop Advert On GPS Update'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'App setting: when your GPS position changes, automatically advertise your new location to nearby nodes only (requires Advert Location).'; + @override String get settings_multiAck => 'Multi-ACKs'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Telemetry mode updated'; @@ -597,23 +675,39 @@ class AppLocalizationsEn extends AppLocalizations { @override String get settings_infoPublicKey => 'Public Key'; + @override + String get settings_publicKeyCopied => 'Public key copied'; + @override String get settings_infoContactsCount => 'Contacts Count'; @override String get settings_infoChannelCount => 'Channel Count'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Presets'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frequency (MHz)'; @override - String get settings_frequencyHelper => '300.0 - 2500.0'; + String get settings_frequencyHelper => '150.0 - 2500.0'; @override - String get settings_frequencyInvalid => 'Invalid frequency (300-2500 MHz)'; + String get settings_frequencyInvalid => 'Invalid frequency (150-2500 MHz)'; @override String get settings_bandwidth => 'Bandwidth'; @@ -628,21 +722,28 @@ class AppLocalizationsEn extends AppLocalizations { String get settings_txPower => 'TX Power (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override - String get settings_txPowerInvalid => 'Invalid TX power (0-22 dBm)'; + String get settings_txPowerInvalid => 'Invalid TX power'; @override String get settings_clientRepeat => 'Off-Grid Repeat'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Allow this device to repeat mesh packets for others'; @override String get settings_clientRepeatFreqWarning => - 'Off-grid repeat requires 433, 869, or 918 MHz frequency'; + 'Off-grid repeat requires 433, 869.495, or 918 MHz frequency'; @override String settings_error(String message) { @@ -719,11 +820,57 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_languageUk => 'Українська'; @override - String get appSettings_enableMessageTracing => 'Enable Message Tracing'; + String get repeater_pathHashModeOption0 => '1 byte'; + + @override + String get repeater_pathHashModeOption1 => '2 bytes'; + + @override + String get repeater_pathHashModeOption2 => '3 bytes'; + + @override + String get repeater_pathHashModeOption3 => '4 bytes'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + + @override + String get appSettings_enableMessageTracing => + 'Show full repeater path in messages'; @override String get appSettings_enableMessageTracingSubtitle => - 'Show detailed routing and timing metadata for messages'; + 'Also show repeat counts and trip times. Long-press a message and choose Path for full details.'; @override String get appSettings_notifications => 'Notifications'; @@ -752,6 +899,13 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Show notification when receiving new messages'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Channel Message Notifications'; @@ -862,6 +1016,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3.0-4.2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3.0-4.35V)'; + @override String get appSettings_mapDisplay => 'Map Display'; @@ -919,6 +1076,28 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_lastWeek => 'Last week'; + @override + String get appSettings_rasterTileSource => 'Raster Tile Source'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia Endpoint'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API Key'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Required for Stadia Maps usage'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Configured: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Enter your Stadia Maps API key. This app uses it for raster tile requests.'; + @override String get appSettings_offlineMapCache => 'Offline Map Cache'; @@ -1011,6 +1190,29 @@ class AppLocalizationsEn extends AppLocalizations { return 'Remove $contactName from contacts?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Manage Repeater'; @@ -1158,6 +1360,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_private => 'Private'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Edit channel'; @@ -1287,6 +1501,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_publicChannelAdded => 'Public channel added'; + @override + String get channels_noFreeSlots => 'All channel slots are in use'; + @override String get channels_sortBy => 'Sort by'; @@ -1353,6 +1570,19 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_clearRegion => 'Clear region'; + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; + @override String get chat_noMessages => 'No messages yet'; @@ -1405,9 +1635,27 @@ class AppLocalizationsEn extends AppLocalizations { return 'Retry $current/$max'; } + @override + String get chat_selectSendAction => 'Select send action'; + @override String get chat_sendGif => 'Send GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Send low-res image over radio'; + + @override + String get chat_imagePickFailed => 'Couldn\'t open that image'; + + @override + String get chat_receivedGif => 'Received a GIF'; + @override String get chat_reply => 'Reply'; @@ -1417,6 +1665,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_me => 'Me'; + @override + String get reaction_report => 'Emoji Reactions'; + @override String get emojiCategorySmileys => 'Smileys'; @@ -1702,6 +1953,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_path => 'Path'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Public Key'; @@ -1739,6 +1993,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_newMessages => 'New messages'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Open Link?'; @@ -1784,6 +2044,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get map_centerOnNode => 'Center on node'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Details'; @@ -1802,6 +2065,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get map_noNodesWithLocation => 'No nodes with location data'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Nodes need to share their GPS coordinates\nto appear on the map'; @@ -1943,6 +2210,16 @@ class AppLocalizationsEn extends AppLocalizations { @override String get map_showGuessedLocations => 'Show guessed node locations'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Show Discovery Contacts'; @@ -1964,6 +2241,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get map_manageRepeater => 'Manage Repeater'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Tap on nodes to add them to the path.'; @@ -2051,6 +2331,42 @@ class AppLocalizationsEn extends AppLocalizations { return 'Failed downloads: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2128,6 +2444,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get login_enterPassword => 'Enter password'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Save password'; @@ -2137,12 +2459,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get login_repeaterDescription => - 'Enter the repeater password for guest or admin access.'; + 'The admin password unlocks settings and the CLI. A guest password (or blank) shows status only.'; @override String get login_roomDescription => 'Enter the room password for guest or admin access.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Routing'; @@ -2181,6 +2506,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get common_clear => 'Clear'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Current path'; @@ -2205,6 +2533,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_guestTools => 'Guest Tools'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Status'; @@ -2583,11 +2917,46 @@ class AppLocalizationsEn extends AppLocalizations { 'Tuning knobs for experienced operators'; @override - String get repeater_pathHashMode => 'Path hash mode'; + String get repeater_pathHashMode => 'Node ID size in paths'; @override String get repeater_pathHashModeHelper => - 'Bytes used to encode this repeater\'s ID in flood path/loop-detect tags. 0=1 byte (256 IDs, up to 64 hops), 1=2 bytes (65K IDs, up to 32 hops), 2=3 bytes (16M IDs, up to 21 hops). v1.13 and older firmware drops multi-byte paths — only raise once your network is on v1.14+.'; + 'Size of this repeater\'s ID in the paths of adverts it sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Does not affect forwarding; v1.14+ repeaters forward all sizes, but older firmware drops packets with 2- or 3-byte IDs.'; + + @override + String get repeater_keySettings => 'Change Identity Keys'; + + @override + String get repeater_keySettingsSubtitle => + 'Change the public/private keypair'; + + @override + String get repeater_prvKey => 'Private key'; + + @override + String get repeater_prvKeyHelper => + 'A new private key for the repeater, a 128-character hex string.'; + + @override + String get repeater_generatePrvKey => 'Generate a random keypair'; + + @override + String get repeater_stopGeneratingPrvKey => 'Interrupt search for keypair'; + + @override + String get repeater_pubKey => 'Public key'; + + @override + String get repeater_pubKeyHelper => + 'This is the public key that goes with the generated private key. You can\'t set this directly.'; + + @override + String get repeater_pubKeyPrefix => 'Desired prefix'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Find a public key that starts with these hex digits. Expected tries needed: $tries.'; + } @override String get repeater_txDelay => 'Flood TX delay'; @@ -2683,6 +3052,17 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Refresh Privacy Mode'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label refreshed'; @@ -2974,6 +3354,74 @@ class AppLocalizationsEn extends AppLocalizations { String get repeater_commandsListNote => 'NOTE: for the various \"set ...\" commands, there is also a \"get ...\" command.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Invalid frequency (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 to 30 dBm'; + + @override + String get repeater_recvErrors => 'Receive Errors'; + + @override + String get room_postsStored => 'Posts'; + + @override + String get room_postsPushed => 'Posts Pushed'; + + @override + String get repeater_cliRegionLoadActive => + 'Region load mode: send one region name per line, indented with spaces under its parent (add F after the name to allow flood). Lines get no reply. Send an empty line to finish, then \"region save\" to keep the result.'; + + @override + String get repeater_cliRegionLoadHint => 'Region line, or empty to finish'; + + @override + String get repeater_cliRegionLoadEnd => '(end of region load)'; + + @override + String get repeater_cliHelpRegionDef => + 'Defines a chain of regions in one command: each name is added under the previous one; \"name,parent\" adds the name, then continues under the given parent. Replies with the region list.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Sets the maximum hop count for forwarding flood packets that have no region scope (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Sets the maximum hop count for forwarding flood adverts (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Shows the maximum hop count for unscoped flood packets.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Shows the maximum hop count for flood adverts.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Toggles the LoRa front-end module\'s RX gain (LNA). Boards without one reply \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Toggles the LoRa front-end module\'s TX gain (PA). Boards without one reply \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Shows whether the LoRa front-end module\'s RX gain is on.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Shows whether the LoRa front-end module\'s TX gain is on.'; + + @override + String get repeater_bridgeNote => + 'Only available on firmware built with a bridge (RS232 or ESP-NOW).'; + @override String get repeater_general => 'General'; @@ -3059,7 +3507,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_cliHelpSetPrvKey => - '(Serial only) Replaces the device identity private key. Reboot required to apply. Generates a new public key.'; + 'Replaces the device identity private key. Reboot required to apply. Generates a new public key.'; @override String get repeater_cliHelpSetRadioRxGain => @@ -3071,7 +3519,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_cliHelpSetPathHashMode => - 'Sets the path-hash mode. 0 = legacy, 1 = standard, 2 = strict. Affects how routing paths are matched.'; + 'Sets the node ID size used in this repeater\'s adverts: 0 = 1 byte (up to 64 hops), 1 = 2 bytes (up to 32 hops), 2 = 3 bytes (up to 21 hops). 3 is reserved. Does not affect which sizes are forwarded. Requires firmware v1.14+.'; @override String get repeater_cliHelpSetLoopDetect => @@ -3180,7 +3628,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_cliHelpGetPathHashMode => - 'Shows the path-hash mode (0/1/2).'; + 'Shows the node ID size mode used in adverts (0 = 1 byte, 1 = 2 bytes, 2 = 3 bytes).'; @override String get repeater_cliHelpGetLoopDetect => @@ -4042,6 +4490,23 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Add Contact from Clipboard'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Copy contact to Clipboard'; @@ -4164,6 +4629,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Last seen'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Contacts settings'; @@ -4263,6 +4732,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get radioStats_screenTitle => 'Radio stats'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Connect to a device to view radio statistics.'; @@ -4321,6 +4796,43 @@ class AppLocalizationsEn extends AppLocalizations { @override String get translation_title => 'Translation'; + @override + String get imageMessages_enableTitle => 'Enable image messages'; + + @override + String get imageMessages_enableSubtitle => + 'Send images over the mesh. Requires a one-time image model download.'; + + @override + String get imageMessages_modelSectionTitle => 'Image model'; + + @override + String get imageMessages_downloadModel => 'Download'; + + @override + String get imageMessages_cancelDownload => 'Cancel'; + + @override + String get imageMessages_removeModel => 'Remove model'; + + @override + String get imageMessages_modelReady => 'Ready'; + + @override + String get imageMessages_modelNotPublished => + 'Not published yet — this build cannot download it.'; + + @override + String get imageMessages_downloadFailed => + 'The image model could not be downloaded.'; + + @override + String get imageMessages_autoProcessTitle => 'Process images automatically'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Reconstruct every image as soon as it arrives. Uses about 2 GB of memory for a second each time; leave off to reconstruct with a tap instead.'; + @override String get translation_enableTitle => 'Enable translation'; @@ -4602,4 +5114,248 @@ class AppLocalizationsEn extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Unlock view from packet'; + + @override + String get imageSend_title => 'Send image'; + + @override + String get imageSend_cropNote => + 'Resized to 512 × 512 · aspect ratio not preserved'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Original'; + + @override + String get imageSend_onAirSize => 'On air'; + + @override + String get imageSend_quality => 'Quality'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'High'; + + @override + String get imageSend_packetsLabel => 'Packets'; + + @override + String get imageSend_airtimeLabel => 'Time on air'; + + @override + String get imageSend_sizeLabel => 'Payload'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'packets', + one: 'packet', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Radio settings unknown'; + + @override + String get imageSend_radioUnknownBody => + 'Connect to a device so the time on air can be calculated.'; + + @override + String get imageSend_longSendTitle => 'Long transmission'; + + @override + String imageSend_longSendBody(String duration) { + return 'This will hold the channel for about $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood routing: every repeater in range retransmits each packet, so the channel stays busy longer than this.'; + + @override + String get imageSend_parityTitle => 'Add recovery packet'; + + @override + String get imageSend_paritySubtitle => + 'One extra packet. Group messages are not acknowledged, so this lets the receiver rebuild the image if a single packet is lost.'; + + @override + String get imageSend_send => 'Send'; + + @override + String get imageSend_cancel => 'Cancel'; + + @override + String get imageSend_encodeFailed => 'This image could not be encoded.'; + + @override + String get imageSend_codecDownloading => + 'The image model is still downloading.'; + + @override + String get imageSend_codecUnavailable => + 'Image sending is not available on this device.'; + + @override + String get imageSend_codecDisabled => + 'Image messages are turned off in settings.'; + + @override + String get imageSend_deviceUnsupported => + 'This radio cannot send image packets. Connect a device running companion firmware 13 or newer.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Images travel as group data, so they can only be sent to a channel — not in a direct message.'; + + @override + String get imageSend_tooLarge => + 'That image encoded to more packets than the mesh format allows.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'packets', + one: 'packet', + ); + return 'Image sent as $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'The image could not be sent: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Sending image — packet $sent of $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Node $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received of $total packets'; + } + + @override + String get receivedImage_queued => 'Waiting to decode'; + + @override + String get receivedImage_tapToDecode => 'Tap to decode'; + + @override + String get receivedImage_decoding => 'Reconstructing… about 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Image incomplete — $received of $total packets arrived'; + } + + @override + String get receivedImage_corrupt => 'Image could not be reconstructed'; + + @override + String get receivedImage_decoderMissing => + 'Image received — image decoding is off'; + + @override + String get receivedImage_evicted => 'Image no longer stored'; + + @override + String get receivedImage_retry => 'Try again'; + + @override + String get receivedImage_decodeAgain => 'Decode again'; + + @override + String get receivedImage_openSettings => 'Set up'; + + @override + String get receivedImage_tapToProcess => 'Tap to process'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'packets', + one: 'packet', + ); + return '$bytes bytes · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds s'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes m $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Over 158 bytes: sent at most $count times'; + } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index da9decb1..364ebc2f 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -110,6 +110,46 @@ class AppLocalizationsEs extends AppLocalizations { @override String get messageStatus_repeated => 'Escuchado repetidamente'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Habilitar imágenes de URL'; + + @override + String get urlImage_possible => + 'Posible imagen de URL; actívala en Configuración.'; + @override String get common_reboot => 'Reiniciar'; @@ -368,42 +408,64 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_radioSettingsUpdated => 'Ajustes de radio actualizados'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'La radio no aplicó esta configuración'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regiones'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Gestionar regiones almacenadas'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Gestión de Regiones'; + + @override + String get settings_regionNameHint => 'Nombre de la región'; + + @override + String get settings_regionAddRegion => 'Añadir región'; + + @override + String get settings_regionFetchRegions => 'Obtener regiones de repetidores'; + + @override + String get settings_regionFetchRegionsFail => 'No se encontraron regiones'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Esta región ya ha sido agregada'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Nombre de la Región'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Región eliminada'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Eliminar Región'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return '¿Eliminar \"$region\" de la lista de regiones?'; } @override @@ -497,15 +559,31 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Modo de entorno de telemetría'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Ubicación de anuncio'; @override String get settings_advertLocationSubtitle => 'Incluir ubicación en anuncio'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Anuncio de cero saltos automático al actualizar GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Cuando cambie la ubicación GPS, enviar un anuncio de cero saltos (requiere ubicación en anuncio).'; + @override String get settings_multiAck => 'Múltiples respuestas de confirmación'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Modo de telemetría actualizado'; @@ -608,15 +686,31 @@ class AppLocalizationsEs extends AppLocalizations { @override String get settings_infoPublicKey => 'Clave pública'; + @override + String get settings_publicKeyCopied => 'Clave pública copiada'; + @override String get settings_infoContactsCount => 'Número de contactos'; @override String get settings_infoChannelCount => 'Número de canales'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Preajustes'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frecuencia (MHz)'; @@ -639,7 +733,9 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_txPower => 'Potencia TX (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Potencia de TX inválida (0-22 dBm)'; @@ -647,6 +743,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get settings_clientRepeat => 'Repetir sin conexión'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Permita que este dispositivo repita los paquetes de red para otros usuarios.'; @@ -729,6 +830,51 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_languageUk => 'Ucraniano'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bytes'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bytes'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bytes'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Habilitar seguimiento de mensajes'; @@ -764,6 +910,13 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Mostrar notificación al recibir nuevos mensajes'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Notificaciones de mensajes del canal'; @@ -876,6 +1029,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2 V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3.0-4.35V)'; + @override String get appSettings_mapDisplay => 'Visualización del mapa'; @@ -933,6 +1089,28 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_lastWeek => 'La semana pasada'; + @override + String get appSettings_rasterTileSource => 'Fuente de teselas ráster'; + + @override + String get appSettings_stadiaEndpoint => 'Punto de acceso de Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Clave API de Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Obligatorio para usar Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Configurado: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Introduce tu clave API de Stadia Maps. La aplicación la usa para solicitar teselas ráster.'; + @override String get appSettings_offlineMapCache => 'Caché de mapa sin conexión'; @@ -1027,6 +1205,29 @@ class AppLocalizationsEs extends AppLocalizations { return '¿Eliminar $contactName de los contactos?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Gestionar repetidor'; @@ -1178,6 +1379,18 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_private => 'Privado'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Editar canal'; @@ -1311,6 +1524,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canal público añadido'; + @override + String get channels_noFreeSlots => 'Todos los espacios de canal están en uso'; + @override String get channels_sortBy => 'Ordenar por'; @@ -1368,17 +1584,30 @@ class AppLocalizationsEs extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Región: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Región: ninguna'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Seleccione una región'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Zona despejada'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Aún no hay mensajes'; @@ -1432,9 +1661,27 @@ class AppLocalizationsEs extends AppLocalizations { return 'Reintentar $current/$max'; } + @override + String get chat_selectSendAction => 'Seleccionar acción de envío'; + @override String get chat_sendGif => 'Enviar GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Enviar imagen mediante MeshCore'; + + @override + String get chat_imagePickFailed => 'No pude abrir esa imagen'; + + @override + String get chat_receivedGif => 'Recibido un GIF'; + @override String get chat_reply => 'Responder'; @@ -1444,6 +1691,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_me => 'Yo'; + @override + String get reaction_report => 'Reacciones con Emoji'; + @override String get emojiCategorySmileys => 'Emoticones'; @@ -1731,6 +1981,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_path => 'Ruta'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Clave pública'; @@ -1768,6 +2021,12 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_newMessages => 'Nuevos mensajes'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => '¿Abrir enlace?'; @@ -1813,6 +2072,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get map_centerOnNode => 'Enfocar en el nodo'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Detalles'; @@ -1831,6 +2093,10 @@ class AppLocalizationsEs extends AppLocalizations { @override String get map_noNodesWithLocation => 'No hay nodos con datos de ubicación'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Los nodos necesitan compartir sus coordenadas GPS\npara aparecer en el mapa'; @@ -1973,6 +2239,16 @@ class AppLocalizationsEs extends AppLocalizations { String get map_showGuessedLocations => 'Mostrar las ubicaciones estimadas de los nodos.'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Mostrar contactos de descubrimiento'; @@ -1994,6 +2270,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get map_manageRepeater => 'Gestionar repetidor'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Toque los nodos para añadirlos a la ruta.'; @@ -2084,6 +2363,42 @@ class AppLocalizationsEs extends AppLocalizations { return 'Descargas fallidas: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2161,6 +2476,12 @@ class AppLocalizationsEs extends AppLocalizations { @override String get login_enterPassword => 'Introduce la contraseña'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Guardar contraseña'; @@ -2176,6 +2497,9 @@ class AppLocalizationsEs extends AppLocalizations { String get login_roomDescription => 'Introduce la contraseña de la sala para acceder como invitado o administrador.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Enrutamiento'; @@ -2214,6 +2538,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get common_clear => 'Borrar'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Ruta actual'; @@ -2239,6 +2566,12 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_guestTools => 'Herramientas para invitados'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Estado'; @@ -2577,7 +2910,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_loopDetectHelper => - 'Crea paquetes de \"flujo\" que parezcan bucles de enrutamiento.'; + 'Descarta los paquetes de inundación que parezcan bucles de enrutamiento'; @override String get repeater_loopDetectOff => 'Desactivado'; @@ -2634,6 +2967,42 @@ class AppLocalizationsEs extends AppLocalizations { String get repeater_pathHashModeHelper => 'Bytes utilizados para codificar el ID de este repetidor en las etiquetas de ruta/detección de bucles. 0=1 byte (256 IDs, hasta 64 saltos), 1=2 bytes (65.000 IDs, hasta 32 saltos), 2=3 bytes (16 millones de IDs, hasta 21 saltos). Las versiones 1.13 y anteriores de firmware eliminan rutas de múltiples bytes; solo se detectan una vez que la red está activa en la versión 1.14 o posterior.'; + @override + String get repeater_keySettings => 'Cambiar Claves de Identidad'; + + @override + String get repeater_keySettingsSubtitle => + 'Cambiar la pareja de claves pública/privada'; + + @override + String get repeater_prvKey => 'Clave privada'; + + @override + String get repeater_prvKeyHelper => + 'Una nueva clave privada para el repetidor, una cadena hexadecimal de 128 caracteres.'; + + @override + String get repeater_generatePrvKey => 'Genera un par de claves aleatorias'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Interrumpir la búsqueda de par de claves'; + + @override + String get repeater_pubKey => 'Clave pública'; + + @override + String get repeater_pubKeyHelper => + 'Esta es la clave pública que corresponde a la clave privada generada. No se puede establecer directamente.'; + + @override + String get repeater_pubKeyPrefix => 'Prefijo deseado'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Encuentre una clave pública que comience con estos dígitos hexadecimales. Se esperan $tries intentos.'; + } + @override String get repeater_txDelay => 'Retraso TX por inundación'; @@ -2729,6 +3098,17 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Actualizar Modo Privacidad'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label actualizado'; @@ -2806,7 +3186,7 @@ class AppLocalizationsEs extends AppLocalizations { String get repeater_cliQuickDiscovery => 'Descubrir Vecinos'; @override - String get repeater_cliHelpAdvert => 'Envía un paquete de publicidad'; + String get repeater_cliHelpAdvert => 'Envía un paquete de anuncio'; @override String get repeater_cliHelpReboot => @@ -2876,11 +3256,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_cliHelpSetLat => - 'Establece la latitud del mapa de publicidad. (grados decimales)'; + 'Establece la latitud del mapa del anuncio. (grados decimales)'; @override String get repeater_cliHelpSetLon => - 'Establece la longitud del mapa de la publicidad. (grados decimales)'; + 'Establece la longitud del mapa del anuncio. (grados decimales)'; @override String get repeater_cliHelpSetRadio => @@ -2976,7 +3356,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_cliHelpRegionAllowf => - 'Establece el permiso de \'F\'lujo para la región dada. (\'\' para el ámbito global/legado)'; + 'Establece el permiso de \'F\'lood para la región dada. (\'\' para el ámbito global/legado)'; @override String get repeater_cliHelpRegionDenyf => @@ -3010,11 +3390,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - 'Da la configuración de la publicidad del nodo de ubicación:\n- ninguno: no incluir la ubicación en las publicidad\n- compartir: compartir la ubicación GPS (del SensorManager)\n- preferencias: publicidad la ubicación almacenada en preferencias'; + 'Da la configuración de anuncio de ubicación del nodo:\n- ninguno: no incluir la ubicación en los anuncios\n- compartir: compartir la ubicación GPS (del SensorManager)\n- preferencias: anunciar la ubicación almacenada en preferencias'; @override String get repeater_cliHelpGpsAdvertSet => - 'Configura la configuración de la publicidad de la ubicación.'; + 'Configura la configuración de anuncio de la ubicación.'; @override String get repeater_commandsListTitle => 'Lista de comandos'; @@ -3023,6 +3403,75 @@ class AppLocalizationsEs extends AppLocalizations { String get repeater_commandsListNote => 'NOTA: para los diversos comandos \"set...\", también existe un comando \"get...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Frecuencia inválida (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 a 30 dBm'; + + @override + String get repeater_recvErrors => 'Errores de Recepción'; + + @override + String get room_postsStored => 'Publicaciones'; + + @override + String get room_postsPushed => 'Publicaciones Enviadas'; + + @override + String get repeater_cliRegionLoadActive => + 'Modo de carga de regiones: envíe un nombre de región por línea, sangrado con espacios bajo su región padre (añada F después del nombre para permitir inundación). Las líneas no reciben respuesta. Envíe una línea vacía para terminar y luego \"region save\" para guardar el resultado.'; + + @override + String get repeater_cliRegionLoadHint => + 'Línea de región, o vacía para terminar'; + + @override + String get repeater_cliRegionLoadEnd => '(fin de la carga de regiones)'; + + @override + String get repeater_cliHelpRegionDef => + 'Define una cadena de regiones en un solo comando: cada nombre se añade bajo el anterior; \"name,parent\" añade el nombre y continúa bajo el padre indicado. Responde con la lista de regiones.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Establece el número máximo de saltos para reenviar paquetes de inundación que no tienen ámbito regional (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Establece el número máximo de saltos para reenviar anuncios por inundación (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Muestra el número máximo de saltos para los paquetes de inundación sin ámbito.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Muestra el número máximo de saltos para los anuncios por inundación.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Activa o desactiva la ganancia RX (LNA) del módulo frontal de LoRa. Las placas que no lo tengan responden \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Activa o desactiva la ganancia TX (PA) del módulo frontal de LoRa. Las placas que no lo tengan responden \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Muestra si la ganancia RX del módulo frontal de LoRa está activada.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Muestra si la ganancia TX del módulo frontal de LoRa está activada.'; + + @override + String get repeater_bridgeNote => + 'Solo disponible en firmware compilado con un puente (RS232 o ESP-NOW).'; + @override String get repeater_general => 'General'; @@ -3194,11 +3643,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Muestra el intervalo de publicidad local en minutos.'; + 'Muestra el intervalo de anuncio local en minutos.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Muestra el intervalo de publicidad para la emisión de la señal de inundación, expresado en horas.'; + 'Muestra el intervalo de anuncio por inundación, en horas.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3311,11 +3760,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Enumera las regiones que permiten el paso de vehículos debido a inundaciones.'; + 'Enumera las regiones que permiten el tráfico por inundación.'; @override String get repeater_cliHelpRegionListDenied => - 'Enumera las regiones que prohíben el tráfico debido a las inundaciones.'; + 'Enumera las regiones que prohíben el tráfico por inundación.'; @override String get repeater_cliHelpStatsPackets => @@ -4104,6 +4553,23 @@ class AppLocalizationsEs extends AppLocalizations { String get contacts_addContactFromClipboard => 'Agregar contacto desde el portapapeles'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Copiar contacto al portapapeles'; @@ -4230,6 +4696,10 @@ class AppLocalizationsEs extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Visto por última vez'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Configuración de contactos'; @@ -4338,6 +4808,12 @@ class AppLocalizationsEs extends AppLocalizations { @override String get radioStats_screenTitle => 'Estadísticas de radio'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Conéctese a un dispositivo para visualizar estadísticas de radio.'; @@ -4396,6 +4872,44 @@ class AppLocalizationsEs extends AppLocalizations { @override String get translation_title => 'Traducción'; + @override + String get imageMessages_enableTitle => 'Mensajes de imagen'; + + @override + String get imageMessages_enableSubtitle => + 'Enviar imágenes a través de la malla. Requiere la descarga de un modelo de imagen único.'; + + @override + String get imageMessages_modelSectionTitle => 'Modelo de imagen'; + + @override + String get imageMessages_downloadModel => 'Descargar'; + + @override + String get imageMessages_cancelDownload => 'Cancelar'; + + @override + String get imageMessages_removeModel => 'Eliminar modelo'; + + @override + String get imageMessages_modelReady => 'Listo'; + + @override + String get imageMessages_modelNotPublished => + 'Aún no publicado — esta versión no puede descargarlo.'; + + @override + String get imageMessages_downloadFailed => + 'El modelo de imagen no pudo ser descargado.'; + + @override + String get imageMessages_autoProcessTitle => + 'Procesar imágenes automáticamente'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Reconstruya cada imagen tan pronto como llegue. Utiliza aproximadamente 2 GB de memoria durante un segundo cada vez; desactívelo para reconstruir con un toque.'; + @override String get translation_enableTitle => 'Habilitar la traducción'; @@ -4681,4 +5195,250 @@ class AppLocalizationsEs extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Dejar de seguir el paquete'; + + @override + String get imageSend_title => 'Enviar imagen'; + + @override + String get imageSend_cropNote => + 'Redimensionado a 512 × 512 · la relación de aspecto no se conservó'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Texto original'; + + @override + String get imageSend_onAirSize => 'En emisión'; + + @override + String get imageSend_quality => 'Calidad'; + + @override + String get imageSend_qualityStandard => 'Estándar'; + + @override + String get imageSend_qualityHigh => 'Alto'; + + @override + String get imageSend_packetsLabel => 'Paquetes'; + + @override + String get imageSend_airtimeLabel => 'Tiempo en pantalla'; + + @override + String get imageSend_sizeLabel => 'Carga útil'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paquetes', + one: 'paquete', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => + 'Configuración de radio desconocida'; + + @override + String get imageSend_radioUnknownBody => + 'Conéctese a un dispositivo para que se pueda calcular la hora de transmisión.'; + + @override + String get imageSend_longSendTitle => 'Larga transmisión'; + + @override + String imageSend_longSendBody(String duration) { + return 'Esto mantendrá el canal durante aproximadamente $duration.'; + } + + @override + String get imageSend_floodNote => + 'Enrutamiento de inundación: cada repetidor dentro del rango retransmite cada paquete, por lo que el canal permanece ocupado durante más tiempo que esto.'; + + @override + String get imageSend_parityTitle => 'Paquete de recuperación'; + + @override + String get imageSend_paritySubtitle => + 'Un paquete adicional. Los mensajes grupales no son reconocidos, por lo que esto permite al receptor reconstruir la imagen si se pierde un solo paquete.'; + + @override + String get imageSend_send => 'Enviar'; + + @override + String get imageSend_cancel => 'Cancelar'; + + @override + String get imageSend_encodeFailed => 'Esta imagen no pudo ser codificada.'; + + @override + String get imageSend_codecDownloading => + 'El modelo de imagen todavía se está descargando.'; + + @override + String get imageSend_codecUnavailable => + 'El envío de imágenes no está disponible en este dispositivo.'; + + @override + String get imageSend_codecDisabled => + 'Los mensajes de imagen están desactivados en la configuración.'; + + @override + String get imageSend_deviceUnsupported => + 'Esta radio no puede enviar paquetes de imagen. Conecte un dispositivo con el firmware Companion versión 13 o superior.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Las imágenes se transmiten como datos grupales, por lo que solo se pueden enviar a un canal, no mediante mensajes directos.'; + + @override + String get imageSend_tooLarge => + 'Esa imagen se codificó en más paquetes de los que permite el formato de malla.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paquetes', + one: 'paquete', + ); + return 'Imagen enviada como $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'La imagen no pudo ser enviada: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Envío de imagen — paquete $sent de $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Nodo $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received de $total paquetes'; + } + + @override + String get receivedImage_queued => 'Esperando descifrar'; + + @override + String get receivedImage_tapToDecode => 'Toque para decodificar'; + + @override + String get receivedImage_decoding => + 'Reconstruyendo… aproximadamente 1 segundo'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Imagen incompleta — $received de $total paquetes llegados'; + } + + @override + String get receivedImage_corrupt => 'La imagen no pudo ser reconstruida'; + + @override + String get receivedImage_decoderMissing => + 'Imagen recibida — la decodificación de la imagen no funciona'; + + @override + String get receivedImage_evicted => 'Imagen ya no almacenada'; + + @override + String get receivedImage_retry => 'Inténtalo de nuevo'; + + @override + String get receivedImage_decodeAgain => 'Decodificar de nuevo'; + + @override + String get receivedImage_openSettings => 'Configurar'; + + @override + String get receivedImage_tapToProcess => 'Toque para procesar'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'paquetes', + one: 'paquete', + ); + return '$bytes bytes · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds segundos'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Más de 158 bytes: se envía como máximo $count veces'; + } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 2f9205cf..3c68ca8f 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -110,6 +110,46 @@ class AppLocalizationsFr extends AppLocalizations { @override String get messageStatus_repeated => 'Reçu plusieurs fois'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Activer les images URL'; + + @override + String get urlImage_possible => + 'Image URL possible ; activez-la dans les Paramètres.'; + @override String get common_reboot => 'Redémarrer'; @@ -370,42 +410,65 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_radioSettingsUpdated => 'Paramètres radio mis à jour'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'La radio n\'a pas appliqué ces paramètres'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Régions'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Gérer les régions stockées'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Gestion de région'; + + @override + String get settings_regionNameHint => 'Entrer le nom de la région'; + + @override + String get settings_regionAddRegion => 'Ajouter une région'; + + @override + String get settings_regionFetchRegions => + 'Récupérer les régions à partir des répéteurs'; + + @override + String get settings_regionFetchRegionsFail => + 'Aucune région n\'a été trouvée'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Cette région a déjà été ajoutée'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Nom de la région'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Région supprimée'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Supprimer la région'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Supprimez $region de la liste des régions ?'; } @override @@ -500,6 +563,10 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Mode d\'environnement de la télémétrie'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Localisation de l\'annonce'; @@ -507,9 +574,21 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_advertLocationSubtitle => 'Inclure la localisation dans l\'annonce'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Annonce zéro saut automatique lors de la mise à jour GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Lorsque la position GPS change, envoyer une annonce zéro saut (nécessite la position dans l\'annonce).'; + @override String get settings_multiAck => 'Plusieurs accusés de réception'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Le mode télémétrie a été mis à jour'; @@ -612,15 +691,31 @@ class AppLocalizationsFr extends AppLocalizations { @override String get settings_infoPublicKey => 'Clé publique'; + @override + String get settings_publicKeyCopied => 'Clé publique copiée'; + @override String get settings_infoContactsCount => 'Nombre de contacts'; @override String get settings_infoChannelCount => 'Nombre de canaux'; + @override + String get settings_infoHardware => 'Matériel'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Préréglages'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Fréquence (MHz)'; @@ -643,7 +738,9 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_txPower => 'Puissance TX (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Puissance TX invalide (0-22 dBm)'; @@ -651,6 +748,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get settings_clientRepeat => 'Répétition hors réseau'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Permettre à cet appareil de relayer les paquets du maillage pour les autres.'; @@ -733,6 +835,51 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_languageUk => 'Ukrainien'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 octet'; + + @override + String get repeater_pathHashModeOption1 => '1 à 2 octets'; + + @override + String get repeater_pathHashModeOption2 => '2 à 3 octets'; + + @override + String get repeater_pathHashModeOption3 => '3 à 4 octets'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Activer le traçage des messages'; @@ -768,6 +915,13 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Afficher une notification lors de la réception de nouveaux messages'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Notifications des messages de canal'; @@ -880,6 +1034,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'Tension élevée LiPo (3,0-4,35 V)'; + @override String get appSettings_mapDisplay => 'Affichage de la carte'; @@ -937,6 +1094,28 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_lastWeek => 'La semaine dernière'; + @override + String get appSettings_rasterTileSource => 'Source de tuiles raster'; + + @override + String get appSettings_stadiaEndpoint => 'Point de terminaison Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Clé API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Requis pour l’utilisation de Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Configuré : $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Entrez votre clé API Stadia Maps. Cette application l’utilise pour les requêtes de tuiles raster.'; + @override String get appSettings_offlineMapCache => 'Cache de carte hors ligne'; @@ -1031,6 +1210,29 @@ class AppLocalizationsFr extends AppLocalizations { return 'Supprimer $contactName des contacts ?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Gérer le répéteur'; @@ -1181,6 +1383,18 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_private => 'Privé'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Modifier le canal'; @@ -1313,6 +1527,10 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canal public ajouté'; + @override + String get channels_noFreeSlots => + 'Tous les emplacements de canaux sont utilisés'; + @override String get channels_sortBy => 'Trier par'; @@ -1370,17 +1588,30 @@ class AppLocalizationsFr extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Région : $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Région : aucune'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Choisissez une région'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Zone dégagée'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Aucun message pour le moment'; @@ -1434,9 +1665,27 @@ class AppLocalizationsFr extends AppLocalizations { return 'Essai $current/$max'; } + @override + String get chat_selectSendAction => 'Sélectionner une action d’envoi'; + @override String get chat_sendGif => 'Envoyer un GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Envoyer une image via MeshCore'; + + @override + String get chat_imagePickFailed => 'Je n\'ai pas pu ouvrir cette image'; + + @override + String get chat_receivedGif => 'Reçu un GIF'; + @override String get chat_reply => 'Répondre'; @@ -1446,6 +1695,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_me => 'Moi'; + @override + String get reaction_report => 'Réactions emoji'; + @override String get emojiCategorySmileys => 'Émojis'; @@ -1734,6 +1986,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_path => 'Chemin'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Clé publique'; @@ -1772,6 +2027,12 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_newMessages => 'Nouveaux messages'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Ouvrir le lien ?'; @@ -1817,6 +2078,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get map_centerOnNode => 'Centrer sur le nœud'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Détails'; @@ -1836,6 +2100,10 @@ class AppLocalizationsFr extends AppLocalizations { String get map_noNodesWithLocation => 'Aucun nœud avec des données de localisation'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Les nœuds doivent partager leurs coordonnées GPS\npour apparaître sur la carte.'; @@ -1978,6 +2246,16 @@ class AppLocalizationsFr extends AppLocalizations { String get map_showGuessedLocations => 'Afficher les emplacements estimés des nœuds'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Afficher les contacts de découverte'; @@ -1999,6 +2277,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get map_manageRepeater => 'Gérer le répéteur'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Appuyez sur les nœuds pour les ajouter au chemin.'; @@ -2091,6 +2372,42 @@ class AppLocalizationsFr extends AppLocalizations { return 'Téléchargements échoués : $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2168,6 +2485,12 @@ class AppLocalizationsFr extends AppLocalizations { @override String get login_enterPassword => 'Entrez votre mot de passe'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Sauvegarder le mot de passe'; @@ -2183,6 +2506,9 @@ class AppLocalizationsFr extends AppLocalizations { String get login_roomDescription => 'Entrez le mot de passe de la pièce pour accéder aux paramètres et à l\'état.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Redirection'; @@ -2221,6 +2547,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get common_clear => 'Effacer'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Chemin actuel'; @@ -2245,6 +2574,12 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_guestTools => 'Outils pour les invités'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'État'; @@ -2645,6 +2980,42 @@ class AppLocalizationsFr extends AppLocalizations { String get repeater_pathHashModeHelper => 'Octets utilisés pour encoder l\'ID de ce routeur dans les balises de détection de flux/boucles. 0 = 1 octet (256 ID, jusqu\'à 64 sauts), 1 = 2 octets (65 000 ID, jusqu\'à 32 sauts), 2 = 3 octets (16 millions d\'ID, jusqu\'à 21 sauts). Les versions 1.13 et antérieures utilisent des chemins multi-octets ; à partir de la version 1.14, cela n\'est plus nécessaire.'; + @override + String get repeater_keySettings => 'Modifier les clés d\'identité'; + + @override + String get repeater_keySettingsSubtitle => + 'Modifier la paire de clés publique/privée'; + + @override + String get repeater_prvKey => 'Clé privée'; + + @override + String get repeater_prvKeyHelper => + 'Une nouvelle clé privée pour le répéteur, une chaîne hexadécimale de 128 caractères.'; + + @override + String get repeater_generatePrvKey => 'Générez une paire de clés aléatoire'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Arrêter la recherche de la paire de clés'; + + @override + String get repeater_pubKey => 'Clé publique'; + + @override + String get repeater_pubKeyHelper => + 'Voici la clé publique associée à la clé privée générée. Vous ne pouvez pas la définir directement.'; + + @override + String get repeater_pubKeyPrefix => 'Préfixe souhaité'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Trouvez une clé publique qui commence par ces chiffres hexadécimaux. Nombre de tentatives nécessaires : $tries.'; + } + @override String get repeater_txDelay => 'Délai de transmission en flood'; @@ -2743,6 +3114,17 @@ class AppLocalizationsFr extends AppLocalizations { String get repeater_refreshPrivacyMode => 'Rafraîchir le Mode Confidentialité'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label rafraîchi'; @@ -2860,7 +3242,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Définit le nombre maximal de sauts pour les paquets de balayage entrants (si >= max, le paquet n\'est pas acheminé).'; + 'Définit le nombre maximal de sauts pour les paquets flood entrants (si >= max, le paquet n\'est pas acheminé).'; @override String get repeater_cliHelpSetIntThresh => @@ -2990,7 +3372,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_cliHelpRegionAllowf => - 'Définit les autorisations de \"Flot\" pour la région donnée. (\'\' pour la portée globale/héritée)'; + 'Définit les autorisations de \'F\'lood pour la région donnée. (\'\' pour la portée globale/héritée)'; @override String get repeater_cliHelpRegionDenyf => @@ -3037,6 +3419,75 @@ class AppLocalizationsFr extends AppLocalizations { String get repeater_commandsListNote => 'NOTE : pour les diverses commandes « set »..., il existe également une commande « get »...'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Fréquence invalide (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 à 30 dBm'; + + @override + String get repeater_recvErrors => 'Erreurs de réception'; + + @override + String get room_postsStored => 'Publications'; + + @override + String get room_postsPushed => 'Publications envoyées'; + + @override + String get repeater_cliRegionLoadActive => + 'Mode de chargement des régions : envoyez un nom de région par ligne, indenté avec des espaces sous sa région parente (ajoutez F après le nom pour autoriser le flood). Les lignes ne reçoivent pas de réponse. Envoyez une ligne vide pour terminer, puis \"region save\" pour conserver le résultat.'; + + @override + String get repeater_cliRegionLoadHint => + 'Ligne de région, ou vide pour terminer'; + + @override + String get repeater_cliRegionLoadEnd => '(fin du chargement des régions)'; + + @override + String get repeater_cliHelpRegionDef => + 'Définit une chaîne de régions en une seule commande : chaque nom est ajouté sous le précédent ; \"name,parent\" ajoute le nom, puis continue sous le parent indiqué. Répond avec la liste des régions.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Définit le nombre maximal de sauts pour la retransmission des paquets flood sans portée régionale (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Définit le nombre maximal de sauts pour la retransmission des annonces flood (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Affiche le nombre maximal de sauts pour les paquets flood sans portée régionale.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Affiche le nombre maximal de sauts pour les annonces flood.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Active ou désactive le gain RX (LNA) du module frontal LoRa. Les cartes qui n\'en ont pas répondent \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Active ou désactive le gain TX (PA) du module frontal LoRa. Les cartes qui n\'en ont pas répondent \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Indique si le gain RX du module frontal LoRa est activé.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Indique si le gain TX du module frontal LoRa est activé.'; + + @override + String get repeater_bridgeNote => + 'Disponible uniquement sur un firmware compilé avec un pont (RS232 ou ESP-NOW).'; + @override String get repeater_general => 'Général'; @@ -3086,7 +3537,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Envoie une publicité sans intermédiaire (uniquement aux voisins immédiats).'; + 'Envoie une annonce zéro saut (uniquement aux voisins immédiats).'; @override String get repeater_cliHelpStartOta => @@ -3208,11 +3659,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Indique l\'intervalle publicitaire local en minutes.'; + 'Indique l\'intervalle d\'annonce locale en minutes.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Indique l\'intervalle publicitaire pour la diffusion de l\'annonce en heures.'; + 'Indique l\'intervalle des annonces flood, en heures.'; @override String get repeater_cliHelpGetGuestPassword => @@ -4120,6 +4571,23 @@ class AppLocalizationsFr extends AppLocalizations { String get contacts_addContactFromClipboard => 'Ajouter un contact depuis le presse-papiers'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Copier le contact dans le presse-papiers'; @@ -4250,6 +4718,10 @@ class AppLocalizationsFr extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Vu pour la dernière fois'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Paramètres des contacts'; @@ -4358,6 +4830,12 @@ class AppLocalizationsFr extends AppLocalizations { @override String get radioStats_screenTitle => 'Statistiques de radio'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Connectez-vous à un appareil pour visualiser les statistiques de la radio.'; @@ -4417,6 +4895,44 @@ class AppLocalizationsFr extends AppLocalizations { @override String get translation_title => 'Traduction'; + @override + String get imageMessages_enableTitle => 'Messages avec images'; + + @override + String get imageMessages_enableSubtitle => + 'Envoyer des images via le maillage. Nécessite un téléchargement unique du modèle d\'image.'; + + @override + String get imageMessages_modelSectionTitle => 'Modèle d\'image'; + + @override + String get imageMessages_downloadModel => 'Télécharger'; + + @override + String get imageMessages_cancelDownload => 'Annuler'; + + @override + String get imageMessages_removeModel => 'Supprimer le modèle'; + + @override + String get imageMessages_modelReady => 'Prêt'; + + @override + String get imageMessages_modelNotPublished => + 'Non publié — cette version ne peut pas le télécharger.'; + + @override + String get imageMessages_downloadFailed => + 'Le modèle d\'image ne pouvait pas être téléchargé.'; + + @override + String get imageMessages_autoProcessTitle => + 'Traiter automatiquement les images'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Reconstruisez chaque image dès son arrivée. Cela utilise environ 2 Go de mémoire pendant une seconde à chaque fois ; désactivez la reconstruction au toucher pour éviter cela.'; + @override String get translation_enableTitle => 'Activer la traduction'; @@ -4702,4 +5218,250 @@ class AppLocalizationsFr extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Déverrouiller la vue du paquet'; + + @override + String get imageSend_title => 'Envoyer l\'image'; + + @override + String get imageSend_cropNote => + 'Redimensionné à 512 × 512 · le rapport d’aspect n’a pas été conservé'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + 'Texte original\n\nVeuillez traduire le texte suivant en français :'; + + @override + String get imageSend_onAirSize => 'En direct'; + + @override + String get imageSend_quality => 'Qualité'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Haut'; + + @override + String get imageSend_packetsLabel => 'Paquets'; + + @override + String get imageSend_airtimeLabel => 'Durée de diffusion'; + + @override + String get imageSend_sizeLabel => 'Charge utile'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paquets', + one: 'paquet', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Réglages de la radio inconnus'; + + @override + String get imageSend_radioUnknownBody => + 'Connectez-vous à un appareil afin que l\'heure de diffusion puisse être calculée.'; + + @override + String get imageSend_longSendTitle => 'Longue transmission'; + + @override + String imageSend_longSendBody(String duration) { + return 'Cela maintiendra la chaîne pendant environ $duration.'; + } + + @override + String get imageSend_floodNote => + 'Routage flood : chaque répéteur dans la zone retransmet chaque paquet, de sorte que le canal reste occupé plus longtemps que cela.'; + + @override + String get imageSend_parityTitle => 'Paquet de récupération'; + + @override + String get imageSend_paritySubtitle => + 'Un paquet supplémentaire. Les messages de groupe ne sont pas reconnus, ce qui permet au destinataire de reconstruire l\'image si un seul paquet est perdu.'; + + @override + String get imageSend_send => 'Envoyer'; + + @override + String get imageSend_cancel => 'Annuler'; + + @override + String get imageSend_encodeFailed => 'Cette image ne peut pas être encodée.'; + + @override + String get imageSend_codecDownloading => + 'Le modèle d\'image est toujours en téléchargement.'; + + @override + String get imageSend_codecUnavailable => + 'L\'envoi d\'images n\'est pas disponible sur cet appareil.'; + + @override + String get imageSend_codecDisabled => + 'Les messages d\'images sont désactivés dans les paramètres.'; + + @override + String get imageSend_deviceUnsupported => + 'Cette radio ne peut pas envoyer de paquets d\'images. Connectez un appareil exécutant le firmware compagnon version 13 ou ultérieure.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Les images se déplacent en tant que données de groupe, elles ne peuvent donc être envoyées que sur un canal — et non par message direct.'; + + @override + String get imageSend_tooLarge => + 'Cette image a été encodée en plus de paquets que le format de maillage ne permet.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paquets', + one: 'paquet', + ); + return 'Image envoyée en $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'L\'image n\'a pas pu être envoyée : $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Envoi de l\'image — paquet $sent sur $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Nœud $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received sur $total paquets'; + } + + @override + String get receivedImage_queued => 'En attendant de décoder'; + + @override + String get receivedImage_tapToDecode => 'Tapez pour décoder'; + + @override + String get receivedImage_decoding => 'Reconstitution… d’environ 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Image incomplète — $received sur $total paquets reçus'; + } + + @override + String get receivedImage_corrupt => + 'L\'image ne pouvait pas être reconstruite'; + + @override + String get receivedImage_decoderMissing => + 'Image reçue — le décodage de l\'image est interrompu'; + + @override + String get receivedImage_evicted => 'Image non stockée'; + + @override + String get receivedImage_retry => 'Réessayez'; + + @override + String get receivedImage_decodeAgain => 'Décoder à nouveau'; + + @override + String get receivedImage_openSettings => 'Mettre en place'; + + @override + String get receivedImage_tapToProcess => 'Tapez pour traiter'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'paquets', + one: 'paquet', + ); + return '$bytes octets · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds s'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes minutes $seconds secondes'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Plus de 158 octets : envoi au maximum $count fois'; + } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index d64268ed..62ba1c00 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -110,6 +110,46 @@ class AppLocalizationsHu extends AppLocalizations { @override String get messageStatus_repeated => '– ismételte Heard'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'URL-képek engedélyezése'; + + @override + String get urlImage_possible => + 'Lehetséges URL-kép; engedélyezze a Beállításokban.'; + @override String get common_reboot => 'Indítsa újra'; @@ -366,42 +406,64 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_radioSettingsUpdated => 'A rádió beállításai frissítve'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'A rádió nem alkalmazta ezeket a beállításokat'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Tájak'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Kincstani megjelenítette gyakorlatos területeket'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Regionális Kezelés'; + + @override + String get settings_regionNameHint => 'Felhasználja a regioni név'; + + @override + String get settings_regionAddRegion => 'Egyes region'; + + @override + String get settings_regionFetchRegions => 'Féregelmezők a repeaterekból'; + + @override + String get settings_regionFetchRegionsFail => 'Nem található egyéb területek'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Ez a terítet nemisértették meg.'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Feldúr Neve'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Felült region'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Felajánlatos Tér'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Kell kiszámítsd a ${region}ot a részekre?'; } @override @@ -495,6 +557,10 @@ class AppLocalizationsHu extends AppLocalizations { @override String get settings_telemetryEnvironmentMode => 'Telemetriás környezeti mód'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Hirdetés helye'; @@ -502,9 +568,21 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_advertLocationSubtitle => 'A hirdetésben szerepeljen a helyszín.'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatikus zero-hop hirdetés GPS-frissítéskor'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Ha a GPS-helyzet megváltozik, küldjön zero-hop hirdetést (a hirdetésben helymegadás szükséges).'; + @override String get settings_multiAck => 'Multi-ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Telemetriai mód frissítve'; @@ -526,7 +604,7 @@ class AppLocalizationsHu extends AppLocalizations { 'Jelenlét a közvetítésben most'; @override - String get settings_advertisementSent => 'Reklám elküldve'; + String get settings_advertisementSent => 'Hirdetés elküldve'; @override String get settings_syncTime => 'Szinkronizálási idő'; @@ -605,15 +683,31 @@ class AppLocalizationsHu extends AppLocalizations { @override String get settings_infoPublicKey => 'Nyilvános kulcs'; + @override + String get settings_publicKeyCopied => 'Nyilvános kulcs másolva'; + @override String get settings_infoContactsCount => 'Névjegyek száma'; @override String get settings_infoChannelCount => 'Csatornaszám'; + @override + String get settings_infoHardware => 'Hardverő'; + + @override + String get settings_infoFirmware => 'Firmver'; + @override String get settings_presets => 'Előbeállítások'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frekvencia (MHz)'; @@ -637,7 +731,9 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_txPower => 'TX teljesítmény (dBm)'; @override - String get settings_txPowerHelper => '0-22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => @@ -646,6 +742,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get settings_clientRepeat => 'Hálózaton kívüli ismétlés'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Engedélyezze az eszköznek, hogy megismételje a mesh-csomagokat mások számára'; @@ -728,6 +829,51 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_languageUk => 'Українська'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 szavak'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bajt'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bajt'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Üzenetkövetés engedélyezése'; @@ -762,6 +908,13 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Értesítés megjelenítése új üzenetek fogadásakor'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Csatorna üzenetek értesítései'; @@ -771,7 +924,7 @@ class AppLocalizationsHu extends AppLocalizations { 'Értesítés megjelenítése csatornaüzenetek fogadásakor'; @override - String get appSettings_advertisementNotifications => 'Reklám Értesítések'; + String get appSettings_advertisementNotifications => 'Hirdetési értesítések'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -871,6 +1024,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2 V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3.0-4.35V)'; + @override String get appSettings_mapDisplay => 'Térkép megjelenítése'; @@ -929,6 +1085,28 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_lastWeek => 'Múlt héten'; + @override + String get appSettings_rasterTileSource => 'Raszteres csempeforrás'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia végpont'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API-kulcs'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'A Stadia Maps használatához kötelező'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Konfigurálva: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Adja meg a Stadia Maps API-kulcsát. Az alkalmazás ezt használja raszteres csempekérésekhez.'; + @override String get appSettings_offlineMapCache => 'Offline térképgyorsítótár'; @@ -1023,6 +1201,29 @@ class AppLocalizationsHu extends AppLocalizations { return 'Eltávolítja a $contactName alkalmazást a névjegyek közül?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Repeater kezelése'; @@ -1174,6 +1375,18 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_private => 'Magán'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Csatorna szerkesztése'; @@ -1304,6 +1517,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_publicChannelAdded => 'Nyilvános csatorna hozzáadva'; + @override + String get channels_noFreeSlots => 'Minden csatornahely foglalt'; + @override String get channels_sortBy => 'Rendezés'; @@ -1363,17 +1579,30 @@ class AppLocalizationsHu extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Tájékoztatás: A $region -t\n\nEz a tájékoztatás a magyar nyelvben a következően kell szóva:\n\nTájékoztatás: A $region -t'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Tájékoztetés: nem'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Válassz egy regionot'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Kéres kör'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Még nincsenek üzenetek'; @@ -1427,9 +1656,27 @@ class AppLocalizationsHu extends AppLocalizations { return 'Próbálja újra $current/$max'; } + @override + String get chat_selectSendAction => 'Küldési művelet kiválasztása'; + @override String get chat_sendGif => 'GIF küldése'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Kép küldése MeshCore-on keresztül'; + + @override + String get chat_imagePickFailed => 'Nem tudtam ezt a fenti fényre kapni'; + + @override + String get chat_receivedGif => 'GIF-ot kapott'; + @override String get chat_reply => 'Válasz'; @@ -1439,6 +1686,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_me => 'Nekem'; + @override + String get reaction_report => 'Emoji reakciók'; + @override String get emojiCategorySmileys => 'Hangulatjelek'; @@ -1585,7 +1835,7 @@ class AppLocalizationsHu extends AppLocalizations { String get routing_modeAuto => 'Auto'; @override - String get routing_modeFlood => 'Árvíz'; + String get routing_modeFlood => 'Elárasztás'; @override String get routing_modeManual => 'Kézikönyv'; @@ -1644,7 +1894,7 @@ class AppLocalizationsHu extends AppLocalizations { String get routing_qualityWorked => 'Szállított'; @override - String get routing_qualityFlood => 'Árvízen keresztül hallatszott'; + String get routing_qualityFlood => 'Elárasztáson keresztül hallatszott'; @override String get routing_qualityUntested => 'Nem tesztelt'; @@ -1663,7 +1913,7 @@ class AppLocalizationsHu extends AppLocalizations { } @override - String get routing_floodDelivery => 'Árvízi szállítás'; + String get routing_floodDelivery => 'Elárasztási szállítás'; @override String get pathEditor_title => 'Építsd meg az útvonalat'; @@ -1678,7 +1928,7 @@ class AppLocalizationsHu extends AppLocalizations { 'Még nincs ugrás. Koppintson az alábbi ismétlőkre, ha sorrendben szeretné felvenni őket, vagy mentse ugrás nélkül a közvetlen küldéshez.'; @override - String get pathEditor_addHops => 'Sorrendben adjuk hozzá a komlót'; + String get pathEditor_addHops => 'Sorrendben adjuk hozzá az ugrásokat'; @override String get pathEditor_searchRepeaters => 'Ismétlő keresése'; @@ -1726,6 +1976,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_path => 'Útvonal'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Nyilvános kulcs'; @@ -1733,7 +1986,7 @@ class AppLocalizationsHu extends AppLocalizations { String get chat_compressOutgoingMessages => 'A kimenő üzenetek tömörítése'; @override - String get chat_floodForced => 'Árvíz (kényszerített)'; + String get chat_floodForced => 'Elárasztás (kényszerített)'; @override String get chat_directForced => 'Közvetlen (kényszerített)'; @@ -1744,7 +1997,7 @@ class AppLocalizationsHu extends AppLocalizations { } @override - String get chat_floodAuto => 'Árvíz (automatikus)'; + String get chat_floodAuto => 'Elárasztás (automatikus)'; @override String get chat_direct => 'Közvetlen'; @@ -1763,6 +2016,12 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_newMessages => 'Új üzenetek'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Link megnyitása?'; @@ -1809,6 +2068,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get map_centerOnNode => 'Középre a csomóponton'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Részletek'; @@ -1828,6 +2090,10 @@ class AppLocalizationsHu extends AppLocalizations { String get map_noNodesWithLocation => 'Nincsenek helyadatokkal rendelkező csomópontok'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'A csomópontoknak meg kell osztaniuk GPS-koordinátáikat\nhogy megjelenjen a térképen'; @@ -1970,6 +2236,16 @@ class AppLocalizationsHu extends AppLocalizations { String get map_showGuessedLocations => 'Talált csomópont-helyek megjelenítése'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Felfedezési névjegyek megjelenítése'; @@ -1991,6 +2267,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get map_manageRepeater => 'Repeater kezelése'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Érintse meg a csomópontokat, hogy hozzáadja őket az útvonalhoz.'; @@ -2082,6 +2361,42 @@ class AppLocalizationsHu extends AppLocalizations { return 'Sikertelen letöltések: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2159,6 +2474,12 @@ class AppLocalizationsHu extends AppLocalizations { @override String get login_enterPassword => 'Adja meg a jelszót'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Jelszó mentése'; @@ -2174,6 +2495,9 @@ class AppLocalizationsHu extends AppLocalizations { String get login_roomDescription => 'Adja meg a szoba jelszavát a vendég vagy adminisztrátori hozzáféréshez.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Útválasztás'; @@ -2213,6 +2537,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get common_clear => 'Világos'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Jelenlegi útvonal'; @@ -2238,6 +2565,12 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_guestTools => 'Vendégeszközök'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Állapot'; @@ -2360,17 +2693,17 @@ class AppLocalizationsHu extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Összesen: $total, Árvíz: $flood, Közvetlen: $direct'; + return 'Összesen: $total, Elárasztás: $flood, Közvetlen: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Összesen: $total, Árvíz: $flood, Közvetlen: $direct'; + return 'Összesen: $total, Elárasztás: $flood, Közvetlen: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Árvíz: $flood, Közvetlen: $direct'; + return 'Elárasztás: $flood, Közvetlen: $direct'; } @override @@ -2467,7 +2800,7 @@ class AppLocalizationsHu extends AppLocalizations { 'Név/hely elrejtése a hirdetésekben'; @override - String get repeater_advertisementSettings => 'Reklámbeállítások'; + String get repeater_advertisementSettings => 'Hirdetésbeállítások'; @override String get repeater_localAdvertInterval => 'Helyi hirdetési intervallum'; @@ -2478,7 +2811,8 @@ class AppLocalizationsHu extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => 'Árvízi hirdetési intervallum'; + String get repeater_floodAdvertInterval => + 'Elárasztási hirdetési intervallum'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2572,7 +2906,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_loopDetectHelper => - 'Dobd el az útválasztó huroknak tűnő árvízcsomagokat'; + 'Dobd el az útválasztó huroknak tűnő elárasztási csomagokat'; @override String get repeater_loopDetectOff => 'Le'; @@ -2608,11 +2942,11 @@ class AppLocalizationsHu extends AppLocalizations { String get repeater_refreshOwnerInfo => 'Frissítse az operátor adatait'; @override - String get repeater_floodMax => 'Árvíz max ugrás'; + String get repeater_floodMax => 'Elárasztás max ugrás'; @override String get repeater_floodMaxHelper => - 'Maximum ugrások, amelyeket egy árvízcsomag utazhat (0-64)'; + 'Maximum ugrások, amelyeket egy elárasztási csomag utazhat (0-64)'; @override String get repeater_advancedSettings => 'Fejlett'; @@ -2628,12 +2962,48 @@ class AppLocalizationsHu extends AppLocalizations { String get repeater_pathHashModeHelper => 'Az átjátszó azonosítójának elárasztási útvonal/hurokészlelési címkékbe való kódolására használt bájtok. 0 = 1 bájt (256 azonosító, legfeljebb 64 ugrás), 1 = 2 bájt (65 000 azonosító, legfeljebb 32 ugrás), 2 = 3 bájt (16 millió azonosító, legfeljebb 21 ugrás). A v1.13 és régebbi firmware eldobja a többbájtos elérési utat – csak akkor emelje meg, ha a hálózat a v1.14+ verziót használja.'; + @override + String get repeater_keySettings => 'Képzőítsekei jelölt'; + + @override + String get repeater_keySettingsSubtitle => + 'Közelítse a közlekedési/private képlékt'; + + @override + String get repeater_prvKey => 'Kis házas'; + + @override + String get repeater_prvKeyHelper => + 'Kínai nyelvben:\n\nA repeteróhoz új képes kód, 128 karakteri hex-kód.'; + + @override + String get repeater_generatePrvKey => 'Egy random képléktár generáld meg'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Kéypair szavakat kérdéset kaphatás'; + + @override + String get repeater_pubKey => 'Kiváló kiegészítő'; + + @override + String get repeater_pubKeyHelper => + 'Ez a kiváló kód, amely tükrözi a gyártott kiegészítő kódot. Ezet nem lehet megjelenítani direktusan.'; + + @override + String get repeater_pubKeyPrefix => 'Kiváló prefix'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Kiválasztsa meg a közös kódot, amely az alábbi hex-kifüggőnek előre van. Várható kiválasztások száma: $tries.'; + } + @override String get repeater_txDelay => 'Áradási TX késleltetés'; @override String get repeater_txDelayHelper => - 'Újraküldési térköz az árvízi forgalomhoz, a csomag sugárzási idejének szorzójaként (0-2, alapértelmezett 0,5). Magasabb = kevesebb ütközés, de lassabb szállítás.'; + 'Újraküldési térköz az elárasztási forgalomhoz, a csomag sugárzási idejének szorzójaként (0-2, alapértelmezett 0,5). Magasabb = kevesebb ütközés, de lassabb szállítás.'; @override String get repeater_directTxDelay => 'Közvetlen TX késleltetés'; @@ -2660,11 +3030,11 @@ class AppLocalizationsHu extends AppLocalizations { String get repeater_actionsTitle => 'Akciók'; @override - String get repeater_sendAdvert => 'Árvízhirdetés küldése'; + String get repeater_sendAdvert => 'Elárasztási hirdetés küldése'; @override String get repeater_sendAdvertSubtitle => - 'Adjon árvízreklámot a hálózaton keresztül'; + 'Küldjön elárasztási hirdetést a hálózaton keresztül'; @override String get repeater_sendAdvertZeroHop => 'Zéró ugrású hirdetés küldése'; @@ -2723,6 +3093,17 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Frissítse az adatvédelmi módot'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label frissítve'; @@ -2800,7 +3181,7 @@ class AppLocalizationsHu extends AppLocalizations { String get repeater_cliQuickDiscovery => 'Fedezze fel a szomszédokat'; @override - String get repeater_cliHelpAdvert => 'Reklámcsomagot küld'; + String get repeater_cliHelpAdvert => 'Hirdetési csomagot küld'; @override String get repeater_cliHelpReboot => @@ -2839,7 +3220,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Beállítja a bejövő árvízcsomag ugrásainak maximális számát (ha >= max, a csomag nem kerül továbbításra)'; + 'Beállítja a bejövő elárasztási csomag ugrásainak maximális számát (ha >= max, a csomag nem kerül továbbításra)'; @override String get repeater_cliHelpSetIntThresh => @@ -2859,7 +3240,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Beállítja az időzítő intervallumát órákban az árvízhirdetési csomag küldéséhez. A letiltáshoz állítsa 0-ra.'; + 'Beállítja az időzítő intervallumát órákban az elárasztási hirdetési csomag küldéséhez. A letiltáshoz állítsa 0-ra.'; @override String get repeater_cliHelpSetGuestPassword => @@ -2950,7 +3331,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(csak soros) Felsorolja az összes meghatározott régiót és az aktuális árvízi engedélyeket.'; + '(csak soros) Felsorolja az összes meghatározott régiót és az aktuális elárasztási engedélyeket.'; @override String get repeater_cliHelpRegionLoad => @@ -3018,6 +3399,75 @@ class AppLocalizationsHu extends AppLocalizations { String get repeater_commandsListNote => 'MEGJEGYZÉS: a különféle \"set ...\" parancsokhoz van egy \"get ...\" parancs is.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => + 'Érvénytelen frekvencia (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9-től 30 dBm-ig'; + + @override + String get repeater_recvErrors => 'Vételi hibák'; + + @override + String get room_postsStored => 'Bejegyzések'; + + @override + String get room_postsPushed => 'Kiküldött bejegyzések'; + + @override + String get repeater_cliRegionLoadActive => + 'Régióbetöltési mód: soronként küldjön egy régiónevet, szóközökkel behúzva a szülője alá (a név után F hozzáadásával engedélyezhető az elárasztás). A sorokra nem érkezik válasz. Egy üres sor küldésével fejezze be, majd a \"region save\" paranccsal mentse az eredményt.'; + + @override + String get repeater_cliRegionLoadHint => 'Régiósor, vagy üres a befejezéshez'; + + @override + String get repeater_cliRegionLoadEnd => '(régióbetöltés vége)'; + + @override + String get repeater_cliHelpRegionDef => + 'Egy paranccsal régiók láncát határozza meg: minden név az előző alá kerül; a \"name,parent\" hozzáadja a nevet, majd a megadott szülő alatt folytatja. Válaszként a régiólistát adja.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Beállítja a hatókör nélküli elárasztási csomagok továbbításának maximális ugrásszámát (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Beállítja az elárasztási hirdetések továbbításának maximális ugrásszámát (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Megjeleníti a hatókör nélküli elárasztási csomagok maximális ugrásszámát.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Megjeleníti az elárasztási hirdetések maximális ugrásszámát.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Ki-/bekapcsolja a LoRa front-end modul RX erősítését (LNA). Az ezzel nem rendelkező áramkörök válasza \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Ki-/bekapcsolja a LoRa front-end modul TX erősítését (PA). Az ezzel nem rendelkező áramkörök válasza \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Megjeleníti, hogy a LoRa front-end modul RX erősítése be van-e kapcsolva.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Megjeleníti, hogy a LoRa front-end modul TX erősítése be van-e kapcsolva.'; + + @override + String get repeater_bridgeNote => + 'Csak híddal (RS232 vagy ESP-NOW) épített firmware-en érhető el.'; + @override String get repeater_general => 'Általános'; @@ -3194,7 +3644,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Megjeleníti az árvízhirdetés intervallumát órákban.'; + 'Megjeleníti az elárasztási hirdetés intervallumát órákban.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3307,11 +3757,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Felsorolja azokat a régiókat, amelyek lehetővé teszik az árvízi forgalmat.'; + 'Felsorolja azokat a régiókat, amelyek lehetővé teszik az elárasztási forgalmat.'; @override String get repeater_cliHelpRegionListDenied => - 'Felsorolja azokat a régiókat, amelyek megtagadják az árvízi forgalmat.'; + 'Felsorolja azokat a régiókat, amelyek megtagadják az elárasztási forgalmat.'; @override String get repeater_cliHelpStatsPackets => @@ -3555,7 +4005,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channelPath_noHopDetails => - 'Ennél a csomagnál a komlórészletek nincsenek megadva.'; + 'Ennél a csomagnál az ugrásrészletek nincsenek megadva.'; @override String get channelPath_messageDetails => 'Üzenet részletei'; @@ -3599,7 +4049,7 @@ class AppLocalizationsHu extends AppLocalizations { String get channelPath_unknownPath => 'Ismeretlen'; @override - String get channelPath_floodPath => 'Árvíz'; + String get channelPath_floodPath => 'Elárasztás'; @override String get channelPath_directPath => 'Közvetlen'; @@ -3873,7 +4323,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Egy vagy több komló helye hiányzik!'; + 'Egy vagy több ugrás helye hiányzik!'; @override String get pathTrace_clearTooltip => 'Tiszta útvonal.'; @@ -4093,7 +4543,7 @@ class AppLocalizationsHu extends AppLocalizations { String get contacts_zeroHopAdvert => 'Zero Hop hirdetés'; @override - String get contacts_floodAdvert => 'Árvíz hirdetés'; + String get contacts_floodAdvert => 'Elárasztási hirdetés'; @override String get contacts_copyAdvertToClipboard => 'Hirdetés másolása a vágólapra'; @@ -4102,6 +4552,23 @@ class AppLocalizationsHu extends AppLocalizations { String get contacts_addContactFromClipboard => 'Névjegy hozzáadása a vágólapról'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Névjegy másolása a vágólapra'; @@ -4226,6 +4693,10 @@ class AppLocalizationsHu extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Utoljára látott'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Névjegyek beállításai'; @@ -4333,6 +4804,12 @@ class AppLocalizationsHu extends AppLocalizations { @override String get radioStats_screenTitle => 'Rádió statisztika'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Csatlakozzon egy eszközhöz a rádióstatisztikák megtekintéséhez.'; @@ -4390,6 +4867,43 @@ class AppLocalizationsHu extends AppLocalizations { @override String get translation_title => 'Fordítás'; + @override + String get imageMessages_enableTitle => 'Fenti hírüket biztosítani'; + + @override + String get imageMessages_enableSubtitle => + 'Fényokat a hálózatban küldd el. Egyértelmű fénymodell hozzáadásra kell.'; + + @override + String get imageMessages_modelSectionTitle => 'Image model'; + + @override + String get imageMessages_downloadModel => 'Hozzáladás'; + + @override + String get imageMessages_cancelDownload => 'Színviselés'; + + @override + String get imageMessages_removeModel => 'Kisnövezdés'; + + @override + String get imageMessages_modelReady => 'Hozzá'; + + @override + String get imageMessages_modelNotPublished => + 'Érkeztetve nem — ez a építési módszert nem lehet lejobbítani.'; + + @override + String get imageMessages_downloadFailed => 'Életmódelmát nem tudtam hozni.'; + + @override + String get imageMessages_autoProcessTitle => + 'Automatikusan kínaltatja fénybetek'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Minden fenti image-t kiválasztsa meg, amikor érkezik. Minden más esetben 2 GB fényre kell szükséges; megoldja a rekonstruálisi a támogatásra egy klikkel.'; + @override String get translation_enableTitle => 'Fordítás engedélyezése'; @@ -4673,4 +5187,248 @@ class AppLocalizationsHu extends AppLocalizations { @override String get pathMap_unfollowPacket => 'A nézet feloldása a csomagból'; + + @override + String get imageSend_title => 'Felhasználj az image'; + + @override + String get imageSend_cropNote => + '512 × 512 órák számára megosztva · képszöget nem biztosítva'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Következtetés:'; + + @override + String get imageSend_onAirSize => 'Erőben'; + + @override + String get imageSend_quality => 'Hosszú Képesség'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'High: Magas'; + + @override + String get imageSend_packetsLabel => 'Paketek'; + + @override + String get imageSend_airtimeLabel => 'Kiválasztás a fent'; + + @override + String get imageSend_sizeLabel => 'Kártya'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'csomag', + one: 'csomag', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Radiooldalok nem tudom'; + + @override + String get imageSend_radioUnknownBody => + 'Kizárdhoz kapcsolódd a rendszert, hogy a súly az az álló időt lehet elismerni.'; + + @override + String get imageSend_longSendTitle => 'Uzun hírás'; + + @override + String imageSend_longSendBody(String duration) { + return 'Ez megbízható a kanal $duration-n.'; + } + + @override + String get imageSend_floodNote => + 'Fúró irányozás: Minden repeater a fúró körüléggel megköveti mindkét paketet, ezért a kanal eltartja más a lehetséges időt.'; + + @override + String get imageSend_parityTitle => 'Korzolás paksa'; + + @override + String get imageSend_paritySubtitle => + 'Egy kibőbbes kapszula. Gruppos hírselek nem érkezik, ezért az empfangó nem kell elismerni a jel, ha egy egyes kapszula kaland, hogy nem teljesen érkezz.'; + + @override + String get imageSend_send => 'Keresés'; + + @override + String get imageSend_cancel => 'Színviselés'; + + @override + String get imageSend_encodeFailed => 'Ez a fényet nem tudtam kódolni.'; + + @override + String get imageSend_codecDownloading => + 'Érdekesz az image model megstálása még van.'; + + @override + String get imageSend_codecUnavailable => + 'Felhasználó észintje nem kapható ezen a rendszert.'; + + @override + String get imageSend_codecDisabled => + 'Image hírletek belsőoldal elkalmáznak a konfigurációban.'; + + @override + String get imageSend_deviceUnsupported => + 'Ez a radio nem tudja verseni színekfájltakat. Habilítd a kompatibilis firmware 13 vagy újabb versionot kapcsált eszközet.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Fényiak gyakorolják grupos adatban, ezért nem lehetek versenek egy hozzáfűzésre, csak egy kanalra.'; + + @override + String get imageSend_tooLarge => + 'A figyelmetes fentet nem kínálhat a körközlettel ismétálás elterjesztésére.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'csomagként', + one: 'csomagként', + ); + return 'Kép elküldve $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Fentami nem tűnik: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Felhasználó: Lehet a következőkét kifejezetet – $sent paket $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Node $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return 'Kulcsfontosságú: Kiválasztja meg a $received $total paketot'; + } + + @override + String get receivedImage_queued => 'Kódoláshoz küldőzve'; + + @override + String get receivedImage_tapToDecode => 'Kódoláshoz klikd el'; + + @override + String get receivedImage_decoding => 'Korlátozás… egy 1 perc után'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Kérem, az $received $total paketet kapottak.'; + } + + @override + String get receivedImage_corrupt => 'Fény nem tudtam megrealítani'; + + @override + String get receivedImage_decoderMissing => + 'Kezd az image — image decodálás nem kapható'; + + @override + String get receivedImage_evicted => 'Fény nem tartalmazva'; + + @override + String get receivedImage_retry => 'Kérem kell próbálni'; + + @override + String get receivedImage_decodeAgain => 'Kodoldó'; + + @override + String get receivedImage_openSettings => 'Jelzése'; + + @override + String get receivedImage_tapToProcess => 'Klikd a feljelenítést'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'csomag', + one: 'csomag', + ); + return '$bytes bájt · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds sekünd\n\n(Note: The placeholder $seconds is kept unchanged as requested.)'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes per $seconds sekünd\n\n(Note: The original text appears to be a placeholder format rather than a complete sentence. The translation reflects the literal structure while preserving the placeholders as requested.)'; + } + + @override + String chat_longMessageRetryNote(int count) { + return '158 bájt felett: legfeljebb $count alkalommal küldve'; + } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 350e7b78..8ea33a55 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -110,6 +110,46 @@ class AppLocalizationsIt extends AppLocalizations { @override String get messageStatus_repeated => 'Ricevuto ripetutamente'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Abilita immagini URL'; + + @override + String get urlImage_possible => + 'Possibile immagine URL; abilitala nelle Impostazioni.'; + @override String get common_reboot => 'Riavvia'; @@ -370,42 +410,66 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_radioSettingsUpdated => 'Impostazioni radio aggiornate'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'La radio non ha applicato queste impostazioni'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regioni'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Gestione delle regioni salvate'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Gestione Regionale'; + + @override + String get settings_regionNameHint => 'Inserisci il nome della regione'; + + @override + String get settings_regionAddRegion => 'Aggiungi regione'; + + @override + String get settings_regionFetchRegions => + 'Recupera le regioni dai ripetitori'; + + @override + String get settings_regionFetchRegionsFail => + 'Non sono state trovate regioni'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Questa regione è già stata aggiunta'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Nome della Regione'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Regione cancellata'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Elimina Regione'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Rimuovere \"$region\" dalla lista delle regioni?'; } @override @@ -500,6 +564,10 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Modalità di ambiente di telemetria'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Posizione dell\'annuncio'; @@ -507,9 +575,21 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_advertLocationSubtitle => 'Includi la posizione nell\'annuncio'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Annuncio zero-hop automatico all\'aggiornamento GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Quando la posizione GPS cambia, invia un annuncio zero-hop (richiede la posizione nell\'annuncio).'; + @override String get settings_multiAck => 'ACK multipli'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Modalità telemetria aggiornata'; @@ -610,15 +690,31 @@ class AppLocalizationsIt extends AppLocalizations { @override String get settings_infoPublicKey => 'Chiave Pubblica'; + @override + String get settings_publicKeyCopied => 'Chiave pubblica copiata'; + @override String get settings_infoContactsCount => 'Numero di contatti'; @override String get settings_infoChannelCount => 'Numero di canali'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Preset'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frequenza (MHz)'; @@ -641,7 +737,9 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_txPower => 'Potenza TX (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Potenza TX non valida (0-22 dBm)'; @@ -649,6 +747,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get settings_clientRepeat => 'Ripetizione \"fuori dalla rete\"'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Permetti a questo dispositivo di ripetere i pacchetti di rete per gli altri.'; @@ -731,6 +834,51 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_languageUk => 'Ucraino'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 byte'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 byte'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 byte'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Abilita tracciamento messaggi'; @@ -766,6 +914,13 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Mostra notifica all\'arrivo di nuovi messaggi'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Notifiche Messaggi Canale'; @@ -776,7 +931,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_advertisementNotifications => - 'Notifiche Pubblicitarie'; + 'Notifiche degli Annunci'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -879,6 +1034,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0-4,35 V)'; + @override String get appSettings_mapDisplay => 'Visualizzazione Mappa'; @@ -936,6 +1094,28 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_lastWeek => 'La settimana scorsa'; + @override + String get appSettings_rasterTileSource => 'Sorgente tile raster'; + + @override + String get appSettings_stadiaEndpoint => 'Endpoint Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Chiave API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Obbligatoria per usare Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Configurata: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Inserisci la chiave API di Stadia Maps. Questa app la usa per le richieste di tile raster.'; + @override String get appSettings_offlineMapCache => 'Cache Mappa Offline'; @@ -1029,6 +1209,29 @@ class AppLocalizationsIt extends AppLocalizations { return 'Eliminare $contactName dai contatti?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Gestisci ripetitore'; @@ -1179,6 +1382,18 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_private => 'Privato'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Modifica canale'; @@ -1312,6 +1527,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canale pubblico aggiunto'; + @override + String get channels_noFreeSlots => 'Tutti gli slot dei canali sono in uso'; + @override String get channels_sortBy => 'Ordina per'; @@ -1369,17 +1587,30 @@ class AppLocalizationsIt extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Regione: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Regione: nessuna'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Scegli una regione'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Zona chiara'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Nessun messaggio ancora'; @@ -1433,9 +1664,28 @@ class AppLocalizationsIt extends AppLocalizations { return 'Riprova $current/$max'; } + @override + String get chat_selectSendAction => 'Seleziona azione di invio'; + @override String get chat_sendGif => 'Invia GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Invia immagine tramite MeshCore'; + + @override + String get chat_imagePickFailed => + 'Non sono riuscito ad aprire quell\'immagine'; + + @override + String get chat_receivedGif => 'Ricevuto un GIF'; + @override String get chat_reply => 'Rispondi'; @@ -1445,6 +1695,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_me => 'Io'; + @override + String get reaction_report => 'Reazioni con Emoji'; + @override String get emojiCategorySmileys => 'Emoji'; @@ -1734,6 +1987,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_path => 'Percorso'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Chiave pubblica'; @@ -1771,6 +2027,12 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_newMessages => 'Nuovi messaggi'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Apri il link?'; @@ -1816,6 +2078,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get map_centerOnNode => 'Centra sul nodo'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Dettagli'; @@ -1834,6 +2099,10 @@ class AppLocalizationsIt extends AppLocalizations { @override String get map_noNodesWithLocation => 'Nessun nodo con dati di posizione'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'I nodi devono condividere le loro coordinate GPS\nper apparire sulla mappa'; @@ -1975,6 +2244,16 @@ class AppLocalizationsIt extends AppLocalizations { @override String get map_showGuessedLocations => 'Mostra le posizioni stimate dei nodi'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Mostra contatti di scoperta'; @@ -1996,6 +2275,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get map_manageRepeater => 'Gestisci ripetitore'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Tocca i nodi per aggiungerli al percorso.'; @@ -2086,6 +2368,42 @@ class AppLocalizationsIt extends AppLocalizations { return 'Download falliti: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2163,6 +2481,12 @@ class AppLocalizationsIt extends AppLocalizations { @override String get login_enterPassword => 'Inserisci password'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Salva password'; @@ -2178,6 +2502,9 @@ class AppLocalizationsIt extends AppLocalizations { String get login_roomDescription => 'Inserisci la password della stanza per accedere alle impostazioni e allo stato.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Instradamento'; @@ -2216,6 +2543,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get common_clear => 'Cancella'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Percorso corrente'; @@ -2241,6 +2571,12 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_guestTools => 'Strumenti per gli ospiti'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Stato'; @@ -2595,8 +2931,7 @@ class AppLocalizationsIt extends AppLocalizations { String get repeater_dutyCycle => 'Ciclo di lavoro'; @override - String get repeater_dutyCycleHelper => - 'Percentuale massima di utilizzo dello spazio pubblicitario'; + String get repeater_dutyCycleHelper => 'Percentuale massima di airtime'; @override String repeater_dutyCyclePercent(int percent) { @@ -2615,8 +2950,7 @@ class AppLocalizationsIt extends AppLocalizations { 'Aggiorna le informazioni sull\'operatore'; @override - String get repeater_floodMax => - 'Massimo numero di salti in caso di inondazione'; + String get repeater_floodMax => 'Numero massimo di salti in flood'; @override String get repeater_floodMaxHelper => @@ -2634,7 +2968,43 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Byte utilizzati per codificare l\'ID di questo ripetitore nei tag per il rilevamento del percorso/loop. 0=1 byte (256 ID, fino a 64 salti), 1=2 byte (65.000 ID, fino a 32 salti), 2=3 byte (16 milioni di ID, fino a 21 salti). Le versioni 1.13 e precedenti utilizzano percorsi multi-byte: è necessario attivare la rete prima di utilizzare questa funzionalità (a partire dalla versione 1.14).'; + 'Byte utilizzati per codificare l\'ID di questo ripetitore nei tag di percorso flood/rilevamento loop. 0=1 byte (256 ID, fino a 64 salti), 1=2 byte (65.000 ID, fino a 32 salti), 2=3 byte (16 milioni di ID, fino a 21 salti). Il firmware precedente alla v1.14 usava sempre percorsi a 1 byte; v1.14 e versioni successive possono essere configurate per percorsi a 2 o 3 byte.'; + + @override + String get repeater_keySettings => 'Cambia le Chiavi di Identità'; + + @override + String get repeater_keySettingsSubtitle => + 'Cambia la coppia di chiavi pubblica/privata'; + + @override + String get repeater_prvKey => 'Chiave privata'; + + @override + String get repeater_prvKeyHelper => + 'Una nuova chiave privata per il ripetitore, una stringa esadecimale di 128 caratteri.'; + + @override + String get repeater_generatePrvKey => 'Genera una coppia di chiavi casuale'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Interrompi la ricerca della coppia di chiavi'; + + @override + String get repeater_pubKey => 'Chiave pubblica'; + + @override + String get repeater_pubKeyHelper => + 'Questa è la chiave pubblica che accompagna la chiave privata generata. Non è possibile impostarla direttamente.'; + + @override + String get repeater_pubKeyPrefix => 'Prefisso desiderato'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Trova una chiave pubblica che inizia con queste cifre esadecimali. Tentativi necessari previsti: $tries.'; + } @override String get repeater_txDelay => 'Ritardo a Flood, TX'; @@ -2668,12 +3038,11 @@ class AppLocalizationsIt extends AppLocalizations { String get repeater_actionsTitle => 'Azioni'; @override - String get repeater_sendAdvert => - 'Inviare annuncio relativo alle inondazioni'; + String get repeater_sendAdvert => 'Invia annuncio flood'; @override String get repeater_sendAdvertSubtitle => - 'Trasmettere un annuncio pubblicitario relativo alle inondazioni attraverso la rete.'; + 'Trasmettere un annuncio flood attraverso la rete.'; @override String get repeater_sendAdvertZeroHop => @@ -2733,6 +3102,17 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Aggiorna Modalità Privacy'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label aggiornato'; @@ -2810,7 +3190,7 @@ class AppLocalizationsIt extends AppLocalizations { String get repeater_cliQuickDiscovery => 'Scopri vicini'; @override - String get repeater_cliHelpAdvert => 'Invia un pacchetto pubblicitario'; + String get repeater_cliHelpAdvert => 'Invia un pacchetto di annuncio'; @override String get repeater_cliHelpReboot => @@ -2850,7 +3230,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Imposta il numero massimo di salti per i pacchetti di inondazione in entrata (se >= max, il pacchetto non viene inoltrato)'; + 'Imposta il numero massimo di salti per i pacchetti flood in entrata (se >= max, il pacchetto non viene inoltrato)'; @override String get repeater_cliHelpSetIntThresh => @@ -2866,11 +3246,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - 'Imposta l\'intervallo del timer in minuti per inviare un pacchetto di pubblicità locale (senza salto). Imposta su 0 per disabilitare.'; + 'Imposta l\'intervallo del timer in minuti per inviare un pacchetto di annuncio locale (senza salto). Imposta su 0 per disabilitare.'; @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Imposta l\'intervallo del timer in ore per inviare un pacchetto pubblicitario di massa. Imposta su 0 per disabilitare.'; + 'Imposta l\'intervallo del timer in ore per inviare un pacchetto di annuncio flood. Imposta su 0 per disabilitare.'; @override String get repeater_cliHelpSetGuestPassword => @@ -2881,11 +3261,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_cliHelpSetLat => - 'Imposta la latitudine della mappa pubblicitaria. (gradi decimali)'; + 'Imposta la latitudine della mappa dell\'annuncio. (gradi decimali)'; @override String get repeater_cliHelpSetLon => - 'Imposta la longitudine della mappa pubblicitaria. (gradi decimali)'; + 'Imposta la longitudine della mappa dell\'annuncio. (gradi decimali)'; @override String get repeater_cliHelpSetRadio => @@ -2961,7 +3341,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(solo serie) Elenca tutte le regioni definite e le autorizzazioni di allagamento correnti.'; + '(solo serie) Elenca tutte le regioni definite e le autorizzazioni flood correnti.'; @override String get repeater_cliHelpRegionLoad => @@ -3029,6 +3409,75 @@ class AppLocalizationsIt extends AppLocalizations { String get repeater_commandsListNote => 'NOTA: per i vari comandi \"set...\", esiste anche un comando \"get...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Frequenza non valida (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => 'Da -9 a 30 dBm'; + + @override + String get repeater_recvErrors => 'Errori di ricezione'; + + @override + String get room_postsStored => 'Post'; + + @override + String get room_postsPushed => 'Post Inviati'; + + @override + String get repeater_cliRegionLoadActive => + 'Modalità di caricamento regioni: invia un nome di regione per riga, indentato con spazi sotto la sua regione padre (aggiungi F dopo il nome per consentire il flood). Le righe non ricevono risposta. Invia una riga vuota per terminare, poi \"region save\" per salvare il risultato.'; + + @override + String get repeater_cliRegionLoadHint => + 'Riga di regione, o vuota per terminare'; + + @override + String get repeater_cliRegionLoadEnd => '(fine caricamento regioni)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definisce una catena di regioni in un solo comando: ogni nome viene aggiunto sotto il precedente; \"name,parent\" aggiunge il nome e continua sotto il padre indicato. Risponde con l\'elenco delle regioni.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Imposta il numero massimo di salti per l\'inoltro dei pacchetti flood privi di ambito regionale (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Imposta il numero massimo di salti per l\'inoltro degli annunci flood (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Mostra il numero massimo di salti per i pacchetti flood senza ambito regionale.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Mostra il numero massimo di salti per gli annunci flood.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Attiva o disattiva il guadagno RX (LNA) del modulo frontend LoRa. Le schede prive di questo modulo rispondono \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Attiva o disattiva il guadagno TX (PA) del modulo frontend LoRa. Le schede prive di questo modulo rispondono \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Mostra se il guadagno RX del modulo frontend LoRa è attivo.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Mostra se il guadagno TX del modulo frontend LoRa è attivo.'; + + @override + String get repeater_bridgeNote => + 'Disponibile solo su firmware compilato con un bridge (RS232 o ESP-NOW).'; + @override String get repeater_general => 'Generale'; @@ -3200,7 +3649,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Indica l\'intervallo pubblicitario locale in minuti.'; + 'Indica l\'intervallo di annuncio locale in minuti.'; @override String get repeater_cliHelpGetFloodAdvertInterval => @@ -3881,7 +4330,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Uno o più hop non hanno una posizione!'; + 'Uno o più salti non hanno una posizione!'; @override String get pathTrace_clearTooltip => 'Cancella percorso'; @@ -4100,7 +4549,7 @@ class AppLocalizationsIt extends AppLocalizations { String get contacts_zeroHopAdvert => 'Annuncio Zero Hop'; @override - String get contacts_floodAdvert => 'Annuncio alluvionale'; + String get contacts_floodAdvert => 'Annuncio Flood'; @override String get contacts_copyAdvertToClipboard => 'Copia Annuncio negli Appunti'; @@ -4109,6 +4558,23 @@ class AppLocalizationsIt extends AppLocalizations { String get contacts_addContactFromClipboard => 'Aggiungere contatto dalla clipboard'; + @override + String get contacts_scanQrCode => 'Scansiona codice QR'; + + @override + String get contacts_scanQrInstructions => + 'Inquadra un codice QR di un contatto MeshCore'; + + @override + String get contacts_qrFromGallery => 'Scansiona QR dalla galleria'; + + @override + String get contacts_noQrCodeFound => + 'Nessun codice QR trovato nell\'immagine selezionata.'; + + @override + String get contacts_qrGalleryFailed => 'Impossibile aprire la galleria.'; + @override String get contacts_ShareContact => 'Copia contatto negli Appunti'; @@ -4236,6 +4702,10 @@ class AppLocalizationsIt extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Ultimo accesso'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Impostazioni dei contatti'; @@ -4342,6 +4812,12 @@ class AppLocalizationsIt extends AppLocalizations { @override String get radioStats_screenTitle => 'Statistiche radio'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Connettiti a un dispositivo per visualizzare le statistiche radio.'; @@ -4400,6 +4876,44 @@ class AppLocalizationsIt extends AppLocalizations { @override String get translation_title => 'Traduzione'; + @override + String get imageMessages_enableTitle => 'Messaggi con immagini'; + + @override + String get imageMessages_enableSubtitle => + 'Invia le immagini tramite la mesh. È necessario scaricare il modello dell\'immagine una tantum.'; + + @override + String get imageMessages_modelSectionTitle => 'Modello di immagine'; + + @override + String get imageMessages_downloadModel => 'Scarica'; + + @override + String get imageMessages_cancelDownload => 'Annullare'; + + @override + String get imageMessages_removeModel => 'Rimuovi il modello'; + + @override + String get imageMessages_modelReady => 'Pronto'; + + @override + String get imageMessages_modelNotPublished => + 'Non pubblicato ancora — questa versione non può scaricarlo.'; + + @override + String get imageMessages_downloadFailed => + 'Il modello di immagine non può essere scaricato.'; + + @override + String get imageMessages_autoProcessTitle => + 'Elabora automaticamente le immagini'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Ricostruisci ogni immagine non appena arriva. Utilizza circa 2 GB di memoria per un secondo ogni volta; disattiva la ricostruzione con un semplice tocco.'; + @override String get translation_enableTitle => 'Abilitare la traduzione'; @@ -4686,4 +5200,251 @@ class AppLocalizationsIt extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Sblocca la vista dal pacchetto'; + + @override + String get imageSend_title => 'Invia immagine'; + + @override + String get imageSend_cropNote => + 'Ridimensionato a 512 × 512 · rapporto d\'aspetto non conservato'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + 'Traduzione:\n\nOriginal text:\n\nPlease translate the following English text into Italian:\n\nOriginal text:\n\n(No original English text provided)'; + + @override + String get imageSend_onAirSize => 'In onda'; + + @override + String get imageSend_quality => 'Qualità'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Alto'; + + @override + String get imageSend_packetsLabel => 'Pacchetti'; + + @override + String get imageSend_airtimeLabel => 'Tempo in onda'; + + @override + String get imageSend_sizeLabel => 'Carico utile'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pacchetti', + one: 'pacchetto', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Impostazioni radio sconosciute'; + + @override + String get imageSend_radioUnknownBody => + 'Collegati a un dispositivo in modo che si possa calcolare l\'orario di trasmissione.'; + + @override + String get imageSend_longSendTitle => 'Lunga trasmissione'; + + @override + String imageSend_longSendBody(String duration) { + return 'Questo manterrà il canale per circa $duration.'; + } + + @override + String get imageSend_floodNote => + 'Instradamento flood: ogni ripetitore nel raggio ritrasmette ogni pacchetto, quindi il canale rimane occupato più a lungo.'; + + @override + String get imageSend_parityTitle => 'Pacchetto di recupero'; + + @override + String get imageSend_paritySubtitle => + 'Un pacchetto aggiuntivo. I messaggi di gruppo non vengono riconosciuti, quindi questo permette al destinatario di ricostruire l\'immagine se un singolo pacchetto viene perso.'; + + @override + String get imageSend_send => 'Invia'; + + @override + String get imageSend_cancel => 'Annullare'; + + @override + String get imageSend_encodeFailed => + 'Questa immagine non può essere codificata.'; + + @override + String get imageSend_codecDownloading => + 'Il modello di immagine sta ancora scaricando.'; + + @override + String get imageSend_codecUnavailable => + 'L\'invio di immagini non è disponibile su questo dispositivo.'; + + @override + String get imageSend_codecDisabled => + 'I messaggi immagine sono disattivati nelle impostazioni.'; + + @override + String get imageSend_deviceUnsupported => + 'Questa radio non può inviare pacchetti di immagini. Collegare un dispositivo con firmware companion versione 13 o successiva.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Le immagini viaggiano come dati di gruppo, quindi possono essere inviate solo a un canale — non tramite messaggio diretto.'; + + @override + String get imageSend_tooLarge => + 'Quella immagine è stata codificata in un numero di pacchetti superiore a quello consentito dal formato mesh.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pacchetti', + one: 'pacchetto', + ); + return 'Immagine inviata come $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'L\'immagine non può essere inviata: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Invio immagine — pacchetto $sent di $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Nodo $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received di $total pacchetti'; + } + + @override + String get receivedImage_queued => 'In attesa di decodificare'; + + @override + String get receivedImage_tapToDecode => 'Tocca per decodificare'; + + @override + String get receivedImage_decoding => 'Ricostruire… circa 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Immagine incompleta — $received su $total pacchetti ricevuti'; + } + + @override + String get receivedImage_corrupt => + 'L\'immagine non potrebbe essere ricostruita'; + + @override + String get receivedImage_decoderMissing => + 'Immagine ricevuta — decodifica dell\'immagine non funzionante'; + + @override + String get receivedImage_evicted => 'Immagine non più memorizzata'; + + @override + String get receivedImage_retry => 'Prova ancora'; + + @override + String get receivedImage_decodeAgain => 'Decodifica di nuovo'; + + @override + String get receivedImage_openSettings => 'Imposta'; + + @override + String get receivedImage_tapToProcess => 'Premi per elaborare'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'pacchetti', + one: 'pacchetto', + ); + return '$bytes byte · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds secondi'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Oltre 158 byte: inviato al massimo $count volte'; + } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 53851ba3..8a8fc5e3 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -110,6 +110,45 @@ class AppLocalizationsJa extends AppLocalizations { @override String get messageStatus_repeated => '何度も聞いた'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'URL画像を有効にする'; + + @override + String get urlImage_possible => 'URL画像の可能性があります。設定で有効にしてください。'; + @override String get common_reboot => '再起動'; @@ -354,42 +393,61 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_radioSettingsUpdated => 'ラジオの設定が更新されました'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => 'ラジオがこれらの設定を適用しませんでした'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => '地域'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => '保存された領域の管理'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; @override - String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + String get settings_regionDefaultNone => 'None'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionManagement_screenTitle => '地域管理'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionNameHint => '地域名を入力してください'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_regionAddRegion => '地域を追加'; + + @override + String get settings_regionFetchRegions => 'リピーターからのフェッチ地域'; + + @override + String get settings_regionFetchRegionsFail => '地域は見つかりませんでした'; + + @override + String get settings_regionFetchRegionsAlreadyExists => 'この地域はすでに追加されています。'; + + @override + String get settings_regionName => '地域名'; + + @override + String get settings_regionDeleted => '地域が削除されました'; + + @override + String get settings_deleteRegion => '地域を削除'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return '$region を地域リストから削除しますか?'; } @override @@ -436,11 +494,11 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_privacyMode => 'プライバシーモード'; @override - String get settings_privacyModeSubtitle => '広告に名前や位置を表示しない'; + String get settings_privacyModeSubtitle => 'アドバートに名前や位置を表示しない'; @override String get settings_privacyModeToggle => - 'プライバシーモードを有効にすると、広告に表示される名前と位置を非表示にします。'; + 'プライバシーモードを有効にすると、アドバートに表示される名前と位置を非表示にします。'; @override String get settings_privacyModeEnabled => 'プライバシーモードが有効になっています'; @@ -477,14 +535,29 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'テレメトリ環境モード'; @override - String get settings_advertLocation => '広告掲載場所'; + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; @override - String get settings_advertLocationSubtitle => '広告に場所を記載してください。'; + String get settings_advertLocation => 'アドバート位置'; + + @override + String get settings_advertLocationSubtitle => 'アドバートに位置情報を含めてください。'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => 'GPS更新時にゼロホップアドバートを自動送信'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'GPS位置が変化したときにゼロホップアドバートを送信します(アドバートへの位置情報の含有が必要)。'; @override String get settings_multiAck => 'マルチ ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'テレメトリモードが更新されました'; @@ -498,13 +571,13 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_deleteAllPathsSubtitle => '連絡先からすべての経路データを消去します。'; @override - String get settings_sendAdvertisement => '広告を送信'; + String get settings_sendAdvertisement => 'アドバートを送信'; @override String get settings_sendAdvertisementSubtitle => '現在の存在を送信します'; @override - String get settings_advertisementSent => '広告を送信しました'; + String get settings_advertisementSent => 'アドバートを送信しました'; @override String get settings_syncTime => '時刻を同期'; @@ -581,15 +654,31 @@ class AppLocalizationsJa extends AppLocalizations { @override String get settings_infoPublicKey => '公開鍵'; + @override + String get settings_publicKeyCopied => '公開鍵がコピーされました'; + @override String get settings_infoContactsCount => '連絡先数'; @override String get settings_infoChannelCount => 'チャンネル数'; + @override + String get settings_infoHardware => 'ハードウェア'; + + @override + String get settings_infoFirmware => 'ファームウェア'; + @override String get settings_presets => 'プリセット'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => '周波数 (MHz)'; @@ -612,7 +701,9 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_txPower => 'TX 信号電力 (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => '無効な送信電力 (0-22 dBm)'; @@ -620,6 +711,11 @@ class AppLocalizationsJa extends AppLocalizations { @override String get settings_clientRepeat => 'オフグリッド中継'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'このデバイスが他のデバイス向けにメッシュパケットを中継できるようにします。'; @@ -702,6 +798,51 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_languageUk => 'ウクライナ語'; + @override + String get repeater_pathHashModeOption0 => '0 - 1バイト'; + + @override + String get repeater_pathHashModeOption1 => '1〜2バイト'; + + @override + String get repeater_pathHashModeOption2 => '2〜3バイト'; + + @override + String get repeater_pathHashModeOption3 => '3〜4バイト'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'メッセージ追跡を有効にする'; @@ -716,7 +857,7 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_enableNotifications => '通知を有効にする'; @override - String get appSettings_enableNotificationsSubtitle => 'メッセージや広告の通知を受け取ります'; + String get appSettings_enableNotificationsSubtitle => 'メッセージやアドバートの通知を受け取ります'; @override String get appSettings_notificationPermissionDenied => '通知の許可が拒否されました'; @@ -734,6 +875,13 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => '新しいメッセージを受信した際に、通知を表示する'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'チャネルメッセージの通知'; @@ -742,7 +890,7 @@ class AppLocalizationsJa extends AppLocalizations { 'チャンネルからのメッセージを受信した際に、通知を表示する'; @override - String get appSettings_advertisementNotifications => '広告通知'; + String get appSettings_advertisementNotifications => 'アドバート通知'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -831,6 +979,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3.0-4.2V)'; + @override + String get appSettings_batteryLipoHv => 'リポバッテリー HV(3.0〜4.35V)'; + @override String get appSettings_mapDisplay => '地図表示'; @@ -884,6 +1035,27 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_lastWeek => '過去1週間'; + @override + String get appSettings_rasterTileSource => 'ラスタタイルのソース'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia エンドポイント'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API キー'; + + @override + String get appSettings_stadiaApiKeyRequired => 'Stadia Maps の利用に必要です'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return '設定済み: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Stadia Maps の API キーを入力してください。このアプリはラスタタイルの取得に使用します。'; + @override String get appSettings_offlineMapCache => 'オフライン地図キャッシュ'; @@ -927,7 +1099,7 @@ class AppLocalizationsJa extends AppLocalizations { String get contacts_noContacts => 'まだ連絡先はありません'; @override - String get contacts_contactsWillAppear => 'デバイスが広告を送信すると連絡先が表示されます'; + String get contacts_contactsWillAppear => 'デバイスがアドバートを送信すると連絡先が表示されます'; @override String get contacts_unread => '未読'; @@ -974,6 +1146,29 @@ class AppLocalizationsJa extends AppLocalizations { return '$contactName を連絡先から削除しますか?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'リピータの管理'; @@ -1120,6 +1315,18 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_private => '非公開'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'チャンネルを編集'; @@ -1247,6 +1454,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_publicChannelAdded => '公開チャンネルを追加しました'; + @override + String get channels_noFreeSlots => 'すべてのチャンネルスロットが使用中です'; + @override String get channels_sortBy => '並び替え'; @@ -1300,17 +1510,30 @@ class AppLocalizationsJa extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return '地域:$region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => '地域:なし'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => '地域を選択する'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'クリアな地域'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'まだメッセージは届いていません'; @@ -1364,9 +1587,27 @@ class AppLocalizationsJa extends AppLocalizations { return '$current/$max 回目'; } + @override + String get chat_selectSendAction => '送信アクションを選択'; + @override String get chat_sendGif => 'GIF を送信'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'MeshCore経由で画像を送信'; + + @override + String get chat_imagePickFailed => 'その画像を開けませんでした'; + + @override + String get chat_receivedGif => 'GIFを受け取りました'; + @override String get chat_reply => '返信'; @@ -1376,6 +1617,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_me => '私'; + @override + String get reaction_report => '絵文字リアクション'; + @override String get emojiCategorySmileys => '顔文字'; @@ -1654,6 +1898,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_path => '道'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => '公開鍵'; @@ -1691,6 +1938,12 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_newMessages => '新しいメッセージ'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'リンクを開きますか?'; @@ -1735,6 +1988,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get map_centerOnNode => 'ノードを中央に表示'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => '詳細'; @@ -1753,6 +2009,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get map_noNodesWithLocation => '位置情報を持つノードはありません'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'ノードを地図に表示するには GPS 座標の共有が必要です'; @@ -1891,6 +2151,16 @@ class AppLocalizationsJa extends AppLocalizations { @override String get map_showGuessedLocations => '推測されたノードの位置を表示する'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Discovery 連絡先を表示'; @@ -1912,6 +2182,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get map_manageRepeater => 'リピータの管理'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'ノードをタップして経路に追加します。'; @@ -1999,6 +2272,42 @@ class AppLocalizationsJa extends AppLocalizations { return '失敗したダウンロード: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2075,6 +2384,12 @@ class AppLocalizationsJa extends AppLocalizations { @override String get login_enterPassword => 'パスワードを入力してください'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'パスワードを保存する'; @@ -2088,6 +2403,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get login_roomDescription => '設定やステータスへのアクセスには、部屋のパスワードを入力してください。'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => '経路設定'; @@ -2126,6 +2444,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get common_clear => 'クリア'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => '現在の経路'; @@ -2150,6 +2471,12 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_guestTools => 'ゲスト向けツール'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'ステータス'; @@ -2366,13 +2693,13 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_privacyMode => 'プライバシーモード'; @override - String get repeater_privacyModeSubtitle => '広告に名前/場所を記載しない'; + String get repeater_privacyModeSubtitle => 'アドバートに名前/場所を記載しない'; @override - String get repeater_advertisementSettings => '広告設定'; + String get repeater_advertisementSettings => 'アドバート設定'; @override - String get repeater_localAdvertInterval => '地域広告掲載期間'; + String get repeater_localAdvertInterval => '地域アドバート掲載期間'; @override String repeater_localAdvertIntervalMinutes(int minutes) { @@ -2380,7 +2707,7 @@ class AppLocalizationsJa extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => 'フラッドに関する広告の表示間隔'; + String get repeater_floodAdvertInterval => 'フラッドに関するアドバートの表示間隔'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2388,7 +2715,7 @@ class AppLocalizationsJa extends AppLocalizations { } @override - String get repeater_encryptedAdvertInterval => '暗号化された広告表示間'; + String get repeater_encryptedAdvertInterval => '暗号化されたアドバート表示間'; @override String get repeater_dangerZone => '危険区域'; @@ -2519,6 +2846,38 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_pathHashModeHelper => 'このリピータのIDをフローパス/ループ検出タグにエンコードするために使用されるバイト数。 0=1バイト (256個のID、最大64ホップ)、1=2バイト (65,000個のID、最大32ホップ)、2=3バイト (160万個のID、最大21ホップ)。 v1.13およびそれ以前のファームウェアでは、マルチバイトパスがサポートされていません。 v1.14以降のバージョンでは、一度ネットワークが起動されると、パスが一度だけ検出されます。'; + @override + String get repeater_keySettings => 'アイデンティティキーの変更'; + + @override + String get repeater_keySettingsSubtitle => '公開鍵/秘密鍵を変更する'; + + @override + String get repeater_prvKey => 'プライベートキー'; + + @override + String get repeater_prvKeyHelper => 'リピーター用の新しいプライベートキー。128文字の16進文字列です。'; + + @override + String get repeater_generatePrvKey => 'ランダムな鍵ペアを生成する'; + + @override + String get repeater_stopGeneratingPrvKey => 'キーペアの検索を中断'; + + @override + String get repeater_pubKey => '公開鍵'; + + @override + String get repeater_pubKeyHelper => 'これは生成された秘密鍵に対応する公開鍵です。直接設定することはできません。'; + + @override + String get repeater_pubKeyPrefix => '希望する接頭辞'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'これらの16進数で始まる公開鍵を見つけてください。予想される試行回数: $tries。'; + } + @override String get repeater_txDelay => 'フロイド・TXでの遅延'; @@ -2551,16 +2910,16 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_actionsTitle => '操作'; @override - String get repeater_sendAdvert => 'フラッド広告を送信'; + String get repeater_sendAdvert => 'フラッドアドバートを送信'; @override - String get repeater_sendAdvertSubtitle => 'ネットワーク全体にフラッド広告をブロードキャストします'; + String get repeater_sendAdvertSubtitle => 'ネットワーク全体にフラッドアドバートをブロードキャストします'; @override - String get repeater_sendAdvertZeroHop => 'ゼロホップ広告を送信'; + String get repeater_sendAdvertZeroHop => 'ゼロホップアドバートを送信'; @override - String get repeater_sendAdvertZeroHopSubtitle => '1 ホップ広告を送信します(リピータなし)'; + String get repeater_sendAdvertZeroHopSubtitle => '1 ホップアドバートを送信します(リピータなし)'; @override String get repeater_clockSync => '時刻を同期'; @@ -2610,6 +2969,17 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'プライバシーモードをリセットする'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label が更新されました'; @@ -2675,7 +3045,7 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_cliQuickVersion => 'バージョン'; @override - String get repeater_cliQuickAdvertise => '広告送信'; + String get repeater_cliQuickAdvertise => 'アドバート送信'; @override String get repeater_cliQuickClock => '時刻'; @@ -2687,7 +3057,7 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_cliQuickDiscovery => '近隣を発見する'; @override - String get repeater_cliHelpAdvert => '広告用資料を送る'; + String get repeater_cliHelpAdvert => 'アドバートパケットを送信します'; @override String get repeater_cliHelpReboot => @@ -2735,24 +3105,24 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - 'ローカル(ホップなし)の広告パケットを送信する間隔を分単位で設定します。 0 に設定すると、機能を無効にします。'; + 'ローカル(ホップなし)のアドバートパケットを送信する間隔を分単位で設定します。 0 に設定すると、機能を無効にします。'; @override String get repeater_cliHelpSetFloodAdvertInterval => - 'フラッド広告の送信間隔を時間単位で設定します。0に設定すると、送信を停止します。'; + 'フラッドアドバートの送信間隔を時間単位で設定します。0に設定すると、送信を停止します。'; @override String get repeater_cliHelpSetGuestPassword => 'ゲストのパスワードを設定/更新します。(繰り返し利用の場合、ゲストのログインは「統計情報を取得」のリクエストを送信できます)'; @override - String get repeater_cliHelpSetName => '広告の名前を設定します。'; + String get repeater_cliHelpSetName => 'アドバートの名前を設定します。'; @override - String get repeater_cliHelpSetLat => '広告表示の地図の緯度を設定します。(度分秒表記)'; + String get repeater_cliHelpSetLat => 'アドバート表示の地図の緯度を設定します。(度分秒表記)'; @override - String get repeater_cliHelpSetLon => '広告表示の地図の経度を設定します。(度数、分)'; + String get repeater_cliHelpSetLon => 'アドバート表示の地図の経度を設定します。(度数、分)'; @override String get repeater_cliHelpSetRadio => @@ -2764,7 +3134,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - '時間経過に応じた「フラッシュモード」パケットの送信遅延を設定します。この遅延は、ランダムなスロットシステムと組み合わせて使用され、パケットの衝突を減らすことを目的としています。'; + '時間経過に応じた「フラッドモード」パケットの送信遅延を設定します。この遅延は、ランダムなスロットシステムと組み合わせて使用され、パケットの衝突を減らすことを目的としています。'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2813,7 +3183,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - 'ゼロホップ広告を通じて受信した他のリピータノードの一覧を表示します。各行は、IDプレフィックス(16進数)、タイムスタンプ、SNR(シグナル強度)の情報を4つ含みます。'; + 'ゼロホップアドバートを通じて受信した他のリピータノードの一覧を表示します。各行は、IDプレフィックス(16進数)、タイムスタンプ、SNR(シグナル強度)の情報を4つ含みます。'; @override String get repeater_cliHelpNeighborRemove => @@ -2871,10 +3241,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - 'ノードの広告設定における場所情報の指定:\n- none: 広告に場所情報を含まない\n- share: GPS位置情報を共有 (SensorManagerから取得)\n- prefs: プリファレンスに保存された場所情報を広告'; + 'ノードのアドバート設定における場所情報の指定:\n- none: アドバートに場所情報を含まない\n- share: GPS位置情報を共有 (SensorManagerから取得)\n- prefs: プリファレンスに保存された場所情報をアドバートする'; @override - String get repeater_cliHelpGpsAdvertSet => '場所に関する広告設定を行います。'; + String get repeater_cliHelpGpsAdvertSet => '場所に関するアドバート設定を行います。'; @override String get repeater_commandsListTitle => 'コマンド一覧'; @@ -2883,6 +3253,73 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_commandsListNote => '注:さまざまな「set ...」コマンドには、「get ...」コマンドも存在します。'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => '無効な周波数 (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9~30 dBm'; + + @override + String get repeater_recvErrors => '受信エラー'; + + @override + String get room_postsStored => '投稿'; + + @override + String get room_postsPushed => 'プッシュされた投稿'; + + @override + String get repeater_cliRegionLoadActive => + '地域読み込みモード:1行に1つの地域名を送信し、親の下にスペースでインデントします(フラッドを許可する場合は名前の後にFを追加)。各行に返信はありません。空行を送信して終了し、その後「region save」を送信すると結果が保存されます。'; + + @override + String get repeater_cliRegionLoadHint => '地域行、または空欄で終了'; + + @override + String get repeater_cliRegionLoadEnd => '(地域読み込み終了)'; + + @override + String get repeater_cliHelpRegionDef => + '1つのコマンドで地域のチェーンを定義します。各名前は直前の名前の下に追加されます。「name,parent」を指定すると、その名前を追加した後、指定した親の下に続けます。地域リストを返信します。'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + '地域スコープを持たないフラッドパケットを転送する際の最大ホップ数を設定します(0-64)。'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'フラッドアドバートを転送する際の最大ホップ数を設定します(0-64)。'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + '地域スコープのないフラッドパケットの最大ホップ数を表示します。'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => 'フラッドアドバートの最大ホップ数を表示します。'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'LoRaフロントエンドモジュールのRXゲイン(LNA)の有効/無効を切り替えます。対応していない基板は「Error: unsupported」と返信します。'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'LoRaフロントエンドモジュールのTXゲイン(PA)の有効/無効を切り替えます。対応していない基板は「Error: unsupported」と返信します。'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'LoRaフロントエンドモジュールのRXゲインが有効になっているかどうかを表示します。'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'LoRaフロントエンドモジュールのTXゲインが有効になっているかどうかを表示します。'; + + @override + String get repeater_bridgeNote => + 'RS232またはESP-NOWのブリッジ機能を備えたファームウェアでのみ利用可能です。'; + @override String get repeater_general => '一般的な'; @@ -2926,7 +3363,7 @@ class AppLocalizationsJa extends AppLocalizations { String get repeater_cliHelpClkReboot => '時計を既知の基準時点にリセットし、デバイスを再起動します。'; @override - String get repeater_cliHelpAdvertZeroHop => '近隣のデバイスのみに、ゼロホップの広告を送信します。'; + String get repeater_cliHelpAdvertZeroHop => '近隣のデバイスのみに、ゼロホップのアドバートを送信します。'; @override String get repeater_cliHelpStartOta => @@ -2968,7 +3405,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_cliHelpSetOwnerInfo => - '広告に記載されている所有者連絡先情報を設定します。改行には\'|\'を使用してください。'; + 'アドバートに記載されている所有者連絡先情報を設定します。改行には\'|\'を使用してください。'; @override String get repeater_cliHelpSetPathHashMode => @@ -3035,11 +3472,11 @@ class AppLocalizationsJa extends AppLocalizations { 'ゲストによる読み取り専用アクセスが許可されているかどうかを示す。'; @override - String get repeater_cliHelpGetAdvertInterval => 'ローカル広告の時間を分単位で表示します。'; + String get repeater_cliHelpGetAdvertInterval => 'ローカルアドバートの時間を分単位で表示します。'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'フラッドに関する広告の放送時間を時間単位で表示します。'; + 'フラッドに関するアドバートの放送時間を時間単位で表示します。'; @override String get repeater_cliHelpGetGuestPassword => '設定されたゲストパスワードを表示します。'; @@ -3891,34 +4328,52 @@ class AppLocalizationsJa extends AppLocalizations { String get contacts_contactImportFailed => '連絡先のインポートに失敗しました。'; @override - String get contacts_zeroHopAdvert => 'ゼロホップ広告'; + String get contacts_zeroHopAdvert => 'ゼロホップアドバート'; @override - String get contacts_floodAdvert => 'フラッドに関する広告'; + String get contacts_floodAdvert => 'フラッドアドバート'; @override - String get contacts_copyAdvertToClipboard => '広告をクリップボードにコピー'; + String get contacts_copyAdvertToClipboard => 'アドバートをクリップボードにコピー'; @override String get contacts_addContactFromClipboard => 'クリップボードから連絡先を追加する'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => '連絡先をクリップボードにコピー'; @override - String get contacts_ShareContactZeroHop => '広告を通じて連絡先を共有する'; + String get contacts_ShareContactZeroHop => 'アドバートを通じて連絡先を共有する'; @override - String get contacts_zeroHopContactAdvertSent => '広告を通じて連絡先を得た。'; + String get contacts_zeroHopContactAdvertSent => 'アドバートを通じて連絡先を得た。'; @override String get contacts_zeroHopContactAdvertFailed => '連絡を送信できませんでした。'; @override - String get contacts_contactAdvertCopied => '広告がクリップボードにコピーされました。'; + String get contacts_contactAdvertCopied => 'アドバートがクリップボードにコピーされました。'; @override - String get contacts_contactAdvertCopyFailed => '広告のコピーがクリップボードにコピーできませんでした。'; + String get contacts_contactAdvertCopyFailed => + 'アドバートのコピーがクリップボードにコピーできませんでした。'; @override String get notification_activityTitle => 'メッシュコアの活動'; @@ -4019,6 +4474,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get snrIndicator_lastSeen => '最後に確認された場所'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => '連絡先設定'; @@ -4116,6 +4575,12 @@ class AppLocalizationsJa extends AppLocalizations { @override String get radioStats_screenTitle => 'ラジオの統計'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'ラジオの統計情報を表示するために、デバイスに接続してください。'; @@ -4171,6 +4636,42 @@ class AppLocalizationsJa extends AppLocalizations { @override String get translation_title => '翻訳'; + @override + String get imageMessages_enableTitle => '画像メッセージを有効にする'; + + @override + String get imageMessages_enableSubtitle => + 'メッシュ経由で画像を送信してください。画像モデルを一度限りのダウンロードが必要です。'; + + @override + String get imageMessages_modelSectionTitle => '画像モデル'; + + @override + String get imageMessages_downloadModel => 'ダウンロード'; + + @override + String get imageMessages_cancelDownload => 'キャンセル'; + + @override + String get imageMessages_removeModel => 'モデルを削除'; + + @override + String get imageMessages_modelReady => '準備完了'; + + @override + String get imageMessages_modelNotPublished => + 'まだ公開されていません — このビルドではダウンロードできません。'; + + @override + String get imageMessages_downloadFailed => '画像モデルがダウンロードできませんでした。'; + + @override + String get imageMessages_autoProcessTitle => '画像を自動的に処理する'; + + @override + String get imageMessages_autoProcessSubtitle => + '画像が届き次第、すぐに再構築してください。1回あたり約2GBのメモリを使用します。タップで再構築を解除できます。'; + @override String get translation_enableTitle => '翻訳機能を有効にする'; @@ -4446,4 +4947,242 @@ class AppLocalizationsJa extends AppLocalizations { @override String get pathMap_unfollowPacket => 'パケットの追跡を解除'; + + @override + String get imageSend_title => '画像を送信'; + + @override + String get imageSend_cropNote => '512 × 512にリサイズされました。アスペクト比は保持されませんでした。'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + '原文:\nThe early morning light filtered through the curtains, casting a soft glow on the room.\n\n翻訳:\n早朝の光がカーテンをすり抜け、部屋に柔らかな光を投げかけていた。'; + + @override + String get imageSend_onAirSize => '放送中'; + + @override + String get imageSend_quality => '品質'; + + @override + String get imageSend_qualityStandard => '標準'; + + @override + String get imageSend_qualityHigh => 'ハイ'; + + @override + String get imageSend_packetsLabel => 'パケット'; + + @override + String get imageSend_airtimeLabel => '放送時間'; + + @override + String get imageSend_sizeLabel => 'ペイロード'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'パケット', + one: 'パケット', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'ラジオの設定が不明です'; + + @override + String get imageSend_radioUnknownBody => '放送時間の計算ができるように、デバイスに接続してください。'; + + @override + String get imageSend_longSendTitle => '長距離伝送'; + + @override + String imageSend_longSendBody(String duration) { + return 'このチャンネルは約 $duration 間保持されます。'; + } + + @override + String get imageSend_floodNote => + 'フラッドルーティング:範囲内の各リピーターが各パケットを再送信するため、チャネルはこれよりも長く占有されたままになります。'; + + @override + String get imageSend_parityTitle => '回復パケット'; + + @override + String get imageSend_paritySubtitle => + '追加のパケットが1つあります。グループメッセージは確認されないため、1つのパケットが失われても受信者が画像を再構築できます。'; + + @override + String get imageSend_send => '送る'; + + @override + String get imageSend_cancel => 'キャンセル'; + + @override + String get imageSend_encodeFailed => 'この画像はエンコードできませんでした。'; + + @override + String get imageSend_codecDownloading => '画像モデルはまだダウンロード中です。'; + + @override + String get imageSend_codecUnavailable => 'このデバイスでは画像送信が利用できません。'; + + @override + String get imageSend_codecDisabled => '設定で画像メッセージはオフになっています。'; + + @override + String get imageSend_deviceUnsupported => + 'このラジオは画像パケットを送信できません。コンパニオン ファームウェア 13 以降を実行しているデバイスを接続してください。'; + + @override + String get imageSend_directMessagesUnsupported => + '画像はグループデータとして送信されるため、ダイレクトメッセージではなくチャンネルに送ることができます。'; + + @override + String get imageSend_tooLarge => 'その画像は、メッシュ形式が許容するよりも多くのパケットにエンコードされています。'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'パケット', + one: 'パケット', + ); + return '$count $_temp0として画像を送信しました。'; + } + + @override + String imageSend_sendFailed(String error) { + return '画像を送信できませんでした:$error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return '画像送信 — パケット $sent 件、合計 $total 件'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'ノード $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$total パケット中 $received パケット'; + } + + @override + String get receivedImage_queued => '復号を待っている'; + + @override + String get receivedImage_tapToDecode => 'デコードするにはタップしてください。'; + + @override + String get receivedImage_decoding => '再構築… 約1秒'; + + @override + String receivedImage_incomplete(int received, int total) { + return '画像が不完全です — $total パケット中 $received パケットが到着しました'; + } + + @override + String get receivedImage_corrupt => '画像を再構成することはできませんでした'; + + @override + String get receivedImage_decoderMissing => '画像を受信しました — 画像のデコードが失敗しました'; + + @override + String get receivedImage_evicted => '画像はもう保存されていません'; + + @override + String get receivedImage_retry => 'もう一度試してください'; + + @override + String get receivedImage_decodeAgain => 'もう一度デコードしてください'; + + @override + String get receivedImage_openSettings => '設定する'; + + @override + String get receivedImage_tapToProcess => '処理するにはタップしてください'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'パケット', + one: 'パケット', + ); + return '$bytes バイト・$packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds秒'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes分 $seconds秒'; + } + + @override + String chat_longMessageRetryNote(int count) { + return '158バイトを超える場合:最大 $count 回まで送信されます'; + } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 3ddff59a..7fc13bd6 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -110,6 +110,45 @@ class AppLocalizationsKo extends AppLocalizations { @override String get messageStatus_repeated => '반복 수신됨'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'URL 이미지 활성화'; + + @override + String get urlImage_possible => 'URL 이미지일 수 있습니다. 설정에서 활성화하세요.'; + @override String get common_reboot => '재부팅'; @@ -354,42 +393,61 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_radioSettingsUpdated => '라디오 설정이 업데이트되었습니다.'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => '라디오가 이 설정을 적용하지 않았습니다'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => '지역'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => '저장된 지역 관리'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; @override - String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + String get settings_regionDefaultNone => 'None'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionManagement_screenTitle => '지역 관리'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionNameHint => '지역 이름 입력'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_regionAddRegion => '지역 추가'; + + @override + String get settings_regionFetchRegions => '리피터에서 지역을 가져옵니다.'; + + @override + String get settings_regionFetchRegionsFail => '어떤 지역도 발견되지 않았습니다.'; + + @override + String get settings_regionFetchRegionsAlreadyExists => '이 지역은 이미 추가되었습니다.'; + + @override + String get settings_regionName => '지역 이름'; + + @override + String get settings_regionDeleted => '지역 삭제'; + + @override + String get settings_deleteRegion => '지역 삭제'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return '\"$region\"을(를) 지역 목록에서 삭제하시겠습니까?'; } @override @@ -437,11 +495,11 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_privacyMode => '개인 정보 보호 모드'; @override - String get settings_privacyModeSubtitle => '광고에 이름/위치 정보 숨기기'; + String get settings_privacyModeSubtitle => '어드버트에 이름/위치 정보 숨기기'; @override String get settings_privacyModeToggle => - '광고에 자신의 이름과 위치를 숨기기 위해 개인 정보 보호 모드를 켜거나 끄십시오.'; + '어드버트에 자신의 이름과 위치를 숨기기 위해 개인 정보 보호 모드를 켜거나 끄십시오.'; @override String get settings_privacyModeEnabled => '개인 정보 보호 모드 활성화'; @@ -478,14 +536,30 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_telemetryEnvironmentMode => '텔레메트리 환경 모드'; @override - String get settings_advertLocation => '광고 위치'; + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; @override - String get settings_advertLocationSubtitle => '광고에 위치 정보를 포함하세요.'; + String get settings_advertLocation => '어드버트 위치'; + + @override + String get settings_advertLocationSubtitle => '어드버트에 위치 정보를 포함하세요.'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'GPS 업데이트 시 제로 홉 어드버트 자동 전송'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'GPS 위치가 변경되면 제로 홉 어드버트를 전송합니다(어드버트에 위치 포함 필요).'; @override String get settings_multiAck => '다중 ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => '텔레메트리 모드 업데이트 완료'; @@ -499,13 +573,13 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_deleteAllPathsSubtitle => '연락처의 모든 경로 데이터를 지웁니다.'; @override - String get settings_sendAdvertisement => '광고 전송'; + String get settings_sendAdvertisement => '어드버트 전송'; @override String get settings_sendAdvertisementSubtitle => '현재 존재를 방송합니다.'; @override - String get settings_advertisementSent => '광고가 전송되었습니다.'; + String get settings_advertisementSent => '어드버트가 전송되었습니다.'; @override String get settings_syncTime => '시간 동기화'; @@ -581,15 +655,31 @@ class AppLocalizationsKo extends AppLocalizations { @override String get settings_infoPublicKey => '공개 키'; + @override + String get settings_publicKeyCopied => '공개 키가 복사되었습니다'; + @override String get settings_infoContactsCount => '연락처 수'; @override String get settings_infoChannelCount => '채널 수'; + @override + String get settings_infoHardware => '하드웨어'; + + @override + String get settings_infoFirmware => '펌웨어'; + @override String get settings_presets => '프리셋'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => '주파수 (MHz)'; @@ -612,7 +702,9 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_txPower => '송신 전력 (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => '유효하지 않은 송신 전력 (0-22 dBm)'; @@ -620,6 +712,11 @@ class AppLocalizationsKo extends AppLocalizations { @override String get settings_clientRepeat => '오프그리드 반복'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => '이 장치가 다른 장치의 메시 패킷을 반복하도록 허용합니다.'; @@ -702,6 +799,51 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_languageUk => '우크라이나어'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 바이트'; + + @override + String get repeater_pathHashModeOption1 => '1~2 바이트'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 바이트'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 바이트'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => '메시지 추적 기능 활성화'; @@ -716,7 +858,8 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_enableNotifications => '알림 활성화'; @override - String get appSettings_enableNotificationsSubtitle => '메시지와 광고에 대한 알림을 받으세요.'; + String get appSettings_enableNotificationsSubtitle => + '메시지와 어드버트에 대한 알림을 받으세요.'; @override String get appSettings_notificationPermissionDenied => '알림 권한 거부'; @@ -733,6 +876,13 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_messageNotificationsSubtitle => '새로운 메시지를 받을 때 알림 표시'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => '채널 메시지 알림'; @@ -741,7 +891,7 @@ class AppLocalizationsKo extends AppLocalizations { '채널 메시지를 수신할 때 알림 표시'; @override - String get appSettings_advertisementNotifications => '광고 알림'; + String get appSettings_advertisementNotifications => '어드버트 알림'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -768,7 +918,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - '최적 경로와 플러드 모드 사이를 전환합니다.'; + '최적 경로와 플러딩 모드 사이를 전환합니다.'; @override String get appSettings_autoRouteRotationEnabled => '자동 경로 순환 기능 활성화'; @@ -833,6 +983,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_batteryLipo => '리튬 폴리머 (3.0-4.2V)'; + @override + String get appSettings_batteryLipoHv => '리포 HV (3.0-4.35V)'; + @override String get appSettings_mapDisplay => '지도 표시'; @@ -886,6 +1039,27 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_lastWeek => '지난 주'; + @override + String get appSettings_rasterTileSource => '래스터 타일 소스'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia 엔드포인트'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API 키'; + + @override + String get appSettings_stadiaApiKeyRequired => 'Stadia Maps를 사용하려면 필요합니다'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return '설정됨: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Stadia Maps API 키를 입력하세요. 이 앱은 래스터 타일 요청에 이 키를 사용합니다.'; + @override String get appSettings_offlineMapCache => '오프라인 지도 캐시'; @@ -929,7 +1103,7 @@ class AppLocalizationsKo extends AppLocalizations { String get contacts_noContacts => '아직 연락처는 없습니다.'; @override - String get contacts_contactsWillAppear => '장치가 광고를 할 때, 연락처 정보가 표시됩니다.'; + String get contacts_contactsWillAppear => '장치가 어드버트를 전송하면 연락처 정보가 표시됩니다.'; @override String get contacts_unread => '읽지 않음'; @@ -976,6 +1150,29 @@ class AppLocalizationsKo extends AppLocalizations { return '$contactName를 연락처 목록에서 제거하시겠습니까?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => '리피터 관리'; @@ -1122,6 +1319,18 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_private => '사립'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => '채널 편집'; @@ -1249,6 +1458,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_publicChannelAdded => '공개 채널 추가'; + @override + String get channels_noFreeSlots => '모든 채널 슬롯이 사용 중입니다'; + @override String get channels_sortBy => '정렬 기준 선택'; @@ -1302,17 +1514,30 @@ class AppLocalizationsKo extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return '지역: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => '지역: 없음'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => '지역을 선택하세요'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => '명확한 지역'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => '아직 메시지가 없습니다.'; @@ -1366,9 +1591,27 @@ class AppLocalizationsKo extends AppLocalizations { return '$current/$max 시도'; } + @override + String get chat_selectSendAction => '전송 작업 선택'; + @override String get chat_sendGif => 'GIF 보내기'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'MeshCore를 통해 이미지 보내기'; + + @override + String get chat_imagePickFailed => '그 이미지를 열 수 없었어요.'; + + @override + String get chat_receivedGif => 'GIF를 받았습니다'; + @override String get chat_reply => '답변'; @@ -1378,6 +1621,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_me => '나'; + @override + String get reaction_report => '이모지 반응'; + @override String get emojiCategorySmileys => '이모티콘'; @@ -1521,14 +1767,14 @@ class AppLocalizationsKo extends AppLocalizations { String get routing_modeAuto => '자동'; @override - String get routing_modeFlood => '플러드'; + String get routing_modeFlood => '플러딩'; @override String get routing_modeManual => '수동'; @override String get routing_modeAutoHint => - '가장 잘 알려진 경로를 자동으로 선택하고, 경로가 없으면 플러드로 전환합니다.'; + '가장 잘 알려진 경로를 자동으로 선택하고, 경로가 없으면 플러딩으로 전환합니다.'; @override String get routing_modeFloodHint => @@ -1577,7 +1823,7 @@ class AppLocalizationsKo extends AppLocalizations { String get routing_qualityWorked => '작동함'; @override - String get routing_qualityFlood => '플러드로 수신됨'; + String get routing_qualityFlood => '플러딩으로 수신됨'; @override String get routing_qualityUntested => '미검증'; @@ -1596,7 +1842,7 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get routing_floodDelivery => '플러드 전송'; + String get routing_floodDelivery => '플러딩 전송'; @override String get pathEditor_title => '경로 만들기'; @@ -1657,6 +1903,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_path => '경로'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => '공개 키'; @@ -1664,7 +1913,7 @@ class AppLocalizationsKo extends AppLocalizations { String get chat_compressOutgoingMessages => '전송되는 메시지 압축'; @override - String get chat_floodForced => '플러드 (강제)'; + String get chat_floodForced => '플러딩 (강제)'; @override String get chat_directForced => '직접 (강제)'; @@ -1675,7 +1924,7 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get chat_floodAuto => '플러드 (자동)'; + String get chat_floodAuto => '플러딩 (자동)'; @override String get chat_direct => '직접'; @@ -1694,6 +1943,12 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_newMessages => '새로운 메시지'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => '링크를 열기?'; @@ -1738,6 +1993,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get map_centerOnNode => '노드 중심으로 보기'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => '세부 정보'; @@ -1756,6 +2014,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get map_noNodesWithLocation => '위치 정보가 있는 노드가 없습니다.'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => '노드는 지도에 표시되려면 GPS 좌표를 공유해야 합니다.'; @@ -1894,6 +2156,16 @@ class AppLocalizationsKo extends AppLocalizations { @override String get map_showGuessedLocations => '추정된 노드 위치 표시'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => '디스커버리 담당자 연락처 보기'; @@ -1915,6 +2187,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get map_manageRepeater => '리피터 관리'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => '노드에 클릭하여 경로에 추가합니다.'; @@ -2002,6 +2277,42 @@ class AppLocalizationsKo extends AppLocalizations { return '실패한 다운로드: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2078,6 +2389,12 @@ class AppLocalizationsKo extends AppLocalizations { @override String get login_enterPassword => '비밀번호를 입력하세요'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => '비밀번호 저장'; @@ -2090,6 +2407,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get login_roomDescription => '설정 및 상태에 액세스하려면 방 비밀번호를 입력하세요.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => '라우팅'; @@ -2100,7 +2420,7 @@ class AppLocalizationsKo extends AppLocalizations { String get login_autoUseSavedPath => '자동 (저장된 경로 사용)'; @override - String get login_forceFloodMode => '강수 모드 활성화'; + String get login_forceFloodMode => '플러딩 모드 강제 활성화'; @override String get login_managePaths => '경로 관리'; @@ -2128,6 +2448,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get common_clear => '지우기'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => '현재 경로'; @@ -2152,6 +2475,12 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_guestTools => '손님용 도구'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => '상태'; @@ -2269,17 +2598,17 @@ class AppLocalizationsKo extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return '총: $total, 홍수: $flood, 직접: $direct'; + return '총: $total, 플러딩: $flood, 직접: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return '총: $total, 홍수: $flood, 직접: $direct'; + return '총: $total, 플러딩: $flood, 직접: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return '홍수: $flood, 직접: $direct'; + return '플러딩: $flood, 직접: $direct'; } @override @@ -2369,13 +2698,13 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_privacyMode => '개인 정보 보호 모드'; @override - String get repeater_privacyModeSubtitle => '광고에 이름/위치 정보 숨기기'; + String get repeater_privacyModeSubtitle => '어드버트에 이름/위치 정보 숨기기'; @override - String get repeater_advertisementSettings => '광고 설정'; + String get repeater_advertisementSettings => '어드버트 설정'; @override - String get repeater_localAdvertInterval => '지역 광고 시간 간격'; + String get repeater_localAdvertInterval => '지역 어드버트 시간 간격'; @override String repeater_localAdvertIntervalMinutes(int minutes) { @@ -2383,7 +2712,7 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => '홍수 광고 간격'; + String get repeater_floodAdvertInterval => '플러딩 어드버트 간격'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2391,7 +2720,7 @@ class AppLocalizationsKo extends AppLocalizations { } @override - String get repeater_encryptedAdvertInterval => '암호화된 광고 간격'; + String get repeater_encryptedAdvertInterval => '암호화된 어드버트 간격'; @override String get repeater_dangerZone => '위험 구역'; @@ -2522,14 +2851,47 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_pathHashModeHelper => - '이 리피터의 ID를 플러드 경로/루프 감지 태그에 인코딩하는 데 사용되는 바이트 수: 0=1 바이트 (256개의 ID, 최대 64개의 홉), 1=2 바이트 (65,000개의 ID, 최대 32개의 홉), 2=3 바이트 (16백만 개의 ID, 최대 21개의 홉). v1.13 및 이전 버전의 펌웨어는 다중 바이트 경로를 지원하지 않으며, 네트워크가 v1.14 이상으로 업그레이드되면 한 번만 감지합니다.'; + '이 리피터의 ID를 플러딩 경로/루프 감지 태그에 인코딩하는 데 사용되는 바이트 수입니다. 0=1바이트(256개 ID, 최대 64홉), 1=2바이트(65,000개 ID, 최대 32홉), 2=3바이트(1,600만 개 ID, 최대 21홉). v1.14 이전 펌웨어는 항상 1바이트 경로를 사용했으며, v1.14 이상은 2바이트 또는 3바이트 경로로 설정할 수 있습니다.'; @override - String get repeater_txDelay => '플러드 TX 지연'; + String get repeater_keySettings => '신원 키 변경'; + + @override + String get repeater_keySettingsSubtitle => '공개/비공개 키 쌍을 변경하세요'; + + @override + String get repeater_prvKey => '개인 키'; + + @override + String get repeater_prvKeyHelper => '리피터의 새로운 개인 키로, 128자리의 16진수 문자열입니다.'; + + @override + String get repeater_generatePrvKey => '임의의 키 쌍을 생성하세요.'; + + @override + String get repeater_stopGeneratingPrvKey => '키페어 검색 중단'; + + @override + String get repeater_pubKey => '공개 키'; + + @override + String get repeater_pubKeyHelper => + '이것은 생성된 개인 키와 함께 사용되는 공개 키입니다. 직접 설정할 수 없습니다.'; + + @override + String get repeater_pubKeyPrefix => '원하는 접두사'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return '이러한 16진수로 시작하는 공개 키를 찾으세요. 필요한 시도 횟수: $tries.'; + } + + @override + String get repeater_txDelay => '플러딩 TX 지연'; @override String get repeater_txDelayHelper => - '홍수 시 교통량에 맞춰 재전송 간격을 설정합니다. 이는 패킷의 전송 시간을 곱한 값 (0-2, 기본값 0.5)으로 설정합니다. 값이 클수록 충돌이 줄어들지만 전송 속도가 느려집니다.'; + '플러딩 시 교통량에 맞춰 재전송 간격을 설정합니다. 이는 패킷의 전송 시간을 곱한 값 (0-2, 기본값 0.5)으로 설정합니다. 값이 클수록 충돌이 줄어들지만 전송 속도가 느려집니다.'; @override String get repeater_directTxDelay => '직접적인 TX 지연'; @@ -2556,16 +2918,16 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_actionsTitle => '행동'; @override - String get repeater_sendAdvert => '홍수 관련 광고 전송'; + String get repeater_sendAdvert => '플러딩 관련 어드버트 전송'; @override - String get repeater_sendAdvertSubtitle => '네트워크를 통해 홍수 광고를 방송'; + String get repeater_sendAdvertSubtitle => '네트워크를 통해 플러딩 어드버트를 방송'; @override - String get repeater_sendAdvertZeroHop => '제로 홉 광고 전송'; + String get repeater_sendAdvertZeroHop => '제로 홉 어드버트 전송'; @override - String get repeater_sendAdvertZeroHopSubtitle => '단일 중계 (중계 없이) 광고를 송출'; + String get repeater_sendAdvertZeroHopSubtitle => '1홉 어드버트를 전송합니다 (중계 없음).'; @override String get repeater_clockSync => '현재 시계 동기화'; @@ -2615,6 +2977,17 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_refreshPrivacyMode => '개인 정보 보호 모드 재설정'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label가 갱신됨'; @@ -2679,7 +3052,7 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_cliQuickVersion => '버전'; @override - String get repeater_cliQuickAdvertise => '광고'; + String get repeater_cliQuickAdvertise => '어드버트'; @override String get repeater_cliQuickClock => '시계'; @@ -2691,7 +3064,7 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_cliQuickDiscovery => '이웃 발견하기'; @override - String get repeater_cliHelpAdvert => '광고 패킷을 발송'; + String get repeater_cliHelpAdvert => '어드버트 패킷을 발송'; @override String get repeater_cliHelpReboot => @@ -2725,7 +3098,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - '들어오는 플러드 패킷의 최대 홉 수를 설정합니다 (최대 홉 수보다 크거나 같으면 패킷은 전달되지 않습니다).'; + '들어오는 플러딩 패킷의 최대 홉 수를 설정합니다 (최대 홉 수보다 크거나 같으면 패킷은 전달되지 않습니다).'; @override String get repeater_cliHelpSetIntThresh => @@ -2741,24 +3114,24 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - '로컬 (제로 홉) 광고 패킷을 전송하는 간격 (분 단위)을 설정합니다. 0으로 설정하면 비활성화됩니다.'; + '로컬 (제로 홉) 어드버트 패킷을 전송하는 간격 (분 단위)을 설정합니다. 0으로 설정하면 비활성화됩니다.'; @override String get repeater_cliHelpSetFloodAdvertInterval => - '시간 단위로 광고 패킷을 전송하는 간격을 설정합니다. 0으로 설정하면 비활성화됩니다.'; + '시간 단위로 어드버트 패킷을 전송하는 간격을 설정합니다. 0으로 설정하면 비활성화됩니다.'; @override String get repeater_cliHelpSetGuestPassword => '게스트 비밀번호를 설정하거나 업데이트합니다. (반복 사용자, 게스트 로그인 시 \"통계 가져오기\" 요청을 보낼 수 있음)'; @override - String get repeater_cliHelpSetName => '광고 이름을 설정합니다.'; + String get repeater_cliHelpSetName => '어드버트 이름을 설정합니다.'; @override - String get repeater_cliHelpSetLat => '광고 지도의 위도를 설정합니다. (십진법 단위)'; + String get repeater_cliHelpSetLat => '어드버트 지도의 위도를 설정합니다. (십진법 단위)'; @override - String get repeater_cliHelpSetLon => '광고 지도의 경도를 설정합니다. (십진도)'; + String get repeater_cliHelpSetLon => '어드버트 지도의 경도를 설정합니다. (십진도)'; @override String get repeater_cliHelpSetRadio => @@ -2819,7 +3192,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - '제로 홉 광고를 통해 수신된 다른 리피터 노드 목록을 보여줍니다. 각 줄은 ID-프리픽스-16진수:타임스탬프:SNR-횟수-4 형식입니다.'; + '제로 홉 어드버트를 통해 수신된 다른 리피터 노드 목록을 보여줍니다. 각 줄은 ID-프리픽스-16진수:타임스탬프:SNR-횟수-4 형식입니다.'; @override String get repeater_cliHelpNeighborRemove => @@ -2827,7 +3200,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(단일 시리즈) 정의된 모든 지역과 현재 홍수 허가 정보를 나열합니다.'; + '(단일 시리즈) 정의된 모든 지역과 현재 플러딩 허가 정보를 나열합니다.'; @override String get repeater_cliHelpRegionLoad => @@ -2877,10 +3250,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - '노드의 위치 광고 설정:\n- none: 광고에 위치 정보를 포함하지 않음\n- share: GPS 위치 정보를 공유 (SensorManager에서 가져옴)\n- prefs: 설정에 저장된 위치를 광고'; + '노드의 위치 어드버트 설정:\n- none: 어드버트에 위치 정보를 포함하지 않음\n- share: GPS 위치 정보를 공유 (SensorManager에서 가져옴)\n- prefs: 설정에 저장된 위치를 어드버트에 포함'; @override - String get repeater_cliHelpGpsAdvertSet => '위치 기반 광고 설정 구성'; + String get repeater_cliHelpGpsAdvertSet => '위치 기반 어드버트 설정 구성'; @override String get repeater_commandsListTitle => '명령 목록'; @@ -2889,6 +3262,73 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_commandsListNote => '참고: 다양한 \"set...\" 명령과 함께 \"get...\" 명령도 존재합니다.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => '유효하지 않은 주파수 (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9~30 dBm'; + + @override + String get repeater_recvErrors => '수신 오류'; + + @override + String get room_postsStored => '게시물'; + + @override + String get room_postsPushed => '푸시된 게시물'; + + @override + String get repeater_cliRegionLoadActive => + '지역 로드 모드: 한 줄에 지역 이름 하나씩 보내고, 상위 지역 아래에 공백으로 들여씁니다 (플러딩을 허용하려면 이름 뒤에 F를 추가). 각 줄에는 응답이 없습니다. 빈 줄을 보내 완료한 뒤 \"region save\"를 보내면 결과가 저장됩니다.'; + + @override + String get repeater_cliRegionLoadHint => '지역 줄, 또는 완료하려면 비워 두기'; + + @override + String get repeater_cliRegionLoadEnd => '(지역 로드 종료)'; + + @override + String get repeater_cliHelpRegionDef => + '하나의 명령으로 지역 체인을 정의합니다. 각 이름은 이전 이름 아래에 추가됩니다. \"name,parent\"를 사용하면 해당 이름을 추가한 뒤 지정한 상위 지역 아래로 이어집니다. 지역 목록으로 응답합니다.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + '지역 범위가 없는 플러딩 패킷을 전달할 때의 최대 홉 수를 설정합니다(0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + '플러딩 어드버트를 전달할 때의 최대 홉 수를 설정합니다(0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + '지역 범위가 없는 플러딩 패킷의 최대 홉 수를 표시합니다.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => '플러딩 어드버트의 최대 홉 수를 표시합니다.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'LoRa 프런트엔드 모듈의 RX 게인(LNA)을 전환합니다. 이 기능이 없는 보드는 \"Error: unsupported\"로 응답합니다.'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'LoRa 프런트엔드 모듈의 TX 게인(PA)을 전환합니다. 이 기능이 없는 보드는 \"Error: unsupported\"로 응답합니다.'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'LoRa 프런트엔드 모듈의 RX 게인이 켜져 있는지 표시합니다.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'LoRa 프런트엔드 모듈의 TX 게인이 켜져 있는지 표시합니다.'; + + @override + String get repeater_bridgeNote => + 'RS232 또는 ESP-NOW 브리지 기능이 포함된 펌웨어에서만 사용할 수 있습니다.'; + @override String get repeater_general => '일반'; @@ -2933,7 +3373,7 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_cliHelpClkReboot => '시계를 알려진 시점으로 재설정하고 장치를 재부팅합니다.'; @override - String get repeater_cliHelpAdvertZeroHop => '직접적인 연결 없이 이웃에게만 광고를 전송합니다.'; + String get repeater_cliHelpAdvertZeroHop => '직접적인 연결 없이 이웃에게만 어드버트를 전송합니다.'; @override String get repeater_cliHelpStartOta => '지원되는 보드에서 무선으로 펌웨어 업데이트를 시작합니다.'; @@ -2974,7 +3414,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_cliHelpSetOwnerInfo => - '광고에 포함된 소유자 연락처 정보를 지정합니다. 줄 바꿈을 위해 \'|\' 문자를 사용합니다.'; + '어드버트에 포함된 소유자 연락처 정보를 지정합니다. 줄 바꿈을 위해 \'|\' 문자를 사용합니다.'; @override String get repeater_cliHelpSetPathHashMode => @@ -3042,11 +3482,11 @@ class AppLocalizationsKo extends AppLocalizations { '게스트의 읽기 전용 액세스가 허용되는지 여부를 표시합니다.'; @override - String get repeater_cliHelpGetAdvertInterval => '지역 광고 시간 간격을 분 단위로 표시합니다.'; + String get repeater_cliHelpGetAdvertInterval => '지역 어드버트 시간 간격을 분 단위로 표시합니다.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - '홍수 광고 시간 간격을 시간 단위로 표시합니다.'; + '플러딩 어드버트 시간 간격을 시간 단위로 표시합니다.'; @override String get repeater_cliHelpGetGuestPassword => '구성된 게스트 비밀번호를 표시합니다.'; @@ -3061,13 +3501,13 @@ class AppLocalizationsKo extends AppLocalizations { String get repeater_cliHelpGetRxDelay => 'Rxdelay 기본 값을 표시합니다.'; @override - String get repeater_cliHelpGetTxDelay => '홍수 모드에서의 전송 지연 계수를 보여줍니다.'; + String get repeater_cliHelpGetTxDelay => '플러딩 모드에서의 전송 지연 계수를 보여줍니다.'; @override String get repeater_cliHelpGetDirectTxDelay => '직렬 모드에서의 딜레이 계수를 보여줍니다.'; @override - String get repeater_cliHelpGetFloodMax => '최대 홍수 발생 횟수를 보여줍니다.'; + String get repeater_cliHelpGetFloodMax => '최대 플러딩 홉 수를 보여줍니다.'; @override String get repeater_cliHelpGetOwnerInfo => '소유주 연락처 정보를 표시합니다.'; @@ -3143,10 +3583,10 @@ class AppLocalizationsKo extends AppLocalizations { '기본 지역 범위를 설정합니다. \"\"을 사용하여 초기화합니다.'; @override - String get repeater_cliHelpRegionListAllowed => '홍수 피해 차량 통행이 가능한 지역 목록'; + String get repeater_cliHelpRegionListAllowed => '플러딩 트래픽이 허용되는 지역 목록'; @override - String get repeater_cliHelpRegionListDenied => '홍수 발생 시 통행 금지 지역 목록'; + String get repeater_cliHelpRegionListDenied => '플러딩 트래픽이 금지되는 지역 목록'; @override String get repeater_cliHelpStatsPackets => '(전송 속도만 표시) 패킷 수준의 통계 정보를 보여줍니다.'; @@ -3428,7 +3868,7 @@ class AppLocalizationsKo extends AppLocalizations { String get channelPath_unknownPath => '알 수 없음'; @override - String get channelPath_floodPath => '홍수'; + String get channelPath_floodPath => '플러딩'; @override String get channelPath_directPath => '직접'; @@ -3899,34 +4339,51 @@ class AppLocalizationsKo extends AppLocalizations { String get contacts_contactImportFailed => '연락처를 가져오지 못했습니다.'; @override - String get contacts_zeroHopAdvert => '제로 홉 광고'; + String get contacts_zeroHopAdvert => '제로 홉 어드버트'; @override - String get contacts_floodAdvert => '홍수 광고'; + String get contacts_floodAdvert => '플러딩 어드버트'; @override - String get contacts_copyAdvertToClipboard => '광고 텍스트를 클립보드에 복사'; + String get contacts_copyAdvertToClipboard => '어드버트 텍스트를 클립보드에 복사'; @override String get contacts_addContactFromClipboard => '복사본에서 연락처 추가'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => '연락처를 복사'; @override - String get contacts_ShareContactZeroHop => '광고를 통해 연락처 공유'; + String get contacts_ShareContactZeroHop => '어드버트를 통해 연락처 공유'; @override - String get contacts_zeroHopContactAdvertSent => '광고를 통해 연락처를 받았습니다.'; + String get contacts_zeroHopContactAdvertSent => '어드버트를 통해 연락처를 받았습니다.'; @override String get contacts_zeroHopContactAdvertFailed => '연락처 전송에 실패했습니다.'; @override - String get contacts_contactAdvertCopied => '광고 내용이 복사되었습니다.'; + String get contacts_contactAdvertCopied => '어드버트 내용이 복사되었습니다.'; @override - String get contacts_contactAdvertCopyFailed => '광고를 클립보드에 복사하는 데 실패했습니다.'; + String get contacts_contactAdvertCopyFailed => '어드버트를 클립보드에 복사하는 데 실패했습니다.'; @override String get notification_activityTitle => '메쉬코어 활동'; @@ -4026,6 +4483,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get snrIndicator_lastSeen => '마지막으로 목격'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => '연락처 설정'; @@ -4123,6 +4584,12 @@ class AppLocalizationsKo extends AppLocalizations { @override String get radioStats_screenTitle => '라디오 통계'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => '라디오 통계를 확인하기 위해 장치에 연결합니다.'; @@ -4178,6 +4645,42 @@ class AppLocalizationsKo extends AppLocalizations { @override String get translation_title => '번역'; + @override + String get imageMessages_enableTitle => '이미지 메시지 활성화'; + + @override + String get imageMessages_enableSubtitle => + '메시를 통해 이미지를 전송하세요. 일회성 이미지 모델 다운로드가 필요합니다.'; + + @override + String get imageMessages_modelSectionTitle => '이미지 모델'; + + @override + String get imageMessages_downloadModel => '다운로드'; + + @override + String get imageMessages_cancelDownload => '취소'; + + @override + String get imageMessages_removeModel => '모델 제거'; + + @override + String get imageMessages_modelReady => '준비 완료'; + + @override + String get imageMessages_modelNotPublished => + '아직 출판되지 않았습니다 — 이 빌드로는 다운로드할 수 없습니다.'; + + @override + String get imageMessages_downloadFailed => '이미지 모델을 다운로드할 수 없었습니다.'; + + @override + String get imageMessages_autoProcessTitle => '자동으로 프로세스 이미지를 처리합니다.'; + + @override + String get imageMessages_autoProcessSubtitle => + '이미지가 도착하는 즉시 재구성하세요. 매번 2GB의 메모리를 사용하며, 탭으로 재구성을 원할 경우 해제하세요.'; + @override String get translation_enableTitle => '번역 기능 활성화'; @@ -4453,4 +4956,241 @@ class AppLocalizationsKo extends AppLocalizations { @override String get pathMap_unfollowPacket => '패킷 고정 해제'; + + @override + String get imageSend_title => '이미지를 보내세요'; + + @override + String get imageSend_cropNote => '512 × 512로 크기가 조정되었으며, 종횡비는 유지되지 않았습니다.'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => '원문 없음'; + + @override + String get imageSend_onAirSize => '방송 중'; + + @override + String get imageSend_quality => '품질'; + + @override + String get imageSend_qualityStandard => '표준'; + + @override + String get imageSend_qualityHigh => '높다'; + + @override + String get imageSend_packetsLabel => '패킷'; + + @override + String get imageSend_airtimeLabel => '방송 시간'; + + @override + String get imageSend_sizeLabel => '페이로드'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '패킷', + one: '패킷', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min~$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => '라디오 설정 정보 없음'; + + @override + String get imageSend_radioUnknownBody => '방송 시간을 계산할 수 있도록 기기와 연결하세요.'; + + @override + String get imageSend_longSendTitle => '장거리 송신'; + + @override + String imageSend_longSendBody(String duration) { + return '이것은 약 $duration 동안 채널을 유지할 것입니다.'; + } + + @override + String get imageSend_floodNote => + '플러딩 라우팅: 범위 내의 모든 리피터가 각 패킷을 재전송하므로, 채널이 이보다 더 오래 점유 상태를 유지합니다.'; + + @override + String get imageSend_parityTitle => '회복 패킷'; + + @override + String get imageSend_paritySubtitle => + '추가 한 개의 패킷입니다. 그룹 메시지는 확인되지 않으므로, 하나의 패킷이 손실되었을 경우 수신자가 이미지를 다시 구성할 수 있습니다.'; + + @override + String get imageSend_send => '보내다'; + + @override + String get imageSend_cancel => '취소'; + + @override + String get imageSend_encodeFailed => '이 이미지는 인코딩할 수 없습니다.'; + + @override + String get imageSend_codecDownloading => '이미지 모델이 아직 다운로드 중입니다.'; + + @override + String get imageSend_codecUnavailable => '이 기기에서는 이미지 전송이 불가능합니다.'; + + @override + String get imageSend_codecDisabled => '설정에서 이미지 메시지가 꺼져 있습니다.'; + + @override + String get imageSend_deviceUnsupported => + '이 라디오는 이미지 패킷을 전송할 수 없습니다. 컴패니언 펌웨어 13 이상을 실행하는 장치를 연결해 주세요.'; + + @override + String get imageSend_directMessagesUnsupported => + '이미지는 그룹 데이터로 전송되므로, 직접 메시지가 아닌 채널로만 보낼 수 있습니다.'; + + @override + String get imageSend_tooLarge => '그 이미지는 메시 형식이 허용하는 것보다 더 많은 패킷으로 인코딩되었습니다.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '패킷', + one: '패킷', + ); + return '이미지가 $count $_temp0로 전송되었습니다.'; + } + + @override + String imageSend_sendFailed(String error) { + return '이미지를 보낼 수 없습니다: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return '이미지 전송 — $sent개의 $total 패킷'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return '노드 $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$total개 패킷 중 $received개'; + } + + @override + String get receivedImage_queued => '해독을 기다리는 중입니다.'; + + @override + String get receivedImage_tapToDecode => '해독하려면 탭을 누르세요.'; + + @override + String get receivedImage_decoding => '재구성하는… 약 1초 정도'; + + @override + String receivedImage_incomplete(int received, int total) { + return '이미지 불완전 — $total개 중 $received개 패킷 수신됨'; + } + + @override + String get receivedImage_corrupt => '이미지는 재구성될 수 없습니다.'; + + @override + String get receivedImage_decoderMissing => '수신된 이미지 — 이미지 해독이 되지 않았습니다'; + + @override + String get receivedImage_evicted => '이미지는 더 이상 저장되지 않았습니다.'; + + @override + String get receivedImage_retry => '다시 시도해 보세요'; + + @override + String get receivedImage_decodeAgain => '다시 해독하다'; + + @override + String get receivedImage_openSettings => '설정하다'; + + @override + String get receivedImage_tapToProcess => '처리하려면 탭을 누르세요.'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: '패킷', + one: '패킷', + ); + return '$bytes 바이트 · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds 초'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes분 $seconds초'; + } + + @override + String chat_longMessageRetryNote(int count) { + return '158바이트 초과 시: 최대 $count회 전송됩니다'; + } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index ade730a2..213272e9 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -110,6 +110,46 @@ class AppLocalizationsNl extends AppLocalizations { @override String get messageStatus_repeated => 'Hearsay, herhaald'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'URL-afbeeldingen inschakelen'; + + @override + String get urlImage_possible => + 'Mogelijke URL-afbeelding; schakel dit in bij Instellingen.'; + @override String get common_reboot => 'Herstarten'; @@ -366,42 +406,65 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_radioSettingsUpdated => 'Radio instellingen bijgewerkt'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'De radio heeft deze instellingen niet toegepast'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regio\'s'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Beheer van opgeslagen regio\'s'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Regionale Bestuur'; + + @override + String get settings_regionNameHint => 'Regio naam invoeren'; + + @override + String get settings_regionAddRegion => 'Regio toevoegen'; + + @override + String get settings_regionFetchRegions => 'Haal regio\'s uit herhalers'; + + @override + String get settings_regionFetchRegionsFail => + 'Er zijn geen regio\'s gevonden'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Deze regio is al toegevoegd.'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Regio Naam'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Regio verwijderd'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Regio verwijden'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Verwijder \"$region\" uit de regio-lijst?'; } @override @@ -494,6 +557,10 @@ class AppLocalizationsNl extends AppLocalizations { @override String get settings_telemetryEnvironmentMode => 'Telemetrie-omgevingsmodus'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Advertentielocatie'; @@ -501,9 +568,21 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_advertLocationSubtitle => 'Locatie opnemen in advertentie'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatische zero-hop-advertentie bij GPS-update'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Wanneer de GPS-locatie verandert, een zero-hop-advertentie verzenden (vereist locatie in advertentie).'; + @override String get settings_multiAck => 'Meerdere bevestigingen'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Telemetrie-modus bijgewerkt'; @@ -604,15 +683,31 @@ class AppLocalizationsNl extends AppLocalizations { @override String get settings_infoPublicKey => 'Openbare Sleutel'; + @override + String get settings_publicKeyCopied => 'Openbare sleutel gekopieerd'; + @override String get settings_infoContactsCount => 'Aantal Contacten'; @override String get settings_infoChannelCount => 'Aantal Kanalen'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Voorgeprogrammeerde instellingen'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frequentie (MHz)'; @@ -635,7 +730,9 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_txPower => 'TX-Vermogen (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Ongeldige TX-vermogen (0-22 dBm)'; @@ -643,6 +740,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get settings_clientRepeat => 'Off-Grid Herhalen'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Laat dit apparaat de berichten van andere apparaten doorsturen.'; @@ -725,6 +827,51 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_languageUk => 'Oekraïens'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bytes'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bytes'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bytes'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Berichttracking inschakelen'; @@ -761,6 +908,13 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Toon notificatie bij het ontvangen van nieuwe berichten'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Kanaal Bericht Meldingen'; @@ -871,6 +1025,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0-4,35 V)'; + @override String get appSettings_mapDisplay => 'Kaartweergave'; @@ -928,6 +1085,28 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_lastWeek => 'Afgelopen week'; + @override + String get appSettings_rasterTileSource => 'Rastertegelbron'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia-eindpunt'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API-sleutel'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Vereist voor gebruik van Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Geconfigureerd: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Voer je Stadia Maps API-sleutel in. De app gebruikt die voor rastertegelverzoeken.'; + @override String get appSettings_offlineMapCache => 'Offline Kaartcache'; @@ -1021,6 +1200,29 @@ class AppLocalizationsNl extends AppLocalizations { return 'Verwijder $contactName uit de contacten?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Beheer Repeater'; @@ -1169,6 +1371,18 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_private => 'Privé'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Kanaal bewerken'; @@ -1300,6 +1514,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_publicChannelAdded => 'Open kanaal toegevoegd'; + @override + String get channels_noFreeSlots => 'Alle kanaalslots zijn bezet'; + @override String get channels_sortBy => 'Sorteren door'; @@ -1357,17 +1574,30 @@ class AppLocalizationsNl extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Regio: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Regio: geen'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Kies een regio'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Duidelijke regio'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Nog geen berichten.'; @@ -1421,9 +1651,27 @@ class AppLocalizationsNl extends AppLocalizations { return 'Poging opnieuw $current/$max'; } + @override + String get chat_selectSendAction => 'Verzendactie selecteren'; + @override String get chat_sendGif => 'GIF verzenden'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Afbeelding verzenden via MeshCore'; + + @override + String get chat_imagePickFailed => 'Kunde die afbeelding niet openen'; + + @override + String get chat_receivedGif => 'Ontvangen van een GIF'; + @override String get chat_reply => 'Reageren'; @@ -1433,6 +1681,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_me => 'Mijn'; + @override + String get reaction_report => 'Emoji-reacties'; + @override String get emojiCategorySmileys => 'Emoji\'s'; @@ -1579,7 +1830,7 @@ class AppLocalizationsNl extends AppLocalizations { String get routing_modeAuto => 'Auto'; @override - String get routing_modeFlood => 'Overstroming'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Handleiding'; @@ -1637,7 +1888,7 @@ class AppLocalizationsNl extends AppLocalizations { String get routing_qualityWorked => 'Is geleverd'; @override - String get routing_qualityFlood => 'Hears via een overstroming'; + String get routing_qualityFlood => 'Gehoord via flood'; @override String get routing_qualityUntested => 'Niet getest'; @@ -1656,14 +1907,14 @@ class AppLocalizationsNl extends AppLocalizations { } @override - String get routing_floodDelivery => 'Levering bij overstroming'; + String get routing_floodDelivery => 'Flood-levering'; @override String get pathEditor_title => 'Pad creëren'; @override String pathEditor_hopCounter(int count) { - return '$count van 64 hopgranen'; + return '$count van 64 hops'; } @override @@ -1692,7 +1943,7 @@ class AppLocalizationsNl extends AppLocalizations { } @override - String get pathEditor_tooManyHops => 'Maximaal 64 hopken'; + String get pathEditor_tooManyHops => 'Maximaal 64 hops'; @override String get pathEditor_usePath => 'Gebruik deze route.'; @@ -1719,6 +1970,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_path => 'Pad'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Openbare Sleutel'; @@ -1738,7 +1992,7 @@ class AppLocalizationsNl extends AppLocalizations { } @override - String get chat_floodAuto => 'Overstroming (van een auto)'; + String get chat_floodAuto => 'Flood (automatisch)'; @override String get chat_direct => 'Direct'; @@ -1757,6 +2011,12 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_newMessages => 'Nieuwe berichten'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Link openen?'; @@ -1802,6 +2062,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get map_centerOnNode => 'Centreer op node'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Details'; @@ -1820,6 +2083,10 @@ class AppLocalizationsNl extends AppLocalizations { @override String get map_noNodesWithLocation => 'Geen nodes met locatiegegevens'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Nodes moeten hun GPS-coördinaten delen\nom op de kaart te verschijnen'; @@ -1962,6 +2229,16 @@ class AppLocalizationsNl extends AppLocalizations { String get map_showGuessedLocations => 'Toon de voorspelde locaties van de knopen'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Ontdek contacten weergeven'; @@ -1983,6 +2260,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get map_manageRepeater => 'Beheer Repeater'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Tik op knooppunten om ze toe te voegen aan het pad'; @@ -2074,6 +2354,42 @@ class AppLocalizationsNl extends AppLocalizations { return 'Mislukte downloads: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2151,6 +2467,12 @@ class AppLocalizationsNl extends AppLocalizations { @override String get login_enterPassword => 'Wachtwoord invoeren'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Wachtwoord opslaan'; @@ -2166,6 +2488,9 @@ class AppLocalizationsNl extends AppLocalizations { String get login_roomDescription => 'Voer het wachtwoord van de kamer in om toegang te krijgen tot instellingen en status.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Routeplanning'; @@ -2204,6 +2529,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get common_clear => 'Schoonmaken'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Huidige pad'; @@ -2228,6 +2556,12 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_guestTools => 'Gastenfuncties'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Status'; @@ -2358,7 +2692,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Overstroming: $flood, Direct: $direct'; + return 'Flood: $flood, Direct: $direct'; } @override @@ -2615,14 +2949,49 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Bytes die gebruikt worden om de ID van deze repeater te coderen in flood-pad/lusdetectietags. 0=1 byte (256 ID\'s, tot 64 hops), 1=2 bytes (65.000 ID\'s, tot 32 hops), 2=3 bytes (16 miljoen ID\'s, tot 21 hops). Versies 1.13 en ouder gebruiken multi-byte paden – alleen na het activeren van het netwerk.'; + 'Bytes die gebruikt worden om de ID van deze repeater te coderen in flood-pad/lusdetectietags. 0=1 byte (256 ID\'s, tot 64 hops), 1=2 bytes (65.000 ID\'s, tot 32 hops), 2=3 bytes (16 miljoen ID\'s, tot 21 hops). Firmware vóór v1.14 gebruikte altijd 1-byte paden; v1.14 en nieuwer kunnen worden ingesteld op 2- of 3-byte paden.'; + + @override + String get repeater_keySettings => 'Verander de Identiteitskies'; + + @override + String get repeater_keySettingsSubtitle => + 'Wijzig de openbare/private sleutelpaar'; + + @override + String get repeater_prvKey => 'Geheime sleutel'; + + @override + String get repeater_prvKeyHelper => + 'Een nieuwe private sleutel voor de repeater, een 128-karakter lange hexadecimale string.'; + + @override + String get repeater_generatePrvKey => 'Stel een willekeurige sleutelpaar op'; + + @override + String get repeater_stopGeneratingPrvKey => 'Stop zoek naar sleutelpaar'; + + @override + String get repeater_pubKey => 'Openbaar sleutel'; + + @override + String get repeater_pubKeyHelper => + 'Dit is de openbare sleutel die past bij de gegenereerde privésleutel. U kunt dit niet direct instellen.'; + + @override + String get repeater_pubKeyPrefix => 'Verlangde voorvoegsel'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Zoek een openbare sleutel die begint met deze hexadecimale cijfers. Verwacht aantal pogingen: $tries.'; + } @override String get repeater_txDelay => 'Vertraging bij Flood TX'; @override String get repeater_txDelayHelper => - 'Herzendinterval voor verkeer tijdens overstromingen, als een veelvoud van de tijd die het pakket nodig heeft (0-2, standaard 0.5). Een hoger getal betekent minder botsingen, maar ook een langere leveringstijd.'; + 'Herzendinterval voor flood-verkeer, als een veelvoud van de tijd die het pakket nodig heeft (0-2, standaard 0.5). Een hoger getal betekent minder botsingen, maar ook een langere leveringstijd.'; @override String get repeater_directTxDelay => 'Directe vertraging'; @@ -2650,11 +3019,11 @@ class AppLocalizationsNl extends AppLocalizations { String get repeater_actionsTitle => 'Acties'; @override - String get repeater_sendAdvert => 'Verzend advertentie over overstromingen'; + String get repeater_sendAdvert => 'Verzend flood-advertentie'; @override String get repeater_sendAdvertSubtitle => - 'Zend een advertentie over overstromingen uit via het netwerk.'; + 'Zend een flood-advertentie uit via het netwerk.'; @override String get repeater_sendAdvertZeroHop => @@ -2715,6 +3084,17 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Privacymode vernieuwen'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label is vernieuwd'; @@ -3008,6 +3388,75 @@ class AppLocalizationsNl extends AppLocalizations { String get repeater_commandsListNote => 'LET OP: voor de verschillende \"set ...\" commando\'s is er ook een \"get ...\" commando.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Ongeldige frequentie (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 tot 30 dBm'; + + @override + String get repeater_recvErrors => 'Ontvangstfouten'; + + @override + String get room_postsStored => 'Opgeslagen posts'; + + @override + String get room_postsPushed => 'Verzonden posts'; + + @override + String get repeater_cliRegionLoadActive => + 'Regio-laadmodus: verstuur per regel één regionaam, ingesprongen met spaties onder de bovenliggende regio (voeg F toe na de naam om flood toe te staan). Regels krijgen geen antwoord. Verstuur een lege regel om te voltooien en dan \"region save\" om het resultaat te bewaren.'; + + @override + String get repeater_cliRegionLoadHint => + 'Regioregel, of leeg om te voltooien'; + + @override + String get repeater_cliRegionLoadEnd => '(einde van regio-laadmodus)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definieert een keten van regio\'s in één commando: elke naam wordt onder de vorige toegevoegd; \"name,parent\" voegt de naam toe en gaat dan verder onder de opgegeven bovenliggende regio. Antwoordt met de regiolijst.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Stelt het maximale aantal hops in voor het doorsturen van flood-pakketten zonder regio-scope (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Stelt het maximale aantal hops in voor het doorsturen van flood-advertenties (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Toont het maximale aantal hops voor flood-pakketten zonder regio-scope.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Toont het maximale aantal hops voor flood-advertenties.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Schakelt de RX-versterking (LNA) van de LoRa-frontendmodule. Boards zonder deze module antwoorden met \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Schakelt de TX-versterking (PA) van de LoRa-frontendmodule. Boards zonder deze module antwoorden met \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Toont of de RX-versterking van de LoRa-frontendmodule aan staat.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Toont of de TX-versterking van de LoRa-frontendmodule aan staat.'; + + @override + String get repeater_bridgeNote => + 'Alleen beschikbaar bij firmware gebouwd met een bridge (RS232 of ESP-NOW).'; + @override String get repeater_general => 'Algemeen'; @@ -3179,11 +3628,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Geeft de duur van de lokale reclame in minuten aan.'; + 'Geeft de duur van het lokale advertentie-interval in minuten aan.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Geeft de duur van de reclame-interval in uren aan.'; + 'Geeft de duur van het flood-advertentie-interval in uren aan.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3209,7 +3658,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Toont het maximale aantal keer dat een overstroming heeft plaatsgevonden.'; + 'Toont het maximale aantal hops voor flood-pakketten.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3297,11 +3746,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Lijst van gebieden waar doorstromen tijdens overstromingen is toegestaan.'; + 'Geeft een lijst van regio\'s die flood-verkeer toestaan.'; @override String get repeater_cliHelpRegionListDenied => - 'Geeft een lijst van regio\'s die het verkeer tijdens overstromingen verbieden.'; + 'Geeft een lijst van regio\'s die flood-verkeer verbieden.'; @override String get repeater_cliHelpStatsPackets => @@ -3588,7 +4037,7 @@ class AppLocalizationsNl extends AppLocalizations { String get channelPath_unknownPath => 'Onbekend'; @override - String get channelPath_floodPath => 'Overstroming'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Direct'; @@ -4078,10 +4527,10 @@ class AppLocalizationsNl extends AppLocalizations { 'Contact kon niet geïmporteerd worden.'; @override - String get contacts_zeroHopAdvert => 'Zero Hop Reclame'; + String get contacts_zeroHopAdvert => 'Zero-hop-advertentie'; @override - String get contacts_floodAdvert => 'Overstromingsadvertentie'; + String get contacts_floodAdvert => 'Flood-advertentie'; @override String get contacts_copyAdvertToClipboard => 'Advert naar klembord kopiëren'; @@ -4090,6 +4539,23 @@ class AppLocalizationsNl extends AppLocalizations { String get contacts_addContactFromClipboard => 'Contact uit klembord toevoegen'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Contact naar Klembord kopiëren'; @@ -4106,7 +4572,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contacts_contactAdvertCopied => - 'Reclame gekopieerd naar Klembord.'; + 'Advertentie gekopieerd naar Klembord.'; @override String get contacts_contactAdvertCopyFailed => @@ -4215,6 +4681,10 @@ class AppLocalizationsNl extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Laatst gezien'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Instellingen voor contacten'; @@ -4320,6 +4790,12 @@ class AppLocalizationsNl extends AppLocalizations { @override String get radioStats_screenTitle => 'Statistieken over radio'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Verbind met een apparaat om radio-statistieken te bekijken.'; @@ -4378,6 +4854,43 @@ class AppLocalizationsNl extends AppLocalizations { @override String get translation_title => 'Vertaling'; + @override + String get imageMessages_enableTitle => 'Bijbehorende afbeeldingen activeren'; + + @override + String get imageMessages_enableSubtitle => + 'Beeldjes verzenden via het netwerk. Vereist eenmalig afdaling van een beeldmodel.'; + + @override + String get imageMessages_modelSectionTitle => 'Beeldmodel'; + + @override + String get imageMessages_downloadModel => 'Download'; + + @override + String get imageMessages_cancelDownload => 'Annuleren'; + + @override + String get imageMessages_removeModel => 'Model verwijderen'; + + @override + String get imageMessages_modelReady => 'Klaar'; + + @override + String get imageMessages_modelNotPublished => + 'Nog niet gepubliceerd — deze versie kan dit niet downloaden.'; + + @override + String get imageMessages_downloadFailed => + 'Het beeldmodel kon niet worden gedownload.'; + + @override + String get imageMessages_autoProcessTitle => 'Beeldverwerking automatisch'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Reconstrueer elk beeld direct nadat het binnenkomt. Het gebruikt ongeveer 2 GB geheugen voor elke keer; schakel het reconstrueren uit met een tik als je het niet nodig hebt.'; + @override String get translation_enableTitle => 'Activeer vertaling'; @@ -4661,4 +5174,249 @@ class AppLocalizationsNl extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Weergave ontgrendelen van pakket'; + + @override + String get imageSend_title => 'Beeld verzenden'; + + @override + String get imageSend_cropNote => + 'Aangepast aan 512 × 512 · het aspectverhouding is niet behouden'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Oorspronkelijk'; + + @override + String get imageSend_onAirSize => 'Op de lucht'; + + @override + String get imageSend_quality => 'Kwaliteit'; + + @override + String get imageSend_qualityStandard => 'Standaard'; + + @override + String get imageSend_qualityHigh => 'Hoog'; + + @override + String get imageSend_packetsLabel => 'Pakketten'; + + @override + String get imageSend_airtimeLabel => 'Tijd op de lucht'; + + @override + String get imageSend_sizeLabel => 'Belasting'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pakketten', + one: 'pakket', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Radio-instellingen onbekend'; + + @override + String get imageSend_radioUnknownBody => + 'Verbinding maken met een apparaat zodat de uitzendtijd kan worden berekend.'; + + @override + String get imageSend_longSendTitle => 'Lange transmissie'; + + @override + String imageSend_longSendBody(String duration) { + return 'Dit houdt de kanaal ongeveer voor $duration stand.'; + } + + @override + String get imageSend_floodNote => + 'Flood-routing: elke repeater binnen bereik herzendsends elk pakket opnieuw, waardoor het kanaal langer bezig blijft dan dit.'; + + @override + String get imageSend_parityTitle => 'Herstelpakket'; + + @override + String get imageSend_paritySubtitle => + 'Een extra pakje. Groepsberichten worden niet bevestigd, waardoor de ontvanger het beeld kan herstellen als een enkel pakket verloren gaat.'; + + @override + String get imageSend_send => 'Stuur'; + + @override + String get imageSend_cancel => 'Annuleren'; + + @override + String get imageSend_encodeFailed => 'Dit beeld kon niet worden gecodeerd.'; + + @override + String get imageSend_codecDownloading => + 'Het beeldmodel wordt nog steeds gedownload.'; + + @override + String get imageSend_codecUnavailable => + 'Het verzenden van een afbeelding is niet mogelijk op dit apparaat.'; + + @override + String get imageSend_codecDisabled => + 'Boodschappen met afbeeldingen zijn uitgeschakeld in de instellingen.'; + + @override + String get imageSend_deviceUnsupported => + 'Dit radio kan geen beeldpakketten verzenden. Verbind een apparaat met de bijbehorende firmware versie 13 of nieuwer.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Afbeeldingen worden verzonden als groepsgegevens, dus ze kunnen alleen naar een kanaal worden gestuurd — niet via een directe boodschap.'; + + @override + String get imageSend_tooLarge => + 'Die afbeelding werd gecodeerd in meer pakketten dan het mesh-formaat toelaat.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pakketten', + one: 'pakket', + ); + return 'Afbeelding verzonden als $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Het beeld kon niet worden verzonden: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Beeld verzenden — pakket $sent van $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Knipper $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received van de $total pakketten'; + } + + @override + String get receivedImage_queued => 'Wachten op het ontcijferen'; + + @override + String get receivedImage_tapToDecode => 'Tik om te decoderen'; + + @override + String get receivedImage_decoding => 'Herstellen… ongeveer 1 seconde'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Afbeelding onvolledig — $received van $total pakketten ontvangen'; + } + + @override + String get receivedImage_corrupt => + 'Afbeelding kon niet worden gereconstrueerd'; + + @override + String get receivedImage_decoderMissing => + 'Beeld ontvangen — beeldontcipheringsapparatuur is uitgeschakeld'; + + @override + String get receivedImage_evicted => 'Afbeelding niet langer opgeslagen'; + + @override + String get receivedImage_retry => 'Probeer het opnieuw'; + + @override + String get receivedImage_decodeAgain => 'Decode opnieuw'; + + @override + String get receivedImage_openSettings => 'Inricht'; + + @override + String get receivedImage_tapToProcess => 'Tik om te verwerken'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'pakketten', + one: 'pakket', + ); + return '$bytes bytes · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds seconden'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes m $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Meer dan 158 bytes: maximaal $count keer verzonden'; + } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 627b332b..e3a2d0b0 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -110,6 +110,46 @@ class AppLocalizationsPl extends AppLocalizations { @override String get messageStatus_repeated => 'Usłyszałem to wielokrotnie'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Włącz obrazy z URL'; + + @override + String get urlImage_possible => + 'Możliwy obraz z URL; włącz go w Ustawieniach.'; + @override String get common_reboot => 'Uruchom ponownie'; @@ -372,42 +412,65 @@ class AppLocalizationsPl extends AppLocalizations { 'Ustawienia radia zostały zaktualizowane'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Radio nie zastosowało tych ustawień'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regiony'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Zarządzanie zapisanymi regionami'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Zarządzanie Regionami'; + + @override + String get settings_regionNameHint => 'Wprowadź nazwę regionu'; + + @override + String get settings_regionAddRegion => 'Dodaj region'; + + @override + String get settings_regionFetchRegions => 'Pobierz regiony z repeaterów'; + + @override + String get settings_regionFetchRegionsFail => + 'Nie znaleziono żadnych regionów'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Ten region został już dodany'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Nazwa Regionu'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Region usunięto'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Usuń Region'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Czy usunąć \"$region\" z listy regionów?'; } @override @@ -502,15 +565,31 @@ class AppLocalizationsPl extends AppLocalizations { 'Tryb środowiska telemetrycznego'; @override - String get settings_advertLocation => 'Lokalizacja reklamowa'; + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + + @override + String get settings_advertLocation => 'Lokalizacja rozgłoszenia'; @override String get settings_advertLocationSubtitle => 'Uwzględnij lokalizację w ogłoszeniu'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatyczne ogłoszenie zero-hop przy aktualizacji GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Gdy lokalizacja GPS się zmieni, wyślij ogłoszenie zero-hop (wymaga lokalizacji w ogłoszeniu).'; + @override String get settings_multiAck => 'Wielokrotne potwierdzenia odbioru'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Tryb telemetryczny zaktualizowany'; @@ -612,15 +691,31 @@ class AppLocalizationsPl extends AppLocalizations { @override String get settings_infoPublicKey => 'Klucz Publiczny'; + @override + String get settings_publicKeyCopied => 'Skopiowano klucz publiczny'; + @override String get settings_infoContactsCount => 'Liczba kontaktów'; @override String get settings_infoChannelCount => 'Liczba kanałów'; + @override + String get settings_infoHardware => 'Sprzęt'; + + @override + String get settings_infoFirmware => 'Oprogramowanie wbudowane'; + @override String get settings_presets => 'Presety'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Częstotliwość (MHz)'; @@ -644,7 +739,9 @@ class AppLocalizationsPl extends AppLocalizations { String get settings_txPower => 'Moc TX (dBm)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Nieprawidłowa moc TX (0-22 dBm)'; @@ -652,6 +749,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get settings_clientRepeat => 'Powtórzenie: Niezależne od sieci'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Pozwól temu urządzeniu powtarzać pakiety danych dla innych urządzeń.'; @@ -734,6 +836,51 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_languageUk => 'Ukraińska'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 bajt'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bity'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bajty'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bajty'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Włącz śledzenie wiadomości'; @@ -769,6 +916,13 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Pokaż powiadomienie przy otrzymywaniu nowych wiadomości'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Powiadomienia o Wiadomościach na Kanałach'; @@ -809,7 +963,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Przełączaj się między najlepszymi ścieżkami a trybem zalewowym.'; + 'Przełączaj się między najlepszymi ścieżkami a trybem flood.'; @override String get appSettings_autoRouteRotationEnabled => @@ -881,6 +1035,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'Bateria LiPo HV (3,0-4,35 V)'; + @override String get appSettings_mapDisplay => 'Wyświetlanie mapy'; @@ -937,6 +1094,28 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_lastWeek => 'Ostatni tydzień'; + @override + String get appSettings_rasterTileSource => 'Źródło kafelków rastrowych'; + + @override + String get appSettings_stadiaEndpoint => 'Punkt końcowy Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Klucz API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Wymagane do korzystania ze Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Skonfigurowano: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Wprowadź swój klucz API Stadia Maps. Aplikacja używa go do żądań kafelków rastrowych.'; + @override String get appSettings_offlineMapCache => 'Pamięć podręczna map offline'; @@ -1039,6 +1218,29 @@ class AppLocalizationsPl extends AppLocalizations { return 'Usunąć $contactName z kontaktów?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Zarządzaj przekaźnikiem'; @@ -1189,6 +1391,18 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_private => 'Prywatny'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Edytuj kanał'; @@ -1322,6 +1536,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_publicChannelAdded => 'Kanał publiczny dodany'; + @override + String get channels_noFreeSlots => 'Wszystkie miejsca na kanały są zajęte'; + @override String get channels_sortBy => 'Sortuj po'; @@ -1383,13 +1600,26 @@ class AppLocalizationsPl extends AppLocalizations { } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Region: brak'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Wybierz region'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Przejrzyste obszar'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Brak jeszcze wiadomości'; @@ -1444,9 +1674,27 @@ class AppLocalizationsPl extends AppLocalizations { return 'Próba $current/$max'; } + @override + String get chat_selectSendAction => 'Wybierz czynność wysyłania'; + @override String get chat_sendGif => 'Wyślij GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Wyślij obraz przez MeshCore'; + + @override + String get chat_imagePickFailed => 'Nie mogłem otworzyć tego obrazu'; + + @override + String get chat_receivedGif => 'Otrzymano GIF'; + @override String get chat_reply => 'Odpowiedz'; @@ -1456,6 +1704,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_me => 'Ja'; + @override + String get reaction_report => 'Reakcje Emoji'; + @override String get emojiCategorySmileys => 'Emoji'; @@ -1604,7 +1855,7 @@ class AppLocalizationsPl extends AppLocalizations { String get routing_modeAuto => 'Samochód'; @override - String get routing_modeFlood => 'Powódź'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Instrukcja obsługi'; @@ -1684,22 +1935,22 @@ class AppLocalizationsPl extends AppLocalizations { } @override - String get routing_floodDelivery => 'Dostawa w przypadku powodzi'; + String get routing_floodDelivery => 'Dostawa flood'; @override String get pathEditor_title => 'Stworzenie ścieżki'; @override String pathEditor_hopCounter(int count) { - return '$count z 64 rodzajów chmielu'; + return '$count z 64 skoków'; } @override String get pathEditor_noHops => - 'Na razie nie dodano żadnych chmielu. Aby dodać je w odpowiedniej kolejności, kliknij w odpowiednie przyciski poniżej, lub zapisz przepis bez chmielu, aby wysłać go bezpośrednio.'; + 'Nie dodano jeszcze żadnych skoków. Stuknij przekaźniki poniżej, aby dodać je w kolejności, lub zapisz bez skoków, aby wysłać bezpośrednio.'; @override - String get pathEditor_addHops => 'Dodawaj chmiel zgodnie z kolejnością.'; + String get pathEditor_addHops => 'Dodawaj skoki w kolejności.'; @override String get pathEditor_searchRepeaters => 'Funkcje powtarzania'; @@ -1727,7 +1978,7 @@ class AppLocalizationsPl extends AppLocalizations { String get pathEditor_usePath => 'Użyj tej ścieżki.'; @override - String get pathEditor_removeHop => 'Usuń dziką psiankę'; + String get pathEditor_removeHop => 'Usuń skok'; @override String get pathEditor_unknownHop => 'Nieznany repeater'; @@ -1749,6 +2000,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_path => 'Ścieżka'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Klucz Publiczny'; @@ -1756,7 +2010,7 @@ class AppLocalizationsPl extends AppLocalizations { String get chat_compressOutgoingMessages => 'Kompresuj wychodzące wiadomości'; @override - String get chat_floodForced => 'Zalew (wymuszony)'; + String get chat_floodForced => 'Flood (wymuszony)'; @override String get chat_directForced => 'Bezpośrednio (wymuszono)'; @@ -1767,7 +2021,7 @@ class AppLocalizationsPl extends AppLocalizations { } @override - String get chat_floodAuto => 'Zalew (automatyczny)'; + String get chat_floodAuto => 'Flood (automatyczny)'; @override String get chat_direct => 'Bezpośrednio'; @@ -1786,6 +2040,12 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_newMessages => 'Nowe wiadomości'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Otworzyć link?'; @@ -1831,6 +2091,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get map_centerOnNode => 'Wyśrodkuj na węźle'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Szczegóły'; @@ -1849,6 +2112,10 @@ class AppLocalizationsPl extends AppLocalizations { @override String get map_noNodesWithLocation => 'Brak węzłów z danymi lokalizacyjnymi'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Węzły muszą udostępniać swoje współrzędne GPS,\naby pojawić się na mapie.'; @@ -1991,6 +2258,16 @@ class AppLocalizationsPl extends AppLocalizations { String get map_showGuessedLocations => 'Pokaż przypuszczalne lokalizacje węzłów'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Pokaż odkryte kontakty'; @@ -2012,6 +2289,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get map_manageRepeater => 'Zarządzaj przekaźnikiem'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Kliknij na węzły, aby dodać je do ścieżki.'; @@ -2104,6 +2384,42 @@ class AppLocalizationsPl extends AppLocalizations { return 'Nieudane pobrania: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2181,6 +2497,12 @@ class AppLocalizationsPl extends AppLocalizations { @override String get login_enterPassword => 'Wprowadź hasło'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Zapisz hasło'; @@ -2196,6 +2518,9 @@ class AppLocalizationsPl extends AppLocalizations { String get login_roomDescription => 'Wprowadź hasło do pokoju, aby uzyskać dostęp do ustawień i statusu.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Trasowanie'; @@ -2206,7 +2531,7 @@ class AppLocalizationsPl extends AppLocalizations { String get login_autoUseSavedPath => 'Automatycznie (użyj zapisanej ścieżki)'; @override - String get login_forceFloodMode => 'Wymuś tryb zalewowy'; + String get login_forceFloodMode => 'Wymuś tryb flood'; @override String get login_managePaths => 'Zarządzaj Ścieżkami'; @@ -2234,6 +2559,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get common_clear => 'Wyczyść'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Aktualna ścieżka'; @@ -2259,6 +2587,12 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_guestTools => 'Narzędzia dla gości'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Stan'; @@ -2380,17 +2714,17 @@ class AppLocalizationsPl extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Razem: $total, Zalew: $flood, Bezpośrednio: $direct'; + return 'Razem: $total, Flood: $flood, Bezpośrednio: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Razem: $total, Zalew: $flood, Bezpośrednio: $direct'; + return 'Razem: $total, Flood: $flood, Bezpośrednio: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Zalew: $flood, Bezpośrednie: $direct'; + return 'Flood: $flood, Bezpośrednie: $direct'; } @override @@ -2497,7 +2831,7 @@ class AppLocalizationsPl extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => 'Interwał rozgłoszenia zalewowego'; + String get repeater_floodAdvertInterval => 'Interwał rozgłoszenia flood'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2630,7 +2964,7 @@ class AppLocalizationsPl extends AppLocalizations { 'Aktualizacja danych dotyczących operatora'; @override - String get repeater_floodMax => 'Maksymalna liczba skoków podczas powodzi'; + String get repeater_floodMax => 'Maksymalna liczba skoków flood'; @override String get repeater_floodMaxHelper => @@ -2648,14 +2982,50 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Bity wykorzystywane do kodowania identyfikatora tego urządzenia w tagach ścieżek/detekcji pętli. 0=1 bity (256 identyfikatorów, do 64 skoków), 1=2 bity (65 000 identyfikatorów, do 32 skoków), 2=3 bity (1 600 000 identyfikatorów, do 21 skoków). Wersje 1.13 i wcześniejsze nie obsługują ścieżek wielobitowych – wykrywają tylko jedną, gdy sieć jest w wersji 1.14 lub nowszej.'; + 'Bajty używane do kodowania identyfikatora tego repeatera w tagach ścieżki flood/wykrywania pętli. 0=1 bajt (256 identyfikatorów, do 64 skoków), 1=2 bajty (65 000 identyfikatorów, do 32 skoków), 2=3 bajty (16 milionów identyfikatorów, do 21 skoków). Firmware sprzed v1.14 zawsze używał ścieżek 1-bajtowych; v1.14 i nowsze można skonfigurować na ścieżki 2- lub 3-bajtowe.'; + + @override + String get repeater_keySettings => 'Zmiana kluczy tożsamości'; + + @override + String get repeater_keySettingsSubtitle => + 'Zmień parę kluczy publiczną/prywatną'; + + @override + String get repeater_prvKey => 'Klucz prywatny'; + + @override + String get repeater_prvKeyHelper => + 'Nowy klucz prywatny dla wzmacniacza, 128-znakowa string hexadecyimalny.'; + + @override + String get repeater_generatePrvKey => 'Wygeneruj losowy klucz parowy'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Przerwij wyszukiwanie kluczowego paru'; + + @override + String get repeater_pubKey => 'Klucz publiczny'; + + @override + String get repeater_pubKeyHelper => + 'To jest klucz publiczny, który odpowiada wygenerowanemu kluczowi prywatnemu. Nie można go ustawić bezpośrednio.'; + + @override + String get repeater_pubKeyPrefix => 'Pożądane przedrostek'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Znajdź klucz publiczny, który zaczyna się od tych cyfr hex. Oczekiwana liczba prób: $tries.'; + } @override String get repeater_txDelay => 'Opóźnienie w Flood, TX'; @override String get repeater_txDelayHelper => - 'Ustawienie odstępu dla ruchu związanego z powodzią, jako mnożnik czasu przesyłania pakietu (0-2, domyślnie 0,5). Wyższe wartości oznaczają mniejszą liczbę kolizji, ale wolniejszą prędkość przesyłania.'; + 'Ustawienie odstępu dla ruchu flood, jako mnożnik czasu przesyłania pakietu (0-2, domyślnie 0,5). Wyższe wartości oznaczają mniejszą liczbę kolizji, ale wolniejszą prędkość przesyłania.'; @override String get repeater_directTxDelay => 'Bezpośrednie opóźnienie sygnału TX'; @@ -2682,18 +3052,18 @@ class AppLocalizationsPl extends AppLocalizations { String get repeater_actionsTitle => 'Działania'; @override - String get repeater_sendAdvert => 'Wysłać reklamę dotyczącą powodzi'; + String get repeater_sendAdvert => 'Wysłać rozgłoszenie flood'; @override String get repeater_sendAdvertSubtitle => - 'Wyemituj reklamę dotyczącą powodzi w sieci.'; + 'Wyemituj rozgłoszenie flood w sieci.'; @override - String get repeater_sendAdvertZeroHop => 'Wysłać reklamę bez pośrednictwa'; + String get repeater_sendAdvertZeroHop => 'Wysłać rozgłoszenie zero-hop'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Napisz reklamę, która będzie transmitowana bezpośrednio (bez powtarzania).'; + 'Wyemituj rozgłoszenie jednoskokowe (bez pośredników).'; @override String get repeater_clockSync => 'Synchronizuj zegar'; @@ -2744,6 +3114,17 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Odśwież Tryb Prywatności'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label odświeżone'; @@ -2860,7 +3241,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Ustawia maksymalną liczbę skoków pakietu zalewowego (jeśli >= max, pakiet nie jest przekierowywany)'; + 'Ustawia maksymalną liczbę skoków pakietu flood (jeśli >= max, pakiet nie jest przekierowywany)'; @override String get repeater_cliHelpSetIntThresh => @@ -2907,7 +3288,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - 'Ustawia czynnik mnożony przez czas utrzymania w trybie zalewowym dla pakietu oraz z wykorzystaniem losowego systemu slotów, aby opóźnić jego przesyłanie (zmniejszając prawdopodobieństwo kolizji).'; + 'Ustawia czynnik mnożony przez czas utrzymania w trybie flood dla pakietu oraz z wykorzystaniem losowego systemu slotów, aby opóźnić jego przesyłanie (zmniejszając prawdopodobieństwo kolizji).'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2970,7 +3351,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(tylko port szeregowy) Wyświetla wszystkie zdefiniowane regiony i aktualne uprawnienia do zalewu.'; + '(tylko port szeregowy) Wyświetla wszystkie zdefiniowane regiony i aktualne uprawnienia flood.'; @override String get repeater_cliHelpRegionLoad => @@ -2990,11 +3371,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpRegionAllowf => - 'Ustawia uprawnienia \'F\' (zalewowe) dla podanego regionu. (\'\' dla zakresu globalnego/starszego)'; + 'Ustawia uprawnienia \'F\' (flood) dla podanego regionu. (\'\' dla zakresu globalnego/starszego)'; @override String get repeater_cliHelpRegionDenyf => - 'Usuwa uprawnienie \'F\' (zalewowe) dla podanej strefy. (ZALECANE: na tym etapie NIE zaleca się używania tego na globalnym/starszym zakresie!!).'; + 'Usuwa uprawnienie \'F\' (flood) dla podanej strefy. (ZALECANE: na tym etapie NIE zaleca się używania tego na globalnym/starszym zakresie!!).'; @override String get repeater_cliHelpRegionHome => @@ -3037,6 +3418,76 @@ class AppLocalizationsPl extends AppLocalizations { String get repeater_commandsListNote => 'UWAGA: dla różnych poleceń \"set ...\" istnieje również polecenie \"get ...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => + 'Nieprawidłowa częstotliwość (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 do 30 dBm'; + + @override + String get repeater_recvErrors => 'Błędy Odbioru'; + + @override + String get room_postsStored => 'Posty'; + + @override + String get room_postsPushed => 'Wysłane Posty'; + + @override + String get repeater_cliRegionLoadActive => + 'Tryb wczytywania regionów: wysyłaj po jednej nazwie regionu w linii, wcięte spacjami pod regionem nadrzędnym (dodaj F po nazwie, aby zezwolić na flood). Linie nie otrzymują odpowiedzi. Wyślij pustą linię, aby zakończyć, a następnie \"region save\", aby zachować wynik.'; + + @override + String get repeater_cliRegionLoadHint => + 'Linia regionu lub pusta, aby zakończyć'; + + @override + String get repeater_cliRegionLoadEnd => '(koniec wczytywania regionów)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definiuje łańcuch regionów w jednej komendzie: każda nazwa jest dodawana pod poprzednią; \"name,parent\" dodaje nazwę, a następnie kontynuuje pod podanym regionem nadrzędnym. Odpowiada listą regionów.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Ustawia maksymalną liczbę skoków przy przekazywaniu pakietów flood bez przypisanego regionu (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Ustawia maksymalną liczbę skoków przy przekazywaniu rozgłoszeń flood (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Pokazuje maksymalną liczbę skoków dla pakietów flood bez przypisanego regionu.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Pokazuje maksymalną liczbę skoków dla rozgłoszeń flood.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Przełącza wzmocnienie RX (LNA) modułu front-end LoRa. Płytki bez tej funkcji odpowiadają \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Przełącza wzmocnienie TX (PA) modułu front-end LoRa. Płytki bez tej funkcji odpowiadają \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Pokazuje, czy wzmocnienie RX modułu front-end LoRa jest włączone.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Pokazuje, czy wzmocnienie TX modułu front-end LoRa jest włączone.'; + + @override + String get repeater_bridgeNote => + 'Dostępne tylko w firmware zbudowanym z mostkiem (RS232 lub ESP-NOW).'; + @override String get repeater_general => 'Ogólne'; @@ -3086,7 +3537,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Wysyła reklamę, która dociera bezpośrednio do sąsiadów (bez pośrednictwa).'; + 'Wysyła rozgłoszenie, które dociera bezpośrednio do sąsiadów (bez pośrednictwa).'; @override String get repeater_cliHelpStartOta => @@ -3209,11 +3660,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Pokazuje czas trwania lokalnej reklamy w minutach.'; + 'Pokazuje interwał lokalnego rozgłoszenia w minutach.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Pokazuje interwał reklamowy dotyczący powodzi w godzinach.'; + 'Pokazuje interwał rozgłoszenia flood w godzinach.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3233,7 +3684,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Pokazuje współczynnik opóźnienia transmisji w trybie zalewowym.'; + 'Pokazuje współczynnik opóźnienia transmisji w trybie flood.'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3241,7 +3692,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Pokazuje maksymalną liczbę skoków spowodowanych powodzią.'; + 'Pokazuje maksymalną liczbę skoków flood.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3329,11 +3780,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Wymienia regiony, w których dopuszczony jest ruch związany z powodzami.'; + 'Wymienia regiony, w których dozwolony jest ruch flood.'; @override String get repeater_cliHelpRegionListDenied => - 'Wymienia regiony, w których ruch związany z powodziami jest ograniczony.'; + 'Wymienia regiony, w których ruch flood jest zabroniony.'; @override String get repeater_cliHelpStatsPackets => @@ -3621,7 +4072,7 @@ class AppLocalizationsPl extends AppLocalizations { String get channelPath_unknownPath => 'Nieznane'; @override - String get channelPath_floodPath => 'Zalew'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Bezpośrednio'; @@ -3895,7 +4346,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Jeden lub więcej z chmieli nie ma określonej lokalizacji!'; + 'Jeden lub więcej skoków nie ma określonej lokalizacji!'; @override String get pathTrace_clearTooltip => 'Wyczyść ścieżkę'; @@ -4113,7 +4564,7 @@ class AppLocalizationsPl extends AppLocalizations { String get contacts_zeroHopAdvert => 'Rozgłoszenie zero-hop'; @override - String get contacts_floodAdvert => 'Rozgłoszenie zalewowe'; + String get contacts_floodAdvert => 'Rozgłoszenie flood'; @override String get contacts_copyAdvertToClipboard => 'Kopiuj rozgłoszenie do schowka'; @@ -4121,6 +4572,23 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Dodaj kontakt z schowka'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Kopiuj kontakt do schowka'; @@ -4254,6 +4722,10 @@ class AppLocalizationsPl extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Ostatnio widziany'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Ustawienia kontaktów'; @@ -4359,6 +4831,12 @@ class AppLocalizationsPl extends AppLocalizations { @override String get radioStats_screenTitle => 'Statystyki radiowe'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Połącz się z urządzeniem, aby wyświetlić statystyki radiowe.'; @@ -4417,6 +4895,44 @@ class AppLocalizationsPl extends AppLocalizations { @override String get translation_title => 'Tłumaczenie'; + @override + String get imageMessages_enableTitle => 'Włącz wiadomości ze zdjęciami'; + + @override + String get imageMessages_enableSubtitle => + 'Przesyłaj zdjęcia przez siatkę. Wymaga jednorazowego pobrania modelu obrazu.'; + + @override + String get imageMessages_modelSectionTitle => 'Model obrazowy'; + + @override + String get imageMessages_downloadModel => 'Pobierz'; + + @override + String get imageMessages_cancelDownload => 'Anuluj'; + + @override + String get imageMessages_removeModel => 'Usuń model'; + + @override + String get imageMessages_modelReady => 'Gotowy'; + + @override + String get imageMessages_modelNotPublished => + 'Nie opublikowane — ten build nie może tego pobrać.'; + + @override + String get imageMessages_downloadFailed => + 'Model obrazowy nie mógł zostać pobrany.'; + + @override + String get imageMessages_autoProcessTitle => + 'Obrazki są przetwarzane automatycznie.'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Odbuduj każde zdjęcie, jak tylko przyjdzie. Zużywa około 2 GB pamięci za każdą drugą sekundę; wyłącz odbudowywanie jednym dotknięciem.'; + @override String get translation_enableTitle => 'Włącz tłumaczenie'; @@ -4705,4 +5221,248 @@ class AppLocalizationsPl extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Przestań śledzić pakiet'; + + @override + String get imageSend_title => 'Wyślij obraz'; + + @override + String get imageSend_cropNote => + 'Zmniejszone do 512 × 512 · proporcje nie zostały zachowane'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Oryginalny'; + + @override + String get imageSend_onAirSize => 'W eterze'; + + @override + String get imageSend_quality => 'Jakość'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Wysoko'; + + @override + String get imageSend_packetsLabel => 'Pakiet'; + + @override + String get imageSend_airtimeLabel => 'Czas w eterze'; + + @override + String get imageSend_sizeLabel => 'Payload'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pakietów', + one: 'pakiet', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Ustawienia radia nieznane'; + + @override + String get imageSend_radioUnknownBody => + 'Połącz urządzenie, aby można było obliczyć czas trwania transmisji.'; + + @override + String get imageSend_longSendTitle => 'Długa transmisja'; + + @override + String imageSend_longSendBody(String duration) { + return 'Ten kanał będzie dostępny przez około $duration.'; + } + + @override + String get imageSend_floodNote => + 'Przepływ pakietów: każdy retransmitujący w zasięgu przekazuje każdy pakiet, przez co kanał pozostaje zajęty dłużej niż ten czas.'; + + @override + String get imageSend_parityTitle => 'Pakiet odzysku'; + + @override + String get imageSend_paritySubtitle => + 'Jedna dodatkowa paczka. Wiadomości grupowe nie są potwierdzane, dzięki czemu odbiorca może odbudować obraz, jeśli zostanie utracona pojedyncza paczka.'; + + @override + String get imageSend_send => 'Wyślij'; + + @override + String get imageSend_cancel => 'Anuluj'; + + @override + String get imageSend_encodeFailed => 'Ten obraz nie mógł zostać zakodowany.'; + + @override + String get imageSend_codecDownloading => + 'Model obrazowy jest nadal pobierany.'; + + @override + String get imageSend_codecUnavailable => + 'Wysyłanie obrazu nie jest dostępne na tym urządzeniu.'; + + @override + String get imageSend_codecDisabled => + 'Wiadomości ze zdjęciami są wyłączone w ustawieniach.'; + + @override + String get imageSend_deviceUnsupported => + 'Ten radiodysk nie może wysyłać pakietów obrazu. Podłącz urządzenie z oprogramowaniem firmware 13 lub nowszym.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Obrazy są przesyłane jako dane grupowe, więc można je wysłać tylko do kanału — nie w wiadomości prywatnej.'; + + @override + String get imageSend_tooLarge => + 'Obraz zakodowany do więcej pakietów niż pozwala format siatki.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pakietów', + one: 'pakiet', + ); + return 'Obraz wysłany jako $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Obraz nie mogł zostać wysłany: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Wysyłanie obrazu — pakiet $sent z $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Węzeł $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return 'Otrzymano: $received z $total pakietów'; + } + + @override + String get receivedImage_queued => 'Oczekiwanie na rozszyfrowanie'; + + @override + String get receivedImage_tapToDecode => 'Kliknij, aby odszyfrować'; + + @override + String get receivedImage_decoding => 'Odtwarzanie… około 1 sekundy'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Obraz niepełny — $received z $total pakietów dotarło'; + } + + @override + String get receivedImage_corrupt => 'Obraz nie może zostać zrekonstruowany'; + + @override + String get receivedImage_decoderMissing => + 'Otrzymano obraz — dekodowanie obrazu jest nieprawidłowe.'; + + @override + String get receivedImage_evicted => 'Obraz nie jest już przechowywany'; + + @override + String get receivedImage_retry => 'Spróbuj ponownie'; + + @override + String get receivedImage_decodeAgain => 'Zdekoduj ponownie'; + + @override + String get receivedImage_openSettings => 'Ustaw'; + + @override + String get receivedImage_tapToProcess => 'Kliknij, aby przetworzyć'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'pakiety', + one: 'pakiet', + ); + return '$bytes bajtów · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds sekund'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes minut $seconds sekundy'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Powyżej 158 bajtów: wysyłane maksymalnie $count razy'; + } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 0c9f67e2..9511d76e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -110,6 +110,46 @@ class AppLocalizationsPt extends AppLocalizations { @override String get messageStatus_repeated => 'Ouvi repetidamente'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Ativar imagens de URL'; + + @override + String get urlImage_possible => + 'Possível imagem de URL; ative-a em Configurações.'; + @override String get common_reboot => 'Reiniciar'; @@ -370,42 +410,64 @@ class AppLocalizationsPt extends AppLocalizations { 'Configurações de rádio atualizadas'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'O rádio não aplicou estas configurações'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regiões'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Gerenciar regiões armazenadas'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Gestão de Região'; + + @override + String get settings_regionNameHint => 'Nome da região'; + + @override + String get settings_regionAddRegion => 'Adicionar região'; + + @override + String get settings_regionFetchRegions => + 'Regiões de obtenção a partir de repetidores'; + + @override + String get settings_regionFetchRegionsFail => 'Nenhuma região foi encontrada'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Esta região já foi adicionada'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Nome da Região'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Região excluída'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Excluir Região'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Remover \"$region\" da lista de regiões?'; } @override @@ -498,6 +560,10 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Modo de Ambiente de Telemetria'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Localização do Anúncio'; @@ -505,9 +571,21 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_advertLocationSubtitle => 'Incluir localização no anúncio'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Anúncio zero-hop automático na atualização do GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Quando a localização GPS mudar, enviar um anúncio zero-hop (requer localização no anúncio).'; + @override String get settings_multiAck => 'Multi-ACKs'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Modo de telemetria atualizado'; @@ -522,7 +600,7 @@ class AppLocalizationsPt extends AppLocalizations { 'Clear all path data from contacts.'; @override - String get settings_sendAdvertisement => 'Enviar Publicidade'; + String get settings_sendAdvertisement => 'Enviar Anúncio'; @override String get settings_sendAdvertisementSubtitle => @@ -610,15 +688,31 @@ class AppLocalizationsPt extends AppLocalizations { @override String get settings_infoPublicKey => 'Chave Pública'; + @override + String get settings_publicKeyCopied => 'Chave pública copiada'; + @override String get settings_infoContactsCount => 'Número de Contatos'; @override String get settings_infoChannelCount => 'Número do Canal'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Configurações pré-definidas'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frequência (MHz)'; @@ -641,7 +735,9 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_txPower => 'TX Potência (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Potência de TX inválida (0-22 dBm)'; @@ -649,6 +745,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get settings_clientRepeat => 'Repetição sem rede'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Permita que este dispositivo repita pacotes de rede para outros dispositivos.'; @@ -731,6 +832,51 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_languageUk => 'Ucraniano'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bytes'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bytes'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bytes'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Ativar rastreamento de mensagens'; @@ -766,6 +912,13 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Mostrar notificação ao receber novas mensagens'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Notificações de Mensagens do Canal'; @@ -878,6 +1031,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0-4,35V)'; + @override String get appSettings_mapDisplay => 'Exibição do Mapa'; @@ -934,6 +1090,28 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_lastWeek => 'Da última semana'; + @override + String get appSettings_rasterTileSource => 'Fonte de blocos raster'; + + @override + String get appSettings_stadiaEndpoint => 'Endpoint da Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Chave da API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Obrigatório para usar o Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Configurado: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Insira sua chave da API Stadia Maps. O aplicativo a usa para solicitações de blocos raster.'; + @override String get appSettings_offlineMapCache => 'Cache de Mapa Offline'; @@ -1029,6 +1207,29 @@ class AppLocalizationsPt extends AppLocalizations { return 'Remover $contactName dos contatos?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Gerenciar Repetidor'; @@ -1179,6 +1380,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_private => 'Privado'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Editar canal'; @@ -1310,6 +1523,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_publicChannelAdded => 'Canal público adicionado'; + @override + String get channels_noFreeSlots => 'Todos os slots de canal estão em uso'; + @override String get channels_sortBy => 'Ordenar por'; @@ -1367,17 +1583,30 @@ class AppLocalizationsPt extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Região: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Região: nenhuma'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Escolha uma região'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Região desimpedida'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Ainda não existem mensagens.'; @@ -1431,9 +1660,27 @@ class AppLocalizationsPt extends AppLocalizations { return 'Tentar $current/$max'; } + @override + String get chat_selectSendAction => 'Selecionar ação de envio'; + @override String get chat_sendGif => 'Enviar GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Enviar imagem via MeshCore'; + + @override + String get chat_imagePickFailed => 'Não consegui abrir essa imagem'; + + @override + String get chat_receivedGif => 'Recebi um GIF'; + @override String get chat_reply => 'Responder'; @@ -1443,6 +1690,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_me => 'Eu'; + @override + String get reaction_report => 'Reações com Emoji'; + @override String get emojiCategorySmileys => 'Emojis'; @@ -1677,15 +1927,15 @@ class AppLocalizationsPt extends AppLocalizations { @override String pathEditor_hopCounter(int count) { - return '$count de 64 gramas de lúpulo'; + return '$count de 64 saltos'; } @override String get pathEditor_noHops => - 'Ainda não há lúpulos adicionados. Clique nos repetidores abaixo para adicioná-los na ordem desejada, ou salve sem adicionar lúpulos para enviar diretamente.'; + 'Ainda não há saltos adicionados. Clique nos repetidores abaixo para adicioná-los na ordem desejada, ou salve sem adicionar saltos para enviar diretamente.'; @override - String get pathEditor_addHops => 'Adicione os lúpulos na seguinte ordem.'; + String get pathEditor_addHops => 'Adicione os saltos na seguinte ordem.'; @override String get pathEditor_searchRepeaters => 'Encontrar repetidores'; @@ -1712,7 +1962,7 @@ class AppLocalizationsPt extends AppLocalizations { String get pathEditor_usePath => 'Utilize este caminho.'; @override - String get pathEditor_removeHop => 'Remova o lúpulo'; + String get pathEditor_removeHop => 'Remova o salto'; @override String get pathEditor_unknownHop => 'Repetidor desconhecido'; @@ -1733,6 +1983,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_path => 'Caminho'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Chave Pública'; @@ -1770,6 +2023,12 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_newMessages => 'Novas mensagens'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Abrir link?'; @@ -1815,6 +2074,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get map_centerOnNode => 'Centralizar no nó'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Detalhes'; @@ -1834,6 +2096,10 @@ class AppLocalizationsPt extends AppLocalizations { String get map_noNodesWithLocation => 'Não existem nós com dados de localização.'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Os nós precisam partilhar as suas coordenadas GPS\npara aparecerem no mapa'; @@ -1976,6 +2242,16 @@ class AppLocalizationsPt extends AppLocalizations { String get map_showGuessedLocations => 'Mostrar as localizações dos nós estimados'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Mostrar Contatos de Descoberta'; @@ -1997,6 +2273,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get map_manageRepeater => 'Gerenciar Repetidor'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Toque nos nós para adicioná-los ao caminho.'; @@ -2087,6 +2366,42 @@ class AppLocalizationsPt extends AppLocalizations { return 'Downloads falhas: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2164,6 +2479,12 @@ class AppLocalizationsPt extends AppLocalizations { @override String get login_enterPassword => 'Insira a senha'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Salvar senha'; @@ -2179,6 +2500,9 @@ class AppLocalizationsPt extends AppLocalizations { String get login_roomDescription => 'Insira a senha da sala para acessar as configurações e o status.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Rotas'; @@ -2217,6 +2541,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get common_clear => 'Limpar'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Caminho atual'; @@ -2242,6 +2569,12 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_guestTools => 'Ferramentas para hóspedes'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Estado'; @@ -2633,7 +2966,43 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Bytes utilizados para codificar o ID deste repetidor nas tags de caminho/detecção de loop. 0=1 byte (256 IDs, até 64 saltos), 1=2 bytes (65.000 IDs, até 32 saltos), 2=3 bytes (16 milhões de IDs, até 21 saltos). As versões 1.13 e anteriores do firmware não suportam caminhos multi-byte — apenas funcionam uma vez após a ativação da rede (a partir da versão 1.14+).'; + 'Bytes usados para codificar o ID deste repetidor nas tags de caminho flood/detecção de loop. 0=1 byte (256 IDs, até 64 saltos), 1=2 bytes (65.000 IDs, até 32 saltos), 2=3 bytes (16 milhões de IDs, até 21 saltos). O firmware anterior à v1.14 sempre usava caminhos de 1 byte; v1.14 e versões mais recentes podem ser configuradas para caminhos de 2 ou 3 bytes.'; + + @override + String get repeater_keySettings => 'Alterar Chaves de Identidade'; + + @override + String get repeater_keySettingsSubtitle => + 'Altere a chave pública/chave privada'; + + @override + String get repeater_prvKey => 'Chave privada'; + + @override + String get repeater_prvKeyHelper => + 'Uma nova chave privada para o repetidor, uma string hexadecimal de 128 caracteres.'; + + @override + String get repeater_generatePrvKey => 'Gere um par de chaves aleatório'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Interrompa a busca por par de chaves'; + + @override + String get repeater_pubKey => 'Chave pública'; + + @override + String get repeater_pubKeyHelper => + 'Esta é a chave pública que acompanha a chave privada gerada. Você não pode definir isso diretamente.'; + + @override + String get repeater_pubKeyPrefix => 'Prefixo desejado'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Encontre uma chave pública que comece com esses dígitos hexadecimais. Número esperado de tentativas: $tries.'; + } @override String get repeater_txDelay => 'Atraso na entrega em Flood, TX'; @@ -2731,6 +3100,17 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Atualizar Modo Privacidade'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label atualizado'; @@ -2867,7 +3247,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Define o intervalo do timer em horas para enviar um pacote de anúncio em massa. Defina como 0 para desativar.'; + 'Define o intervalo do timer em horas para enviar um pacote de anúncio de inundação. Defina como 0 para desativar.'; @override String get repeater_cliHelpSetGuestPassword => @@ -2977,11 +3357,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_cliHelpRegionAllowf => - 'Define a permissão de \'F\'luido para a região especificada. (\'\' para o escopo global/legado)'; + 'Define a permissão de \'F\'lood para a região especificada. (\'\' para o escopo global/legado)'; @override String get repeater_cliHelpRegionDenyf => - 'Remove a permissão de \"F\"luido para a região especificada. (NOTA: neste momento NÃO é aconselhável usar isso no escopo global/legado!!)'; + 'Remove a permissão de \"F\"lood para a região especificada. (NOTA: neste momento NÃO é aconselhável usar isso no escopo global/legado!!)'; @override String get repeater_cliHelpRegionHome => @@ -3024,6 +3404,75 @@ class AppLocalizationsPt extends AppLocalizations { String get repeater_commandsListNote => 'NOTA: para os diversos comandos \"set...\", também existe um comando \"get...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Frequência inválida (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 a 30 dBm'; + + @override + String get repeater_recvErrors => 'Erros de Recepção'; + + @override + String get room_postsStored => 'Publicações'; + + @override + String get room_postsPushed => 'Publicações Enviadas'; + + @override + String get repeater_cliRegionLoadActive => + 'Modo de carregamento de regiões: envie um nome de região por linha, indentado com espaços sob sua região pai (adicione F após o nome para permitir inundação). As linhas não recebem resposta. Envie uma linha vazia para terminar e depois \"region save\" para salvar o resultado.'; + + @override + String get repeater_cliRegionLoadHint => + 'Linha de região, ou vazia para terminar'; + + @override + String get repeater_cliRegionLoadEnd => '(fim do carregamento de regiões)'; + + @override + String get repeater_cliHelpRegionDef => + 'Define uma cadeia de regiões em um único comando: cada nome é adicionado sob o anterior; \"name,parent\" adiciona o nome e continua sob o pai indicado. Responde com a lista de regiões.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Define o número máximo de saltos para encaminhar pacotes de inundação sem escopo regional (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Define o número máximo de saltos para encaminhar anúncios de inundação (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Mostra o número máximo de saltos para pacotes de inundação sem escopo regional.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Mostra o número máximo de saltos para os anúncios de inundação.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Ativa ou desativa o ganho RX (LNA) do módulo frontal de LoRa. Placas sem esse módulo respondem \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Ativa ou desativa o ganho TX (PA) do módulo frontal de LoRa. Placas sem esse módulo respondem \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Mostra se o ganho RX do módulo frontal de LoRa está ativado.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Mostra se o ganho TX do módulo frontal de LoRa está ativado.'; + + @override + String get repeater_bridgeNote => + 'Disponível apenas em firmware compilado com uma ponte (RS232 ou ESP-NOW).'; + @override String get repeater_general => 'Geral'; @@ -3195,11 +3644,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Indica o intervalo de publicidade local em minutos.'; + 'Indica o intervalo de anúncio local em minutos.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Mostra o intervalo de tempo da publicidade relacionada às inundações, em horas.'; + 'Mostra o intervalo do anúncio de inundação, em horas.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3313,11 +3762,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Lista as regiões que permitem o tráfego em áreas de risco de inundações.'; + 'Lista as regiões que permitem o tráfego por inundação.'; @override String get repeater_cliHelpRegionListDenied => - 'Lista as regiões que restringem o tráfego em áreas de risco de inundações.'; + 'Lista as regiões que negam o tráfego por inundação.'; @override String get repeater_cliHelpStatsPackets => @@ -3645,7 +4094,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channelPath_noHopDetailsAvailable => - 'Não estão disponíveis detalhes de voo para este pacote.'; + 'Não estão disponíveis detalhes de salto para este pacote.'; @override String get channelPath_unknownRepeater => 'Repetidor Desconhecido'; @@ -3880,7 +4329,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Um ou mais dos lúpulos estão sem localização!'; + 'Um ou mais dos saltos estão sem localização!'; @override String get pathTrace_clearTooltip => 'Limpar caminho'; @@ -4106,6 +4555,23 @@ class AppLocalizationsPt extends AppLocalizations { String get contacts_addContactFromClipboard => 'Adicionar Contato da Área de Transferência'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Copiar contato para Área de Transferência'; @@ -4230,6 +4696,10 @@ class AppLocalizationsPt extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Visto pela última vez'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Configurações de contatos'; @@ -4337,6 +4807,12 @@ class AppLocalizationsPt extends AppLocalizations { @override String get radioStats_screenTitle => 'Estatísticas de rádio'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Conecte-se a um dispositivo para visualizar estatísticas de rádio.'; @@ -4395,6 +4871,44 @@ class AppLocalizationsPt extends AppLocalizations { @override String get translation_title => 'Tradução'; + @override + String get imageMessages_enableTitle => 'Mensagens de imagem'; + + @override + String get imageMessages_enableSubtitle => + 'Envie as imagens pela malha. Requer o download de um modelo de imagem único.'; + + @override + String get imageMessages_modelSectionTitle => 'Modelo de imagem'; + + @override + String get imageMessages_downloadModel => 'Download'; + + @override + String get imageMessages_cancelDownload => 'Cancelar'; + + @override + String get imageMessages_removeModel => 'Remover modelo'; + + @override + String get imageMessages_modelReady => 'Pronto'; + + @override + String get imageMessages_modelNotPublished => + 'Ainda não publicado — esta versão não pode baixá-lo.'; + + @override + String get imageMessages_downloadFailed => + 'O modelo de imagem não pôde ser baixado.'; + + @override + String get imageMessages_autoProcessTitle => + 'Processar imagens automaticamente'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Reconstrua cada imagem assim que ela chegar. Utiliza cerca de 2 GB de memória por segundo; dispense a reconstrução com um toque.'; + @override String get translation_enableTitle => 'Ativar a tradução'; @@ -4677,4 +5191,249 @@ class AppLocalizationsPt extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Liberar vista do pacote'; + + @override + String get imageSend_title => 'Enviar imagem'; + + @override + String get imageSend_cropNote => + 'Redimensionado para 512 × 512 · a proporção de aspecto não foi preservada'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Texto Original'; + + @override + String get imageSend_onAirSize => 'Ao ar'; + + @override + String get imageSend_quality => 'Qualidade'; + + @override + String get imageSend_qualityStandard => 'Padrão'; + + @override + String get imageSend_qualityHigh => 'Alto'; + + @override + String get imageSend_packetsLabel => 'Pacotes'; + + @override + String get imageSend_airtimeLabel => 'Tempo em transmissão'; + + @override + String get imageSend_sizeLabel => 'Carga útil'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pacotes', + one: 'pacote', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => + 'Configurações de rádio desconhecidas'; + + @override + String get imageSend_radioUnknownBody => + 'Conecte-se a um dispositivo para que o horário de transmissão possa ser calculado.'; + + @override + String get imageSend_longSendTitle => 'Transmissão longa'; + + @override + String imageSend_longSendBody(String duration) { + return 'Isso manterá o canal por cerca de $duration.'; + } + + @override + String get imageSend_floodNote => + 'Roteamento de inundação: cada repetidor na faixa retransmite cada pacote, fazendo com que o canal permaneça ocupado por mais tempo do que isso.'; + + @override + String get imageSend_parityTitle => 'Pacote de recuperação'; + + @override + String get imageSend_paritySubtitle => + 'Um pacote extra. As mensagens em grupo não são reconhecidas, assim permitindo que o destinatário reconstrua a imagem caso um pacote seja perdido.'; + + @override + String get imageSend_send => 'Enviar'; + + @override + String get imageSend_cancel => 'Cancelar'; + + @override + String get imageSend_encodeFailed => 'Esta imagem não pode ser codificada.'; + + @override + String get imageSend_codecDownloading => + 'O modelo de imagem ainda está baixando.'; + + @override + String get imageSend_codecUnavailable => + 'O envio de imagem não está disponível neste dispositivo.'; + + @override + String get imageSend_codecDisabled => + 'As mensagens de imagem estão desativadas nas configurações.'; + + @override + String get imageSend_deviceUnsupported => + 'Este rádio não pode enviar pacotes de imagem. Conecte um dispositivo com firmware companheiro versão 13 ou superior.'; + + @override + String get imageSend_directMessagesUnsupported => + 'As imagens viajam como dados em grupo, portanto, só podem ser enviadas para um canal — não em mensagem direta.'; + + @override + String get imageSend_tooLarge => + 'Essa imagem foi codificada em mais pacotes do que o formato de malha permite.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'pacotes', + one: 'pacote', + ); + return 'Imagem enviada como $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'A imagem não pôde ser enviada: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Envio da imagem — pacote $sent de $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Nó $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received de $total pacotes'; + } + + @override + String get receivedImage_queued => 'Aguardando para decodificar'; + + @override + String get receivedImage_tapToDecode => 'Toque para decodificar'; + + @override + String get receivedImage_decoding => 'Reconstruindo… cerca de 1 segundo'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Imagem incompleta — $received de $total pacotes chegaram'; + } + + @override + String get receivedImage_corrupt => 'A imagem não pôde ser reconstruída'; + + @override + String get receivedImage_decoderMissing => + 'Imagem recebida — decodificação de imagem incorreta'; + + @override + String get receivedImage_evicted => 'Imagem não armazenada'; + + @override + String get receivedImage_retry => 'Tente novamente'; + + @override + String get receivedImage_decodeAgain => 'Decodifique novamente'; + + @override + String get receivedImage_openSettings => 'Configurar'; + + @override + String get receivedImage_tapToProcess => 'Toque para processar'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'pacotes', + one: 'pacote', + ); + return '$bytes bytes · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds segundos'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Mais de 158 bytes: enviado no máximo $count vezes'; + } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 1ddc9c79..2337936d 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -110,6 +110,46 @@ class AppLocalizationsRu extends AppLocalizations { @override String get messageStatus_repeated => 'Услышал несколько раз'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Показывать изображения по URL'; + + @override + String get urlImage_possible => + 'Возможно изображение по URL; включите это в настройках.'; + @override String get common_reboot => 'Перезагрузить'; @@ -369,42 +409,66 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_radioSettingsUpdated => 'Настройки радио обновлены'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Радиомодуль не применил эти настройки'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Регионы'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => + 'Управление сохранёнными регионами'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Управление регионами'; + + @override + String get settings_regionNameHint => 'Введите название региона'; + + @override + String get settings_regionAddRegion => 'Добавить регион'; + + @override + String get settings_regionFetchRegions => + 'Извлекать регионы с ретрансляторов'; + + @override + String get settings_regionFetchRegionsFail => + 'Не были найдены никакие регионы'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Этот регион уже был добавлен'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Название региона'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Регион удалён'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Удалить регион'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Удалить \"$region\" из списка регионов?'; } @override @@ -499,15 +563,31 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Режим среды телеметрии'; @override - String get settings_advertLocation => 'Местоположение рекламы'; + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + + @override + String get settings_advertLocation => 'Местоположение анонса'; @override String get settings_advertLocationSubtitle => - 'Включить местоположение в объявление'; + 'Включить местоположение в анонс'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Авто-анонс без хопов при обновлении GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Когда GPS-местоположение меняется, отправлять анонс без хопов (требуется геопозиция в анонсе).'; @override String get settings_multiAck => 'Несколько подтверждений'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Режим телеметрии обновлен'; @@ -609,15 +689,32 @@ class AppLocalizationsRu extends AppLocalizations { @override String get settings_infoPublicKey => 'Публичный ключ'; + @override + String get settings_publicKeyCopied => 'Публичный ключ скопирован'; + @override String get settings_infoContactsCount => 'Количество контактов'; @override String get settings_infoChannelCount => 'Количество каналов'; + @override + String get settings_infoHardware => 'Оборудование'; + + @override + String get settings_infoFirmware => + 'Производственное программное обеспечение'; + @override String get settings_presets => 'Пресеты'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Частота (МГц)'; @@ -640,7 +737,9 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_txPower => 'Мощность передачи (дБм)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => @@ -649,6 +748,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get settings_clientRepeat => 'Повторение \"вне сети\"'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Позвольте этому устройству повторять пакеты данных для других устройств.'; @@ -731,6 +835,51 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_languageUk => 'Українська'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 байт'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 байта'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 байта'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 байта'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Включить трассировку сообщений'; @@ -747,7 +896,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_enableNotificationsSubtitle => - 'Получать уведомления о сообщениях и оповещениях'; + 'Получать уведомления о сообщениях и анонсах'; @override String get appSettings_notificationPermissionDenied => @@ -766,6 +915,13 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Показывать уведомление при получении новых сообщений'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Уведомления о сообщениях в каналах'; @@ -880,6 +1036,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3.0–4.2 В)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0–4,35 В)'; + @override String get appSettings_mapDisplay => 'Отображение карты'; @@ -937,6 +1096,28 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_lastWeek => 'Последнюю неделю'; + @override + String get appSettings_rasterTileSource => 'Источник растровых тайлов'; + + @override + String get appSettings_stadiaEndpoint => 'Конечная точка Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Ключ API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Требуется для использования Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Настроено: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Введите свой ключ API Stadia Maps. Приложение использует его для запросов растровых тайлов.'; + @override String get appSettings_offlineMapCache => 'Кэш офлайн-карты'; @@ -983,7 +1164,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_contactsWillAppear => - 'Контакты появятся, когда устройства начнут рассылать оповещения'; + 'Контакты появятся, когда устройства начнут рассылать анонсы'; @override String get contacts_unread => 'Непрочитанное'; @@ -1030,6 +1211,29 @@ class AppLocalizationsRu extends AppLocalizations { return 'Удалить $contactName из контактов?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Управление репитером'; @@ -1180,6 +1384,18 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_private => 'Приватный'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Изменить канал'; @@ -1311,6 +1527,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публичный канал добавлен'; + @override + String get channels_noFreeSlots => 'Нет свободных слотов для каналов'; + @override String get channels_sortBy => 'Сортировка'; @@ -1368,17 +1587,30 @@ class AppLocalizationsRu extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'РЕГИОН: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Регион: отсутствует'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Выберите регион'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Чистый регион'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Сообщений пока нет'; @@ -1432,9 +1664,27 @@ class AppLocalizationsRu extends AppLocalizations { return 'Попытка $current/$max'; } + @override + String get chat_selectSendAction => 'Выберите действие отправки'; + @override String get chat_sendGif => 'Отправить GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Отправить изображение через MeshCore'; + + @override + String get chat_imagePickFailed => 'Не удалось открыть это изображение'; + + @override + String get chat_receivedGif => 'Получен GIF'; + @override String get chat_reply => 'Ответить'; @@ -1444,6 +1694,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_me => 'Я'; + @override + String get reaction_report => 'Реакции'; + @override String get emojiCategorySmileys => 'Смайлы'; @@ -1592,7 +1845,7 @@ class AppLocalizationsRu extends AppLocalizations { String get routing_modeAuto => 'Авто'; @override - String get routing_modeFlood => 'Наводнение'; + String get routing_modeFlood => 'Рассылка'; @override String get routing_modeManual => 'Инструкция'; @@ -1640,7 +1893,7 @@ class AppLocalizationsRu extends AppLocalizations { String get routing_inUse => 'В эксплуатации'; @override - String get routing_qualityStrong => 'Сильный первый скачок'; + String get routing_qualityStrong => 'Сильный первый хоп'; @override String get routing_qualityGood => 'Хорошее начало'; @@ -1672,23 +1925,22 @@ class AppLocalizationsRu extends AppLocalizations { } @override - String get routing_floodDelivery => 'Доставка при затоплении'; + String get routing_floodDelivery => 'Доставка рассылкой'; @override String get pathEditor_title => 'Создать маршрут'; @override String pathEditor_hopCounter(int count) { - return '$count из 64 хмеля'; + return '$count из 64 хопов'; } @override String get pathEditor_noHops => - 'На данный момент хмель еще не добавлен. Чтобы добавить его, нажмите на соответствующие кнопки ниже в нужном порядке, или сохраните рецепт без хмеля, чтобы отправить его напрямую.'; + 'Пока не добавлено ни одного хопа. Нажимайте на репитеры ниже, чтобы добавлять их по порядку, или сохраните маршрут без хопов, чтобы отправить напрямую.'; @override - String get pathEditor_addHops => - 'Добавляйте хмель в соответствии с указанным порядком.'; + String get pathEditor_addHops => 'Добавляйте хопы по порядку'; @override String get pathEditor_searchRepeaters => 'Поиск повторителей'; @@ -1717,7 +1969,7 @@ class AppLocalizationsRu extends AppLocalizations { String get pathEditor_usePath => 'Используйте этот путь'; @override - String get pathEditor_removeHop => 'Удалить хмель'; + String get pathEditor_removeHop => 'Удалить хоп'; @override String get pathEditor_unknownHop => 'Неизвестный ретранслятор'; @@ -1738,6 +1990,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_path => 'Маршрут'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Публичный ключ'; @@ -1775,6 +2030,12 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_newMessages => 'Новые сообщения'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Открыть ссылку?'; @@ -1820,6 +2081,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get map_centerOnNode => 'Центрировать на узле'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Детали'; @@ -1838,6 +2102,10 @@ class AppLocalizationsRu extends AppLocalizations { @override String get map_noNodesWithLocation => 'Нет нод с данными о местоположении'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Ноды должны передавать свои GPS-координаты, чтобы отображаться на карте'; @@ -1980,6 +2248,16 @@ class AppLocalizationsRu extends AppLocalizations { String get map_showGuessedLocations => 'Отобразить предполагаемые места расположения узлов'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Показать контакты Discovery'; @@ -2001,6 +2279,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get map_manageRepeater => 'Управление репитером'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Нажимайте на узлы, чтобы добавить их в путь.'; @@ -2091,6 +2372,42 @@ class AppLocalizationsRu extends AppLocalizations { return 'Неудачных загрузок: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2168,6 +2485,12 @@ class AppLocalizationsRu extends AppLocalizations { @override String get login_enterPassword => 'Введите пароль'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Сохранить пароль'; @@ -2183,6 +2506,9 @@ class AppLocalizationsRu extends AppLocalizations { String get login_roomDescription => 'Введите пароль комнаты для доступа к настройкам и статусу.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Маршрутизация'; @@ -2222,6 +2548,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get common_clear => 'Очистить'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Текущий маршрут'; @@ -2246,6 +2575,12 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_guestTools => 'Инструменты для гостей'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Статус'; @@ -2472,7 +2807,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_privacyModeSubtitle => - 'Скрывать имя/местоположение в оповещениях'; + 'Скрывать имя/местоположение в анонсах'; @override String get repeater_advertisementSettings => 'Настройки анонсирования'; @@ -2619,8 +2954,7 @@ class AppLocalizationsRu extends AppLocalizations { String get repeater_refreshOwnerInfo => 'Обновить информацию о операторе'; @override - String get repeater_floodMax => - 'Максимальное количество прыжков при наводнении'; + String get repeater_floodMax => 'Максимальное количество хопов при рассылке'; @override String get repeater_floodMaxHelper => @@ -2638,14 +2972,49 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Байты, используемые для кодирования идентификатора этого ретранслятора в тегах для обнаружения потоков/циклов. 0 = 1 байт (256 идентификаторов, до 64 переходов), 1 = 2 байта (65 000 идентификаторов, до 32 переходов), 2 = 3 байта (1 600 000 идентификаторов, до 21 перехода). Версии прошивки v1.13 и более ранние версии не поддерживают многобайтовые пути — они поднимаются только после того, как ваша сеть будет обновлена до версии v1.14 и выше.'; + 'Байты, используемые для кодирования идентификатора этого ретранслятора в тегах flood-маршрута/обнаружения циклов. 0 = 1 байт (256 идентификаторов, до 64 хопов), 1 = 2 байта (65 000 идентификаторов, до 32 хопов), 2 = 3 байта (16 миллионов идентификаторов, до 21 хопа). Прошивки до v1.14 всегда использовали 1-байтовые маршруты; v1.14 и новее можно настроить на 2- или 3-байтовые маршруты.'; + + @override + String get repeater_keySettings => 'Изменить ключи идентичности'; + + @override + String get repeater_keySettingsSubtitle => + 'Измените пару публичных/частных ключей'; + + @override + String get repeater_prvKey => 'Личный ключ'; + + @override + String get repeater_prvKeyHelper => + 'Для повторителя генерируется новый приватный ключ — шестнадцатеричная строка из 128 символов.'; + + @override + String get repeater_generatePrvKey => 'Сгенерируйте случайный ключ-пару'; + + @override + String get repeater_stopGeneratingPrvKey => 'Прервать поиск ключной пары'; + + @override + String get repeater_pubKey => 'Публичный ключ'; + + @override + String get repeater_pubKeyHelper => + 'Это публичный ключ, который соответствует сгенерированному приватному ключу. Вы не можете установить его напрямую.'; + + @override + String get repeater_pubKeyPrefix => 'Желаемый префикс'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Найдите публичный ключ, начинающийся этими шестнадцатеричными цифрами. Ожидаемое количество попыток: $tries.'; + } @override String get repeater_txDelay => 'Задержка в работе системы Flood TX'; @override String get repeater_txDelayHelper => - 'Передача с увеличенным интервалом для трафика во время наводнения, в качестве коэффициента, умножающего время передачи пакета (от 0 до 2, по умолчанию 0,5). Более высокое значение означает меньшее количество столкновений, но более медленную передачу.'; + 'Задержка повторной передачи для трафика при рассылке (flood), в качестве коэффициента, умножающего время передачи пакета (от 0 до 2, по умолчанию 0,5). Более высокое значение означает меньшее количество столкновений, но более медленную передачу.'; @override String get repeater_directTxDelay => 'Прямая задержка сигнала TX'; @@ -2672,19 +3041,19 @@ class AppLocalizationsRu extends AppLocalizations { String get repeater_actionsTitle => 'Действия'; @override - String get repeater_sendAdvert => 'Отправить объявление о наводнении'; + String get repeater_sendAdvert => 'Отправить анонс рассылкой'; @override String get repeater_sendAdvertSubtitle => - 'Разместите рекламу о наводнении в эфире по всей сети.'; + 'Разошлите анонс рассылкой по всей сети.'; @override String get repeater_sendAdvertZeroHop => - 'Опубликуйте рекламу, не требующую промежуточного распространения.'; + 'Опубликуйте анонс, не требующий промежуточного распространения.'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Разместите рекламу, распространяемую одним способом (без использования ретрансляторов).'; + 'Разместите анонс, распространяемый одним способом (без использования ретрансляторов).'; @override String get repeater_clockSync => 'Синхронизировать время сейчас'; @@ -2735,6 +3104,17 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Обновить режим конфиденциальности'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label обновлён'; @@ -2879,15 +3259,15 @@ class AppLocalizationsRu extends AppLocalizations { 'Устанавливает/обновляет гостевой пароль. (для репитеров гости могут отправлять запрос «Get Stats»)'; @override - String get repeater_cliHelpSetName => 'Устанавливает имя в оповещениях.'; + String get repeater_cliHelpSetName => 'Устанавливает имя анонса.'; @override String get repeater_cliHelpSetLat => - 'Устанавливает широту для карты в оповещениях. (десятичные градусы)'; + 'Устанавливает широту для карты анонса. (десятичные градусы)'; @override String get repeater_cliHelpSetLon => - 'Устанавливает долготу для карты в оповещениях. (десятичные градусы)'; + 'Устанавливает долготу для карты анонса. (десятичные градусы)'; @override String get repeater_cliHelpSetRadio => @@ -2954,7 +3334,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - 'Показывает список других репитеров, услышанных через оповещения нулевого хопа. Каждая строка: префикс-id-в-hex:временная-метка:snr×4'; + 'Показывает список других репитеров, услышанных через анонсы нулевого хопа. Каждая строка: префикс-id-в-hex:временная-метка:snr×4'; @override String get repeater_cliHelpNeighborRemove => @@ -3030,6 +3410,75 @@ class AppLocalizationsRu extends AppLocalizations { String get repeater_commandsListNote => 'ПРИМЕЧАНИЕ: для большинства команд «set ...» существуют соответствующие команды «get ...».'; + @override + String get repeater_frequencyRangeHelper => '150-2500 МГц'; + + @override + String get repeater_frequencyInvalid => 'Недопустимая частота (150-2500 МГц)'; + + @override + String get repeater_txPowerRangeHelper => 'от -9 до 30 dBm'; + + @override + String get repeater_recvErrors => 'Ошибки приёма'; + + @override + String get room_postsStored => 'Публикации'; + + @override + String get room_postsPushed => 'Отправлено публикаций'; + + @override + String get repeater_cliRegionLoadActive => + 'Режим загрузки регионов: отправляйте по одному имени региона на строку, с отступом пробелами под родителем (добавьте F после имени, чтобы разрешить рассылку по сети). Строки не получают ответа. Отправьте пустую строку, чтобы завершить, затем \"region save\", чтобы сохранить результат.'; + + @override + String get repeater_cliRegionLoadHint => + 'Строка региона или пусто для завершения'; + + @override + String get repeater_cliRegionLoadEnd => '(конец загрузки регионов)'; + + @override + String get repeater_cliHelpRegionDef => + 'Задаёт цепочку регионов одной командой: каждое имя добавляется под предыдущим; \"name,parent\" добавляет имя и продолжает под указанным родителем. В ответ возвращается список регионов.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Задаёт максимальное число хопов для пересылки пакетов рассылки (flood) без региональной области (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Задаёт максимальное число хопов для пересылки анонсов, рассылаемых по сети (flood) (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Показывает максимальное число хопов для пакетов рассылки (flood) без региональной области.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Показывает максимальное число хопов для анонсов, рассылаемых по сети (flood).'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Переключает усиление RX (LNA) входного модуля LoRa. Платы без него отвечают \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Переключает усиление TX (PA) входного модуля LoRa. Платы без него отвечают \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Показывает, включено ли усиление RX на входном модуле LoRa.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Показывает, включено ли усиление TX на входном модуле LoRa.'; + + @override + String get repeater_bridgeNote => + 'Доступно только на прошивке, собранной с мостом (RS232 или ESP-NOW).'; + @override String get repeater_general => 'Общие'; @@ -3079,7 +3528,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Отправляет рекламу, распространяемую только среди ближайших соседей (без промежуточных узлов).'; + 'Отправляет анонс, распространяемый только среди ближайших соседей (без промежуточных узлов).'; @override String get repeater_cliHelpStartOta => @@ -3123,7 +3572,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpSetOwnerInfo => - 'Указывает строку с контактной информацией владельца, которая должна быть включена в объявления. Используйте \'|\' для переносов строк.'; + 'Указывает строку с контактной информацией владельца, которая должна быть включена в анонсы. Используйте \'|\' для переносов строк.'; @override String get repeater_cliHelpSetPathHashMode => @@ -3202,11 +3651,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Отображает продолжительность рекламного блока в минутах.'; + 'Отображает интервал локального анонсирования в минутах.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Отображает интервал времени показа рекламного ролика в часах.'; + 'Отображает интервал анонсирования рассылкой (flood) в часах.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3224,7 +3673,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Отображает коэффициент задержки при работе в режиме затопления.'; + 'Отображает коэффициент задержки при работе в режиме рассылки (flood).'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3232,7 +3681,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Отображает максимальное количество переходов при затоплении.'; + 'Отображает максимальное количество хопов при рассылке.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3320,11 +3769,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Перечисляет регионы, где разрешено движение транспорта во время наводнений.'; + 'Перечисляет регионы, где разрешена рассылка (flood).'; @override String get repeater_cliHelpRegionListDenied => - 'Перечисляет регионы, где запрещено движение транспорта во время наводнений.'; + 'Перечисляет регионы, где запрещена рассылка (flood).'; @override String get repeater_cliHelpStatsPackets => @@ -3886,7 +4335,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Одному или нескольким хмелям не указано местоположение!'; + 'У одного или нескольких хопов не указано местоположение!'; @override String get pathTrace_clearTooltip => 'Очистить путь'; @@ -4101,41 +4550,55 @@ class AppLocalizationsRu extends AppLocalizations { String get contacts_contactImportFailed => 'Контакт не удалось импортировать'; @override - String get contacts_zeroHopAdvert => 'Реклама Zero Hop'; + String get contacts_zeroHopAdvert => 'Анонс без хопов'; @override - String get contacts_floodAdvert => 'Рекламный поток'; + String get contacts_floodAdvert => 'Анонс рассылкой'; @override String get contacts_copyAdvertToClipboard => - 'Копировать рекламу в буфер обмена'; + 'Копировать анонс в буфер обмена'; @override String get contacts_addContactFromClipboard => 'Добавить контакт из буфера обмена'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Копировать контакт в буфер обмена'; @override - String get contacts_ShareContactZeroHop => - 'Поделиться контактом по объявлению'; + String get contacts_ShareContactZeroHop => 'Поделиться контактом по анонсу'; @override - String get contacts_zeroHopContactAdvertSent => - 'Отправлено сообщение по объявлению.'; + String get contacts_zeroHopContactAdvertSent => 'Контакт отправлен анонсом.'; @override String get contacts_zeroHopContactAdvertFailed => 'Не удалось отправить контакт.'; @override - String get contacts_contactAdvertCopied => - 'Реклама скопирована в буфер обмена.'; + String get contacts_contactAdvertCopied => 'Анонс скопирован в буфер обмена.'; @override String get contacts_contactAdvertCopyFailed => - 'Копирование рекламы в буфер обмена не удалось.'; + 'Копирование анонса в буфер обмена не удалось.'; @override String get notification_activityTitle => 'Активность MeshCore'; @@ -4246,6 +4709,10 @@ class AppLocalizationsRu extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Последний раз видели'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Настройки контактов'; @@ -4353,6 +4820,12 @@ class AppLocalizationsRu extends AppLocalizations { @override String get radioStats_screenTitle => 'Статистика радиовещания'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Подключитесь к устройству, чтобы просмотреть статистику радио.'; @@ -4411,6 +4884,44 @@ class AppLocalizationsRu extends AppLocalizations { @override String get translation_title => 'Перевод'; + @override + String get imageMessages_enableTitle => 'Включить изображения в сообщения'; + + @override + String get imageMessages_enableSubtitle => + 'Отправьте изображения через сеть. Требуется однократная загрузка шаблона изображения.'; + + @override + String get imageMessages_modelSectionTitle => 'Модель изображения'; + + @override + String get imageMessages_downloadModel => 'Скачать'; + + @override + String get imageMessages_cancelDownload => 'Отмена'; + + @override + String get imageMessages_removeModel => 'Удалить модель'; + + @override + String get imageMessages_modelReady => 'Готов'; + + @override + String get imageMessages_modelNotPublished => + 'Пока не опубликовано — эта сборка не может скачать это.'; + + @override + String get imageMessages_downloadFailed => + 'Модель изображения не удалось скачать.'; + + @override + String get imageMessages_autoProcessTitle => + 'Автоматически обрабатывать изображения'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Примерно каждое изображение реконструируйте сразу после его поступления. Для этого на каждый раз используется около 2 ГБ памяти; отключите реконструкцию касанием.'; + @override String get translation_enableTitle => 'Включить перевод'; @@ -4697,4 +5208,251 @@ class AppLocalizationsRu extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Не следить за пакетом'; + + @override + String get imageSend_title => 'Отправьте изображение'; + + @override + String get imageSend_cropNote => + 'Меняется размер на 512 × 512 · соотношение сторон не сохраняется'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Оригинал'; + + @override + String get imageSend_onAirSize => 'В эфире'; + + @override + String get imageSend_quality => 'Качество'; + + @override + String get imageSend_qualityStandard => 'Стандарт'; + + @override + String get imageSend_qualityHigh => 'Высота'; + + @override + String get imageSend_packetsLabel => 'Пакеты'; + + @override + String get imageSend_airtimeLabel => 'Время на эфире'; + + @override + String get imageSend_sizeLabel => 'Пакет'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакета', + many: 'пакетов', + few: 'пакета', + one: 'пакет', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Настройки радио неизвестны'; + + @override + String get imageSend_radioUnknownBody => + 'Подключитесь к устройству, чтобы можно было рассчитать время эфирного времени.'; + + @override + String get imageSend_longSendTitle => 'Долгая передача'; + + @override + String imageSend_longSendBody(String duration) { + return 'Это будет поддерживать канал примерно $duration.'; + } + + @override + String get imageSend_floodNote => + 'Руководство по маршрутизации потоков: каждый ретрансатор в зоне перераспределяет каждый пакет, поэтому канал остаётся занятным дольше, чем это.'; + + @override + String get imageSend_parityTitle => 'Пакет восстановления'; + + @override + String get imageSend_paritySubtitle => + 'Один дополнительный пакет. Групповые сообщения не подтверждаются, поэтому это позволяет получателю восстановить изображение, если один пакет потерян.'; + + @override + String get imageSend_send => 'Отправить'; + + @override + String get imageSend_cancel => 'Отмена'; + + @override + String get imageSend_encodeFailed => + 'Это изображение не может быть закодировано.'; + + @override + String get imageSend_codecDownloading => + 'Модель изображения всё ещё загружается.'; + + @override + String get imageSend_codecUnavailable => + 'Отправка изображения на этом устройстве недоступна.'; + + @override + String get imageSend_codecDisabled => + 'В настройках отключены сообщения с изображениями.'; + + @override + String get imageSend_deviceUnsupported => + 'Это радио не может отправлять пакеты изображений. Подключите устройство, работающее на прошивке-компаньоне версии 13 или выше.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Изображения передаются как групповые данные, поэтому их можно отправлять только в канал, а не в личное сообщение.'; + + @override + String get imageSend_tooLarge => + 'Изображение было закодировано в больше пакетов, чем позволяет формат сетки.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакетов', + one: 'пакет', + ); + return 'Изображение отправлено как $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Изображение не может быть отправлено: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Отправка изображения — пакет $sent из $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Узел $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received из $total пакетов'; + } + + @override + String get receivedImage_queued => 'Ожидание расшифровки'; + + @override + String get receivedImage_tapToDecode => 'Нажмите для декодирования'; + + @override + String get receivedImage_decoding => 'Реконструкция… примерно за 1 секунду'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Отсутствует изображение — $received из $total пакетов пришло'; + } + + @override + String get receivedImage_corrupt => 'Изображение не может быть восстановлено'; + + @override + String get receivedImage_decoderMissing => + 'Получен изображение — декодирование изображения неправильное'; + + @override + String get receivedImage_evicted => 'Изображение больше не сохраняется'; + + @override + String get receivedImage_retry => 'Попробуйте снова'; + + @override + String get receivedImage_decodeAgain => 'Декодируйте снова'; + + @override + String get receivedImage_openSettings => 'Настройте'; + + @override + String get receivedImage_tapToProcess => 'Нажмите для обработки'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'пакетов', + one: 'пакет', + ); + return '$bytes байт · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds секунд'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes м $seconds с'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Более 158 байт: отправляется не более $count раз'; + } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index bd16dc0f..ab6e3b6b 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -110,6 +110,46 @@ class AppLocalizationsSk extends AppLocalizations { @override String get messageStatus_repeated => 'Slyšal som to opakovane'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Povoliť obrázky z URL'; + + @override + String get urlImage_possible => + 'Možný obrázok z URL; povoľte ho v Nastaveniach.'; + @override String get common_reboot => 'Restartovať'; @@ -368,42 +408,63 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_radioSettingsUpdated => 'Nastavenia rádia aktualizované'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Rádio tieto nastavenia neuplatnilo'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regiony'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Zohľať uložené regiony'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Regiónne vedenie'; + + @override + String get settings_regionNameHint => 'Vstuptejte název regionu'; + + @override + String get settings_regionAddRegion => 'Dodajte region'; + + @override + String get settings_regionFetchRegions => 'Odberanie regionov z repeaterov'; + + @override + String get settings_regionFetchRegionsFail => 'Nebylo našli žiadné regiony'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Tento oblast je už dodán'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Regionné název'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Regionu zníteno'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Vyniknúcia regionu'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Odstraniť $region z listy regionov?'; } @override @@ -453,11 +514,11 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_privacyMode => 'Režim ochrany súkromia'; @override - String get settings_privacyModeSubtitle => 'Skryť meno/poloha v reklamách'; + String get settings_privacyModeSubtitle => 'Skryť meno/poloha v inzerátoch'; @override String get settings_privacyModeToggle => - 'Prepínač súkromného režimu skryje vaše meno a polohu v reklamách.'; + 'Prepínač súkromného režimu skryje vaše meno a polohu v inzerátoch.'; @override String get settings_privacyModeEnabled => 'Ochranný režim je povolený.'; @@ -493,15 +554,31 @@ class AppLocalizationsSk extends AppLocalizations { @override String get settings_telemetryEnvironmentMode => 'Režim prostredia telemetrie'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Umiestnenie inzerátu'; @override String get settings_advertLocationSubtitle => 'Zahrnúť polohu do inzerátu'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatický zero-hop inzerát pri aktualizácii GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Keď sa GPS poloha zmení, odoslať zero-hop inzerát (vyžaduje polohu v inzeráte).'; + @override String get settings_multiAck => 'Viaceré ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Režim telemetrie bol aktualizovaný'; @@ -517,13 +594,13 @@ class AppLocalizationsSk extends AppLocalizations { 'Clear all path data from contacts.'; @override - String get settings_sendAdvertisement => 'Odoslať reklamu'; + String get settings_sendAdvertisement => 'Odoslať inzerát'; @override String get settings_sendAdvertisementSubtitle => 'Momentálne priezornejšie.'; @override - String get settings_advertisementSent => 'Reklama odeslaná'; + String get settings_advertisementSent => 'Inzerát odoslaný'; @override String get settings_syncTime => 'Čas synchronizácie'; @@ -604,15 +681,31 @@ class AppLocalizationsSk extends AppLocalizations { @override String get settings_infoPublicKey => 'Verejný kľúč'; + @override + String get settings_publicKeyCopied => 'Verejný kľúč skopírovaný'; + @override String get settings_infoContactsCount => 'Počet kontaktov'; @override String get settings_infoChannelCount => 'Počet kanálov'; + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; + @override String get settings_presets => 'Prednastavenia'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frekvencia (MHz)'; @@ -635,7 +728,9 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_txPower => 'TX Výkon (dBm)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Neplatná hodnota výkonu TX (0-22 dBm)'; @@ -643,6 +738,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get settings_clientRepeat => 'Opätovné použitie bez elektrickej siete'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Umožnite, aby toto zariadenie opakovávalo siete pre ostatných.'; @@ -725,6 +825,51 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_languageUk => 'Ukrajinská'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byt'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bity'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bity'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bity'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Povoliť sledovanie správ'; @@ -759,6 +904,13 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Zobraziť upozornenie pri prijímaní nových správ'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Notifikácie z kanálov'; @@ -767,7 +919,8 @@ class AppLocalizationsSk extends AppLocalizations { 'Zobraziť upozornenie pri prijímaní správ z kanálu'; @override - String get appSettings_advertisementNotifications => 'Upozornenia na reklamy'; + String get appSettings_advertisementNotifications => + 'Upozornenia na inzeráty'; @override String get appSettings_advertisementNotificationsSubtitle => @@ -796,7 +949,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_autoRouteRotationSubtitle => - 'Striedajte sa medzi najlepšími trasami a režimom povodňovej analýzy.'; + 'Striedajte sa medzi najlepšími trasami a flood režimom.'; @override String get appSettings_autoRouteRotationEnabled => @@ -867,6 +1020,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3.0-4.35V)'; + @override String get appSettings_mapDisplay => 'Zobrazenie mapy'; @@ -924,6 +1080,28 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_lastWeek => 'Minul týždeň'; + @override + String get appSettings_rasterTileSource => 'Zdroj rastrových dlaždíc'; + + @override + String get appSettings_stadiaEndpoint => 'Koncový bod Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Kľúč API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Vyžaduje sa na používanie Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Nakonfigurované: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Zadajte svoj kľúč API pre Stadia Maps. Aplikácia ho používa na požiadavky na rastrové dlaždice.'; + @override String get appSettings_offlineMapCache => 'Offline Mapa Pamäť'; @@ -970,7 +1148,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_contactsWillAppear => - 'Kontakty sa zobrazia, keď zariadenia spúšťajú reklamu.'; + 'Kontakty sa zobrazia, keď zariadenia vysielajú inzerát.'; @override String get contacts_unread => 'Neprečítané'; @@ -1018,6 +1196,29 @@ class AppLocalizationsSk extends AppLocalizations { return 'Odstrániť $contactName z kontaktov?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Spravovať opakované zoznamy'; @@ -1169,6 +1370,18 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_private => 'Osobné'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Upraviť kanál'; @@ -1301,6 +1514,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_publicChannelAdded => 'Veľký kanál pridaný'; + @override + String get channels_noFreeSlots => 'Všetky miesta pre kanály sú obsadené'; + @override String get channels_sortBy => 'Triediť podľa'; @@ -1361,13 +1577,26 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Region: žiadné'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Vyberte region'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Jasný údajný oblasť'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Zatiaľ žiadne správy.'; @@ -1421,9 +1650,27 @@ class AppLocalizationsSk extends AppLocalizations { return 'Skúsiť $current/$max'; } + @override + String get chat_selectSendAction => 'Vybrať akciu odoslania'; + @override String get chat_sendGif => 'Odoslať GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Odoslať obrázok cez MeshCore'; + + @override + String get chat_imagePickFailed => 'Nesmiela jsem otvoriť tento obrázok'; + + @override + String get chat_receivedGif => 'Odeslaný GIF'; + @override String get chat_reply => 'Odpovedať'; @@ -1433,6 +1680,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_me => 'Mne'; + @override + String get reaction_report => 'Emoji reakcie'; + @override String get emojiCategorySmileys => 'Emoji'; @@ -1580,7 +1830,7 @@ class AppLocalizationsSk extends AppLocalizations { String get routing_modeAuto => 'Auto'; @override - String get routing_modeFlood => 'Povodňová vlna'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Ručná príručka'; @@ -1641,7 +1891,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get routing_qualityFlood => - 'Zistil som to z informácií, ktoré som získal v dôsledku povodňovej situácie.'; + 'Zistil som to z informácií, ktoré som získal cez flood.'; @override String get routing_qualityUntested => 'Neotestované'; @@ -1660,22 +1910,22 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get routing_floodDelivery => 'Doručenie v prípade povodní'; + String get routing_floodDelivery => 'Doručenie cez flood'; @override String get pathEditor_title => 'Vytvorenie cesty'; @override String pathEditor_hopCounter(int count) { - return '$count z 64 chmelových zŕš'; + return '$count z 64 skokov'; } @override String get pathEditor_noHops => - 'Zatiaľ žiadne chmel. Kliknite na opakované, aby ste ich pridali postupne, alebo uložte bez chmelu, aby ste ho mohli poslať priamo.'; + 'Zatiaľ žiadne skoky. Kliknite na opakovače nižšie, aby ste ich pridali postupne, alebo uložte bez skokov, aby ste správu mohli poslať priamo.'; @override - String get pathEditor_addHops => 'Pridávajte chmel podľa zadaného poriadku.'; + String get pathEditor_addHops => 'Pridávajte skoky podľa zadaného poriadku.'; @override String get pathEditor_searchRepeaters => 'Hľadať opakované'; @@ -1702,7 +1952,7 @@ class AppLocalizationsSk extends AppLocalizations { String get pathEditor_usePath => 'Použite túto cestu'; @override - String get pathEditor_removeHop => 'Odstráňte chmel'; + String get pathEditor_removeHop => 'Odstráňte skok'; @override String get pathEditor_unknownHop => @@ -1725,6 +1975,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_path => 'Cesta'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Verejný kľúč'; @@ -1732,7 +1985,7 @@ class AppLocalizationsSk extends AppLocalizations { String get chat_compressOutgoingMessages => 'Komprimovať odoslané správy'; @override - String get chat_floodForced => 'Povodňová (nutená)'; + String get chat_floodForced => 'Flood (vynútený)'; @override String get chat_directForced => 'Priame (donútené)'; @@ -1743,7 +1996,7 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get chat_floodAuto => 'Povod (automaticky)'; + String get chat_floodAuto => 'Flood (automaticky)'; @override String get chat_direct => 'Priamo'; @@ -1762,6 +2015,12 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_newMessages => 'Nové správy'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Otvoriť odkaz?'; @@ -1807,6 +2066,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get map_centerOnNode => 'Nacentrovať na uzol'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Podrobnosti'; @@ -1825,6 +2087,10 @@ class AppLocalizationsSk extends AppLocalizations { @override String get map_noNodesWithLocation => 'Žiadne uzly s údajmi o polohe'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Uholníky musia zdieľať svoje GPS súradnice, aby sa zobrazili na mape.'; @@ -1967,6 +2233,16 @@ class AppLocalizationsSk extends AppLocalizations { String get map_showGuessedLocations => 'Zobraziť umiestnenia odhadnutých uzlov'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Zobraziť kontakty objavov'; @@ -1988,6 +2264,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get map_manageRepeater => 'Spravovať Opakovanie'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Kliknite na uzly, aby ste ich pridali k ceste.'; @@ -2077,6 +2356,42 @@ class AppLocalizationsSk extends AppLocalizations { return 'Neúspešné stiahnutia: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2154,6 +2469,12 @@ class AppLocalizationsSk extends AppLocalizations { @override String get login_enterPassword => 'Zadajte heslo'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Uložiť heslo'; @@ -2169,6 +2490,9 @@ class AppLocalizationsSk extends AppLocalizations { String get login_roomDescription => 'Zadajte heslo do miestnosti na prístup k nastaveniam a stavu.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Rútiace'; @@ -2179,8 +2503,7 @@ class AppLocalizationsSk extends AppLocalizations { String get login_autoUseSavedPath => 'Použiť uloženú cestu'; @override - String get login_forceFloodMode => - 'Zavrieť režim núdzového povodňového režimu'; + String get login_forceFloodMode => 'Zavrieť núdzový flood režim'; @override String get login_managePaths => 'Spravovať Cesty'; @@ -2208,6 +2531,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get common_clear => 'Zmazať'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Aktuálny priebeh'; @@ -2233,6 +2559,12 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_guestTools => 'Nástroje pre hostí'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Stav'; @@ -2353,17 +2685,17 @@ class AppLocalizationsSk extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Celkem: $total, Povodňový režim: $flood, Priamy: $direct'; + return 'Celkem: $total, Flood: $flood, Priamy: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Celkem: $total, Povodňový režim: $flood, Priamy: $direct'; + return 'Celkem: $total, Flood: $flood, Priamy: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Pond: $flood, Priamy: $direct'; + return 'Flood: $flood, Priamy: $direct'; } @override @@ -2455,13 +2787,13 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_privacyMode => 'Režim ochrany súkromia'; @override - String get repeater_privacyModeSubtitle => 'Skryť meno/poloha v reklamách'; + String get repeater_privacyModeSubtitle => 'Skryť meno/poloha v inzerátoch'; @override - String get repeater_advertisementSettings => 'Nastavenia reklamy'; + String get repeater_advertisementSettings => 'Nastavenia inzerátov'; @override - String get repeater_localAdvertInterval => 'Lokálna reklamná časová obdoba'; + String get repeater_localAdvertInterval => 'Lokálna inzertná časová obdoba'; @override String repeater_localAdvertIntervalMinutes(int minutes) { @@ -2469,8 +2801,7 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => - 'Interval reklamnej povodňovej reklamy'; + String get repeater_floodAdvertInterval => 'Interval flood inzerátu'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2478,7 +2809,7 @@ class AppLocalizationsSk extends AppLocalizations { } @override - String get repeater_encryptedAdvertInterval => 'Šifrovaný reklamný interval'; + String get repeater_encryptedAdvertInterval => 'Šifrovaný inzertný interval'; @override String get repeater_dangerZone => 'Nebezpečná zóna'; @@ -2601,7 +2932,7 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_refreshOwnerInfo => 'Zísť informácie o operátore'; @override - String get repeater_floodMax => 'Maximálny počet skokov pri povodni'; + String get repeater_floodMax => 'Maximálny počet skokov flood'; @override String get repeater_floodMaxHelper => @@ -2619,14 +2950,50 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Byty použité na zakódovanie ID tohto opakovača v tagoch pre trasu/detekciu slučky. 0 = 1 bytu (256 ID, až 64 skokov), 1 = 2 byty (65 000 ID, až 32 skokov), 2 = 3 byty (16 miliónov ID, až 21 skokov). Verzie 1.13 a staršie nepodporujú viacbytové trasy – fungujú len, keď je sieť aktivovaná.'; + 'Bajty použité na zakódovanie ID tohto opakovača v tagoch flood trasy/detekcie slučky. 0=1 bajt (256 ID, až 64 skokov), 1=2 bajty (65 000 ID, až 32 skokov), 2=3 bajty (16 miliónov ID, až 21 skokov). Firmvér pred v1.14 vždy používal 1-bajtové trasy; v1.14 a novšie možno nakonfigurovať na 2- alebo 3-bajtové trasy.'; + + @override + String get repeater_keySettings => 'Zmena identititačných klíčov'; + + @override + String get repeater_keySettingsSubtitle => + 'Zmena prehľadného/osobného klíčového zbraň'; + + @override + String get repeater_prvKey => 'Prívatná klíč'; + + @override + String get repeater_prvKeyHelper => + 'Nová prívna klíčová číslo pre repeater, 128-znáčlový šestnáctorýč.'; + + @override + String get repeater_generatePrvKey => 'Vytvorenie príma kľúčového paru'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Prerušenie hľadania klíčového paru'; + + @override + String get repeater_pubKey => 'Public key'; + + @override + String get repeater_pubKeyHelper => + 'Táto je veľká klíč, ktorý sa vztahuje s generovaným manéčným klíčom. Nemožné je to ustanovit priateľne.'; + + @override + String get repeater_pubKeyPrefix => 'Požadovaný prefiks'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Zahľadnite sa veľkú publicenu klíču, ktorá začíná tými šestícih štiastkami. Očekivané potrebné pokusy: $tries.'; + } @override String get repeater_txDelay => 'Zpoždanie v Flood, TX'; @override String get repeater_txDelayHelper => - 'Nastavenie pre opakované vysielanie pre dopravu počas povodní, ako násobok času, ktorý paket využije (0-2, výchoce hodnota 0,5). Vyššia hodnota znamená menej kolízii, ale pomalšie doručovanie.'; + 'Nastavenie pre opakované vysielanie pre flood dopravu, ako násobok času, ktorý paket využije (0-2, výchoce hodnota 0,5). Vyššia hodnota znamená menej kolízii, ale pomalšie doručovanie.'; @override String get repeater_directTxDelay => 'Priame oneskorenie TX'; @@ -2653,18 +3020,17 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_actionsTitle => 'Opatrenia'; @override - String get repeater_sendAdvert => 'Odoslať inzerát o povodňovej situácii'; + String get repeater_sendAdvert => 'Odoslať flood inzerát'; @override - String get repeater_sendAdvertSubtitle => - 'Zverejnite reklamu na povodňu prostredníctvom siete.'; + String get repeater_sendAdvertSubtitle => 'Zverejnite flood inzerát v sieti.'; @override - String get repeater_sendAdvertZeroHop => 'Odoslať reklamu bez prenosu'; + String get repeater_sendAdvertZeroHop => 'Odoslať inzerát bez prenosu'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Zverejnite reklamnú správu, ktorá sa prenáša len raz (bez prenosov).'; + 'Zverejnite inzerát, ktorý sa prenáša len raz (bez prenosov).'; @override String get repeater_clockSync => 'Synchronizujte hodiny teraz'; @@ -2715,6 +3081,17 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Obnoviť Ochranný režim'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label sa znova načítalo'; @@ -2781,7 +3158,7 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_cliQuickVersion => 'Verzia'; @override - String get repeater_cliQuickAdvertise => 'Reklama'; + String get repeater_cliQuickAdvertise => 'Inzerát'; @override String get repeater_cliQuickClock => 'Hodiny'; @@ -2793,7 +3170,7 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_cliQuickDiscovery => 'Objaviť susedov'; @override - String get repeater_cliHelpAdvert => 'Odosiela reklamnú balíček.'; + String get repeater_cliHelpAdvert => 'Odosiela inzertný balíček.'; @override String get repeater_cliHelpReboot => @@ -2848,26 +3225,26 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - 'Nastavuje interval časovača v minútach na odošle miestny (bezprostredný) reklamný paket. Nastavenie na 0 vypne funkciu.'; + 'Nastavuje interval časovača v minútach na odoslanie miestneho (bezprostredného) inzertného paketu. Nastavenie na 0 vypne funkciu.'; @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Nastavuje interval časovača v hodinách na odeslanie reklamnej vlne. Nastavenie na 0 vypne.'; + 'Nastavuje interval časovača v hodinách na odoslanie flood inzerátu. Nastavenie na 0 vypne.'; @override String get repeater_cliHelpSetGuestPassword => 'Nastavuje/aktualizuje heslo hosťa. (pre opakované pripojenia môžu hosťovské prihlásenia posielať požadanie \"Get Stats\")'; @override - String get repeater_cliHelpSetName => 'Nastaví názov reklamy.'; + String get repeater_cliHelpSetName => 'Nastaví názov inzerátu.'; @override String get repeater_cliHelpSetLat => - 'Nastaví geografickú šírku reklamnej mapy. (desatinné stupne)'; + 'Nastaví geografickú šírku mapy inzerátu. (desatinné stupne)'; @override String get repeater_cliHelpSetLon => - 'Nastavuje longitudinu reklamnej mapy. (desatinné stupne)'; + 'Nastavuje longitúdu mapy inzerátu. (desatinné stupne)'; @override String get repeater_cliHelpSetRadio => @@ -2879,7 +3256,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - 'Nastavuje faktor násobený časom na vzduchu pre paket v režime povodňovej vlny a s náhodným systémom slotov, aby sa oneskorene jeho prenosovanie (s cieľom znížiť pravdepodobnosť kolízii).'; + 'Nastavuje faktor násobený časom na vzduchu pre paket v režime flood a s náhodným systémom slotov, aby sa oneskorene jeho prenosovanie (s cieľom znížiť pravdepodobnosť kolízii).'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2934,7 +3311,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - 'Zobrazuje zoznam iných repeaterových uzlov zasielaných cez zero-hop reklamy. Každý riadok je id-prefix-hex:timestamp:snr-times-4'; + 'Zobrazuje zoznam iných repeaterových uzlov zasielaných cez zero-hop inzeráty. Každý riadok je id-prefix-hex:timestamp:snr-times-4'; @override String get repeater_cliHelpNeighborRemove => @@ -2942,7 +3319,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(len sériál) Zobrazuje všetky definované regióny a aktuálne povolenia pre povodňové situácie.'; + '(len sériál) Zobrazuje všetky definované regióny a aktuálne povolenia pre flood.'; @override String get repeater_cliHelpRegionLoad => @@ -2996,11 +3373,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpGpsAdvert => - 'Poskytuje konfiguráciu reklamy pre uzol:\n- žiadna: nezahrňte polohu do reklám\n- zdieľať: zdieľajte GPS polohu (z SensorManager)\n- nastavenia: zobrazujte polohu uloženú v nastaveniach'; + 'Poskytuje konfiguráciu inzerátu pre uzol:\n- žiadna: nezahrňte polohu do inzerátov\n- zdieľať: zdieľajte GPS polohu (z SensorManager)\n- nastavenia: zobrazujte polohu uloženú v nastaveniach'; @override String get repeater_cliHelpGpsAdvertSet => - 'Nastavuje konfiguráciu reklamy na zadané miesto.'; + 'Nastavuje konfiguráciu inzerátu na zadané miesto.'; @override String get repeater_commandsListTitle => 'Zoznam príkazov'; @@ -3009,6 +3386,75 @@ class AppLocalizationsSk extends AppLocalizations { String get repeater_commandsListNote => 'Poznámka: pre rôzne príkazy \"set ...\" existuje aj príkaz \"get ...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Neplatná frekvencia (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 až 30 dBm'; + + @override + String get repeater_recvErrors => 'Chyby príjmu'; + + @override + String get room_postsStored => 'Príspevky'; + + @override + String get room_postsPushed => 'Odoslané príspevky'; + + @override + String get repeater_cliRegionLoadActive => + 'Režim načítania regiónov: pošlite po jednom názve regiónu na riadok, odsadenom medzerami pod jeho nadradeným regiónom (pridaním F za názov povolíte flood). Riadky nedostanú odpoveď. Prázdnym riadkom ukončite a potom príkazom \"region save\" výsledok uložte.'; + + @override + String get repeater_cliRegionLoadHint => + 'Riadok regiónu, alebo prázdny na ukončenie'; + + @override + String get repeater_cliRegionLoadEnd => '(koniec načítania regiónov)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definuje reťazec regiónov v jednom príkaze: každý názov sa pridá pod predchádzajúci; \"name,parent\" pridá názov a potom pokračuje pod zadaným nadradeným regiónom. Odpovie zoznamom regiónov.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Nastavuje maximálny počet skokov pri preposielaní flood paketov bez priradeného regiónu (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Nastavuje maximálny počet skokov pri preposielaní flood inzerátov (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Zobrazuje maximálny počet skokov pre flood pakety bez priradeného regiónu.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Zobrazuje maximálny počet skokov pre flood inzeráty.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Prepína RX zosilnenie (LNA) LoRa front-end modulu. Dosky bez neho odpovedia \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Prepína TX zosilnenie (PA) LoRa front-end modulu. Dosky bez neho odpovedia \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Zobrazuje, či je zapnuté RX zosilnenie LoRa front-end modulu.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Zobrazuje, či je zapnuté TX zosilnenie LoRa front-end modulu.'; + + @override + String get repeater_bridgeNote => + 'Dostupné len vo firmvéri zostavenom s mostom (RS232 alebo ESP-NOW).'; + @override String get repeater_general => 'Obecné'; @@ -3058,7 +3504,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Rozosiela reklamu, ktorá sa prenáša len medzi susednými zariadeniami (bez prenosu cez iné siete).'; + 'Rozosiela inzerát, ktorý sa prenáša len medzi susednými zariadeniami (bez prenosu cez iné siete).'; @override String get repeater_cliHelpStartOta => @@ -3102,7 +3548,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpSetOwnerInfo => - 'Definuje reťazec s informáciami o kontaktnom osobě, ktorý je zahrnutý v reklamách. Používajte \'|\' pre nové riadky.'; + 'Definuje reťazec s informáciami o kontaktnom osobě, ktorý je zahrnutý v inzerátoch. Používajte \'|\' pre nové riadky.'; @override String get repeater_cliHelpSetPathHashMode => @@ -3181,11 +3627,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Zobrazuje čas trvania miestnej reklamnej pauzy v minútach.'; + 'Zobrazuje interval miestneho inzerátu v minútach.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Zobrazuje časový interval reklamy počas záplavy v hodinách.'; + 'Zobrazuje časový interval flood inzerátu v hodinách.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3203,7 +3649,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Ukazuje faktor zpoždenia pre režim povodňovej komunikácie.'; + 'Ukazuje faktor zpoždenia pre režim flood.'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3211,7 +3657,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Zobrazuje maximálny počet opakovaní povodňového stavu.'; + 'Zobrazuje maximálny počet skokov flood.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3299,11 +3745,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Zoznam oblastí, ktoré umožňujú premávku počas povodní.'; + 'Zoznam oblastí, ktoré umožňujú premávku flood.'; @override String get repeater_cliHelpRegionListDenied => - 'Zoznam oblastí, ktoré zakazujú premávku v dôsledku povodní.'; + 'Zoznam oblastí, ktoré zakazujú premávku flood.'; @override String get repeater_cliHelpStatsPackets => @@ -3590,7 +4036,7 @@ class AppLocalizationsSk extends AppLocalizations { String get channelPath_unknownPath => 'Neznáme'; @override - String get channelPath_floodPath => 'Povodňová'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Priamo'; @@ -3863,7 +4309,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Jedna alebo viac chmeľov chýba lokalita!'; + 'Jedna alebo viac skokov chýba lokalita!'; @override String get pathTrace_clearTooltip => 'Zmazať cestu'; @@ -4080,14 +4526,31 @@ class AppLocalizationsSk extends AppLocalizations { String get contacts_zeroHopAdvert => 'Inzerát Zero Hop'; @override - String get contacts_floodAdvert => 'Inzerát povodní'; + String get contacts_floodAdvert => 'Flood inzerát'; @override - String get contacts_copyAdvertToClipboard => 'Kopírovať reklamu do schránky'; + String get contacts_copyAdvertToClipboard => 'Kopírovať inzerát do schránky'; @override String get contacts_addContactFromClipboard => 'Pridať kontakt z schránky'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Kopírovať kontakt do schránky'; @@ -4215,6 +4678,10 @@ class AppLocalizationsSk extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Naposledy videný'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Nastavenia kontaktov'; @@ -4318,6 +4785,12 @@ class AppLocalizationsSk extends AppLocalizations { @override String get radioStats_screenTitle => 'Štatistiky rádiových vysielaní'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Pripojte sa k zariadeniu, aby ste mohli sledovať štatistiky rádiového vysielania.'; @@ -4376,6 +4849,43 @@ class AppLocalizationsSk extends AppLocalizations { @override String get translation_title => 'Preklad'; + @override + String get imageMessages_enableTitle => 'Zabezpečte zobrazi'; + + @override + String get imageMessages_enableSubtitle => + 'Odeslanie obrazov pre mšťanie. Potrebujete jednorazové stáhnutie modelu obrazov.'; + + @override + String get imageMessages_modelSectionTitle => 'Model v kínajme'; + + @override + String get imageMessages_downloadModel => 'Stáhnie'; + + @override + String get imageMessages_cancelDownload => 'Zastavenie'; + + @override + String get imageMessages_removeModel => 'Vyhniť model'; + + @override + String get imageMessages_modelReady => 'Čiačný'; + + @override + String get imageMessages_modelNotPublished => + 'Nesprávne vypisáné — tento prechovka nie môže jej stáhnuť.'; + + @override + String get imageMessages_downloadFailed => + 'Model s obrázkom nemôžno sťažovať.'; + + @override + String get imageMessages_autoProcessTitle => 'Automaticky prepojiť slučaje.'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Rekonstruujte každý obraz tak, ako pridá. Používajete okolo 2 GB pamäti pre drugú hodinu; odložte rekonstrukciu tým kliknutím.'; + @override String get translation_enableTitle => 'Aktivovať preklad'; @@ -4661,4 +5171,249 @@ class AppLocalizationsSk extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Odomknúť pohľad od paketu'; + + @override + String get imageSend_title => 'Vyslat obraz'; + + @override + String get imageSend_cropNote => + 'Zmeneno na 512 × 512 · vzorýst nie byl zachovan'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + 'Výborný text:\n\n\"Language is the road map of a culture. It tells us where to go as a society and helps us understand the world around us. Learning a new language opens up new perspectives and opportunities, allowing us to connect with people from different backgrounds and build bridges between cultures.\"\n\nSlovenská preklada:\n\n\"Jazyk je cesta pre zručnosti a odráža kultúru. Dá nám uvedomi, dokádať, kúdy sa pohladneme a pomáha našej společnosti poradiť sa v rôznych okolnosti a porozumieť o svetu kolem nás. Nauka nového jazyka otviera nové perspektívy a možnosti, čo pohybuje našu schopnosť sa spoluprávať s ľudmi z rôznych okolnosti a budovať mosty medzi kultúry.\"'; + + @override + String get imageSend_onAirSize => 'V prúce'; + + @override + String get imageSend_quality => 'Kvalita'; + + @override + String get imageSend_qualityStandard => 'Stándard'; + + @override + String get imageSend_qualityHigh => 'Vysoká'; + + @override + String get imageSend_packetsLabel => 'Pakety'; + + @override + String get imageSend_airtimeLabel => 'Čas na anteni'; + + @override + String get imageSend_sizeLabel => 'Základ'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Nastavenia radio nezná'; + + @override + String get imageSend_radioUnknownBody => + 'Zkonečte s určým prijemcem, aby sa mohlo výpočet času, ktorý je v prúbežu.'; + + @override + String get imageSend_longSendTitle => 'Dlouhá transmisia'; + + @override + String imageSend_longSendBody(String duration) { + return 'Tento dôvod udrží kanál priamo na $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood routing: každý repeater v rozsahu zrňa každý paket, takže kanál zostá zajetší dlouše, než tu.'; + + @override + String get imageSend_parityTitle => 'Poučný paket pre očudenie'; + + @override + String get imageSend_paritySubtitle => + 'Jedný dodatný paket. Skúsené súhlasy nie sa uznávaú, takže to umožňuje prechovávaču opraviť obraz, pokiaľ sa jedný paket niebyl ztrácený.'; + + @override + String get imageSend_send => 'Odeslať'; + + @override + String get imageSend_cancel => 'Zastavenie'; + + @override + String get imageSend_encodeFailed => 'Tento obráz nie byla byla schována.'; + + @override + String get imageSend_codecDownloading => + 'Model prehľadovania prebeža stále stále stále prechádza.'; + + @override + String get imageSend_codecUnavailable => + 'Zobrazenie nie je dostupný na tomto zariadení.'; + + @override + String get imageSend_codecDisabled => + 'Zobrazy s prešteľkami sú v nastavení vypnené.'; + + @override + String get imageSend_deviceUnsupported => + 'Tento radiok nie môže odeslať obrazové pakety. Podeďte správne určité zařízení s oprogramovaním spolupráce 13 alebo novším.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Obrazy sa prechádzajú jako skupinové údaje, preto sa ich môžu odeslať len na kanál — nie v príbeh sa.'; + + @override + String get imageSend_tooLarge => + 'Tento obraz byl skodyrovany do viac paketov, ako umožňuje si sítka format.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return 'Obrázok odoslaný ako $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Obraz nemôžlo odeslať: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Vysyťanie obrazu — pakét $sent z $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Vęzlo $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return 'Otrzymané $received z $total pakotí'; + } + + @override + String get receivedImage_queued => 'Čekanie na dekódovanie'; + + @override + String get receivedImage_tapToDecode => 'Kliknite, aby dekódovať'; + + @override + String get receivedImage_decoding => 'Rekonstrukcia… o čoľve 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Obraz nieješťajný — $received z $total paciek príšlo'; + } + + @override + String get receivedImage_corrupt => 'Obraz nemôžu byť prepojený'; + + @override + String get receivedImage_decoderMissing => + 'Otrzymaná slúba — dekódovanie slúby je vypadejce'; + + @override + String get receivedImage_evicted => 'Obraz nemá uložený'; + + @override + String get receivedImage_retry => 'Zkôr to opítajte'; + + @override + String get receivedImage_decodeAgain => 'Zdeľte sa znovu'; + + @override + String get receivedImage_openSettings => 'Založte'; + + @override + String get receivedImage_tapToProcess => 'Ukliknite, aby sa príjomili'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return '$bytes bajtov · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds s'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Nad 158 bajtov: odoslané najviac $count-krát'; + } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 064391b7..6fad9840 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -111,6 +111,46 @@ class AppLocalizationsSl extends AppLocalizations { @override String get messageStatus_repeated => 'Slišal sem večkrat'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Omogoči slike iz URL'; + + @override + String get urlImage_possible => + 'Mogoča slika iz URL; omogočite jo v Nastavitvah.'; + @override String get common_reboot => 'Ponoviti'; @@ -367,42 +407,64 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_radioSettingsUpdated => 'Radio nastavitve posodobljene'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Radio teh nastavitev ni uveljavil'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regioni'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Upravljanje opisanih regionov'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Regijonsko upravljanje'; + + @override + String get settings_regionNameHint => 'Naslov občine'; + + @override + String get settings_regionAddRegion => 'Dodaj region'; + + @override + String get settings_regionFetchRegions => + 'Pobražujte izvajne področja iz ponavljalnikov'; + + @override + String get settings_regionFetchRegionsFail => 'Nižnih občin ni izkrali'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Taj oblasi je več pomanjkan.'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Naziv Regiona'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Oblikačena regija'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Prihoda Region'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Ostani $region iz listy regionov?'; } @override @@ -494,15 +556,31 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_telemetryEnvironmentMode => 'Način delovanja okolja telemetrije'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Lokacija oglasa'; @override String get settings_advertLocationSubtitle => 'Vključi lokacijo v oglas.'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Samodejni zero-hop oglas ob posodobitvi GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Ko se GPS lokacija spremeni, pošlji zero-hop oglas (zahteva lokacijo v oglasu).'; + @override String get settings_multiAck => 'Več potrdil'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Način telemetrije posodobljen'; @@ -602,15 +680,31 @@ class AppLocalizationsSl extends AppLocalizations { @override String get settings_infoPublicKey => 'Javni ključ'; + @override + String get settings_publicKeyCopied => 'Javni ključ kopiran'; + @override String get settings_infoContactsCount => 'Število stikov'; @override String get settings_infoChannelCount => 'Število kanalov'; + @override + String get settings_infoHardware => 'Hardver'; + + @override + String get settings_infoFirmware => 'Pravilnik'; + @override String get settings_presets => 'Prednastavitve'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frekvenca (MHz)'; @@ -633,7 +727,9 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_txPower => 'TX Moč (dBm)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Neveljavna TX moč (0-22 dBm)'; @@ -641,6 +737,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get settings_clientRepeat => 'Neovadno ponavljanje'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Omogočite temu naprave, da ponavlja paketne sporočila za druge.'; @@ -723,6 +824,51 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_languageUk => 'Ukrajinsko'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 bajt'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 bite'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 bite'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 bite'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Omogoči sledenje sporočilom'; @@ -757,6 +903,13 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Pokaži obvestilo ob prejemu novih sporočil.'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Obvestila o sporočilih kanala'; @@ -869,6 +1022,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0–4,35 V)'; + @override String get appSettings_mapDisplay => 'Prikaz zemljevida'; @@ -925,6 +1081,28 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_lastWeek => 'Prejšnji teden'; + @override + String get appSettings_rasterTileSource => 'Vir rastrskih ploščic'; + + @override + String get appSettings_stadiaEndpoint => 'Končna točka Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Ključ API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Obvezno za uporabo Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Nastavljeno: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Vnesite svoj ključ API za Stadia Maps. Aplikacija ga uporablja za zahteve rastrskih ploščic.'; + @override String get appSettings_offlineMapCache => 'Shramba zemljevidov brez povezave'; @@ -1018,6 +1196,29 @@ class AppLocalizationsSl extends AppLocalizations { return 'Izbrišem $contactName iz stikov?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Upravljaj Ponovitve'; @@ -1167,6 +1368,18 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_private => 'Zasebni'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Uredi kanal'; @@ -1299,6 +1512,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_publicChannelAdded => 'javna skupnost dodana'; + @override + String get channels_noFreeSlots => 'Vsa mesta za kanale so zasedena'; + @override String get channels_sortBy => 'Sortiraj po'; @@ -1355,17 +1571,30 @@ class AppLocalizationsSl extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Osebno: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Region: brak'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Vablajte region'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Jasna regija'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Še ni sporočil.'; @@ -1420,9 +1649,27 @@ class AppLocalizationsSl extends AppLocalizations { return 'Ponovit $current/$max'; } + @override + String get chat_selectSendAction => 'Izberite dejanje pošiljanja'; + @override String get chat_sendGif => 'Pošlji GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Pošlji sliko prek MeshCore'; + + @override + String get chat_imagePickFailed => 'Nispeval sem tega ta slik'; + + @override + String get chat_receivedGif => 'Otrvljen GIF'; + @override String get chat_reply => 'Odgovori'; @@ -1432,6 +1679,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_me => 'jaz'; + @override + String get reaction_report => 'Emoji reakcije'; + @override String get emojiCategorySmileys => 'Emoji'; @@ -1578,7 +1828,7 @@ class AppLocalizationsSl extends AppLocalizations { String get routing_modeAuto => 'Avto'; @override - String get routing_modeFlood => 'Poplavo'; + String get routing_modeFlood => 'Flood'; @override String get routing_modeManual => 'Navodilo'; @@ -1636,7 +1886,7 @@ class AppLocalizationsSl extends AppLocalizations { String get routing_qualityWorked => 'Izpolnil'; @override - String get routing_qualityFlood => 'Slišano preko poplave'; + String get routing_qualityFlood => 'Slišano prek flooda'; @override String get routing_qualityUntested => 'Ne preizkušen'; @@ -1655,22 +1905,22 @@ class AppLocalizationsSl extends AppLocalizations { } @override - String get routing_floodDelivery => 'Dostava zaradi poplave'; + String get routing_floodDelivery => 'Dostava prek flooda'; @override String get pathEditor_title => 'Izgradnja poti'; @override String pathEditor_hopCounter(int count) { - return '$count od 64 različnih sort hropa'; + return '$count od 64 skokov'; } @override String get pathEditor_noHops => - 'Še niso dodani hmelji. Za dodajanje hmelja v vrstnem redu kliknite na povezavo spodaj, ali pa shranite brez dodanega hmelja, da ga lahko posredujete neposredno.'; + 'Še niso dodani skoki. Za dodajanje skokov v vrstnem redu kliknite na ponovitelje spodaj, ali pa shranite brez dodanih skokov, da ga lahko posredujete neposredno.'; @override - String get pathEditor_addHops => 'Dodajte suho travo v skladu s postopkom.'; + String get pathEditor_addHops => 'Dodajte skoke v vrstnem redu.'; @override String get pathEditor_searchRepeaters => 'Iskanje ponovitev'; @@ -1697,7 +1947,7 @@ class AppLocalizationsSl extends AppLocalizations { String get pathEditor_usePath => 'Uporabite to poto'; @override - String get pathEditor_removeHop => 'Odstranite hmelj'; + String get pathEditor_removeHop => 'Odstranite skok'; @override String get pathEditor_unknownHop => 'Neznani ponovitelj'; @@ -1718,6 +1968,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_path => 'Pot'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Ključ javnega tipa'; @@ -1725,7 +1978,7 @@ class AppLocalizationsSl extends AppLocalizations { String get chat_compressOutgoingMessages => 'Stisnite izhodne sporočila'; @override - String get chat_floodForced => 'Porolni (nasilje).'; + String get chat_floodForced => 'Flood (vsiljeno)'; @override String get chat_directForced => 'Nezglašen (nasilje)'; @@ -1736,7 +1989,7 @@ class AppLocalizationsSl extends AppLocalizations { } @override - String get chat_floodAuto => 'Preplavljenje (avtomatizirano)'; + String get chat_floodAuto => 'Flood (samodejno)'; @override String get chat_direct => 'Neposredni'; @@ -1755,6 +2008,12 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_newMessages => 'Nove novice'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Odpreti povezavo?'; @@ -1800,6 +2059,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get map_centerOnNode => 'Centriraj na vozlišče'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Podrobnosti'; @@ -1819,6 +2081,10 @@ class AppLocalizationsSl extends AppLocalizations { String get map_noNodesWithLocation => 'Nihče od notranjih elementov nima podatkov o lokaciji.'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Omrežje morajo deliti svoje GPS koordinate,\nda se prikazao na zemljeobrazniku.'; @@ -1960,6 +2226,16 @@ class AppLocalizationsSl extends AppLocalizations { @override String get map_showGuessedLocations => 'Pokaži lokacije domnevnih not.'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Prikaži odkritja kontaktov'; @@ -1981,6 +2257,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get map_manageRepeater => 'Upravljajte Ponovitve'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Pritisnite na vozlišča, da jih dodate poti.'; @@ -2074,6 +2353,42 @@ class AppLocalizationsSl extends AppLocalizations { return 'Poslovniški izniki: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2151,6 +2466,12 @@ class AppLocalizationsSl extends AppLocalizations { @override String get login_enterPassword => 'Vnesite geslo'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Shrani geslo'; @@ -2166,6 +2487,9 @@ class AppLocalizationsSl extends AppLocalizations { String get login_roomDescription => 'Vnesite geslo v sobo za dostop do nastavitev in statusa.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Usmerjanje'; @@ -2176,7 +2500,7 @@ class AppLocalizationsSl extends AppLocalizations { String get login_autoUseSavedPath => 'Avto (uporabi shranjeno pot)'; @override - String get login_forceFloodMode => 'Nasilje obvezati v način'; + String get login_forceFloodMode => 'Vsili flood način'; @override String get login_managePaths => 'Upravljajte Potniške Proti'; @@ -2204,6 +2528,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get common_clear => 'Ponoviti'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Trenutna pot'; @@ -2229,6 +2556,12 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_guestTools => 'Naložila za goste'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Stanje'; @@ -2254,7 +2587,7 @@ class AppLocalizationsSl extends AppLocalizations { String get repeater_neighbors => 'Sosedi'; @override - String get repeater_neighborsSubtitle => 'Pogledati nič sosednjih hopjev.'; + String get repeater_neighborsSubtitle => 'Pogledati nič sosednjih skokov.'; @override String get repeater_settings => 'Nastavitve'; @@ -2350,17 +2683,17 @@ class AppLocalizationsSl extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Skupno: $total, Poplava: $flood, Neposredno: $direct'; + return 'Skupno: $total, Flood: $flood, Neposredno: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Skupno: $total, Poplava: $flood, Neposredno: $direct'; + return 'Skupno: $total, Flood: $flood, Neposredno: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Prah: $flood, Neposredni: $direct'; + return 'Flood: $flood, Neposredni: $direct'; } @override @@ -2467,7 +2800,7 @@ class AppLocalizationsSl extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => 'Razpon Obvestil o Poplavah'; + String get repeater_floodAdvertInterval => 'Razpon Flood Oglasov'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2615,14 +2948,50 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Biti, ki so bila uporabljena za kodiranje ID-ja tega releja v oznakah za zaznavanje pot/kroga, imajo naslednje velikosti: 0=1 bit (256 ID-jev, do 64 skokov), 1=2 biti (65.000 ID-jev, do 32 skokov), 2=3 biti (16 milijonov ID-jev, do 21 skokov). V različicah 1.13 in starejših se ustvarjajo večbitne poti – vendar se to zgodi šele, ko je omrežje vklopljeno v različicah 1.14 in kasnejših.'; + 'Bajti, uporabljeni za kodiranje ID-ja tega repetitorja v oznakah flood poti/zaznavanja zank. 0=1 bajt (256 ID-jev, do 64 skokov), 1=2 bajta (65.000 ID-jev, do 32 skokov), 2=3 bajti (16 milijonov ID-jev, do 21 skokov). Vdelana programska oprema pred v1.14 je vedno uporabljala 1-bajtne poti; v1.14 in novejše je mogoče nastaviti na 2- ali 3-bajtne poti.'; @override - String get repeater_txDelay => 'Zatemnitevanje zaradi poplav v Texasu'; + String get repeater_keySettings => 'Zmeničke ključe identitete'; + + @override + String get repeater_keySettingsSubtitle => + 'Zamenjajte publican ali privatni ključni par'; + + @override + String get repeater_prvKey => 'Privarna ključa'; + + @override + String get repeater_prvKeyHelper => + 'Nova privatna ključa za prekaznik, 128- znakovni šestnastik.'; + + @override + String get repeater_generatePrvKey => 'Sporočna ključna para'; + + @override + String get repeater_stopGeneratingPrvKey => + 'Prekajanje odkrivanja ključne paro'; + + @override + String get repeater_pubKey => 'Public key (publična ključa)'; + + @override + String get repeater_pubKeyHelper => + 'Taj je publicna ključ, ki pomeni pripovedno privatno ključ. Ne možeš to vrediti direktno.'; + + @override + String get repeater_pubKeyPrefix => 'Poželana prefiks'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Najdi publicen ključ, ki začne s tih hexnih čitov. Očekivani pokusi: $tries.'; + } + + @override + String get repeater_txDelay => 'Flood TX zakasnitev'; @override String get repeater_txDelayHelper => - 'Uporaba intervalov za ponovno pošiljanje v primeru prometa zaradi poplav, kot pomnožnik časovne trajanje paketa (0-2, privzeto 0,5). Veje vrednost = manjše kolizije, vendar počasnejše dostavo.'; + 'Uporaba intervalov za ponovno pošiljanje v primeru flood prometa, kot pomnožnik časovne trajanje paketa (0-2, privzeto 0,5). Veje vrednost = manjše kolizije, vendar počasnejše dostavo.'; @override String get repeater_directTxDelay => 'Neposredni časovno odlašanje'; @@ -2649,11 +3018,11 @@ class AppLocalizationsSl extends AppLocalizations { String get repeater_actionsTitle => 'Dejanja'; @override - String get repeater_sendAdvert => 'Pošlji oglas o poplavah'; + String get repeater_sendAdvert => 'Pošlji flood oglas'; @override String get repeater_sendAdvertSubtitle => - 'Razpustite oglas o poplavah preko omrežja.'; + 'Razpošlji flood oglas preko omrežja.'; @override String get repeater_sendAdvertZeroHop => @@ -2715,6 +3084,17 @@ class AppLocalizationsSl extends AppLocalizations { String get repeater_refreshPrivacyMode => 'Ponovno aktiviraj način zasebnosti'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label je bil/a posodobljen/a'; @@ -2831,7 +3211,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpSetFloodMax => - 'Nastavi največjo število skokov za vstopne poplave (če je >= maks, paket ni usmerjen)'; + 'Nastavi največje število skokov za vhodni flood paket (če je >= maks, paket ni posredovan)'; @override String get repeater_cliHelpSetIntThresh => @@ -2851,7 +3231,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Nastavi časovno obmesto v urah za pošiljanje plovilnega oglasnega paketa. Nastavi na 0 za onemogočanje.'; + 'Nastavi časovno obmesto v urah za pošiljanje flood oglasnega paketa. Nastavi na 0 za onemogočanje.'; @override String get repeater_cliHelpSetGuestPassword => @@ -2878,7 +3258,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - 'Nastavi faktor, ki se množi s časom delovanja za paket v načinu poplavnega režima in z randomiziranim sistemom slotov, da odvrne njegovo posredovanje. (da se zmanjša verjetnost kolizij)'; + 'Nastavi faktor, ki se množi s časom delovanja za paket v flood načinu in z randomiziranim sistemom slotov, da odvrne njegovo posredovanje. (da se zmanjša verjetnost kolizij)'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2941,7 +3321,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(Serija samo) Navaja vse definirane regije in trenutne poplave dovolilnosti.'; + '(Serija samo) Navaja vse definirane regije in trenutna dovoljenja za flood.'; @override String get repeater_cliHelpRegionLoad => @@ -3008,6 +3388,75 @@ class AppLocalizationsSl extends AppLocalizations { String get repeater_commandsListNote => 'Opomba: za različne ukaze \"nastavi ...\" obstaja tudi ukaz \"dobi ...\".'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Neveljavna frekvenca (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 do 30 dBm'; + + @override + String get repeater_recvErrors => 'Napake sprejema'; + + @override + String get room_postsStored => 'Objave'; + + @override + String get room_postsPushed => 'Poslane objave'; + + @override + String get repeater_cliRegionLoadActive => + 'Način nalaganja regij: pošljite eno ime regije na vrstico, zamaknjeno s presledki pod nadrejeno regijo (dodajte F za imenom, da dovolite flood). Vrstice ne prejmejo odgovora. Pošljite prazno vrstico za konec, nato pa \"region save\", da shranite rezultat.'; + + @override + String get repeater_cliRegionLoadHint => + 'Vrstica regije ali prazna vrstica za konec'; + + @override + String get repeater_cliRegionLoadEnd => '(konec nalaganja regij)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definira verigo regij z enim ukazom: vsako ime se doda pod prejšnje; \"name,parent\" doda ime in nato nadaljuje pod navedeno nadrejeno regijo. Odgovori s seznamom regij.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Nastavi največje število skokov za posredovanje flood paketov brez določenega regijskega obsega (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Nastavi največje število skokov za posredovanje flood oglasov (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Prikaže največje število skokov za flood pakete brez določenega regijskega obsega.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Prikaže največje število skokov za flood oglase.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Preklopi RX ojačanje (LNA) LoRa front-end modula. Plošče brez njega odgovorijo z \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Preklopi TX ojačanje (PA) LoRa front-end modula. Plošče brez njega odgovorijo z \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Prikaže, ali je RX ojačanje LoRa front-end modula vklopljeno.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Prikaže, ali je TX ojačanje LoRa front-end modula vklopljeno.'; + + @override + String get repeater_bridgeNote => + 'Na voljo samo v vdelani programski opremi, zgrajeni z mostom (RS232 ali ESP-NOW).'; + @override String get repeater_general => 'Općenito'; @@ -3177,11 +3626,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Prikazuje časovno obdobje lokalne reklame v minutah.'; + 'Prikazuje časovno obdobje lokalnega oglasa v minutah.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Prikaže časovno obdobje, ko se prikazuje oglas o poplavah, v urah.'; + 'Prikaže časovno obdobje flood oglasa, v urah.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3199,7 +3648,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Prikazuje faktor zamude v načinu delovanja pri plavlju.'; + 'Prikazuje faktor zamude v flood načinu.'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3207,7 +3656,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Prikazuje največjo število, kolikokrat lahko voda doseže najvišjo višino.'; + 'Prikazuje največje število skokov za flood.'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3295,11 +3744,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Navaja regije, ki dovoljujejo promet v času poplav.'; + 'Navaja regije, ki dovoljujejo flood promet.'; @override String get repeater_cliHelpRegionListDenied => - 'Navaja regije, ki preprečujejo promet zaradi poplav.'; + 'Navaja regije, ki preprečujejo flood promet.'; @override String get repeater_cliHelpStatsPackets => @@ -3586,7 +4035,7 @@ class AppLocalizationsSl extends AppLocalizations { String get channelPath_unknownPath => 'Neznano'; @override - String get channelPath_floodPath => 'Prebivalstvo'; + String get channelPath_floodPath => 'Flood'; @override String get channelPath_directPath => 'Neposredni'; @@ -3859,7 +4308,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get pathTrace_someHopsNoLocation => - 'Ena ali več hmelju manjka lokacija!'; + 'Enemu ali več skokom manjka lokacija!'; @override String get pathTrace_clearTooltip => 'Počisti pot'; @@ -4072,10 +4521,10 @@ class AppLocalizationsSl extends AppLocalizations { String get contacts_contactImportFailed => 'Kontakt ni bil uspešno uvožen.'; @override - String get contacts_zeroHopAdvert => 'Reklama brez posrednikov'; + String get contacts_zeroHopAdvert => 'Oglas brez posrednikov'; @override - String get contacts_floodAdvert => 'Poplavna oglás'; + String get contacts_floodAdvert => 'Flood oglas'; @override String get contacts_copyAdvertToClipboard => 'Kopiraj oglas v odložišče'; @@ -4083,6 +4532,23 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Dodaj stik iz odložišča'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Kopiraj stik v Odložišče'; @@ -4213,6 +4679,10 @@ class AppLocalizationsSl extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Zadnjič videno'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Nastavitve stikov'; @@ -4317,6 +4787,12 @@ class AppLocalizationsSl extends AppLocalizations { @override String get radioStats_screenTitle => 'Radijske statistike'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Povežite se z napravo, da si ogledate statistiko o radiju.'; @@ -4375,6 +4851,43 @@ class AppLocalizationsSl extends AppLocalizations { @override String get translation_title => 'Prevod'; + @override + String get imageMessages_enableTitle => 'Pozivni izkričile slike'; + + @override + String get imageMessages_enableSubtitle => + 'Prešli vzorce pre mrežo. Potrebno je jednokratno stworiti model vzorca.'; + + @override + String get imageMessages_modelSectionTitle => 'Obrazni model'; + + @override + String get imageMessages_downloadModel => 'Storba'; + + @override + String get imageMessages_cancelDownload => 'Odločite'; + + @override + String get imageMessages_removeModel => 'Ubrani model'; + + @override + String get imageMessages_modelReady => 'Gotov'; + + @override + String get imageMessages_modelNotPublished => + 'Jo še niso izdana — ta izdelka te ne može prebaviti.'; + + @override + String get imageMessages_downloadFailed => + 'Obrazni model ne može biti preuzet.'; + + @override + String get imageMessages_autoProcessTitle => 'Avtomatizirane slike'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Katero je oblikovanje svega oblikov, ko se pošteva. Za drugo okolo časa se koristi ok. 2 GB pamične prostore; odločite se za oblikovanje s tukom.'; + @override String get translation_enableTitle => 'Omogočite prevod'; @@ -4662,4 +5175,249 @@ class AppLocalizationsSl extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Odkleni pogled od paketa'; + + @override + String get imageSend_title => 'Sločaji slik'; + + @override + String get imageSend_cropNote => + 'Zadovoljno izmenjeno na 512 × 512 · vzorovni odnos ne ohranjen'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => + 'Original text:\n\nThe early bird catches the worm.\n\nTranslation:\n\nPojdi prvi, zlati v kroku.'; + + @override + String get imageSend_onAirSize => 'Na vodi'; + + @override + String get imageSend_quality => 'Kakovost'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Vysoko'; + + @override + String get imageSend_packetsLabel => 'Pakete'; + + @override + String get imageSend_airtimeLabel => 'Čas v eteru'; + + @override + String get imageSend_sizeLabel => 'Napravo'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Naslušniki radio neznane'; + + @override + String get imageSend_radioUnknownBody => + 'Poučajte se na stroj, da se lahko izračunuje čas v prikazu.'; + + @override + String get imageSend_longSendTitle => 'Dluga preposlana'; + + @override + String imageSend_longSendBody(String duration) { + return 'Ovo bo ohranilo kanal prihodno za obliko $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood usmerjanje: vsak ponovitelj v dosegu znova odda vsak paket, zato je kanal zaseden dlje kot to.'; + + @override + String get imageSend_parityTitle => 'Pobavni paket zdržbe'; + + @override + String get imageSend_paritySubtitle => + 'Jedna dodatna paczka. Grupni izjasi ne izvajajo potvarnosti, pa ta izdelka omogoča preuzimanju ponovno izgleda, če je zgubjen pojedni paket.'; + + @override + String get imageSend_send => 'Posyłaj'; + + @override + String get imageSend_cancel => 'Odločite'; + + @override + String get imageSend_encodeFailed => 'Ovo slikovo ne more biti zakodirano.'; + + @override + String get imageSend_codecDownloading => + 'Obrazni model še pospeva preborjanje.'; + + @override + String get imageSend_codecUnavailable => + 'Poslanje slike nema na tem zelo naročnem naročnem.'; + + @override + String get imageSend_codecDisabled => 'Obrazi s pomanjkanjem so v nastavnih.'; + + @override + String get imageSend_deviceUnsupported => + 'Taj radio ne može posredovati slike pakuete. Prepoštijo izbirni napravnik s kompanijskimi programi na čevem 13 ali novšejšim.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Obrazy se pojavijo kot skupnih podatkov, pa lahko ih poslujejo samo na kanal — ne v prilogih.'; + + @override + String get imageSend_tooLarge => + 'Taj slik je zakodiran v viših pakotnih od športne formate, ki omogoča mrežni format.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return 'Slika poslana kot $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Obraz ne može biti poslany: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Prekazivanje izkaza — paket $sent od $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Vrtitev $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return 'Otrteno od $received na $total poslovanih potokov'; + } + + @override + String get receivedImage_queued => 'Čekanje, da se dekodira'; + + @override + String get receivedImage_tapToDecode => 'Kliknite, da razkrivete'; + + @override + String get receivedImage_decoding => + 'Ostvarjanje… o prihodnosti za okolo 1 s'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Obraz nije kompletan — $received od $total poslaničev je prishodil'; + } + + @override + String get receivedImage_corrupt => 'Obraz ne more lahko rekonstruirati'; + + @override + String get receivedImage_decoderMissing => + 'Otrgena slika — dekodirana slika je izključena'; + + @override + String get receivedImage_evicted => 'Obraz ni več niso zakajiren'; + + @override + String get receivedImage_retry => 'Pokušajte znova'; + + @override + String get receivedImage_decodeAgain => 'Dekodiraj ponovno'; + + @override + String get receivedImage_openSettings => 'Nastavite'; + + @override + String get receivedImage_tapToProcess => 'Kliknij za obravnavanje'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'paketov', + one: 'paket', + ); + return '$bytes bajtov · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds s'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes m $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Nad 158 bajtov: poslano največ $count-krat'; + } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1d1ec527..a1d1037a 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -24,7 +24,7 @@ class AppLocalizationsSv extends AppLocalizations { String get common_cancel => 'Avbryt'; @override - String get common_ok => 'Okej'; + String get common_ok => 'OK'; @override String get common_connect => 'Anslut'; @@ -42,10 +42,10 @@ class AppLocalizationsSv extends AppLocalizations { String get common_deleteAll => 'Ta bort alla'; @override - String get common_close => 'Stänga'; + String get common_close => 'Stäng'; @override - String get common_done => 'Done'; + String get common_done => 'Klar'; @override String get common_edit => 'Redigera'; @@ -63,7 +63,7 @@ class AppLocalizationsSv extends AppLocalizations { String get common_connected => 'Ansluten'; @override - String get common_disconnected => 'Ansluten'; + String get common_disconnected => 'Frånkopplad'; @override String get common_create => 'Skapa'; @@ -96,13 +96,13 @@ class AppLocalizationsSv extends AppLocalizations { String get common_undo => 'Ångra'; @override - String get messageStatus_sent => 'Sen'; + String get messageStatus_sent => 'Skickat'; @override - String get messageStatus_delivered => 'Levererad'; + String get messageStatus_delivered => 'Levererat'; @override - String get messageStatus_pending => 'Skicka'; + String get messageStatus_pending => 'Skickar'; @override String get messageStatus_failed => 'Misslyckades med att skicka'; @@ -111,7 +111,47 @@ class AppLocalizationsSv extends AppLocalizations { String get messageStatus_repeated => 'Hördes upprepade gånger'; @override - String get common_reboot => 'Start om'; + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Aktivera URL-bilder'; + + @override + String get urlImage_possible => + 'Möjlig URL-bild; aktivera den i Inställningar.'; + + @override + String get common_reboot => 'Starta om'; @override String get common_loading => 'Laddar...'; @@ -157,7 +197,7 @@ class AppLocalizationsSv extends AppLocalizations { String get tcpHostHint => '192.168.40.10'; @override - String get tcpPortLabel => 'Hamn'; + String get tcpPortLabel => 'Port'; @override String get tcpPortHint => '5000'; @@ -181,7 +221,7 @@ class AppLocalizationsSv extends AppLocalizations { 'TCP-transport fungerar inte på denna plattform.'; @override - String get tcpErrorTimedOut => 'TCP-anslutningen har tidsut gått.'; + String get tcpErrorTimedOut => 'Tidsgränsen för TCP-anslutningen överskreds.'; @override String tcpConnectionFailed(String error) { @@ -225,11 +265,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get usbErrorOpenFailed => - 'Misslyckades med att öppna det valda USB-enheten.'; + 'Det gick inte att öppna den valda USB-enheten.'; @override String get usbErrorConnectFailed => - 'Kunde inte ansluta till det valda USB-enheten.'; + 'Det gick inte att ansluta till den valda USB-enheten.'; @override String get usbErrorUnsupported => @@ -246,10 +286,10 @@ class AppLocalizationsSv extends AppLocalizations { @override String get usbErrorConnectTimedOut => - 'Anslutningen har tidsutgått. Se till att enheten har rätt USB-firmware.'; + 'Anslutningen tog för lång tid. Kontrollera att enheten har USB Companion-firmware.'; @override - String get usbFallbackDeviceName => 'Web-serieenhet'; + String get usbFallbackDeviceName => 'Web Serial-enhet'; @override String get usbStatus_notConnected => 'Välj en USB-enhet'; @@ -269,7 +309,7 @@ class AppLocalizationsSv extends AppLocalizations { String get scanner_scanning => 'Söker efter enheter...'; @override - String get scanner_connecting => 'Anslutning...'; + String get scanner_connecting => 'Ansluter...'; @override String get scanner_disconnecting => 'Anslutning bryts...'; @@ -311,7 +351,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get scanner_chromeRequiredMessage => - 'Denna webbapplikation kräver Google Chrome oder en Chromium-baserader webbläsare för Bluetooth-stöd.'; + 'Den här webbappen kräver Google Chrome eller en Chromium-baserad webbläsare för Bluetooth-stöd.'; @override String get scanner_enableBluetooth => 'Aktivera Bluetooth'; @@ -330,14 +370,14 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_title => 'Inställningar'; @override - String get settings_deviceInfo => 'Enhetens information'; + String get settings_deviceInfo => 'Enhetsinformation'; @override String get settings_appSettings => 'Appinställningar'; @override String get settings_appSettingsSubtitle => - 'Meddelanden, notiser och kartinställningar'; + 'Notifieringar, meddelanden och kartinställningar'; @override String get settings_nodeSettings => 'Nodinställningar'; @@ -366,49 +406,70 @@ class AppLocalizationsSv extends AppLocalizations { 'Radioinställningarna har uppdaterats'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Radion tillämpade inte dessa inställningar'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Regioner'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Hämtade regioner'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Regionhantering'; + + @override + String get settings_regionNameHint => 'Ange regionnamn'; + + @override + String get settings_regionAddRegion => 'Lägg till region'; + + @override + String get settings_regionFetchRegions => 'Hämta regioner från repeaters'; + + @override + String get settings_regionFetchRegionsFail => 'Ingen region hittades'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Den här regionen har redan lagts till'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Regionnamn'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Regionen har tagits bort'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Radera region'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Ta bort “$region” från regionlistan?'; } @override String get settings_location => 'Plats'; @override - String get settings_locationSubtitle => 'GPS koordinater'; + String get settings_locationSubtitle => 'GPS-koordinater'; @override String get settings_locationUpdated => 'Plats uppdaterad'; @@ -437,7 +498,7 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_latitude => 'Latitud'; @override - String get settings_longitude => 'Längdgrad'; + String get settings_longitude => 'Longitud'; @override String get settings_contactSettings => 'Kontaktinställningar'; @@ -486,10 +547,14 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_telemetryBaseMode => 'Telemetribasläge'; @override - String get settings_telemetryLocationMode => 'Telemetritillstånd för plats'; + String get settings_telemetryLocationMode => 'Telemetriläge för position'; @override - String get settings_telemetryEnvironmentMode => 'Telemetri miljöläge'; + String get settings_telemetryEnvironmentMode => 'Telemetriläge för miljö'; + + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; @override String get settings_advertLocation => 'Annonsplacering'; @@ -497,9 +562,21 @@ class AppLocalizationsSv extends AppLocalizations { @override String get settings_advertLocationSubtitle => 'Inkludera plats i annonsen'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Automatisk nollhoppsannons vid GPS-uppdatering'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'När GPS-positionen ändras skickas en nollhoppsannons (kräver plats i annonsen).'; + @override String get settings_multiAck => 'Flera bekräftelser'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Telemetri-läge uppdaterat'; @@ -507,23 +584,23 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_actions => 'Åtgärder'; @override - String get settings_deleteAllPaths => 'Delete All Paths'; + String get settings_deleteAllPaths => 'Radera alla rutter'; @override String get settings_deleteAllPathsSubtitle => - 'Clear all path data from contacts.'; + 'Rensa all ruttdata från kontakter.'; @override - String get settings_sendAdvertisement => 'Skicka Annons'; + String get settings_sendAdvertisement => 'Skicka annons'; @override - String get settings_sendAdvertisementSubtitle => 'Sändning finns nu'; + String get settings_sendAdvertisementSubtitle => 'Sänd din närvaro nu'; @override String get settings_advertisementSent => 'Annons skickad'; @override - String get settings_syncTime => 'Synkroniseringstid'; + String get settings_syncTime => 'Synkronisera tid'; @override String get settings_syncTimeSubtitle => 'Ställ enheten till telefonens tid'; @@ -542,7 +619,7 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_rebootDevice => 'Starta om enheten'; @override - String get settings_rebootDeviceSubtitle => 'Starta MeshCore-enheten'; + String get settings_rebootDeviceSubtitle => 'Starta om MeshCore-enheten'; @override String get settings_rebootDeviceConfirm => @@ -552,18 +629,18 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_debug => 'Felsök'; @override - String get settings_companionDebugLog => 'Följande felsökningslogg'; + String get settings_companionDebugLog => 'Companion-felsökningslogg'; @override String get settings_companionDebugLogSubtitle => 'BLE/TCP/USB-kommandon, svar och rådata'; @override - String get settings_appDebugLog => 'Appfelsökning'; + String get settings_appDebugLog => 'Appens felsökningslogg'; @override String get settings_appDebugLogSubtitle => - 'Applikations felsökningsmeddelanden'; + 'Felsökningsmeddelanden från appen'; @override String get settings_about => 'Om'; @@ -574,11 +651,11 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get settings_aboutLegalese => '2024 MeshCore Öppen Källkodsprojekt'; + String get settings_aboutLegalese => '2026 MeshCore Open Source Project'; @override String get settings_aboutDescription => - 'En öppen källkods Flutter-klient för MeshCore LoRa meshnätverksenheter.'; + 'En Flutter-klient med öppen källkod för MeshCore-enheter i LoRa-meshnät.'; @override String get settings_aboutOpenMeteoAttribution => @@ -597,17 +674,33 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_infoBattery => 'Batteri'; @override - String get settings_infoPublicKey => 'Allmänt nyckel'; + String get settings_infoPublicKey => 'Publik nyckel'; @override - String get settings_infoContactsCount => 'Kontakterantal'; + String get settings_publicKeyCopied => 'Publik nyckel kopierad'; @override - String get settings_infoChannelCount => 'Kanalantal'; + String get settings_infoContactsCount => 'Antal kontakter'; + + @override + String get settings_infoChannelCount => 'Antal kanaler'; + + @override + String get settings_infoHardware => 'Hardware'; + + @override + String get settings_infoFirmware => 'Firmware'; @override String get settings_presets => 'Fördefinierade inställningar'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Frekvens (MHz)'; @@ -621,7 +714,7 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_bandwidth => 'Bandbredd'; @override - String get settings_spreadingFactor => 'Spreadingfaktor'; + String get settings_spreadingFactor => 'Spridningsfaktor'; @override String get settings_codingRate => 'Kodningsgrad'; @@ -630,7 +723,9 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_txPower => 'TX-effekt (dBm)'; @override - String get settings_txPowerHelper => '0 – 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Ogiltig TX-effekt (0-22 dBm)'; @@ -638,6 +733,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get settings_clientRepeat => 'Upprepa utan elnät'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Låt enheten repetera nätpaket för andra användare.'; @@ -664,10 +764,10 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_themeSystem => 'Systemstandard'; @override - String get appSettings_themeLight => 'Ljus'; + String get appSettings_themeLight => 'Ljust'; @override - String get appSettings_themeDark => 'Mörk'; + String get appSettings_themeDark => 'Mörkt'; @override String get appSettings_language => 'Språk'; @@ -685,10 +785,10 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_languageEs => 'Spanska'; @override - String get appSettings_languageDe => 'Tyskt'; + String get appSettings_languageDe => 'Tyska'; @override - String get appSettings_languagePl => 'Polsk'; + String get appSettings_languagePl => 'Polska'; @override String get appSettings_languageSl => 'Sloveniska'; @@ -709,7 +809,7 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_languageNl => 'Nederländska'; @override - String get appSettings_languageSk => 'Sloveniska'; + String get appSettings_languageSk => 'Slovakiska'; @override String get appSettings_languageBg => 'Bulgariska'; @@ -720,78 +820,131 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_languageUk => 'Ukrainska'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 byte'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 byte'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 byte'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 byte'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Aktivera meddelandespårning'; @override String get appSettings_enableMessageTracingSubtitle => - 'Visa detaljerade metadata om dirigering och tidsinställningar för meddelanden'; + 'Visa detaljerad routing- och tidsmetadata för meddelanden'; @override - String get appSettings_notifications => 'Meddelanden'; + String get appSettings_notifications => 'Notifieringar'; @override - String get appSettings_enableNotifications => 'Aktivera Notifikationer'; + String get appSettings_enableNotifications => 'Aktivera notifieringar'; @override String get appSettings_enableNotificationsSubtitle => - 'Ta emot notiser för meddelanden och reklam'; + 'Ta emot notifieringar för meddelanden och annonser'; @override String get appSettings_notificationPermissionDenied => 'Tillåtelse för notifikationer nekad'; @override - String get appSettings_notificationsEnabled => 'Notifikationer aktiverade'; + String get appSettings_notificationsEnabled => 'Notifieringar aktiverade'; @override - String get appSettings_notificationsDisabled => 'Meddelanden är avstängda'; + String get appSettings_notificationsDisabled => 'Notifieringar inaktiverade'; @override - String get appSettings_messageNotifications => 'Meddelandekrav'; + String get appSettings_messageNotifications => 'Meddelandenotifieringar'; @override String get appSettings_messageNotificationsSubtitle => - 'Visa notis när nya meddelanden tas emot'; + 'Visa en notifiering när nya meddelanden tas emot'; @override - String get appSettings_channelMessageNotifications => 'Kanalmeddelandena'; + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + + @override + String get appSettings_channelMessageNotifications => 'Kanalnotifieringar'; @override String get appSettings_channelMessageNotificationsSubtitle => - 'Visa notis när meddelanden i kanal mottas'; + 'Visa en notifiering när kanalmeddelanden tas emot'; @override - String get appSettings_advertisementNotifications => 'Annonsmeddelanden'; + String get appSettings_advertisementNotifications => 'Annonsnotifieringar'; @override String get appSettings_advertisementNotificationsSubtitle => - 'Visa notis när nya noder upptäcks'; + 'Visa en notifiering när nya noder upptäcks'; @override String get appSettings_messaging => 'Meddelanden'; @override - String get appSettings_clearPathOnMaxRetry => 'Rensa Vägen på Max Försök'; + String get appSettings_clearPathOnMaxRetry => + 'Rensa rutt efter maximalt antal försök'; @override String get appSettings_clearPathOnMaxRetrySubtitle => - 'Återställ kontaktväg efter 5 misslyckade försök att skicka'; + 'Återställ kontaktens rutt efter 5 misslyckade sändningsförsök'; @override String get appSettings_pathsWillBeCleared => - 'Sökvägar kommer att tömmas efter 5 misslyckade försök.'; + 'Rutter rensas efter 5 misslyckade försök'; @override String get appSettings_pathsWillNotBeCleared => - 'Sökvägar kommer inte att rensas automatiskt.'; + 'Rutter rensas inte automatiskt'; @override - String get appSettings_autoRouteRotation => 'Automatisk Rutväxling'; + String get appSettings_autoRouteRotation => 'Automatisk ruttrotation'; @override String get appSettings_autoRouteRotationSubtitle => - 'Blixtra mellan bästa vägar och flödesläge'; + 'Växla mellan de bästa rutterna och flood-läge'; @override String get appSettings_autoRouteRotationEnabled => @@ -802,18 +955,18 @@ class AppLocalizationsSv extends AppLocalizations { 'Automatisk ruttrotation är avstängd'; @override - String get appSettings_maxRouteWeight => 'Maximalt tillåtet vikt för rutten'; + String get appSettings_maxRouteWeight => 'Maximal ruttvikt'; @override String get appSettings_maxRouteWeightSubtitle => - 'Maximal vikt som en leveransväg kan ackumulera från framgångsrika leveranser.'; + 'Maximal vikt som en rutt kan samla efter lyckade leveranser'; @override String get appSettings_initialRouteWeight => 'Initial vikt för rutt'; @override String get appSettings_initialRouteWeightSubtitle => - 'Initial vikt för nyligen upptäckta vägar'; + 'Startvikt för nyligen upptäckta rutter'; @override String get appSettings_routeWeightSuccessIncrement => @@ -821,7 +974,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_routeWeightSuccessIncrementSubtitle => - 'Vikt läggs till en väg efter en lyckad leverans.'; + 'Vikt som läggs till en rutt efter en lyckad leverans'; @override String get appSettings_routeWeightFailureDecrement => @@ -829,7 +982,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_routeWeightFailureDecrementSubtitle => - 'Vikt som tagits bort från en väg efter ett misslyckat leveransförsök'; + 'Vikt som tas bort från en rutt efter en misslyckad leverans'; @override String get appSettings_maxMessageRetries => 'Maximalt antal försök'; @@ -862,15 +1015,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3,0-4,2V)'; + @override + String get appSettings_batteryLipoHv => 'LiPo HV (3,0-4,35 V)'; + @override String get appSettings_mapDisplay => 'Kartvisning'; @override - String get appSettings_showRepeaters => 'Visa återuppslag'; + String get appSettings_showRepeaters => 'Visa repeaters'; @override String get appSettings_showRepeatersSubtitle => - 'Visa återspelsnoder på kartan'; + 'Visa repeaternoder på kartan'; @override String get appSettings_showChatNodes => 'Visa Chattnoder'; @@ -897,14 +1053,14 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get appSettings_mapTimeFilter => 'Karttid Filter'; + String get appSettings_mapTimeFilter => 'Tidsfilter för kartan'; @override String get appSettings_showNodesDiscoveredWithin => 'Visa noder som upptäckts inom:'; @override - String get appSettings_allTime => 'Totalen'; + String get appSettings_allTime => 'Alla tider'; @override String get appSettings_lastHour => 'Sista timmen'; @@ -918,6 +1074,28 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_lastWeek => 'Förra veckan'; + @override + String get appSettings_rasterTileSource => 'Källa för rasterplattor'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia-slutpunkt'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API-nyckel'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Krävs för att använda Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Konfigurerad: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Ange din Stadia Maps API-nyckel. Appen använder den för förfrågningar om rasterplattor.'; + @override String get appSettings_offlineMapCache => 'Offline Kartcache'; @@ -974,7 +1152,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String contacts_searchContacts(int number, String str) { - return 'Sök kontakter...'; + return 'Sök $number$str kontakter…'; } @override @@ -989,12 +1167,12 @@ class AppLocalizationsSv extends AppLocalizations { @override String contacts_searchRepeaters(int number, String str) { - return 'Sök $number$str upprepningsenheter...'; + return 'Sök $number$str repeaters…'; } @override String contacts_searchRoomServers(int number, String str) { - return 'Sök $number$str Room-servrar...'; + return 'Sök $number$str rumsservrar…'; } @override @@ -1013,16 +1191,39 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get contacts_manageRepeater => 'Hantera Upprepare'; + String get contacts_removeFromContacts => 'Remove from contacts'; @override - String get contacts_manageRoom => 'Hantera Rumserver'; + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } @override - String get contacts_roomLogin => 'Rum Inloggning'; + String get contacts_keepChatHistory => 'Keep chat history'; @override - String get contacts_openChat => 'Öppna Chatt'; + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + + @override + String get contacts_manageRepeater => 'Hantera repeater'; + + @override + String get contacts_manageRoom => 'Hantera rumsserver'; + + @override + String get contacts_roomLogin => 'Inloggning på rumsserver'; + + @override + String get contacts_openChat => 'Öppna chatt'; @override String get contacts_editGroup => 'Redigera Grupp'; @@ -1045,7 +1246,7 @@ class AppLocalizationsSv extends AppLocalizations { String get contacts_searchOpen => 'Sök efter kontakter'; @override - String get contacts_searchClose => 'Avancerad sökning'; + String get contacts_searchClose => 'Stäng sökning'; @override String get contacts_groupName => 'Gruppnamn'; @@ -1150,7 +1351,7 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channels_public => 'Offentligt'; + String get channels_public => 'Publik'; @override String channels_via(String path) { @@ -1160,6 +1361,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_private => 'Privat'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Redigera kanal'; @@ -1197,19 +1410,19 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_channelName => 'Kanalnamn'; @override - String get channels_usePublicChannel => 'Använd Publikkanal'; + String get channels_usePublicChannel => 'Använd publik kanal'; @override - String get channels_standardPublicPsk => 'Standard allmän PSK'; + String get channels_standardPublicPsk => 'Standard-PSK för publik kanal'; @override - String get channels_pskHex => 'PSK (heks)'; + String get channels_pskHex => 'PSK (hex)'; @override String get channels_generateRandomPsk => 'Generera slumpmässig PSK'; @override - String get channels_enterChannelName => 'Ange en kanalnamn'; + String get channels_enterChannelName => 'Ange ett kanalnamn'; @override String get channels_pskMustBe32Hex => 'PSK måste vara 32 hexadecimala tecken'; @@ -1288,7 +1501,10 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channels_publicChannelAdded => 'Allmänt kanal tillagd'; + String get channels_publicChannelAdded => 'Publik kanal har lagts till'; + + @override + String get channels_noFreeSlots => 'Alla kanalplatser är upptagna'; @override String get channels_sortBy => 'Sortera efter'; @@ -1297,7 +1513,7 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_sortManual => 'Manuell'; @override - String get channels_sortAZ => 'A-Z'; + String get channels_sortAZ => 'A-Ö'; @override String get channels_sortLatestMessages => 'Senaste meddelanden'; @@ -1310,28 +1526,27 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_createPrivateChannelDesc => - 'Skyddat med en hemlig nyckel.'; + 'Säkrad med en hemlig nyckel.'; @override - String get channels_joinPrivateChannel => 'Gå med i en Privat Kanal'; + String get channels_joinPrivateChannel => 'Gå med i en privat kanal'; @override - String get channels_joinPrivateChannelDesc => - 'Ange en hemlig nyckel manuellt.'; + String get channels_joinPrivateChannelDesc => 'Skriv in nyckeln manuellt.'; @override - String get channels_joinPublicChannel => 'Gå med i den Offentliga Kanalen'; + String get channels_joinPublicChannel => 'Gå med i den publika kanalen'; @override String get channels_joinPublicChannelDesc => - 'Vem som helst kan gå med i denna kanal.'; + 'Alla kan gå med i den här kanalen.'; @override - String get channels_joinHashtagChannel => 'Gå med i en Hashtagkanal'; + String get channels_joinHashtagChannel => 'Gå med i en hashtagkanal'; @override String get channels_joinHashtagChannelDesc => - 'Väldigt enkelt att gå med i hashtag-kanaler.'; + 'Vem som helst kan gå med i hashtagkanaler.'; @override String get channels_scanQrCode => 'Skanna en QR-kod'; @@ -1351,13 +1566,26 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Region: ingen'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Välj en region'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Rensa region'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Inga meddelanden ännu'; @@ -1413,9 +1641,27 @@ class AppLocalizationsSv extends AppLocalizations { return 'Försök igen $current/$max'; } + @override + String get chat_selectSendAction => 'Välj sändningsåtgärd'; + @override String get chat_sendGif => 'Skicka GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Skicka bild via MeshCore'; + + @override + String get chat_imagePickFailed => 'Kunde inte öppna bilden'; + + @override + String get chat_receivedGif => 'Mottagit en GIF'; + @override String get chat_reply => 'Svara'; @@ -1425,6 +1671,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_me => 'Mig'; + @override + String get reaction_report => 'Emoji-reaktioner'; + @override String get emojiCategorySmileys => 'Emojis'; @@ -1484,7 +1733,7 @@ class AppLocalizationsSv extends AppLocalizations { 'Aktivera appens felsökningsloggning i inställningarna'; @override - String get debugLog_frames => 'Rammar'; + String get debugLog_frames => 'Ramar'; @override String get debugLog_rawLogRx => 'Rå Log-RX'; @@ -1551,76 +1800,77 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get chat_removePath => 'Ta bort sökväg'; + String get chat_removePath => 'Ta bort rutt'; @override String get chat_noPathHistoryYet => - 'Ingen historik ännu.\nSkicka ett meddelande för att upptäcka spår.'; + 'Ingen rutthistorik ännu.\nSkicka ett meddelande för att upptäcka rutter.'; @override String get chat_pathCleared => - 'Routen är nu fri. Nästa meddelande kommer att upptäcka rutten igen.'; + 'Rutten rensades. Nästa meddelande kommer att upptäcka rutten på nytt.'; @override - String get chat_fullPath => 'Fullständig sökväg'; + String get chat_fullPath => 'Fullständig rutt'; @override String get routing_title => 'Ruttplanering'; @override - String get routing_modeAuto => 'Bil'; + String get routing_modeAuto => 'Automatisk'; @override - String get routing_modeFlood => 'Översvämning'; + String get routing_modeFlood => 'Flood-trafik'; @override - String get routing_modeManual => 'Instruktioner'; + String get routing_modeManual => 'Manuell'; @override String get routing_modeAutoHint => - 'Väljer automatiskt den bästa kända vägen, och använder en \"flooding\"-strategi om ingen väg är känd.'; + 'Väljer automatiskt den bästa kända rutten och använder flood när ingen rutt är känd.'; @override String get routing_modeFloodHint => - 'Sändningar via alla repetrar. Det mest pålitliga alternativet, men kräver mer sändtid.'; + 'Sänder via alla repeatrar. Mest tillförlitligt, men använder mer sändningstid.'; @override String get routing_modeManualHint => - 'Skickar alltid den exakta väg du har angivit.'; + 'Skickar alltid längs exakt den rutt du anger.'; @override String get routing_currentRoute => 'Nuvarande rutt'; @override - String get routing_directNoHops => 'Direkt – utan mellanliggande routrar'; + String get routing_directNoHops => 'Direkt — inga repeaterhopp'; @override String get routing_noPathYet => - 'Ingen väg hittad ännu. Nästa meddelande skickas tills en rutt har upptäckts.'; + 'Ingen rutt ännu. Nästa meddelande floodas tills en rutt hittas.'; @override - String get routing_floodBroadcast => 'Sändas via alla repetrar'; + String get routing_floodBroadcast => 'Sänd via varje repeater'; @override - String get routing_editPath => 'Redigera sökväg'; + String get routing_editPath => 'Redigera rutt'; @override - String get routing_forgetPath => 'Glöm vägen'; + String get routing_forgetPath => 'Glöm rutt'; @override - String get routing_knownPaths => 'Kända vägar'; + String get routing_knownPaths => 'Kända rutter'; @override - String get routing_knownPathsHint => 'Välj en väg för att byta till den.'; + String get routing_knownPathsHint => + 'Tryck på en rutt för att byta till den.'; @override String get routing_inUse => 'I användning'; @override - String get routing_qualityStrong => 'En stark start'; + String get routing_qualityStrong => 'Starkt första hopp'; @override - String get routing_qualityGood => 'Bra första steg'; + String get routing_qualityGood => 'Bra första hopp'; @override String get routing_qualityFair => 'Bra första hopp'; @@ -1629,14 +1879,14 @@ class AppLocalizationsSv extends AppLocalizations { String get routing_qualityWorked => 'Har levererat'; @override - String get routing_qualityFlood => 'Fått information via nyhetsflöde'; + String get routing_qualityFlood => 'Hörd via flood'; @override String get routing_qualityUntested => 'Ej testat'; @override String routing_lastWorked(String when) { - return 'arbetade $when'; + return 'fungerade $when'; } @override @@ -1644,39 +1894,39 @@ class AppLocalizationsSv extends AppLocalizations { @override String routing_deliveryCounts(int successes, int failures) { - return '$successes delivered, $failures failed'; + return '$successes levererade, $failures misslyckade'; } @override - String get routing_floodDelivery => 'Leverans vid översvämningsområde'; + String get routing_floodDelivery => 'Flood-leverans'; @override - String get pathEditor_title => 'Skapa väg'; + String get pathEditor_title => 'Skapa rutt'; @override String pathEditor_hopCounter(int count) { - return '$count av 64 humlor'; + return '$count av 64 hopp'; } @override String get pathEditor_noHops => - 'Inga humle än. Använd knapparna nedan för att lägga till dem i rätt ordning, eller spara utan humle för att skicka direkt.'; + 'Inga hopp ännu. Tryck på repeaters nedan för att lägga till dem i ordning, eller spara utan hopp för att skicka direkt.'; @override - String get pathEditor_addHops => 'Tillsätt humlen i rätt ordning.'; + String get pathEditor_addHops => 'Lägg till hopp i ordning'; @override - String get pathEditor_searchRepeaters => 'Sök efter återupptagna samtal'; + String get pathEditor_searchRepeaters => 'Sök repeaters'; @override - String get pathEditor_advancedHex => 'Avancerat: rå hex-sökväg'; + String get pathEditor_advancedHex => 'Avancerat: rå rutt i hexformat'; @override String get pathEditor_hexLabel => 'Hex-prefikser'; @override String get pathEditor_hexHelper => - 'Två hex-tecken per steg, separerade med kommatecken.'; + 'Två hextecken per hopp, separerade med kommatecken'; @override String pathEditor_invalidTokens(String tokens) { @@ -1684,16 +1934,16 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get pathEditor_tooManyHops => 'Maximalt 64 humlörter'; + String get pathEditor_tooManyHops => 'Maximalt 64 hopp'; @override - String get pathEditor_usePath => 'Använd denna väg'; + String get pathEditor_usePath => 'Använd den här rutten'; @override - String get pathEditor_removeHop => 'Ta bort humlen'; + String get pathEditor_removeHop => 'Ta bort hopp'; @override - String get pathEditor_unknownHop => 'Okänd förstärkare'; + String get pathEditor_unknownHop => 'Okänd repeater'; @override String get chat_pathSavedLocally => @@ -1706,19 +1956,22 @@ class AppLocalizationsSv extends AppLocalizations { String get chat_pathDeviceNotConfirmed => 'Enheten har inte bekräftats ännu.'; @override - String get chat_type => 'Skriv'; + String get chat_type => 'Typ'; @override - String get chat_path => 'Sökväg'; + String get chat_path => 'Rutt'; @override - String get chat_publicKey => 'Allmänt nyckel'; + String get chat_viewPathOnMap => 'View path on map'; @override - String get chat_compressOutgoingMessages => 'Kryptera utgående meddelanden'; + String get chat_publicKey => 'Publik nyckel'; @override - String get chat_floodForced => 'Översvämning (tvingad)'; + String get chat_compressOutgoingMessages => 'Komprimera utgående meddelanden'; + + @override + String get chat_floodForced => 'Flood (tvingad)'; @override String get chat_directForced => 'Direkt (tvingad)'; @@ -1729,7 +1982,7 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get chat_floodAuto => 'Översvämning (auto)'; + String get chat_floodAuto => 'Flood (automatisk)'; @override String get chat_direct => 'Direkt'; @@ -1748,6 +2001,12 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_newMessages => 'Nya meddelanden'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Öppna länk?'; @@ -1793,6 +2052,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get map_centerOnNode => 'Centrera på nod'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Detaljer'; @@ -1803,14 +2065,18 @@ class AppLocalizationsSv extends AppLocalizations { String get map_noResults => 'Inga matchande noder'; @override - String get map_lineOfSight => 'Synlinje'; + String get map_lineOfSight => 'Siktlinje'; @override - String get map_losScreenTitle => 'Synlinje'; + String get map_losScreenTitle => 'Siktlinje'; @override String get map_noNodesWithLocation => 'Inga noder med platsinformation'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Noder måste dela sina GPS-koordinater\nför att visas på kartan'; @@ -1822,14 +2088,14 @@ class AppLocalizationsSv extends AppLocalizations { @override String map_pinsCount(int count) { - return 'Pinnar: $count'; + return 'Markörer: $count'; } @override - String get map_chat => 'Chat'; + String get map_chat => 'Chatt'; @override - String get map_repeater => 'Återuppspelare'; + String get map_repeater => 'Repeater'; @override String get map_room => 'Rum'; @@ -1838,13 +2104,13 @@ class AppLocalizationsSv extends AppLocalizations { String get map_sensor => 'Sensor'; @override - String get map_pinDm => 'Lås (DM)'; + String get map_pinDm => 'Markör (DM)'; @override - String get map_pinPrivate => 'Lås (Privat)'; + String get map_pinPrivate => 'Markör (privat)'; @override - String get map_pinPublic => 'Anslå (Offentligt)'; + String get map_pinPublic => 'Markör (offentlig)'; @override String get map_lastSeen => 'Senast sedd'; @@ -1863,22 +2129,22 @@ class AppLocalizationsSv extends AppLocalizations { String get map_flags => 'Flaggor'; @override - String get map_type => 'Type'; + String get map_type => 'Typ'; @override - String get map_path => 'Path'; + String get map_path => 'Rutt'; @override - String get map_location => 'Location'; + String get map_location => 'Plats'; @override - String get map_estLocation => 'Est. Location'; + String get map_estLocation => 'Uppskattad plats'; @override - String get map_publicKey => 'Public Key'; + String get map_publicKey => 'Publik nyckel'; @override - String get map_publicKeyPrefixHint => 'e.g. ab12'; + String get map_publicKeyPrefixHint => 't.ex. ab12'; @override String get map_shareMarkerHere => 'Dela markeringen här'; @@ -1926,7 +2192,7 @@ class AppLocalizationsSv extends AppLocalizations { String get map_chatNodes => 'Chatnoder'; @override - String get map_repeaters => 'Upprepare'; + String get map_repeaters => 'Repeatrar'; @override String get map_otherNodes => 'Andra noder'; @@ -1941,7 +2207,7 @@ class AppLocalizationsSv extends AppLocalizations { String get map_filterByKeyPrefix => 'Filtrera efter nyckelprefix'; @override - String get map_publicKeyPrefix => 'Allmänt nyckelprästegenskap'; + String get map_publicKeyPrefix => 'Prefix för publik nyckel'; @override String get map_markers => 'Markörer'; @@ -1953,6 +2219,16 @@ class AppLocalizationsSv extends AppLocalizations { String get map_showGuessedLocations => 'Visa upp de antagna nodernas placeringar'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Visa Discovery-kontakter'; @@ -1960,7 +2236,7 @@ class AppLocalizationsSv extends AppLocalizations { String get map_guessedLocation => 'Gissad plats'; @override - String get map_lastSeenTime => 'Senaste Visats Tid'; + String get map_lastSeenTime => 'Senast sedd'; @override String get map_sharedPin => 'Delad PIN'; @@ -1972,22 +2248,25 @@ class AppLocalizationsSv extends AppLocalizations { String get map_joinRoom => 'Gå med i rum'; @override - String get map_manageRepeater => 'Hantera Upprepare'; + String get map_manageRepeater => 'Hantera repeater'; @override - String get map_tapToAdd => 'Tryck på noder för att lägga till dem i banan.'; + String get map_manageServer => 'Manage Server'; @override - String get map_runTrace => 'Kör spårsökning'; + String get map_tapToAdd => 'Tryck på noder för att lägga till dem i rutten.'; @override - String get map_runTraceWithReturnPath => 'Gå tillbaka på samma väg'; + String get map_runTrace => 'Kör ruttspårning'; + + @override + String get map_runTraceWithReturnPath => 'Återvänd längs samma rutt.'; @override String get map_removeLast => 'Ta bort sista'; @override - String get map_pathTraceCancelled => 'Sökvägsspårning avbruten.'; + String get map_pathTraceCancelled => 'Ruttspårningen avbröts.'; @override String get mapCache_title => 'Offline Kartcache'; @@ -1997,34 +2276,35 @@ class AppLocalizationsSv extends AppLocalizations { @override String get mapCache_noTilesToDownload => - 'Inga kuber att ladda ner för detta område'; + 'Inga kartplattor att ladda ned för det här området'; @override - String get mapCache_downloadTilesTitle => 'Ladda ner klick'; + String get mapCache_downloadTilesTitle => 'Ladda ned kartplattor'; @override String mapCache_downloadTilesPrompt(int count) { - return 'Ladda ner $count kuber för offlineanvändning?'; + return 'Ladda ned $count kartplattor för offlineanvändning?'; } @override - String get mapCache_downloadAction => 'Ladda ner'; + String get mapCache_downloadAction => 'Ladda ned'; @override String mapCache_cachedTiles(int count) { - return 'Cache $count kuber'; + return '$count kartplattor cachelagrade'; } @override String mapCache_cachedTilesWithFailed(int downloaded, int failed) { - return 'Cachelagda $downloaded klickark ($failed misslyckades)'; + return '$downloaded kartplattor cachelagrade ($failed misslyckades)'; } @override String get mapCache_clearOfflineCacheTitle => 'Rensa offline-cache'; @override - String get mapCache_clearOfflineCachePrompt => 'Ta bort alla cachemapplaner?'; + String get mapCache_clearOfflineCachePrompt => + 'Ta bort alla cachelagrade kartplattor?'; @override String get mapCache_offlineCacheCleared => 'Offline-cache rensad'; @@ -2043,16 +2323,16 @@ class AppLocalizationsSv extends AppLocalizations { @override String mapCache_estimatedTiles(int count) { - return 'Uppskattat antal klick: $count'; + return 'Uppskattat antal kartplattor: $count'; } @override String mapCache_downloadedTiles(int completed, int total) { - return 'Ladda ner $completed / $total'; + return 'Nedladdade $completed / $total'; } @override - String get mapCache_downloadTilesButton => 'Ladda ner klick'; + String get mapCache_downloadTilesButton => 'Ladda ned kartplattor'; @override String get mapCache_clearCacheButton => 'Rensa Cache'; @@ -2062,6 +2342,43 @@ class AppLocalizationsSv extends AppLocalizations { return 'Misslyckade nedladdningar: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cachelagrade kartplattor'; + + @override + String get mapCache_cachedTileSummaryLabel => + 'Sammanfattning av cachelagrade kartplattor'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Massnedladdning för offlinebruk är inaktiverad för $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Massnedladdning för offlinebruk är inaktiverad för $source i appens konfiguration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Källa: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cachelagrade kartplattor för källan: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cachelagrat i valt område/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Ungefärlig cachestorlek: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2128,10 +2445,10 @@ class AppLocalizationsSv extends AppLocalizations { 'Är du säker på att du vill koppla från enheten?'; @override - String get login_repeaterLogin => 'Återuppta Inloggning'; + String get login_repeaterLogin => 'Repeaterinloggning'; @override - String get login_roomLogin => 'Rum Inloggning'; + String get login_roomLogin => 'Inloggning på rumsserver'; @override String get login_password => 'Lösenord'; @@ -2139,6 +2456,12 @@ class AppLocalizationsSv extends AppLocalizations { @override String get login_enterPassword => 'Ange lösenord'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Spara lösenord'; @@ -2148,12 +2471,15 @@ class AppLocalizationsSv extends AppLocalizations { @override String get login_repeaterDescription => - 'Ange återuppspelarens lösenord för att komma åt inställningar och status.'; + 'Ange repeaterns lösenord för gäst- eller administratörsåtkomst.'; @override String get login_roomDescription => 'Ange rummets lösenord för att komma åt inställningar och status.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Ruttning'; @@ -2161,13 +2487,13 @@ class AppLocalizationsSv extends AppLocalizations { String get login_routingMode => 'Ruttläge'; @override - String get login_autoUseSavedPath => 'Automatisk (använd sparad sökväg)'; + String get login_autoUseSavedPath => 'Automatisk (använd sparad rutt)'; @override - String get login_forceFloodMode => 'Tvinga Översvämningsläge'; + String get login_forceFloodMode => 'Tvinga flood-läge'; @override - String get login_managePaths => 'Hantera Sökvägar'; + String get login_managePaths => 'Hantera rutter'; @override String get login_login => 'Logga in'; @@ -2193,23 +2519,26 @@ class AppLocalizationsSv extends AppLocalizations { String get common_clear => 'Rensa'; @override - String get path_currentPathLabel => 'Nuvarande sökväg'; + String get common_clearSearch => 'Clear search'; + + @override + String get path_currentPathLabel => 'Aktuell rutt'; @override String get path_noRepeatersFound => - 'Inga återuppspelare eller rumsservrar hittades.'; + 'Inga repeatrar eller rumsservrar hittades.'; @override - String get repeater_management => 'Återuppspelarens Hantering'; + String get repeater_management => 'Repeaterhantering'; @override - String get room_management => 'Rumserverhantering'; + String get room_management => 'Rumsserverhantering'; @override - String get repeater_guest => 'Information om repetorer'; + String get repeater_guest => 'Repeaterinformation'; @override - String get room_guest => 'Information om servern'; + String get room_guest => 'Rumsserverinformation'; @override String get repeater_managementTools => 'Administrationsverktyg'; @@ -2217,12 +2546,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_guestTools => 'Gästverktyg'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Status'; @override String get repeater_statusSubtitle => - 'Visa återspolningsstatus, statistik och grannar'; + 'Visa repeaterstatus, statistik och grannar'; @override String get repeater_telemetry => 'Telemetri'; @@ -2235,19 +2570,19 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_cli => 'Kommandoradgränssnitt'; @override - String get repeater_cliSubtitle => 'Skicka kommandon till repetitorn'; + String get repeater_cliSubtitle => 'Skicka kommandon till repeatern'; @override String get repeater_neighbors => 'Grannar'; @override - String get repeater_neighborsSubtitle => 'Visa noll hoppgrannar.'; + String get repeater_neighborsSubtitle => 'Visa nollhoppsgrannar.'; @override String get repeater_settings => 'Inställningar'; @override - String get repeater_settingsSubtitle => 'Konfigurera återspolarparametrar'; + String get repeater_settingsSubtitle => 'Konfigurera repeaterparametrar'; @override String get repeater_clockSyncAfterLogin => @@ -2258,7 +2593,7 @@ class AppLocalizationsSv extends AppLocalizations { 'Automatiskt skicka \"klocksynkronisering\" efter en lyckad inloggning.'; @override - String get repeater_statusTitle => 'Återspelsstatus'; + String get repeater_statusTitle => 'Repeaterstatus'; @override String get repeater_routingMode => 'Ruttläge'; @@ -2285,13 +2620,13 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_clockAtLogin => 'Klocka (vid inloggning)'; @override - String get repeater_uptime => 'Tillgänglighet'; + String get repeater_uptime => 'Drifttid'; @override - String get repeater_queueLength => 'Köans längd'; + String get repeater_queueLength => 'Kölängd'; @override - String get repeater_debugFlags => 'Felsökningsflaggor'; + String get repeater_debugFlags => 'Debugflaggor'; @override String get repeater_radioStatistics => 'Radiostatistik'; @@ -2300,16 +2635,16 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_lastRssi => 'Senaste RSSI'; @override - String get repeater_lastSnr => 'Sista SNR'; + String get repeater_lastSnr => 'Senaste SNR'; @override - String get repeater_noiseFloor => 'Ljudnivå'; + String get repeater_noiseFloor => 'Brusgolv'; @override - String get repeater_txAirtime => 'TX Airtime'; + String get repeater_txAirtime => 'TX-sändningstid'; @override - String get repeater_rxAirtime => 'RX Airtime'; + String get repeater_rxAirtime => 'RX-sändningstid'; @override String get repeater_chanUtil => 'Användning av kanal'; @@ -2338,17 +2673,17 @@ class AppLocalizationsSv extends AppLocalizations { @override String repeater_packetTxTotal(int total, String flood, String direct) { - return 'Totalt: $total, Översvämning: $flood, Direkt: $direct'; + return 'Totalt: $total, Flood: $flood, Direkt: $direct'; } @override String repeater_packetRxTotal(int total, String flood, String direct) { - return 'Totalt: $total, Översvämning: $flood, Direkt: $direct'; + return 'Totalt: $total, Flood: $flood, Direkt: $direct'; } @override String repeater_duplicatesFloodDirect(String flood, String direct) { - return 'Översvämning: $flood, Direkt: $direct'; + return 'Flood: $flood, Direkt: $direct'; } @override @@ -2357,28 +2692,30 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_settingsTitle => 'Återuppspelarens Inställningar'; + String get repeater_settingsTitle => 'Repeaterinställningar'; @override String get repeater_basicSettings => 'Grundinställningar'; @override - String get repeater_repeaterName => 'Upprepare Namn'; + String get repeater_repeaterName => 'Repeaternamn'; @override - String get repeater_repeaterNameHelper => 'Visa namn för denna återupprepare'; + String get repeater_repeaterNameHelper => + 'Visningsnamn för den här repeatern'; @override - String get repeater_adminPassword => 'Adminlösenord'; + String get repeater_adminPassword => 'Administratörslösenord'; @override String get repeater_adminPasswordHelper => 'Fullständig åtkomstlösenord'; @override - String get repeater_guestPassword => 'Gästlösenhet'; + String get repeater_guestPassword => 'Gästlösenord'; @override - String get repeater_guestPasswordHelper => 'Läs-skyddspassord'; + String get repeater_guestPasswordHelper => + 'Lösenord för skrivskyddad åtkomst'; @override String get repeater_radioSettings => 'Radioinställningar'; @@ -2390,7 +2727,7 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_frequencyHelper => '300–2500 MHz'; @override - String get repeater_txPower => 'TX Effekt'; + String get repeater_txPower => 'TX-effekt'; @override String get repeater_txPowerHelper => '1-30 dBm'; @@ -2399,7 +2736,7 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_bandwidth => 'Bandbredd'; @override - String get repeater_spreadingFactor => 'Spreadingfaktor'; + String get repeater_spreadingFactor => 'Spridningsfaktor'; @override String get repeater_codingRate => 'Kodningsgrad'; @@ -2414,7 +2751,7 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_latitudeHelper => 'Decimalgrader (t.ex. 37.7749)'; @override - String get repeater_longitude => 'Längdgrad'; + String get repeater_longitude => 'Longitud'; @override String get repeater_longitudeHelper => 'Decimalgrader (t.ex. -122.4194)'; @@ -2423,11 +2760,11 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_features => 'Funktioner'; @override - String get repeater_packetForwarding => 'Paketväxling'; + String get repeater_packetForwarding => 'Vidarebefordran av paket'; @override String get repeater_packetForwardingSubtitle => - 'Aktivera återuppspelaren för att vidarebefordra paket'; + 'Låt repeatern vidarebefordra paket'; @override String get repeater_guestAccess => 'Gäståtkomst'; @@ -2446,7 +2783,7 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_advertisementSettings => 'Annonsinställningar'; @override - String get repeater_localAdvertInterval => 'Lokalt Annonsintervall'; + String get repeater_localAdvertInterval => 'Intervall för lokal annonsering'; @override String repeater_localAdvertIntervalMinutes(int minutes) { @@ -2454,8 +2791,7 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_floodAdvertInterval => - 'Översvämnadsannonsens tidsintervall'; + String get repeater_floodAdvertInterval => 'Intervall för flood-annonsering'; @override String repeater_floodAdvertIntervalHours(int hours) { @@ -2463,16 +2799,17 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_encryptedAdvertInterval => 'Krypterad Annonsintervall'; + String get repeater_encryptedAdvertInterval => + 'Intervall för krypterad annonsering'; @override String get repeater_dangerZone => 'Faraområde'; @override - String get repeater_rebootRepeater => 'Starta Återuppspelaren'; + String get repeater_rebootRepeater => 'Starta om repeater'; @override - String get repeater_rebootRepeaterSubtitle => 'Starta om repeternheten'; + String get repeater_rebootRepeaterSubtitle => 'Starta om repeatern'; @override String get repeater_rebootRepeaterConfirm => @@ -2487,14 +2824,14 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_regenerateIdentityKeyConfirm => - 'Detta kommer att generera en ny identitet för återspelaren. Fortsätta?'; + 'Detta genererar en ny identitet för repeatern. Fortsätta?'; @override String get repeater_eraseFileSystem => 'Radera Filsystem'; @override String get repeater_eraseFileSystemSubtitle => - 'Formatera återspelsfilsystemet'; + 'Formatera repeaterns filsystem'; @override String get repeater_eraseFileSystemConfirm => @@ -2529,17 +2866,17 @@ class AppLocalizationsSv extends AppLocalizations { 'Ökad känslighet, högre strömförbrukning (endast för SX1262/SX1268)'; @override - String get repeater_refreshRxGain => 'Återställ förbättrad RX-signalstyrka'; + String get repeater_refreshRxGain => 'Uppdatera förstärkt RX-gain'; @override String get repeater_multiAcks => 'Flera bekräftelser'; @override String get repeater_multiAcksSubtitle => - 'Bekräfta meddelanden via flera olika kanaler för bättre leverans.'; + 'Kvittera meddelanden via flera rutter för säkrare leverans'; @override - String get repeater_refreshMultiAcks => 'Återställ flera ACK-meddelanden'; + String get repeater_refreshMultiAcks => 'Uppdatera multi-ACK'; @override String get repeater_networkHealth => 'Nätverkets hälsa'; @@ -2549,7 +2886,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_loopDetectHelper => - 'Skapa \"flödespaket\" som ser ut som att de bildar en loop (en återkommande krets).'; + 'Släpp flood-paket som ser ut att ingå i routingloopar'; @override String get repeater_loopDetectOff => 'Av'; @@ -2575,21 +2912,21 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_ownerInfo => 'Information om operatören'; + String get repeater_ownerInfo => 'Operatörsinformation'; @override String get repeater_ownerInfoHelper => - 'Offentliga metadata för denna sändare'; + 'Publik metadata för den här repeatern'; @override - String get repeater_refreshOwnerInfo => 'Uppdatera information om personal'; + String get repeater_refreshOwnerInfo => 'Uppdatera operatörsinformation'; @override - String get repeater_floodMax => 'Maximala mängden humle'; + String get repeater_floodMax => 'Max antal flood-hopp'; @override String get repeater_floodMaxHelper => - 'Maximalt antal hopp en paket kan färdas (0-64)'; + 'Maximalt antal hopp som ett flood-paket får färdas (0–64)'; @override String get repeater_advancedSettings => 'Avancerad'; @@ -2599,25 +2936,60 @@ class AppLocalizationsSv extends AppLocalizations { 'Ställjusteringsknappar för erfarna användare'; @override - String get repeater_pathHashMode => 'Hash-läge för sökväg'; + String get repeater_pathHashMode => 'Läge för rutthash'; @override String get repeater_pathHashModeHelper => - 'Byte används för att koda denna repeaters ID i taggar för att upptäcka loopar/flödesvägar. 0=1 byte (256 ID:n, upp till 64 hopp), 1=2 byte (65 000 ID:n, upp till 32 hopp), 2=3 byte (16 miljoner ID:n, upp till 21 hopp). Versioner 1.13 och äldre har stöd för multi-byte-vägar – endast en gång när nätverket är aktiverat (från och med version 1.14).'; + 'Byte som används för att koda repeaterns ID i flood-ruttens/loopdetekteringens taggar. 0=1 byte (256 ID:n, upp till 64 hopp), 1=2 byte (65K ID:n, upp till 32 hopp), 2=3 byte (16M ID:n, upp till 21 hopp). Firmware före v1.14 använde alltid 1-byte-rutter; v1.14 och senare kan konfigureras för 2- eller 3-byte-rutter.'; @override - String get repeater_txDelay => 'Försening i Flood TX'; + String get repeater_keySettings => 'Ändra identitetsnyckel'; + + @override + String get repeater_keySettingsSubtitle => + 'Ändra det publika/privata nyckelparet'; + + @override + String get repeater_prvKey => 'Privat nyckel'; + + @override + String get repeater_prvKeyHelper => + 'En ny privat nyckel för repeatern, en hexsträng med 128 tecken.'; + + @override + String get repeater_generatePrvKey => 'Generera ett slumpmässigt nyckelpar'; + + @override + String get repeater_stopGeneratingPrvKey => 'Avbryt sökning efter nyckelpar'; + + @override + String get repeater_pubKey => 'Publik nyckel'; + + @override + String get repeater_pubKeyHelper => + 'Det här är den publika nyckeln som hör till den genererade privata nyckeln. Den kan inte anges direkt.'; + + @override + String get repeater_pubKeyPrefix => 'Önskad prefix'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Hitta en publik nyckel som börjar med dessa hexsiffror. Förväntat antal försök: $tries.'; + } + + @override + String get repeater_txDelay => 'Flood-TX-fördröjning'; @override String get repeater_txDelayHelper => - 'Återöverföringsintervall för trafik under perioder med hög belastning, som en multiplikator av paketets överföringstid (0-2, standard 0,5). Högre värde = färre kollisioner, men långsammare leverans.'; + 'Intervall mellan vidarebefordringar för flood-trafik, som en multiplikator av paketets sändningstid (0–2, standard 0,5). Högre = färre kollisioner men långsammare leverans.'; @override String get repeater_directTxDelay => 'Direkt TX-fördröjning'; @override String get repeater_directTxDelayHelper => - 'Återöverföringsintervall för direkt (icke-översvämmande) trafik, som en multiplikator av paketets överföringstid (0-2, standard 0,3).'; + 'Intervall mellan vidarebefordringar för direkt trafik (icke-flood), som en multiplikator av paketets sändningstid (0–2, standard 0,3).'; @override String get repeater_intThresh => 'Tröskelvärde för störning'; @@ -2637,19 +3009,18 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_actionsTitle => 'Åtgärder'; @override - String get repeater_sendAdvert => 'Skicka annons om översvämning'; + String get repeater_sendAdvert => 'Skicka flood-annonsering'; @override String get repeater_sendAdvertSubtitle => - 'Sänd en reklamfilm om översvämningar via nätverket.'; + 'Sänd en flood-annonsering genom nätverket'; @override - String get repeater_sendAdvertZeroHop => - 'Skicka en annons som inte kräver någon mellanstopp'; + String get repeater_sendAdvertZeroHop => 'Skicka nollhoppsannons'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Sänd en reklamkampanj med en enda sändare (utan mellanliggande sändare).'; + 'Sänd en nollhoppsannons (inga vidarebefordringar)'; @override String get repeater_clockSync => 'Synkronisera klockan nu'; @@ -2670,7 +3041,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_settingsSavedRebootNeeded => - 'Inställningar sparade – starta om repetern för att tillämpa dem'; + 'Inställningarna har sparats — starta om repeatern för att tillämpa dem'; @override String repeater_settingsPartialFailure(String failures) { @@ -2683,23 +3054,34 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_refreshBasicSettings => - 'Återställ Grundläggande Inställningar'; + String get repeater_refreshBasicSettings => 'Uppdatera grundinställningar'; @override - String get repeater_refreshRadioSettings => 'Återställ Radiosinställningar'; + String get repeater_refreshRadioSettings => 'Uppdatera radioinställningar'; @override - String get repeater_refreshTxPower => 'Återställ TX-effekt'; + String get repeater_refreshTxPower => 'Uppdatera TX-effekt'; @override - String get repeater_refreshPacketForwarding => 'Återställ Paketväxling'; + String get repeater_refreshPacketForwarding => + 'Uppdatera paketvidarebefordran'; @override - String get repeater_refreshGuestAccess => 'Återställ Gäståtkomst'; + String get repeater_refreshGuestAccess => 'Uppdatera gäståtkomst'; @override - String get repeater_refreshPrivacyMode => 'Återställ Sekretessläge'; + String get repeater_refreshPrivacyMode => 'Uppdatera privatläge'; + + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; @override String repeater_refreshed(String label) { @@ -2712,13 +3094,13 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get repeater_cliTitle => 'Återuppspelaren CLI'; + String get repeater_cliTitle => 'Repeater-CLI'; @override String get repeater_debugNextCommand => 'Felsök Nästa Kommando'; @override - String get repeater_commandHelp => 'Hjälp'; + String get repeater_commandHelp => 'Kommandohjälp'; @override String get repeater_clearHistory => 'Rensa Historik'; @@ -2808,15 +3190,15 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpSetRepeat => - 'Aktiverar eller inaktiverar återuppspelarens roll för denna nod.'; + 'Aktiverar eller inaktiverar repeaterrollen för den här noden.'; @override String get repeater_cliHelpSetAllowReadOnly => - '(Rumserver) Om \'på\', så tillåts login med tomt lösenord, men kan inte Posta till rummet. (bara läsa).'; + '(Rumsserver) Om detta är på tillåts inloggning med tomt lösenord, men det går inte att posta till rummet (endast läsning).'; @override String get repeater_cliHelpSetFloodMax => - 'Ställer in det maximala antalet hopp för inkommande översvämning (om >= max, skickas inte paketet).'; + 'Anger maximalt antal hopp för inkommande flood-paket (om >= max vidarebefordras inte paketet).'; @override String get repeater_cliHelpSetIntThresh => @@ -2832,18 +3214,19 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpSetAdvertInterval => - 'Ställer in tidsintervallen i minuter för att skicka ett lokalt (utan-hopp) annonseringspaket. Ställs till 0 för att inaktivera.'; + 'Anger tidsintervallet i minuter för att skicka ett lokalt nollhopps-annonseringspaket. Ange 0 för att inaktivera.'; @override String get repeater_cliHelpSetFloodAdvertInterval => - 'Ställer in tidsintervallen i timmar för att skicka ett flödesannonspaket. Ställ in på 0 för att inaktivera.'; + 'Anger tidsintervallet i timmar för att skicka ett flood-annonseringspaket. Ange 0 för att inaktivera.'; @override String get repeater_cliHelpSetGuestPassword => - 'Ställer in/uppdaterar gästlösenordet. (för återvändare kan gästloggar skicka \"Get Stats\"-förfrågan)'; + 'Anger/uppdaterar gästlösenordet. (För repeatrar kan gästinloggningar skicka begäran \"Get Stats\".)'; @override - String get repeater_cliHelpSetName => 'Ställer in annonstexterna namn.'; + String get repeater_cliHelpSetName => + 'Anger namnet som används i annonseringen.'; @override String get repeater_cliHelpSetLat => @@ -2863,7 +3246,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpSetTxDelay => - 'Ställer in en faktor som multipliceras med tid på luft för en översvämningsläge-paket och med ett slumpmässigt slot-system för att fördröja dess vidarebefordran (för att minska risken för kollisioner).'; + 'Anger en faktor som multipliceras med sändningstiden för ett paket i flood-läge och används med ett slumpmässigt slotsystem för att fördröja vidarebefordran (för att minska risken för kollisioner).'; @override String get repeater_cliHelpSetDirectTxDelay => @@ -2916,7 +3299,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpNeighbors => - 'Visar en lista över andra repeaternoder som hörts via noll-hop-annonser. Varje rad är id-prefix-hex:tidsstämpel:snr-g撮-4'; + 'Visar en lista över andra repeaternoder som hörts via nollhoppsannonser. Varje rad är id-prefix-hex:timestamp:snr-times-4.'; @override String get repeater_cliHelpNeighborRemove => @@ -2924,7 +3307,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpRegion => - '(Serien endast) Listar alla definierade regioner och aktuella översvämningsbehörigheter.'; + '(Endast seriell anslutning) Listar alla definierade regioner och aktuella behörigheter för flood-trafik.'; @override String get repeater_cliHelpRegionLoad => @@ -2983,7 +3366,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGpsAdvertSet => - 'Ställer in annonsplatskonfiguration.'; + 'Anger konfigurationen för plats i annonser.'; @override String get repeater_commandsListTitle => 'Inställningslista'; @@ -2992,6 +3375,75 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_commandsListNote => 'OBS: för de olika \"set ...\" -kommandon finns det även ett \"get ...\" -kommando.'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => 'Ogiltig frekvens (150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 till 30 dBm'; + + @override + String get repeater_recvErrors => 'Mottagningsfel'; + + @override + String get room_postsStored => 'Inlägg'; + + @override + String get room_postsPushed => 'Skickade inlägg'; + + @override + String get repeater_cliRegionLoadActive => + 'Regionladdningsläge: skicka ett regionnamn per rad, indraget med blanksteg under sin förälder (lägg till F efter namnet för att tillåta flood). Rader får inget svar. Skicka en tom rad för att avsluta, och sedan \"region save\" för att spara resultatet.'; + + @override + String get repeater_cliRegionLoadHint => + 'Regionrad, eller tom för att avsluta'; + + @override + String get repeater_cliRegionLoadEnd => '(slut på regionladdning)'; + + @override + String get repeater_cliHelpRegionDef => + 'Definierar en kedja av regioner i ett kommando: varje namn läggs till under det föregående; \"name,parent\" lägger till namnet och fortsätter sedan under den angivna föräldern. Svarar med regionlistan.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Anger det maximala antalet hopp för vidarebefordran av flood-paket utan regionscope (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Anger det maximala antalet hopp för vidarebefordran av flood-annonser (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Visar det maximala antalet hopp för flood-paket utan regionscope.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Visar det maximala antalet hopp för flood-annonser.'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Växlar LoRa-frontändmodulens RX-gain (LNA). Kort utan denna modul svarar \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Växlar LoRa-frontändmodulens TX-gain (PA). Kort utan denna modul svarar \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Visar om LoRa-frontändmodulens RX-gain är påslagen.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Visar om LoRa-frontändmodulens TX-gain är påslagen.'; + + @override + String get repeater_bridgeNote => + 'Endast tillgängligt på firmware byggd med en brygga (RS232 eller ESP-NOW).'; + @override String get repeater_general => 'Allmänt'; @@ -3005,11 +3457,11 @@ class AppLocalizationsSv extends AppLocalizations { String get repeater_logging => 'Logga'; @override - String get repeater_neighborsRepeaterOnly => 'Grannar (Endast återspelare)'; + String get repeater_neighborsRepeaterOnly => 'Grannar (endast repeater)'; @override String get repeater_regionManagementRepeaterOnly => - 'Regionhantering (endast återuppspelare)'; + 'Regionhantering (endast repeater)'; @override String get repeater_regionNote => @@ -3041,7 +3493,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Skickar en annons som når endast direkt grannar (endast närmaste grannar).'; + 'Skickar en nollhoppsannons (endast direkta grannar).'; @override String get repeater_cliHelpStartOta => @@ -3057,7 +3509,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpDiscoverNeighbors => - 'Skickar en förfrågan om att upptäcka närliggande noder. (Endast för repetrar)'; + 'Skickar en begäran om nodupptäckt till närliggande grannar. (Endast repeater.)'; @override String get repeater_cliHelpPowersaving => @@ -3093,7 +3545,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpSetLoopDetect => - 'Ställer in känsligheten för att detektera loopar i routningen: av, minimal, måttlig eller strikt.'; + 'Ställer in känsligheten för detektering av routingloopar: av, minimal, måttlig eller strikt.'; @override String get repeater_cliHelpSetFreq => @@ -3108,7 +3560,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetRole => - 'Visar firmware-funktionen (Repeater, Room Server, etc.).'; + 'Visar firmware-rollen (repeater, rumsserver osv.).'; @override String get repeater_cliHelpGetPublicKey => 'Visar enhetens publika nyckel.'; @@ -3126,7 +3578,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetFreq => - 'Visar den konfigurerade radiovågen i MHz.'; + 'Visar den konfigurerade radiofrekvensen i MHz.'; @override String get repeater_cliHelpGetRadio => @@ -3161,11 +3613,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Visar den lokala reklampausens längd i minuter.'; + 'Visar intervallet för lokala annonseringar i minuter.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Visar tidsintervallet för reklamsegmentet under översvämningen, i timmar.'; + 'Visar intervallet för flood-annonseringar i timmar.'; @override String get repeater_cliHelpGetGuestPassword => 'Visar det angivna gästlösen.'; @@ -3181,22 +3633,22 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Visar faktor för fördröjning i flödesläge.'; + 'Visar txdelay-faktorn för flood-läge.'; @override String get repeater_cliHelpGetDirectTxDelay => 'Visar faktorn för fördröjning i direktläge.'; @override - String get repeater_cliHelpGetFloodMax => - 'Visar det maximala antalet gånger en översvämning har inträffat.'; + String get repeater_cliHelpGetFloodMax => 'Visar maximalt antal flood-hopp.'; @override String get repeater_cliHelpGetOwnerInfo => 'Visar strängen med kontaktinformation för ägaren.'; @override - String get repeater_cliHelpGetPathHashMode => 'Visar hash-läge (0/1/2).'; + String get repeater_cliHelpGetPathHashMode => + 'Visar läget för rutthash (0/1/2).'; @override String get repeater_cliHelpGetLoopDetect => @@ -3204,7 +3656,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetAcl => - '(Endast för serier) Visar åtkomstkontrollinställningarna för en repeater.'; + 'Visar åtkomstkontrollposterna på en repeater. (Endast seriell anslutning.)'; @override String get repeater_cliHelpGetBridgeEnabled => 'Visar om bron är aktiverad.'; @@ -3239,7 +3691,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpGetPwrMgtSupport => - 'Anger om styrelsen har stöd för energihantering.'; + 'Anger om kortet har stöd för strömhantering.'; @override String get repeater_cliHelpGetPwrMgtSource => @@ -3255,7 +3707,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpSensorGet => - 'Läser en anpassad sensorinställning via tangentbordet.'; + 'Läser en anpassad sensorinställning via nyckel.'; @override String get repeater_cliHelpSensorSet => @@ -3275,11 +3727,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Lista områden där det är tillåtet med trafik under översvämningsförhållanden.'; + 'Listar regioner som tillåter flood-trafik.'; @override String get repeater_cliHelpRegionListDenied => - 'Listar områden där trafik på grund av översvämningar är förbjuden.'; + 'Listar regioner som blockerar flood-trafik.'; @override String get repeater_cliHelpStatsPackets => @@ -3287,7 +3739,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_cliHelpStatsRadio => - '(Enbart för serier) Visar radiostatistik.'; + '(Endast seriell anslutning) Visar radiostatistik.'; @override String get repeater_cliHelpStatsCore => @@ -3325,7 +3777,7 @@ class AppLocalizationsSv extends AppLocalizations { String get telemetry_temperatureLabel => 'Temperatur'; @override - String get telemetry_currentLabel => 'Aktuell'; + String get telemetry_currentLabel => 'Ström'; @override String telemetry_batteryValue(int percent, String volts) { @@ -3484,7 +3936,8 @@ class AppLocalizationsSv extends AppLocalizations { String get neighbors_receivedData => 'Mottagna grannars data'; @override - String get neighbors_requestTimedOut => 'Grannar begär tidsinställd utskick.'; + String get neighbors_requestTimedOut => + 'Tidsgränsen för grannförfrågan överskreds.'; @override String neighbors_errorLoading(String error) { @@ -3492,7 +3945,7 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get neighbors_repeatersNeighbors => 'Upprepar grannar'; + String get neighbors_repeatersNeighbors => 'Repeatergrannar'; @override String get neighbors_noData => 'Inga grannuppgifter finns tillgängliga.'; @@ -3508,20 +3961,20 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channelPath_title => 'Paketväg'; + String get channelPath_title => 'Paketrutt'; @override String get channelPath_viewMap => 'Visa karta'; @override - String get channelPath_otherObservedPaths => 'Övriga observerade stigar'; + String get channelPath_otherObservedPaths => 'Andra observerade rutter'; @override - String get channelPath_repeaterHops => 'Återupptagningssteg'; + String get channelPath_repeaterHops => 'Repeaterhopp'; @override String get channelPath_noHopDetails => - 'Detaljer för denna paket är inte angivna.'; + 'Hoppdetaljer anges inte för det här paketet.'; @override String get channelPath_messageDetails => 'Meddelandets detaljer'; @@ -3537,7 +3990,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String channelPath_pathLabel(int index) { - return 'Sökväg $index'; + return 'Rutt $index'; } @override @@ -3545,7 +3998,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String channelPath_observedPathTitle(int index, String hops) { - return 'Observerad bana $index • $hops'; + return 'Observerad rutt $index • $hops'; } @override @@ -3562,10 +4015,10 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channelPath_unknownPath => 'Okänt'; + String get channelPath_unknownPath => 'Okänd'; @override - String get channelPath_floodPath => 'Översvämning'; + String get channelPath_floodPath => 'Flood-trafik'; @override String get channelPath_directPath => 'Direkt'; @@ -3581,22 +4034,22 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get channelPath_mapTitle => 'Sökvägskarta'; + String get channelPath_mapTitle => 'Ruttkarta'; @override String get channelPath_noRepeaterLocations => - 'Inga återupprepningsplatser finns tillgängliga för denna väg.'; + 'Inga repeaterpositioner är tillgängliga för den här rutten.'; @override String channelPath_primaryPath(int index) { - return 'Sökväg $index (Primär)'; + return 'Rutt $index (primär)'; } @override - String get channelPath_pathLabelTitle => 'Sökväg'; + String get channelPath_pathLabelTitle => 'Rutt'; @override - String get channelPath_observedPathHeader => 'Observerad Sökväg'; + String get channelPath_observedPathHeader => 'Observerad rutt'; @override String channelPath_selectedPathLabel(String label, String prefixes) { @@ -3608,7 +4061,7 @@ class AppLocalizationsSv extends AppLocalizations { 'Inga hoppdetaljer finns tillgängliga för detta paket.'; @override - String get channelPath_unknownRepeater => 'Okänt Upprepare'; + String get channelPath_unknownRepeater => 'Okänd repeater'; @override String get community_title => 'Gemenskap'; @@ -3642,7 +4095,7 @@ class AppLocalizationsSv extends AppLocalizations { String get community_showQr => 'Visa QR-kod'; @override - String get community_publicChannel => 'Föreningens Offentliga'; + String get community_publicChannel => 'Publik communitykanal'; @override String get community_hashtagChannel => 'Hashtag för gemenskapen'; @@ -3651,7 +4104,7 @@ class AppLocalizationsSv extends AppLocalizations { String get community_name => 'Gemenskapens namn'; @override - String get community_enterName => 'Ange communities namn'; + String get community_enterName => 'Ange communityns namn'; @override String community_created(String name) { @@ -3687,12 +4140,11 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get community_addPublicChannel => - 'Lägg till Gemenskapskanal (Offentlig)'; + String get community_addPublicChannel => 'Lägg till publik communitykanal'; @override String get community_addPublicChannelHint => - 'Lägg automatiskt till den offentliga kanalen för denna community'; + 'Lägg automatiskt till den publika kanalen för den här communityn'; @override String get community_noCommunities => 'Inga gemenskaper har anslutats ännu'; @@ -3735,7 +4187,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String community_secretRegenerated(String name) { - return 'Lösenord återskapad för \"$name\"'; + return 'Hemligheten har genererats om för “$name”'; } @override @@ -3789,10 +4241,10 @@ class AppLocalizationsSv extends AppLocalizations { String get listFilter_latestMessages => 'Senaste meddelanden'; @override - String get listFilter_heardRecently => 'Hörts nyligen'; + String get listFilter_heardRecently => 'Nyligen hörd'; @override - String get listFilter_az => 'A-Z'; + String get listFilter_az => 'A-Ö'; @override String get listFilter_filters => 'Filteralternativ'; @@ -3813,10 +4265,10 @@ class AppLocalizationsSv extends AppLocalizations { String get listFilter_users => 'Användare'; @override - String get listFilter_repeaters => 'Upprepare'; + String get listFilter_repeaters => 'Repeatrar'; @override - String get listFilter_roomServers => 'Rumservrar'; + String get listFilter_roomServers => 'Rumsservrar'; @override String get listFilter_unreadOnly => 'Endast oinlästa'; @@ -3828,20 +4280,20 @@ class AppLocalizationsSv extends AppLocalizations { String get pathTrace_you => 'Du'; @override - String get pathTrace_failed => 'Sökvägsföljning misslyckades.'; + String get pathTrace_failed => 'Ruttspårningen misslyckades.'; @override - String get pathTrace_notAvailable => 'Path trace ej tillgänglig.'; + String get pathTrace_notAvailable => 'Ruttspårning är inte tillgänglig.'; @override - String get pathTrace_refreshTooltip => 'Uppdatera Path Trace'; + String get pathTrace_refreshTooltip => 'Uppdatera ruttspårning.'; @override String get pathTrace_someHopsNoLocation => - 'En eller flera av humlen saknar en plats!'; + 'Ett eller flera hopp saknar position!'; @override - String get pathTrace_clearTooltip => 'Rensa väg'; + String get pathTrace_clearTooltip => 'Rensa rutt'; @override String get losSelectStartEnd => 'Välj start- och slutnoder för LOS.'; @@ -3868,7 +4320,7 @@ class AppLocalizationsSv extends AppLocalizations { String get losShowDisplayNodes => 'Visa displaynoder'; @override - String get losCustomPoints => 'Anpassade poäng'; + String get losCustomPoints => 'Anpassade punkter'; @override String losCustomPointLabel(int index) { @@ -3904,7 +4356,7 @@ class AppLocalizationsSv extends AppLocalizations { String clearance, String heightUnit, ) { - return '$distance $distanceUnit, rensa LOS, min clearance $clearance $heightUnit'; + return '$distance $distanceUnit, fri siktlinje, minsta frigång $clearance $heightUnit'; } @override @@ -3925,7 +4377,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String losStatusSummary(int clear, int total, int blocked, int unknown) { - return 'LOS: $clear/$total rensa, $blocked blockerad, $unknown okänd'; + return 'LOS: $clear/$total fria, $blocked blockerade, $unknown okända'; } @override @@ -3961,7 +4413,7 @@ class AppLocalizationsSv extends AppLocalizations { String get losLegendTerrain => 'Terräng'; @override - String get losBlockedSpotsTitle => 'Reserverade platser'; + String get losBlockedSpotsTitle => 'Blockerade punkter'; @override String get losBlockedSpotsHint => @@ -3978,7 +4430,7 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get losSelectedObstructionTitle => 'Vald hinder'; + String get losSelectedObstructionTitle => 'Valt hinder'; @override String losSelectedObstructionDetails( @@ -3988,7 +4440,7 @@ class AppLocalizationsSv extends AppLocalizations { String distanceUnit, String distanceFromB, ) { - return 'Blocked by $obstruction $heightUnit, $distanceFromA from A and $distanceFromB from B ($distanceUnit).'; + return 'Blockerad av $obstruction $heightUnit, $distanceFromA från A och $distanceFromB från B ($distanceUnit).'; } @override @@ -4011,22 +4463,22 @@ class AppLocalizationsSv extends AppLocalizations { } @override - String get contacts_pathTrace => 'Spårning'; + String get contacts_pathTrace => 'Ruttspårning'; @override - String get contacts_ping => 'Ping'; + String get contacts_ping => 'Pinga'; @override - String get contacts_repeaterPathTrace => 'Vägspårning till repeater'; + String get contacts_repeaterPathTrace => 'Ruttspårning till repeater'; @override String get contacts_repeaterPing => 'Ping-repeater'; @override - String get contacts_roomPathTrace => 'Vägspårning till rumserver'; + String get contacts_roomPathTrace => 'Ruttspårning till rumsserver'; @override - String get contacts_roomPing => 'Ping rumsserver'; + String get contacts_roomPing => 'Pinga rumsserver'; @override String get contacts_chatTraceRoute => 'Spåra rutt'; @@ -4049,10 +4501,10 @@ class AppLocalizationsSv extends AppLocalizations { String get contacts_contactImportFailed => 'Kontakt kunde inte importeras.'; @override - String get contacts_zeroHopAdvert => 'Reklam med nollhopp'; + String get contacts_zeroHopAdvert => 'Nollhoppsannons'; @override - String get contacts_floodAdvert => 'Översvämningsannons'; + String get contacts_floodAdvert => 'Flood-annonsering'; @override String get contacts_copyAdvertToClipboard => 'Kopiera annons till urklipp'; @@ -4061,6 +4513,23 @@ class AppLocalizationsSv extends AppLocalizations { String get contacts_addContactFromClipboard => 'Lägg till kontakt från urklipp'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Kopiera kontakt till Urklipp'; @@ -4127,18 +4596,19 @@ class AppLocalizationsSv extends AppLocalizations { @override String get settings_gpxExportRepeaters => - 'Exportera repeater / rumsservrar till GPX'; + 'Exportera repeatrar/rumsservrar till GPX'; @override String get settings_gpxExportRepeatersSubtitle => - 'Exporterar repeater / roomserver med plats till GPX-fil.'; + 'Exporterar repeatrar/rumsservrar med position till en GPX-fil.'; @override - String get settings_gpxExportContacts => 'Exportera följeslagare till GPX'; + String get settings_gpxExportContacts => + 'Exportera Companion-kontakter till GPX'; @override String get settings_gpxExportContactsSubtitle => - 'Exporterar följeslagare med en plats till GPX-fil.'; + 'Exporterar Companion-enheter med position till en GPX-fil.'; @override String get settings_gpxExportAll => 'Exportera alla kontakter till GPX'; @@ -4166,7 +4636,7 @@ class AppLocalizationsSv extends AppLocalizations { 'Repeater- och rumsserverplatser'; @override - String get settings_gpxExportChat => 'Medhjälparplatser'; + String get settings_gpxExportChat => 'Companion-positioner'; @override String get settings_gpxExportAllContacts => 'Alla kontakters platser'; @@ -4180,11 +4650,15 @@ class AppLocalizationsSv extends AppLocalizations { 'meshcore-open export av GPX-kartdata'; @override - String get snrIndicator_nearByRepeaters => 'Närliggande uppreparstationer'; + String get snrIndicator_nearByRepeaters => 'Närliggande repeatrar'; @override String get snrIndicator_lastSeen => 'Senast sedd'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Kontaktinställningar'; @@ -4201,15 +4675,15 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contactsSettings_autoAddUsersSubtitle => - 'Tillåt kompanjonen att automatiskt lägga till upptäckta användare'; + 'Tillåt Companion-enheten att automatiskt lägga till upptäckta användare.'; @override String get contactsSettings_autoAddRepeatersTitle => - 'Lägg till upprepande enheter automatiskt'; + 'Lägg till repeatrar automatiskt'; @override String get contactsSettings_autoAddRepeatersSubtitle => - 'Tillåt kompanjonen att automatiskt lägga till upptäckta repeater.'; + 'Tillåt Companion-enheten att automatiskt lägga till upptäckta repeatrar.'; @override String get contactsSettings_autoAddRoomServersTitle => @@ -4217,7 +4691,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contactsSettings_autoAddRoomServersSubtitle => - 'Tillåt kompanjonen att automatiskt lägga till upptäckta rumsservrar.'; + 'Tillåt Companion-enheten att automatiskt lägga till upptäckta rumsservrar.'; @override String get contactsSettings_autoAddSensorsTitle => @@ -4225,10 +4699,10 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contactsSettings_autoAddSensorsSubtitle => - 'Tillåt kompanjonen att automatiskt lägga till upptäckta sensorer.'; + 'Tillåt Companion-enheten att automatiskt lägga till upptäckta sensorer.'; @override - String get contactsSettings_overwriteOldestTitle => 'Skriv över äldst'; + String get contactsSettings_overwriteOldestTitle => 'Skriv över äldsta'; @override String get contactsSettings_overwriteOldestSubtitle => @@ -4241,7 +4715,7 @@ class AppLocalizationsSv extends AppLocalizations { String get discoveredContacts_noMatching => 'Inga matchande kontakter'; @override - String get discoveredContacts_searchHint => 'Sök uppfunna kontakter'; + String get discoveredContacts_searchHint => 'Sök bland upptäckta kontakter'; @override String get discoveredContacts_contactAdded => 'Kontakt tillagd'; @@ -4268,15 +4742,14 @@ class AppLocalizationsSv extends AppLocalizations { 'Vänligen vänta en stund innan du skickar igen.'; @override - String get appSettings_jumpToOldestUnread => - 'Gå direkt till det äldsta, obesvarade meddelandet'; + String get appSettings_jumpToOldestUnread => 'Gå till äldsta olästa'; @override String get appSettings_jumpToOldestUnreadSubtitle => 'När du öppnar en chatt med oinlästa meddelanden, scrolla till det första oinlästa meddelandet istället för det senaste.'; @override - String get appSettings_languageHu => 'Ungerskt'; + String get appSettings_languageHu => 'Ungerska'; @override String get appSettings_languageJa => 'Japanska'; @@ -4288,7 +4761,13 @@ class AppLocalizationsSv extends AppLocalizations { String get radioStats_tooltip => 'Radio- och mesh-statistik'; @override - String get radioStats_screenTitle => 'Radiostation'; + String get radioStats_screenTitle => 'Radiostatistik'; + + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; @override String get radioStats_notConnected => @@ -4296,7 +4775,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get radioStats_firmwareTooOld => - 'Radio statistik kräver kompatibel firmware version 8 eller senare.'; + 'Radiostatistik kräver Companion-firmware v8 eller senare.'; @override String get radioStats_waiting => 'Väntar på data…'; @@ -4328,7 +4807,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get radioStats_chartCaption => - 'Ljudnivå (dBm) baserat på de senaste mätningarna.'; + 'Brusgolv (dBm) för de senaste mätningarna.'; @override String radioStats_stripNoise(int noiseDbm) { @@ -4339,15 +4818,52 @@ class AppLocalizationsSv extends AppLocalizations { String get radioStats_stripWaiting => 'Hämtar radiostatistik…'; @override - String get radioStats_settingsTile => 'Radiostation'; + String get radioStats_settingsTile => 'Radiostatistik'; @override String get radioStats_settingsSubtitle => - 'Bakgrundsnivå, RSSI, SNR och tillgänglig tid'; + 'Brusgolv, RSSI, SNR och sändningstid'; @override String get translation_title => 'Översättning'; + @override + String get imageMessages_enableTitle => 'Aktivera bildmeddelanden'; + + @override + String get imageMessages_enableSubtitle => + 'Skicka bilder över meshnätet. Kräver en engångsnedladdning av bildmodellen.'; + + @override + String get imageMessages_modelSectionTitle => 'Bildmodell'; + + @override + String get imageMessages_downloadModel => 'Ladda ned'; + + @override + String get imageMessages_cancelDownload => 'Avbryt'; + + @override + String get imageMessages_removeModel => 'Ta bort modellen'; + + @override + String get imageMessages_modelReady => 'Färdig'; + + @override + String get imageMessages_modelNotPublished => + 'Inte publicerad ännu — den här versionen kan inte ladda ned den.'; + + @override + String get imageMessages_downloadFailed => + 'Bildmodellen kunde inte laddas ner.'; + + @override + String get imageMessages_autoProcessTitle => 'Bearbeta bilder automatiskt'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Rekonstruera varje bild så snart den kommer. Använder cirka 2 GB minne i ungefär en sekund varje gång; låt detta vara avstängt om du hellre vill rekonstruera med ett tryck.'; + @override String get translation_enableTitle => 'Aktivera översättning'; @@ -4368,13 +4884,13 @@ class AppLocalizationsSv extends AppLocalizations { @override String get translation_autoIncomingSubtitle => - 'Översätter meddelanden automatiskt för aviseringar och för chattar eller kanaler.'; + 'Översätter meddelanden automatiskt för notifieringar samt för chattar och kanaler.'; @override String get translation_translateMessage => 'Översätt meddelande'; @override - String get translation_targetLanguage => 'Målmedvetet språk'; + String get translation_targetLanguage => 'Målspråk'; @override String get translation_useAppLanguage => 'Använd appens språk'; @@ -4384,10 +4900,10 @@ class AppLocalizationsSv extends AppLocalizations { @override String get translation_presetModelLabel => - 'Fördefinierat Hugging Face-modell'; + 'Fördefinierad Hugging Face-modell'; @override - String get translation_manualUrlLabel => 'Manualens URL'; + String get translation_manualUrlLabel => 'Manuell modell-URL'; @override String get translation_downloadModel => 'Ladda ner modellen'; @@ -4396,7 +4912,7 @@ class AppLocalizationsSv extends AppLocalizations { String get translation_downloading => 'Nedladdning...'; @override - String get translation_working => 'Arbeta...'; + String get translation_working => 'Arbetar…'; @override String get translation_stop => 'Stopp'; @@ -4467,40 +4983,40 @@ class AppLocalizationsSv extends AppLocalizations { String get translation_systemLanguage => 'Språk för systemet'; @override - String get background_serviceTitle => 'MeshCore running'; + String get background_serviceTitle => 'MeshCore körs'; @override - String get background_serviceText => 'Keeping BLE connected'; + String get background_serviceText => 'Håller BLE-anslutningen aktiv'; @override String appSettings_translationModelDeleted(String name) { - return 'Deleted $name'; + return 'Tog bort $name'; } @override String appSettings_translationModelDeleteFailed(String error) { - return 'Failed to delete: $error'; + return 'Det gick inte att ta bort: $error'; } @override String channels_channelUpdateFailed(String error) { - return 'Failed to update channel: $error'; + return 'Det gick inte att uppdatera kanalen: $error'; } @override - String get contact_typeChat => 'Chat'; + String get contact_typeChat => 'Chatt'; @override String get contact_typeRepeater => 'Repeater'; @override - String get contact_typeRoom => 'Room'; + String get contact_typeRoom => 'Rum'; @override String get contact_typeSensor => 'Sensor'; @override - String get contact_typeUnknown => 'Unknown'; + String get contact_typeUnknown => 'Okänd'; @override String get map_zoomIn => 'Zooma in'; @@ -4509,7 +5025,7 @@ class AppLocalizationsSv extends AppLocalizations { String get map_zoomOut => 'Zooma ut'; @override - String get map_centerMap => 'Kartöversikt'; + String get map_centerMap => 'Centrera kartan'; @override String get chrome_bluetoothRequiresChromium => @@ -4560,7 +5076,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String pathMap_observedPaths(int count) { - return 'Observerade vägar: $count'; + return 'Observerade rutter: $count'; } @override @@ -4595,7 +5111,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String pathMap_sharedNodeCount(int count) { - return 'Används av $count vägar'; + return 'Används av $count rutter'; } @override @@ -4603,8 +5119,8 @@ class AppLocalizationsSv extends AppLocalizations { String _temp0 = intl.Intl.pluralLogic( count, locale: localeName, - other: '$count hopp saknar position — den visade vägen är ofullständig', - one: '1 hopp saknar position — den visade vägen är ofullständig', + other: '$count hopp saknar position — den visade rutten är ofullständig', + one: '1 hopp saknar position — den visade rutten är ofullständig', ); return '$_temp0'; } @@ -4613,10 +5129,10 @@ class AppLocalizationsSv extends AppLocalizations { String get pathMap_showAllPaths => 'Visa allt'; @override - String get pathMap_hidePath => 'Dölj väg'; + String get pathMap_hidePath => 'Dölj rutt'; @override - String get pathMap_showPath => 'Visa väg'; + String get pathMap_showPath => 'Visa rutt'; @override String get pathMap_collapsePanel => 'Fäll ihop panel'; @@ -4632,4 +5148,248 @@ class AppLocalizationsSv extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Lås upp vy från paket'; + + @override + String get imageSend_title => 'Skicka bild'; + + @override + String get imageSend_cropNote => + 'Storleksändrad till 512 × 512 · bildförhållandet bevaras inte'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Original'; + + @override + String get imageSend_onAirSize => 'Överförd storlek'; + + @override + String get imageSend_quality => 'Kvalitet'; + + @override + String get imageSend_qualityStandard => 'Standard'; + + @override + String get imageSend_qualityHigh => 'Hög'; + + @override + String get imageSend_packetsLabel => 'Paket'; + + @override + String get imageSend_airtimeLabel => 'Sändningstid'; + + @override + String get imageSend_sizeLabel => 'Nyttolast'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paket', + one: 'paket', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Radioindikatorer inte kända'; + + @override + String get imageSend_radioUnknownBody => + 'Anslut till en enhet så att sändningstiden kan beräknas.'; + + @override + String get imageSend_longSendTitle => 'Lång överföring'; + + @override + String imageSend_longSendBody(String duration) { + return 'Det här kommer att hålla kanalen upptagen i ungefär $duration.'; + } + + @override + String get imageSend_floodNote => + 'Flood-routing: varje repeater inom räckvidd sänder om varje paket, så kanalen hålls upptagen längre än så här.'; + + @override + String get imageSend_parityTitle => 'Lägg till återställningspaket'; + + @override + String get imageSend_paritySubtitle => + 'Ett extra paket. Gruppmeddelanden kvitteras inte, så mottagaren kan återskapa bilden om ett enda paket går förlorat.'; + + @override + String get imageSend_send => 'Sänd'; + + @override + String get imageSend_cancel => 'Avbryt'; + + @override + String get imageSend_encodeFailed => 'Denna bild kan inte kodas.'; + + @override + String get imageSend_codecDownloading => + 'Bildmodellen laddas fortfarande ned.'; + + @override + String get imageSend_codecUnavailable => + 'Bildsändning är inte tillgänglig på den här enheten.'; + + @override + String get imageSend_codecDisabled => + 'Bildmeddelanden är avstängda i inställningarna.'; + + @override + String get imageSend_deviceUnsupported => + 'Den här radion kan inte skicka bildpaket. Anslut en enhet med Companion-firmware 13 eller senare.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Bilder skickas som gruppdata och kan därför bara skickas till en kanal — inte som direktmeddelande.'; + + @override + String get imageSend_tooLarge => + 'Bilden kodades till mer paket än meshformaten tillåter.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'paket', + one: 'paket', + ); + return 'Bilden skickades som $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Bilden kunde inte skickas: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Skickar bild — paket $sent av $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Nod $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '$received av $total paket'; + } + + @override + String get receivedImage_queued => 'Väntar på avkodning'; + + @override + String get receivedImage_tapToDecode => 'Tryck för att avkoda'; + + @override + String get receivedImage_decoding => 'Rekonstruktion… om 1 sekund'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Bilden är ofullständig — $received av $total paket kom fram'; + } + + @override + String get receivedImage_corrupt => 'Bilden kunde inte rekonstrueras'; + + @override + String get receivedImage_decoderMissing => + 'Bild mottagen — bildavkodning är avstängd'; + + @override + String get receivedImage_evicted => 'Bild inte lagrad längre'; + + @override + String get receivedImage_retry => 'Försök igen'; + + @override + String get receivedImage_decodeAgain => 'Avkoda igen'; + + @override + String get receivedImage_openSettings => 'Konfigurera'; + + @override + String get receivedImage_tapToProcess => 'Tryck för att bearbeta'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'paket', + one: 'paket', + ); + return '$bytes byte · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds sekunder'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes min $seconds s'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Över 158 byte: skickas högst $count gånger'; + } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ab02382b..4c56ad15 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -110,6 +110,46 @@ class AppLocalizationsUk extends AppLocalizations { @override String get messageStatus_repeated => 'Почув неодноразово'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => 'Показувати зображення за URL'; + + @override + String get urlImage_possible => + 'Можливе зображення за URL; увімкніть це в Налаштуваннях.'; + @override String get common_reboot => 'Перезавантажити'; @@ -368,42 +408,63 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_radioSettingsUpdated => 'Налаштування радіо оновлено'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => + 'Радіомодуль не застосував ці налаштування'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => 'Ріси'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => 'Управляти збережених регіонів'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; + + @override + String get settings_regionDefaultNone => 'None'; + + @override + String get settings_regionManagement_screenTitle => 'Рégіональний управління'; + + @override + String get settings_regionNameHint => 'Назва регіону'; + + @override + String get settings_regionAddRegion => 'Добачить регіон'; + + @override + String get settings_regionFetchRegions => 'Збираємо регіони з репітерів'; + + @override + String get settings_regionFetchRegionsFail => 'Ні відкриті регіони'; @override String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + 'Цей регіон вже було доданий'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionName => 'Ріонна назва'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionDeleted => 'Ріон витертений'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_deleteRegion => 'Видалення регіону'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return 'Вирішіть \"$region\" з списку регіонів?'; } @override @@ -494,6 +555,10 @@ class AppLocalizationsUk extends AppLocalizations { @override String get settings_telemetryEnvironmentMode => 'Режим середовища телеметрії'; + @override + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; + @override String get settings_advertLocation => 'Геопозиція в оголошенні'; @@ -501,9 +566,21 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_advertLocationSubtitle => 'Включити геопозицію в оголошення'; + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => + 'Автооголошення без хопів при оновленні GPS'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + 'Коли GPS-локація змінюється, надсилати оголошення без хопів (потрібна геопозиція в оголошенні).'; + @override String get settings_multiAck => 'Багато підтверджень'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => 'Режим телеметрії оновлено'; @@ -607,15 +684,31 @@ class AppLocalizationsUk extends AppLocalizations { @override String get settings_infoPublicKey => 'Відкритий ключ'; + @override + String get settings_publicKeyCopied => 'Публічний ключ скопійовано'; + @override String get settings_infoContactsCount => 'Кількість контактів'; @override String get settings_infoChannelCount => 'Кількість каналів'; + @override + String get settings_infoHardware => 'Оборудовання'; + + @override + String get settings_infoFirmware => 'Програмне вміст (фirmware)'; + @override String get settings_presets => 'Попередні налаштування'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => 'Частота (МГц)'; @@ -638,7 +731,9 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_txPower => 'Потужність TX (дБм)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => 'Некоректна потужність TX (0-22 дБм)'; @@ -646,6 +741,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get settings_clientRepeat => 'Автономна система'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => 'Дозвольте цьому пристрою повторювати пакети даних для інших пристроїв.'; @@ -728,6 +828,51 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_languageUk => 'Українська'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 байт'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 байти'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 байти'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 байта'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => 'Увімкнути відстеження повідомлень'; @@ -763,6 +908,13 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_messageNotificationsSubtitle => 'Показувати сповіщення при отриманні нових повідомлень'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => 'Сповіщення каналів'; @@ -874,6 +1026,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_batteryLipo => 'LiPo (3.0-4.2В)'; + @override + String get appSettings_batteryLipoHv => 'ЛиPo HV (3,0-4,35 В)'; + @override String get appSettings_mapDisplay => 'Відображення карти'; @@ -931,6 +1086,28 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_lastWeek => 'Минулий тиждень'; + @override + String get appSettings_rasterTileSource => 'Джерело растрових тайлів'; + + @override + String get appSettings_stadiaEndpoint => 'Кінцева точка Stadia'; + + @override + String get appSettings_stadiaApiKey => 'Ключ API Stadia'; + + @override + String get appSettings_stadiaApiKeyRequired => + 'Потрібно для використання Stadia Maps'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return 'Налаштовано: $maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + 'Введіть свій ключ API Stadia Maps. Програма використовує його для запитів растрових тайлів.'; + @override String get appSettings_offlineMapCache => 'Офлайн-кеш карти'; @@ -1025,6 +1202,29 @@ class AppLocalizationsUk extends AppLocalizations { return 'Видалити $contactName з контактів?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => 'Керувати ретранслятором'; @@ -1175,6 +1375,18 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_private => 'Приватний'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => 'Редагувати канал'; @@ -1306,6 +1518,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_publicChannelAdded => 'Публічний канал додано'; + @override + String get channels_noFreeSlots => 'Немає вільних слотів для каналів'; + @override String get channels_sortBy => 'Сортувати за'; @@ -1361,17 +1576,30 @@ class AppLocalizationsUk extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return 'Ріон: $region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => 'Ріон: нема'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => 'Вybірте регіон'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => 'Чистя зона'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => 'Поки немає повідомлень.'; @@ -1426,9 +1654,27 @@ class AppLocalizationsUk extends AppLocalizations { return 'Повторна спроба $current/$max'; } + @override + String get chat_selectSendAction => 'Виберіть дію надсилання'; + @override String get chat_sendGif => 'Надіслати GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => 'Надіслати зображення через MeshCore'; + + @override + String get chat_imagePickFailed => 'Неможливо відкрити це изображення'; + + @override + String get chat_receivedGif => 'Підймовано GIF'; + @override String get chat_reply => 'Відповісти'; @@ -1438,6 +1684,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_me => 'Я'; + @override + String get reaction_report => 'Реакції'; + @override String get emojiCategorySmileys => 'Емодзі'; @@ -1587,14 +1836,14 @@ class AppLocalizationsUk extends AppLocalizations { String get routing_modeAuto => 'Автомобіль'; @override - String get routing_modeFlood => 'Повені'; + String get routing_modeFlood => 'Через всю мережу'; @override String get routing_modeManual => 'Інструкція'; @override String get routing_modeAutoHint => - 'Автоматично обирає найкращий відомий шлях, та у разі відсутності відомого шляху, використовує алгоритм \"занурення\".'; + 'Автоматично обирає найкращий відомий шлях, а за відсутності відомого шляху використовує режим «через всю мережу» (flood).'; @override String get routing_modeFloodHint => @@ -1635,7 +1884,7 @@ class AppLocalizationsUk extends AppLocalizations { String get routing_inUse => 'У робочому стані'; @override - String get routing_qualityStrong => 'Сильний перший стрибок'; + String get routing_qualityStrong => 'Сильний перший перехід'; @override String get routing_qualityGood => 'Чудова перша спроба'; @@ -1647,7 +1896,7 @@ class AppLocalizationsUk extends AppLocalizations { String get routing_qualityWorked => 'Доставлено'; @override - String get routing_qualityFlood => 'Дізнався через новини'; + String get routing_qualityFlood => 'Отримано через всю мережу (flood)'; @override String get routing_qualityUntested => 'Не протестовано'; @@ -1666,7 +1915,7 @@ class AppLocalizationsUk extends AppLocalizations { } @override - String get routing_floodDelivery => 'Доставка під час повені'; + String get routing_floodDelivery => 'Доставка через всю мережу (flood)'; @override String get pathEditor_title => 'Створити маршрут'; @@ -1678,10 +1927,10 @@ class AppLocalizationsUk extends AppLocalizations { @override String get pathEditor_noHops => - 'Ще не додано хміль. Натисніть на відповідні кнопки, щоб додати його в потрібному порядку, або збережіть рецепт без хмілю, щоб відправити його безпосередньо.'; + 'Ще не додано жодного переходу. Натисніть на відповідні кнопки нижче, щоб додати їх у потрібному порядку, або збережіть шлях без переходів, щоб надіслати напряму.'; @override - String get pathEditor_addHops => 'Додавайте хміль у наступній послідовності.'; + String get pathEditor_addHops => 'Додавайте переходи в потрібному порядку.'; @override String get pathEditor_searchRepeaters => 'Пошук повторювачів'; @@ -1710,7 +1959,7 @@ class AppLocalizationsUk extends AppLocalizations { String get pathEditor_usePath => 'Використовуйте цей шлях'; @override - String get pathEditor_removeHop => 'Видалити хміль'; + String get pathEditor_removeHop => 'Видалити перехід'; @override String get pathEditor_unknownHop => 'Невідомий ретранслятор'; @@ -1731,6 +1980,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_path => 'Шлях'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => 'Відкритий ключ'; @@ -1768,6 +2020,12 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_newMessages => 'Нові повідомлення'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => 'Відкрити посилання?'; @@ -1813,6 +2071,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get map_centerOnNode => 'Центрувати на вузлі'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => 'Деталі'; @@ -1831,6 +2092,10 @@ class AppLocalizationsUk extends AppLocalizations { @override String get map_noNodesWithLocation => 'Немає вузлів з даними про геопозицію'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => 'Вузли мають надавати свої GPS координати,\nщоб з\'явитись на карті.'; @@ -1973,6 +2238,16 @@ class AppLocalizationsUk extends AppLocalizations { String get map_showGuessedLocations => 'Показати геопозиції передбачених вузлів'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => 'Показати виявлені контакти'; @@ -1994,6 +2269,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get map_manageRepeater => 'Керувати ретранслятором'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => 'Натисніть на вузли, щоб додати їх до шляху'; @@ -2084,6 +2362,42 @@ class AppLocalizationsUk extends AppLocalizations { return 'Невдалі завантаження: $count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2161,6 +2475,12 @@ class AppLocalizationsUk extends AppLocalizations { @override String get login_enterPassword => 'Введіть пароль'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => 'Зберегти пароль'; @@ -2176,6 +2496,9 @@ class AppLocalizationsUk extends AppLocalizations { String get login_roomDescription => 'Введіть пароль кімнати для доступу до налаштувань та статусу.'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => 'Маршрутизація'; @@ -2214,6 +2537,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get common_clear => 'Очистити'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => 'Поточний шлях'; @@ -2239,6 +2565,12 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_guestTools => 'Гостьові інструменти'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => 'Статус'; @@ -2617,7 +2949,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_floodMax => - 'Максимальна кількість стрибків під час повені'; + 'Максимальна кількість переходів під час поширення через всю мережу (flood)'; @override String get repeater_floodMaxHelper => @@ -2635,14 +2967,49 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_pathHashModeHelper => - 'Байти, що використовуються для кодування ідентифікатора цього ретранслятора в тегах для виявлення потоків/петлі. 0=1 байт (256 ідентифікаторів, до 64 перехідів), 1=2 байти (65 000 ідентифікаторів, до 32 перехідів), 2=3 байти (16 мільйонів ідентифікаторів, до 21 переходу). Версії 1.13 та старіші не підтримують багатобайтні шляхи — вони активуються лише після того, як мережа буде оновлена до версії 1.14+.'; + 'Байти, що використовуються для кодування ідентифікатора цього ретранслятора в тегах flood-шляху/виявлення петель. 0=1 байт (256 ідентифікаторів, до 64 переходів), 1=2 байти (65 000 ідентифікаторів, до 32 переходів), 2=3 байти (16 мільйонів ідентифікаторів, до 21 переходу). Прошивки до v1.14 завжди використовували 1-байтові шляхи; v1.14 і новіші можна налаштувати на 2- або 3-байтові шляхи.'; + + @override + String get repeater_keySettings => 'Зміна ключів ідентифікації'; + + @override + String get repeater_keySettingsSubtitle => + 'Замініть публічний/приватний ключ'; + + @override + String get repeater_prvKey => 'Приватний ключ'; + + @override + String get repeater_prvKeyHelper => + 'Нова приватна ключ для репітера, 128-символова штучна штука в шестнадцатеричному форматі.'; + + @override + String get repeater_generatePrvKey => 'Синхронізujте ключовий пару'; + + @override + String get repeater_stopGeneratingPrvKey => 'Прервити шук ключового пару'; + + @override + String get repeater_pubKey => 'Публічна ключ'; + + @override + String get repeater_pubKeyHelper => + 'Це публична ключ, який пов\'язано з створеною приватною ключом. Ви не можете встановлювати його напрямую.'; + + @override + String get repeater_pubKeyPrefix => 'Високорейтингове прикінання'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return 'Найдіть відповідний открытий ключ, який починається ціми шестнадцатыми цифрами. Ожидається кількість потрібних попыток: $tries.'; + } @override String get repeater_txDelay => 'Затримка у Flood, штат Техас'; @override String get repeater_txDelayHelper => - 'Повторне надсилання з урахуванням навантаження від потоків транспорту, як множник від часу передачі пакета (0-2, за замовчуванням 0,5). Чим вище значення, тим менше конфліктів, але повільніше передавання.'; + 'Затримка повторного надсилання для трафіку через всю мережу (flood), як множник від часу передачі пакета (0-2, за замовчуванням 0,5). Чим вище значення, тим менше конфліктів, але повільніше передавання.'; @override String get repeater_directTxDelay => 'Пряме затримка TX'; @@ -2669,18 +3036,20 @@ class AppLocalizationsUk extends AppLocalizations { String get repeater_actionsTitle => 'Дії'; @override - String get repeater_sendAdvert => 'Надіслати рекламу щодо повені'; + String get repeater_sendAdvert => + 'Надіслати оголошення через всю мережу (flood)'; @override String get repeater_sendAdvertSubtitle => - 'Розповсюдити рекламу про надзвичайну ситуацію (повен) через мережу.'; + 'Розповсюдити оголошення через всю мережу (flood).'; @override - String get repeater_sendAdvertZeroHop => 'Надіслати рекламу без посередників'; + String get repeater_sendAdvertZeroHop => + 'Надіслати оголошення без ретрансляції'; @override String get repeater_sendAdvertZeroHopSubtitle => - 'Розповсюдити рекламу з однією переадресацією (без повторного розповсюдження)'; + 'Розповсюдити оголошення лише на один перехід (без ретрансляторів)'; @override String get repeater_clockSync => 'Синхронізувати годинник зараз'; @@ -2731,6 +3100,17 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_refreshPrivacyMode => 'Оновити режим приватності'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label оновлено'; @@ -3024,6 +3404,75 @@ class AppLocalizationsUk extends AppLocalizations { String get repeater_commandsListNote => 'ПРИМІТКА: для різних команд «set»... також існує команда «get»...'; + @override + String get repeater_frequencyRangeHelper => '150-2500 МГц'; + + @override + String get repeater_frequencyInvalid => 'Некоректна частота (150-2500 МГц)'; + + @override + String get repeater_txPowerRangeHelper => 'від -9 до 30 dBm'; + + @override + String get repeater_recvErrors => 'Помилки прийому'; + + @override + String get room_postsStored => 'Публікації'; + + @override + String get room_postsPushed => 'Надіслано публікацій'; + + @override + String get repeater_cliRegionLoadActive => + 'Режим завантаження регіонів: надсилайте по одному імені регіону в рядку, з відступом пробілами під батьківським регіоном (додайте F після імені, щоб дозволити поширення через всю мережу). Рядки не отримують відповіді. Надішліть порожній рядок, щоб завершити, а потім \"region save\", щоб зберегти результат.'; + + @override + String get repeater_cliRegionLoadHint => + 'Рядок регіону або порожній рядок для завершення'; + + @override + String get repeater_cliRegionLoadEnd => '(кінець завантаження регіонів)'; + + @override + String get repeater_cliHelpRegionDef => + 'Визначає ланцюжок регіонів однією командою: кожне ім’я додається під попереднім; \"name,parent\" додає ім’я і продовжує під вказаним батьківським регіоном. У відповідь повертає список регіонів.'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + 'Встановлює максимальну кількість переходів для пересилання пакетів через всю мережу (flood) без визначеної області регіону (0-64).'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => + 'Встановлює максимальну кількість переходів для пересилання оголошень через всю мережу (flood) (0-64).'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => + 'Показує максимальну кількість переходів для пакетів через всю мережу (flood) без визначеної області.'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => + 'Показує максимальну кількість переходів для оголошень через всю мережу (flood).'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + 'Перемикає підсилення RX (LNA) вхідного модуля LoRa. Плати без нього відповідають \"Error: unsupported\".'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + 'Перемикає підсилення TX (PA) вхідного модуля LoRa. Плати без нього відповідають \"Error: unsupported\".'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => + 'Показує, чи увімкнено підсилення RX вхідного модуля LoRa.'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => + 'Показує, чи увімкнено підсилення TX вхідного модуля LoRa.'; + + @override + String get repeater_bridgeNote => + 'Доступно лише для прошивки, зібраної з мостом (RS232 або ESP-NOW).'; + @override String get repeater_general => 'Загальні'; @@ -3073,7 +3522,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_cliHelpAdvertZeroHop => - 'Надсилає рекламу, яка не проходить через інші мережі (лише до безпосередніх сусідів).'; + 'Надсилає оголошення, яке не проходить через інші мережі (лише до безпосередніх сусідів).'; @override String get repeater_cliHelpStartOta => @@ -3197,11 +3646,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_cliHelpGetAdvertInterval => - 'Показує тривалість місцевої рекламної паузи в хвилинах.'; + 'Показує тривалість інтервалу локальних оголошень у хвилинах.'; @override String get repeater_cliHelpGetFloodAdvertInterval => - 'Показує інтервал часу між рекламними роликами про повені, виражений у годинах.'; + 'Показує інтервал оголошень через всю мережу (flood), виражений у годинах.'; @override String get repeater_cliHelpGetGuestPassword => @@ -3219,7 +3668,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_cliHelpGetTxDelay => - 'Показує коефіцієнт затримки сигналу у режимі затоплення.'; + 'Показує коефіцієнт затримки сигналу в режимі «через всю мережу» (flood).'; @override String get repeater_cliHelpGetDirectTxDelay => @@ -3227,7 +3676,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_cliHelpGetFloodMax => - 'Показує максимальну кількість підйомів, спричинених повенем.'; + 'Показує максимальну кількість переходів під час пересилання через всю мережу (flood).'; @override String get repeater_cliHelpGetOwnerInfo => @@ -3315,11 +3764,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_cliHelpRegionListAllowed => - 'Перелік регіонів, де дозволено рух транспорту під час повені.'; + 'Перелік регіонів, де дозволено поширення через всю мережу (flood).'; @override String get repeater_cliHelpRegionListDenied => - 'Перелік регіонів, які забороняють рух транспорту під час повені.'; + 'Перелік регіонів, де заборонено поширення через всю мережу (flood).'; @override String get repeater_cliHelpStatsPackets => @@ -4103,7 +4552,7 @@ class AppLocalizationsUk extends AppLocalizations { String get contacts_zeroHopAdvert => 'Оголошення без ретрансляції'; @override - String get contacts_floodAdvert => 'Оголошення з ретрансляцією'; + String get contacts_floodAdvert => 'Оголошення через всю мережу (flood)'; @override String get contacts_copyAdvertToClipboard => 'Копіювати оголошення'; @@ -4111,6 +4560,23 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Додати контакт з буфера'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => 'Копіювати контакт у буфер обміну'; @@ -4243,6 +4709,10 @@ class AppLocalizationsUk extends AppLocalizations { @override String get snrIndicator_lastSeen => 'Останній раз бачили'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => 'Налаштування контактів'; @@ -4350,6 +4820,12 @@ class AppLocalizationsUk extends AppLocalizations { @override String get radioStats_screenTitle => 'Статистика радіо'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => 'Підключіться до пристрою, щоб переглядати статистику радіо.'; @@ -4408,6 +4884,43 @@ class AppLocalizationsUk extends AppLocalizations { @override String get translation_title => 'Переклад'; + @override + String get imageMessages_enableTitle => 'Підтримка зображень для посилання'; + + @override + String get imageMessages_enableSubtitle => + 'Пошукуєте изображення через сеть. Вимagaєте однократне скачання моделю изображення.'; + + @override + String get imageMessages_modelSectionTitle => 'Модель для зображень'; + + @override + String get imageMessages_downloadModel => 'Скачання'; + + @override + String get imageMessages_cancelDownload => 'Завершити'; + + @override + String get imageMessages_removeModel => 'Видалим модель'; + + @override + String get imageMessages_modelReady => 'Готово'; + + @override + String get imageMessages_modelNotPublished => + 'Щоб не було опубліковано — це версія не дозволяє зробити скачання.'; + + @override + String get imageMessages_downloadFailed => + 'Модель для зображень не можна сказати.'; + + @override + String get imageMessages_autoProcessTitle => 'Автоматично оброблювати obraзи'; + + @override + String get imageMessages_autoProcessSubtitle => + 'Кожна картинка повинні бути відтворена на мій момент прибуття. Використовує приблизно 2 ГБ пам\'яті на кожен раз; відключіть від відтворення за допомогою кlikу.'; + @override String get translation_enableTitle => 'Увімкнути переклад'; @@ -4697,4 +5210,252 @@ class AppLocalizationsUk extends AppLocalizations { @override String get pathMap_unfollowPacket => 'Відв\'язати вигляд від пакету'; + + @override + String get imageSend_title => + 'Нашкоду зовні\n\n(or more naturally, depending on context)\n\nПошукуєте изображення'; + + @override + String get imageSend_cropNote => + 'Манітовано до 512 × 512 · соотношення варість не зберігається'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => 'Оригінал'; + + @override + String get imageSend_onAirSize => 'На ері'; + + @override + String get imageSend_quality => 'Качество'; + + @override + String get imageSend_qualityStandard => 'Стандарт'; + + @override + String get imageSend_qualityHigh => 'Висок'; + + @override + String get imageSend_packetsLabel => 'Пакети'; + + @override + String get imageSend_airtimeLabel => 'Час на ері'; + + @override + String get imageSend_sizeLabel => 'Підлог'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакета', + many: 'пакетів', + few: 'пакети', + one: 'пакет', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => 'Настройки радио неизвестні'; + + @override + String get imageSend_radioUnknownBody => + 'Залучіться до пристрою, щоб можна було розрахунювати час в етері.'; + + @override + String get imageSend_longSendTitle => 'Длуга передача'; + + @override + String imageSend_longSendBody(String duration) { + return 'Це забезпечить канал на approximativno $duration хвилин.'; + } + + @override + String get imageSend_floodNote => + 'Поширення через всю мережу (flood): кожен ретранслятор у діапазоні пересилає кожен пакет, тому канал залишається зайнятим довше, ніж зазначено тут.'; + + @override + String get imageSend_parityTitle => 'Пакет відновлення'; + + @override + String get imageSend_paritySubtitle => + 'Один дополний пакет. Групові посилання не відповідають, тому це дозволяє відвідувачу відтворити зображення, якщо один пакет втрачений.'; + + @override + String get imageSend_send => 'Пошутить'; + + @override + String get imageSend_cancel => 'Завершити'; + + @override + String get imageSend_encodeFailed => + 'Це изображення не може бути кодировано.'; + + @override + String get imageSend_codecDownloading => + 'Модель для відтворення изображень ще збирається.'; + + @override + String get imageSend_codecUnavailable => + 'Постій для відправлення изображень на цьому пристрої не доступний.'; + + @override + String get imageSend_codecDisabled => + 'Пictesovani posyly wyключені в настройках.'; + + @override + String get imageSend_deviceUnsupported => + 'Цей радіопередач не може отправляти пакети зображень. Зконнете пристрої, що працює з обладнанням керемонітом компаньєр 13 або новшим.'; + + @override + String get imageSend_directMessagesUnsupported => + 'Фотографії передаються як дані групою, тому їх можна відправляти лише на канал — не в прямому посилання.'; + + @override + String get imageSend_tooLarge => + 'Це изображення кодує більше пакітів, ніж дозволяє формат сети.'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'пакетів', + one: 'пакет', + ); + return 'Зображення надіслано як $count $_temp0.'; + } + + @override + String imageSend_sendFailed(String error) { + return 'Изображення не можна відправити: $error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return 'Пошускаємо изображення — пакет $sent з $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return 'Нод $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return 'Підходяче: $received з $total пакітів'; + } + + @override + String get receivedImage_queued => 'Очікування розслівання коду'; + + @override + String get receivedImage_tapToDecode => 'Кliknite для декодування'; + + @override + String get receivedImage_decoding => 'Повноювання… за прибуття 1 с.'; + + @override + String receivedImage_incomplete(int received, int total) { + return 'Образок не повний — $received з $total пакітів прибавлено'; + } + + @override + String get receivedImage_corrupt => 'Obraz не можна відтворити'; + + @override + String get receivedImage_decoderMissing => + 'Під час приємки — розшифровка зображення не вдалося.'; + + @override + String get receivedImage_evicted => 'Изображення не зберігається'; + + @override + String get receivedImage_retry => 'Попробуй ще раз'; + + @override + String get receivedImage_decodeAgain => 'Декодуй ще раз'; + + @override + String get receivedImage_openSettings => 'Заведіть'; + + @override + String get receivedImage_tapToProcess => 'Кликніть для обробки'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: 'пакетів', + one: 'пакет', + ); + return '$bytes байтів · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds секунди'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes хв $seconds с'; + } + + @override + String chat_longMessageRetryNote(int count) { + return 'Понад 158 байтів: надсилається не більше $count разів'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 6e0704bb..33e6c36f 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -110,6 +110,45 @@ class AppLocalizationsZh extends AppLocalizations { @override String get messageStatus_repeated => '多次听到'; + @override + String get messageStatus_failedChannel => + 'Your radio couldn\'t send this message.'; + + @override + String messageStatus_resending(int resends, int maxResends) { + return 'Not heard through enough repeaters yet. Resent $resends of $maxResends times.'; + } + + @override + String messageStatus_hopsNotReached(int hops, int required) { + return 'Sent, but only heard back through $hops of $required repeaters. It may still have gone further than your radio can hear.'; + } + + @override + String get messageStatus_sentChannel => + 'Sent. Channels don\'t confirm delivery, so this only means your radio sent it.'; + + @override + String get messageStatus_sentDirect => + 'Sent. Waiting for the contact to confirm.'; + + @override + String messageStatus_heardRepeatedCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: 'once', + ); + return 'Heard repeated $_temp0. Nearby repeaters passed it on.'; + } + + @override + String get urlImage_enable => '启用URL图片'; + + @override + String get urlImage_possible => '可能是URL图片,请在设置中启用。'; + @override String get common_reboot => '重启'; @@ -351,42 +390,61 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_radioSettingsUpdated => '无线电设置已更新'; @override - String get settings_regionSettings => 'Regions'; + String get settings_radioSettingsNotApplied => '收音机未应用这些设置'; @override - String get settings_regionSettingsSubtitle => 'Manage stored regions'; + String get settings_regionSettings => '地区'; @override - String get settings_regionManagement_screenTitle => 'Region Management'; + String get settings_regionSettingsSubtitle => '管理已存储的区域'; @override - String get settings_regionNameHint => 'Enter region name'; + String get settings_regionEmptyExplanation => + 'Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.'; @override - String get settings_regionAddRegion => 'Add region'; + String get settings_regionFetchFromRepeaters => 'Fetch from repeaters'; @override - String get settings_regionFetchRegions => 'Fetch regions from repeaters'; + String get settings_regionDefault => 'Default region'; @override - String get settings_regionFetchRegionsFail => 'No regions were found'; + String get settings_regionDefaultSubtitle => + 'Used by channels without their own region'; @override - String get settings_regionFetchRegionsAlreadyExists => - 'This region has already been added'; + String get settings_regionDefaultNone => 'None'; @override - String get settings_regionName => 'Region Name'; + String get settings_regionManagement_screenTitle => '区域管理'; @override - String get settings_regionDeleted => 'Region deleted'; + String get settings_regionNameHint => '区域名称'; @override - String get settings_deleteRegion => 'Delete Region'; + String get settings_regionAddRegion => '增加地区'; + + @override + String get settings_regionFetchRegions => '从中继器获取区域'; + + @override + String get settings_regionFetchRegionsFail => '未发现任何地区'; + + @override + String get settings_regionFetchRegionsAlreadyExists => '该地区已被添加'; + + @override + String get settings_regionName => '地区名称'; + + @override + String get settings_regionDeleted => '区域已删除'; + + @override + String get settings_deleteRegion => '删除区域'; @override String settings_deleteRegionConfirm(String region) { - return 'Remove \"$region\" from region list?'; + return '从 $region 列表中删除?'; } @override @@ -432,10 +490,10 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_privacyMode => '隐私模式'; @override - String get settings_privacyModeSubtitle => '在广告中隐藏姓名/位置'; + String get settings_privacyModeSubtitle => '在广播中隐藏姓名/位置'; @override - String get settings_privacyModeToggle => '切换隐私模式以在广告中隐藏姓名和位置,保护个人信息。'; + String get settings_privacyModeToggle => '切换隐私模式以在广播中隐藏姓名和位置,保护个人信息。'; @override String get settings_privacyModeEnabled => '隐私模式已启用'; @@ -471,14 +529,29 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_telemetryEnvironmentMode => '遥测环境模式'; @override - String get settings_advertLocation => '广告位置'; + String get settings_telemetryPerContactHint => + 'To allow a contact, open their chat and choose Contact Settings from the menu.'; @override - String get settings_advertLocationSubtitle => '在广告中包含位置'; + String get settings_advertLocation => '广播位置'; + + @override + String get settings_advertLocationSubtitle => '在广播中包含位置'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdate => 'GPS 更新时自动发送零跳广播'; + + @override + String get settings_autoZeroHopAdvertOnGpsUpdateSubtitle => + '当 GPS 位置变化时,发送零跳广播(需要在广播中包含位置)。'; @override String get settings_multiAck => '多重ACK'; + @override + String get settings_multiAckSubtitle => + 'Send extra ACKs for better delivery; uses more airtime'; + @override String get settings_telemetryModeUpdated => '遥测模式已更新'; @@ -574,15 +647,31 @@ class AppLocalizationsZh extends AppLocalizations { @override String get settings_infoPublicKey => '公钥'; + @override + String get settings_publicKeyCopied => '公钥已复制'; + @override String get settings_infoContactsCount => '联系人数量'; @override String get settings_infoChannelCount => '频道数量'; + @override + String get settings_infoHardware => '硬件'; + + @override + String get settings_infoFirmware => '固件'; + @override String get settings_presets => '预设'; + @override + String get settings_presetCustom => 'Custom'; + + @override + String get settings_radioMatchWarning => + 'All nodes you talk to must use the same frequency, bandwidth, SF and CR.'; + @override String get settings_frequency => '频率 (MHz)'; @@ -605,7 +694,9 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_txPower => 'TX 功率 (dBm)'; @override - String get settings_txPowerHelper => '0 - 22'; + String settings_txPowerRangeHelper(int min, int max) { + return '$min to $max dBm'; + } @override String get settings_txPowerInvalid => '无效的发射功率(0-22 dBm)'; @@ -613,6 +704,11 @@ class AppLocalizationsZh extends AppLocalizations { @override String get settings_clientRepeat => '离网重复'; + @override + String settings_clientRepeatFrequencyNote(String freq) { + return 'Frequency set to $freq MHz for off-grid repeat'; + } + @override String get settings_clientRepeatSubtitle => '允许此设备重复发送网状数据包给其他设备'; @@ -694,6 +790,51 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_languageUk => '乌克兰语'; + @override + String get repeater_pathHashModeOption0 => '0 - 1 字节'; + + @override + String get repeater_pathHashModeOption1 => '1 - 2 字节'; + + @override + String get repeater_pathHashModeOption2 => '2 - 3 字节'; + + @override + String get repeater_pathHashModeOption3 => '3 - 4 字节'; + + @override + String get settings_pathHashModeHelper => + 'Size of each node ID recorded in the path of flood packets this radio sends: 1 byte (256 IDs, up to 64 hops), 2 bytes (65K IDs, up to 32 hops), 3 bytes (16M IDs, up to 21 hops). Larger IDs reduce collisions, but repeaters on firmware older than v1.14 drop packets with 2- or 3-byte IDs.'; + + @override + String settings_requiresFirmware(String version) { + return 'Requires firmware $version or newer'; + } + + @override + String get appSettings_channelMinHops => + 'Resend channel messages until they travel far enough'; + + @override + String get appSettings_channelMinHopsSubtitle => + 'If your message isn\'t heard coming back through enough repeaters, send it again. Uses more airtime.'; + + @override + String appSettings_channelMinHopsCount(int count) { + return 'Required hops: $count'; + } + + @override + String appSettings_channelMinHopsRetries(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count times', + one: '1 time', + ); + return 'Resend up to $_temp0'; + } + @override String get appSettings_enableMessageTracing => '启用消息追踪'; @@ -724,6 +865,13 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_messageNotificationsSubtitle => '收到新消息时显示通知'; + @override + String get appSettings_batteryOptimization => 'Background Activity'; + + @override + String get appSettings_batteryOptimizationSubtitle => + 'Set MeshCore Open to \"Don\'t optimize\" in battery settings so messages keep arriving in the background'; + @override String get appSettings_channelMessageNotifications => '频道消息通知'; @@ -818,6 +966,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_batteryLipo => '锂聚合物电池 (3.0-4.2V)'; + @override + String get appSettings_batteryLipoHv => '锂多压电源(3.0-4.35伏)'; + @override String get appSettings_mapDisplay => '地图显示'; @@ -871,6 +1022,27 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_lastWeek => '上周'; + @override + String get appSettings_rasterTileSource => '栅格瓦片源'; + + @override + String get appSettings_stadiaEndpoint => 'Stadia 端点'; + + @override + String get appSettings_stadiaApiKey => 'Stadia API 密钥'; + + @override + String get appSettings_stadiaApiKeyRequired => '使用 Stadia Maps 时必需'; + + @override + String appSettings_stadiaApiKeyConfigured(String maskedKey) { + return '已配置:$maskedKey'; + } + + @override + String get appSettings_stadiaApiKeyDialogDescription => + '请输入你的 Stadia Maps API 密钥。该应用会使用它来请求栅格瓦片。'; + @override String get appSettings_offlineMapCache => '离线地图缓存'; @@ -960,6 +1132,29 @@ class AppLocalizationsZh extends AppLocalizations { return '从联系人中移除 $contactName?'; } + @override + String get contacts_removeFromContacts => 'Remove from contacts'; + + @override + String contacts_removeFromContactsConfirm(String contactName) { + return '$contactName will move to Discovered contacts. Chat history will be deleted.'; + } + + @override + String get contacts_keepChatHistory => 'Keep chat history'; + + @override + String get contacts_remove => 'Remove'; + + @override + String contacts_discoveredNearby(int count) { + return 'Discovered nearby ($count)'; + } + + @override + String get contacts_noContactsDiscoveredHint => + 'Nodes your radio hears but hasn\'t added yet are listed in Discovered contacts'; + @override String get contacts_manageRepeater => '管理转发节点'; @@ -1106,6 +1301,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_private => '私有'; + @override + String get channels_hashtag => 'Hashtag'; + + @override + String get channels_addSectionJoin => 'Join existing'; + + @override + String get channels_addSectionCreate => 'Create new'; + + @override + String get channels_dragToReorder => 'Drag to reorder'; + @override String get channels_editChannel => '编辑频道'; @@ -1233,6 +1440,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_publicChannelAdded => '已添加公共频道'; + @override + String get channels_noFreeSlots => '所有频道插槽都已被占用'; + @override String get channels_sortBy => '排序方式'; @@ -1286,17 +1496,30 @@ class AppLocalizationsZh extends AppLocalizations { @override String channels_regionSetTo(String region) { - return 'Region: $region'; + return '地区:$region'; } @override - String get channels_regionNotSet => 'Region: none'; + String get channels_regionNotSet => '地区:无'; @override - String get channels_regionSelect_Title => 'Select a region'; + String get channels_regionSelect_Title => '选择一个地区'; @override - String get channels_clearRegion => 'Clear region'; + String get channels_clearRegion => '无碍区域'; + + @override + String get channels_regionDefaultSuffix => '(default)'; + + @override + String get channels_regionSelectExplanation => + 'Flood messages on this channel will only be forwarded by repeaters in the selected region.'; + + @override + String get channels_regionEmpty => 'No regions yet.'; + + @override + String get channels_manageRegions => 'Manage regions'; @override String get chat_noMessages => '暂无消息'; @@ -1350,9 +1573,27 @@ class AppLocalizationsZh extends AppLocalizations { return '重试 $current/$max'; } + @override + String get chat_selectSendAction => '选择发送操作'; + @override String get chat_sendGif => '发送 GIF'; + @override + String get chat_removeGif => 'Remove GIF'; + + @override + String get chat_cancelReply => 'Cancel reply'; + + @override + String get chat_sendImageLora => '通过 MeshCore 发送图片'; + + @override + String get chat_imagePickFailed => '无法打开该图片'; + + @override + String get chat_receivedGif => '收到一个GIF'; + @override String get chat_reply => '回复'; @@ -1362,6 +1603,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_me => '我'; + @override + String get reaction_report => '表情反应'; + @override String get emojiCategorySmileys => '表情'; @@ -1499,13 +1743,13 @@ class AppLocalizationsZh extends AppLocalizations { String get routing_modeAuto => '汽车'; @override - String get routing_modeFlood => '洪水'; + String get routing_modeFlood => '泛洪'; @override String get routing_modeManual => '手册'; @override - String get routing_modeAutoHint => '自动选择已知最佳路径,当没有已知路径时,则进行“洪水”搜索。'; + String get routing_modeAutoHint => '自动选择已知最佳路径,当没有已知路径时,则进行“泛洪”搜索。'; @override String get routing_modeFloodHint => '通过所有中继站进行广播。 这种方式最可靠,但占用更多的时间。'; @@ -1553,7 +1797,7 @@ class AppLocalizationsZh extends AppLocalizations { String get routing_qualityWorked => '已完成'; @override - String get routing_qualityFlood => '通过新闻报道'; + String get routing_qualityFlood => '通过泛洪收到'; @override String get routing_qualityUntested => '未经测试'; @@ -1572,7 +1816,7 @@ class AppLocalizationsZh extends AppLocalizations { } @override - String get routing_floodDelivery => '洪水配送'; + String get routing_floodDelivery => '泛洪配送'; @override String get pathEditor_title => '构建路径'; @@ -1584,10 +1828,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get pathEditor_noHops => - '目前还没有添加任何啤酒花。点击下面的“添加”按钮,按顺序添加,或者直接保存,不添加任何啤酒花。'; + '目前还没有添加任何跳点。点击下面的“添加”按钮,按顺序添加,或者直接保存,不添加任何跳点。'; @override - String get pathEditor_addHops => '按照顺序添加啤酒花'; + String get pathEditor_addHops => '按照顺序添加跳点'; @override String get pathEditor_searchRepeaters => '重复搜索'; @@ -1599,7 +1843,7 @@ class AppLocalizationsZh extends AppLocalizations { String get pathEditor_hexLabel => '十六进制前缀'; @override - String get pathEditor_hexHelper => '每次跳跃,使用两个十六进制字符,用逗号分隔。'; + String get pathEditor_hexHelper => '每跳使用两个十六进制字符,用逗号分隔。'; @override String pathEditor_invalidTokens(String tokens) { @@ -1607,13 +1851,13 @@ class AppLocalizationsZh extends AppLocalizations { } @override - String get pathEditor_tooManyHops => '最多 64 个跳跃'; + String get pathEditor_tooManyHops => '最多 64 跳'; @override String get pathEditor_usePath => '请使用此路径'; @override - String get pathEditor_removeHop => '去除啤酒花'; + String get pathEditor_removeHop => '去除跳点'; @override String get pathEditor_unknownHop => '未知的重复器'; @@ -1633,6 +1877,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_path => '路径'; + @override + String get chat_viewPathOnMap => 'View path on map'; + @override String get chat_publicKey => '公钥'; @@ -1670,6 +1917,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_newMessages => '新的消息'; + @override + String get chat_today => 'Today'; + + @override + String get chat_yesterday => 'Yesterday'; + @override String get chat_openLink => '打开链接?'; @@ -1714,6 +1967,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get map_centerOnNode => '以节点为中心'; + @override + String get map_centerOnMe => 'Center on my location'; + @override String get map_details => '详细信息'; @@ -1732,6 +1988,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get map_noNodesWithLocation => '没有包含位置信息的节点'; + @override + String get map_noNodesLocationHint => + 'No nodes with a recent location. Widen the time filter, or set your own location in Settings.'; + @override String get map_nodesNeedGps => '节点需要共享 GPS 坐标才能在地图上显示'; @@ -1870,6 +2130,16 @@ class AppLocalizationsZh extends AppLocalizations { @override String get map_showGuessedLocations => '显示猜测的节点位置'; + @override + String get map_clusterNodes => 'Group nearby nodes'; + + @override + String get map_groupChip => 'Group'; + + @override + String get map_clusterNodesSubtitle => + 'When zoomed out, show nearby nodes as one numbered circle'; + @override String get map_showDiscoveryContacts => '显示发现联系人'; @@ -1891,6 +2161,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get map_manageRepeater => '管理转发节点'; + @override + String get map_manageServer => 'Manage Server'; + @override String get map_tapToAdd => '点击节点以添加到路径'; @@ -1978,6 +2251,42 @@ class AppLocalizationsZh extends AppLocalizations { return '下载失败:$count'; } + @override + String get mapCache_cachedTilesLabel => 'Cached tiles'; + + @override + String get mapCache_cachedTileSummaryLabel => 'Cached tile summary'; + + @override + String mapCache_bulkDownloadDisabledForSource(String source) { + return 'Offline bulk downloads are disabled for $source.'; + } + + @override + String mapCache_bulkDownloadDisabledInConfig(String source) { + return 'Offline bulk downloads are disabled for $source in this app configuration.'; + } + + @override + String mapCache_summarySource(String source) { + return 'Source: $source'; + } + + @override + String mapCache_summaryCachedTilesForSource(int count) { + return 'Cached tiles for source: $count'; + } + + @override + String mapCache_summaryCachedInSelection(int count) { + return 'Cached in selected area/zoom: $count'; + } + + @override + String mapCache_summaryApproxCacheSize(String size) { + return 'Approx cache size: $size'; + } + @override String mapCache_boundsLabel( String north, @@ -2054,6 +2363,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get login_enterPassword => '请输入密码'; + @override + String get login_showPassword => 'Show password'; + + @override + String get login_hidePassword => 'Hide password'; + @override String get login_savePassword => '保存密码'; @@ -2066,6 +2381,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get login_roomDescription => '输入房间服务器密码以访问设置和状态。'; + @override + String get login_advanced => 'Advanced'; + @override String get login_routing => '路由'; @@ -2103,6 +2421,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get common_clear => '清除'; + @override + String get common_clearSearch => 'Clear search'; + @override String get path_currentPathLabel => '当前路径'; @@ -2127,6 +2448,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get repeater_guestTools => '访客工具'; + @override + String get repeater_roleAdmin => 'ADMIN'; + + @override + String get repeater_roleGuest => 'GUEST'; + @override String get repeater_status => '状态'; @@ -2441,7 +2768,7 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_loopDetect => '循环检测'; @override - String get repeater_loopDetectHelper => '创建看起来像路由环的“洪水包”'; + String get repeater_loopDetectHelper => '创建看起来像路由环的“泛洪包”'; @override String get repeater_loopDetectOff => '离开'; @@ -2476,10 +2803,10 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_refreshOwnerInfo => '刷新操作员信息'; @override - String get repeater_floodMax => '最大跳跃次数'; + String get repeater_floodMax => '最大跳数'; @override - String get repeater_floodMaxHelper => '一个洪水包中,最大可以传输的跳数 (0-64)'; + String get repeater_floodMaxHelper => '一个泛洪包中,最大可以传输的跳数 (0-64)'; @override String get repeater_advancedSettings => '高级'; @@ -2492,14 +2819,46 @@ class AppLocalizationsZh extends AppLocalizations { @override String get repeater_pathHashModeHelper => - '用于编码此复用器的 ID 的字节数,在“洪流路径/环检测”标签中使用。 0=1 字节(256 个 ID,最多 64 个跳跃),1=2 字节(65K 个 ID,最多 32 个跳跃),2=3 字节(16M 个 ID,最多 21 个跳跃)。 v1.13 及更早版本的固件会使用多字节路径——只有在您的网络升级到 v1.14 或更高版本后才会生效。'; + '用于在洪泛路径/环路检测标签中编码此中继器 ID 的字节数。0=1 字节(256 个 ID,最多 64 跳),1=2 字节(65K 个 ID,最多 32 跳),2=3 字节(16M 个 ID,最多 21 跳)。v1.14 之前的固件始终使用 1 字节路径;v1.14 及更新版本可配置为 2 或 3 字节路径。'; @override - String get repeater_txDelay => '洪水(德克萨斯州)延误'; + String get repeater_keySettings => '更改身份密钥'; + + @override + String get repeater_keySettingsSubtitle => '更换公钥/私钥对'; + + @override + String get repeater_prvKey => '私钥'; + + @override + String get repeater_prvKeyHelper => '中继器的新私钥,为一个128位的十六进制字符串。'; + + @override + String get repeater_generatePrvKey => '生成一个随机的密钥对'; + + @override + String get repeater_stopGeneratingPrvKey => '中断密钥对搜索'; + + @override + String get repeater_pubKey => '公钥'; + + @override + String get repeater_pubKeyHelper => '这是与生成的私钥配对的公钥。您不能直接设置此内容。'; + + @override + String get repeater_pubKeyPrefix => '期望的前缀'; + + @override + String repeater_pubKeyPrefixHelper(int tries) { + return '找到一组以这些十六进制数字开头的公钥。预计尝试次数:$tries'; + } + + @override + String get repeater_txDelay => '泛洪 TX 延迟'; @override String get repeater_txDelayHelper => - '对于洪水流量,重新传输间隔应设置为包的传输时间(0-2,默认值为0.5)的倍数。 较高的值意味着更少的冲突,但传输速度会变慢。'; + '对于泛洪流量,重新传输间隔应设置为包的传输时间(0-2,默认值为0.5)的倍数。 较高的值意味着更少的冲突,但传输速度会变慢。'; @override String get repeater_directTxDelay => '直接的 TX 延迟'; @@ -2526,16 +2885,16 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_actionsTitle => '行动'; @override - String get repeater_sendAdvert => '发布防洪广告'; + String get repeater_sendAdvert => '发送泛洪广播'; @override - String get repeater_sendAdvertSubtitle => '通过网络播放防洪广告'; + String get repeater_sendAdvertSubtitle => '向整个网络发送泛洪广播'; @override - String get repeater_sendAdvertZeroHop => '发送零跳广告'; + String get repeater_sendAdvertZeroHop => '发送零跳广播'; @override - String get repeater_sendAdvertZeroHopSubtitle => '进行单跳广告广播(不使用中继)'; + String get repeater_sendAdvertZeroHopSubtitle => '发送单跳广播(不使用中继)'; @override String get repeater_clockSync => '现在同步时钟'; @@ -2584,6 +2943,17 @@ class AppLocalizationsZh extends AppLocalizations { @override String get repeater_refreshPrivacyMode => '刷新隐私模式'; + @override + String get repeater_refreshAll => 'Refresh all'; + + @override + String get repeater_settingsNotLoaded => + 'Settings haven\'t been loaded from this repeater yet.'; + + @override + String get repeater_settingsLoadIncomplete => + 'Some settings could not be loaded. Use the refresh buttons to retry.'; + @override String repeater_refreshed(String label) { return '$label 已刷新'; @@ -2828,6 +3198,68 @@ class AppLocalizationsZh extends AppLocalizations { @override String get repeater_commandsListNote => '注意:多数 set 命令也有对应的 get 命令'; + @override + String get repeater_frequencyRangeHelper => '150-2500 MHz'; + + @override + String get repeater_frequencyInvalid => '无效频率(150-2500 MHz)'; + + @override + String get repeater_txPowerRangeHelper => '-9 至 30 dBm'; + + @override + String get repeater_recvErrors => '接收错误'; + + @override + String get room_postsStored => '帖子'; + + @override + String get room_postsPushed => '已推送的帖子'; + + @override + String get repeater_cliRegionLoadActive => + '区域加载模式:每行发送一个区域名称,并用空格缩进表示其位于父级之下(在名称后添加 F 可允许泛洪)。每行不会有回复。发送空行以结束,然后发送“region save”以保存结果。'; + + @override + String get repeater_cliRegionLoadHint => '区域行,或留空以结束'; + + @override + String get repeater_cliRegionLoadEnd => '(区域加载结束)'; + + @override + String get repeater_cliHelpRegionDef => + '在一条命令中定义一条区域链:每个名称都添加在上一个名称之下;“name,parent”会添加该名称,然后在指定的父级下继续。回复区域列表。'; + + @override + String get repeater_cliHelpSetFloodMaxUnscoped => + '设置转发无区域范围的泛洪数据包时的最大跳数(0-64)。'; + + @override + String get repeater_cliHelpSetFloodMaxAdvert => '设置转发泛洪广播包时的最大跳数(0-64)。'; + + @override + String get repeater_cliHelpGetFloodMaxUnscoped => '显示无区域范围的泛洪数据包的最大跳数。'; + + @override + String get repeater_cliHelpGetFloodMaxAdvert => '显示泛洪广播包的最大跳数。'; + + @override + String get repeater_cliHelpSetRadioFemRxGain => + '切换 LoRa 前端模块的 RX 增益(LNA)。不支持此功能的板卡会回复“Error: unsupported”。'; + + @override + String get repeater_cliHelpSetRadioFemTxGain => + '切换 LoRa 前端模块的 TX 增益(PA)。不支持此功能的板卡会回复“Error: unsupported”。'; + + @override + String get repeater_cliHelpGetRadioFemRxGain => '显示 LoRa 前端模块的 RX 增益是否已开启。'; + + @override + String get repeater_cliHelpGetRadioFemTxGain => '显示 LoRa 前端模块的 TX 增益是否已开启。'; + + @override + String get repeater_bridgeNote => '仅支持带有桥接功能(RS232 或 ESP-NOW)的固件。'; + @override String get repeater_general => '通用'; @@ -2871,7 +3303,7 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_cliHelpClkReboot => '将时钟重置为已知的时间点,并重启设备。'; @override - String get repeater_cliHelpAdvertZeroHop => '发送无中继广告(仅限于邻居)。'; + String get repeater_cliHelpAdvertZeroHop => '发送无中继广播(仅限于邻居)。'; @override String get repeater_cliHelpStartOta => '在支持的板上启动通过空中进行固件更新。'; @@ -2907,7 +3339,7 @@ class AppLocalizationsZh extends AppLocalizations { '(仅适用于 SX126x 芯片) 启用增强型 RX 增益,以在较高电流下提高灵敏度。'; @override - String get repeater_cliHelpSetOwnerInfo => '设置广告中包含的联系人信息字符串。使用 \'|\' 作为换行符。'; + String get repeater_cliHelpSetOwnerInfo => '设置广播中包含的联系人信息字符串。使用 \'|\' 作为换行符。'; @override String get repeater_cliHelpSetPathHashMode => @@ -2970,10 +3402,10 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_cliHelpGetAllowReadOnly => '显示是否允许访客仅限查看权限。'; @override - String get repeater_cliHelpGetAdvertInterval => '显示本地广告的时间间隔,单位为分钟。'; + String get repeater_cliHelpGetAdvertInterval => '显示本地广播的时间间隔,单位为分钟。'; @override - String get repeater_cliHelpGetFloodAdvertInterval => '显示洪水广告的播放时间间隔,以小时为单位。'; + String get repeater_cliHelpGetFloodAdvertInterval => '显示泛洪广播的播放时间间隔,以小时为单位。'; @override String get repeater_cliHelpGetGuestPassword => '显示已配置的访客密码。'; @@ -2988,13 +3420,13 @@ class AppLocalizationsZh extends AppLocalizations { String get repeater_cliHelpGetRxDelay => '显示 rxdelay 的基本值。'; @override - String get repeater_cliHelpGetTxDelay => '显示洪水模式下的传输延迟系数。'; + String get repeater_cliHelpGetTxDelay => '显示泛洪模式下的传输延迟系数。'; @override String get repeater_cliHelpGetDirectTxDelay => '显示直接模式下的时延系数。'; @override - String get repeater_cliHelpGetFloodMax => '显示最大洪水传播次数。'; + String get repeater_cliHelpGetFloodMax => '显示最大泛洪跳数。'; @override String get repeater_cliHelpGetOwnerInfo => '显示所有者的联系信息。'; @@ -3061,10 +3493,10 @@ class AppLocalizationsZh extends AppLocalizations { '设置默认的区域范围。使用 \"\" 可以清除。'; @override - String get repeater_cliHelpRegionListAllowed => '列出允许洪水交通的区域。'; + String get repeater_cliHelpRegionListAllowed => '列出允许泛洪交通的区域。'; @override - String get repeater_cliHelpRegionListDenied => '列出禁止洪水交通的区域。'; + String get repeater_cliHelpRegionListDenied => '列出禁止泛洪交通的区域。'; @override String get repeater_cliHelpStatsPackets => '(仅显示序列信息)显示数据包级别的统计信息。'; @@ -3826,6 +4258,23 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_addContactFromClipboard => '从剪贴板添加联系人'; + @override + String get contacts_scanQrCode => 'Scan QR Code'; + + @override + String get contacts_scanQrInstructions => + 'Point the camera at a MeshCore contact QR code'; + + @override + String get contacts_qrFromGallery => 'Scan QR from Gallery'; + + @override + String get contacts_noQrCodeFound => + 'No QR code found in the selected image.'; + + @override + String get contacts_qrGalleryFailed => 'Could not open the gallery.'; + @override String get contacts_ShareContact => '复制联系人信息到剪贴板'; @@ -3921,6 +4370,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get snrIndicator_lastSeen => '最近访问'; + @override + String get snrIndicator_nearByRepeatersDescription => + 'Repeaters your radio heard directly, most recently heard first.'; + @override String get contactsSettings_title => '联系人设置'; @@ -4013,6 +4466,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get radioStats_screenTitle => '广播统计数据'; + @override + String get radioStats_sectionSignal => 'Signal'; + + @override + String get radioStats_sectionAirtime => 'Airtime'; + @override String get radioStats_notConnected => '连接到设备以查看收音机统计信息。'; @@ -4067,6 +4526,40 @@ class AppLocalizationsZh extends AppLocalizations { @override String get translation_title => '翻译'; + @override + String get imageMessages_enableTitle => '启用图片消息'; + + @override + String get imageMessages_enableSubtitle => '通过网格发送图像。需要一次性下载图像模型。'; + + @override + String get imageMessages_modelSectionTitle => '图像模型'; + + @override + String get imageMessages_downloadModel => '下载'; + + @override + String get imageMessages_cancelDownload => '取消'; + + @override + String get imageMessages_removeModel => '移除模型'; + + @override + String get imageMessages_modelReady => '准备就绪'; + + @override + String get imageMessages_modelNotPublished => '尚未发布——此版本无法下载该内容。'; + + @override + String get imageMessages_downloadFailed => '图像模型无法下载。'; + + @override + String get imageMessages_autoProcessTitle => '自动处理图像'; + + @override + String get imageMessages_autoProcessSubtitle => + '每次图像到达后立即重建,每次需要约2GB的内存;若想关闭重建功能,可通过点击取消开启。'; + @override String get translation_enableTitle => '启用翻译功能'; @@ -4341,4 +4834,240 @@ class AppLocalizationsZh extends AppLocalizations { @override String get pathMap_unfollowPacket => '解锁视图跟随'; + + @override + String get imageSend_title => '发送图片'; + + @override + String get imageSend_cropNote => '调整大小至512 × 512 · 宽高比未保留'; + + @override + String imageSend_lossyNote(int bytes) { + return 'Compressed to about $bytes bytes. The receiver\'s model reconstructs it, so details will differ.'; + } + + @override + String get imageSend_viewOriginal => 'Original'; + + @override + String get imageSend_viewReconstruction => 'What recipients see'; + + @override + String get imageSend_reconstructionUnavailable => + 'This device can\'t preview the reconstruction.'; + + @override + String get imageSend_modelNotDownloaded => + 'The image model isn\'t downloaded yet. Download it in Settings to send images.'; + + @override + String get imageSend_originalSize => '原文'; + + @override + String get imageSend_onAirSize => '直播中'; + + @override + String get imageSend_quality => '质量'; + + @override + String get imageSend_qualityStandard => '标准'; + + @override + String get imageSend_qualityHigh => '高'; + + @override + String get imageSend_packetsLabel => '数据包'; + + @override + String get imageSend_airtimeLabel => '播出时间'; + + @override + String get imageSend_sizeLabel => '有效载荷'; + + @override + String imageSend_packetsCount(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '个数据包', + one: '个数据包', + ); + return '$count $_temp0'; + } + + @override + String imageSend_range(String min, String max) { + return '$min–$max'; + } + + @override + String get imageSend_unknownValue => '—'; + + @override + String get imageSend_radioUnknownTitle => '无线电设置未知'; + + @override + String get imageSend_radioUnknownBody => '连接设备以计算播出时间。'; + + @override + String get imageSend_longSendTitle => '长距离传输'; + + @override + String imageSend_longSendBody(String duration) { + return '这将维持频道大约 $duration 时间。'; + } + + @override + String get imageSend_floodNote => '泛洪路由:每个中继站都会转发每个数据包,因此信道比这段时间更长地处于繁忙状态。'; + + @override + String get imageSend_parityTitle => '恢复包'; + + @override + String get imageSend_paritySubtitle => + '多一个数据包。群发消息不被确认,因此如果某个数据包丢失,接收方可以重新构建图像。'; + + @override + String get imageSend_send => '发送'; + + @override + String get imageSend_cancel => '取消'; + + @override + String get imageSend_encodeFailed => '此图像无法编码。'; + + @override + String get imageSend_codecDownloading => '图像模型仍在下载中。'; + + @override + String get imageSend_codecUnavailable => '此设备无法发送图片。'; + + @override + String get imageSend_codecDisabled => '图片消息在设置中已关闭。'; + + @override + String get imageSend_deviceUnsupported => + '此无线电无法发送图像数据包。请连接运行伴侣固件13或更高版本的设备。'; + + @override + String get imageSend_directMessagesUnsupported => + '图片作为群组数据传输,因此只能发送到频道,而不能直接发送给个人。'; + + @override + String get imageSend_tooLarge => '该图像编码的数据包数量超过了网格格式所允许的范围。'; + + @override + String imageSend_sentConfirmation(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '个数据包', + one: '个数据包', + ); + return '图像已作为 $count $_temp0 发送。'; + } + + @override + String imageSend_sendFailed(String error) { + return '无法发送图片:$error'; + } + + @override + String imageSend_sendingProgress(int sent, int total) { + return '发送图像 — 已发送 $sent 包含 $total'; + } + + @override + String receivedImage_senderPrefix(String prefix) { + return '节点 $prefix'; + } + + @override + String receivedImage_incoming(int received, int total) { + return '已收到的 $received 个包含在 $total 个包裹中'; + } + + @override + String get receivedImage_queued => '等待解码'; + + @override + String get receivedImage_tapToDecode => '点击解锁'; + + @override + String get receivedImage_decoding => '重建……大约1秒'; + + @override + String receivedImage_incomplete(int received, int total) { + return '图片不完整 — $received 已收到 $total 个数据包'; + } + + @override + String get receivedImage_corrupt => '图像无法重建'; + + @override + String get receivedImage_decoderMissing => '收到图片 — 图像解码失败'; + + @override + String get receivedImage_evicted => '图片已不再存储'; + + @override + String get receivedImage_retry => '再试一次'; + + @override + String get receivedImage_decodeAgain => '重新解码'; + + @override + String get receivedImage_openSettings => '建立'; + + @override + String get receivedImage_tapToProcess => '点击处理'; + + @override + String get receivedImage_save => 'Save image'; + + @override + String receivedImage_shareCaption(int bytes) { + return 'AI-reconstructed from $bytes bytes; fine detail is generated, not transmitted.'; + } + + @override + String get receivedImage_packetInfo => 'Packet info'; + + @override + String get receivedImage_parityRecovered => + 'One packet was rebuilt from the recovery packet.'; + + @override + String receivedImage_decodeTime(int ms) { + return 'Reconstructed in $ms ms'; + } + + @override + String get receivedImage_saveFailed => 'Couldn\'t save the image'; + + @override + String receivedImage_awaiting(int bytes, int packets) { + String _temp0 = intl.Intl.pluralLogic( + packets, + locale: localeName, + other: '个数据包', + one: '个数据包', + ); + return '$bytes 字节 · $packets $_temp0'; + } + + @override + String imageSend_secondsValue(String seconds) { + return '$seconds 秒'; + } + + @override + String imageSend_minutesSecondsValue(String minutes, String seconds) { + return '$minutes 分 $seconds 秒'; + } + + @override + String chat_longMessageRetryNote(int count) { + return '超过158字节:最多发送 $count 次'; + } } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 8eb7f331..a4f066f3 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Ongeldige breedtegraad of lengtegraad.", "settings_latitude": "Breedtegraad", "settings_longitude": "Lengtegraad", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatische zero-hop-advertentie bij GPS-update", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Wanneer de GPS-locatie verandert, een zero-hop-advertentie verzenden (vereist locatie in advertentie).", "settings_privacyMode": "Privacy-modus", "settings_privacyModeSubtitle": "Naam/locatie verbergen in advertenties", "settings_privacyModeToggle": "Schakel privacy modus in om je naam en locatie in advertenties te verbergen.", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Afgelopen 6 uur", "appSettings_last24Hours": "Afgelopen 24 uur", "appSettings_lastWeek": "Afgelopen week", + "appSettings_rasterTileSource": "Rastertegelbron", + "appSettings_stadiaEndpoint": "Stadia-eindpunt", + "appSettings_stadiaApiKey": "Stadia API-sleutel", + "appSettings_stadiaApiKeyRequired": "Vereist voor gebruik van Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Geconfigureerd: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Voer je Stadia Maps API-sleutel in. De app gebruikt die voor rastertegelverzoeken.", "appSettings_offlineMapCache": "Offline Kaartcache", "appSettings_noAreaSelected": "Geen gebied geselecteerd", "appSettings_areaSelectedZoom": "Geselecteerd gebied (zoom {minZoom}-{maxZoom})", @@ -470,6 +485,7 @@ } } }, + "chat_selectSendAction": "Verzendactie selecteren", "chat_sendGif": "GIF verzenden", "chat_reply": "Reageren", "chat_addReaction": "Reactie toevoegen", @@ -566,7 +582,7 @@ "chat_recentAckPaths": "Recente ACK Paden (tik om te gebruiken):", "chat_pathHistoryFull": "De voorgeschiedenis is vol. Verwijder vermeldingen om er nieuwe aan toe te voegen.", "chat_hopSingular": "Hop", - "chat_hopPlural": "hoppen", + "chat_hopPlural": "hops", "chat_hopsCount": "{count} {count, plural, =1{hop} other{hops}}", "@chat_hopsCount": { "placeholders": { @@ -616,7 +632,7 @@ } } }, - "chat_floodAuto": "Overstroming (van een auto)", + "chat_floodAuto": "Flood (automatisch)", "chat_direct": "Direct", "chat_poiShared": "Gedeelde POI", "chat_unread": "Nieuw: {count}", @@ -769,6 +785,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -980,7 +1046,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Overstroming: {flood}, Direct: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Direct: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1107,9 +1173,9 @@ "repeater_advancedSettings": "Geavanceerd", "repeater_advancedSettingsSubtitle": "Regelhendels voor ervaren gebruikers", "repeater_pathHashMode": "Hash-modus voor paden", - "repeater_pathHashModeHelper": "Bytes die gebruikt worden om de ID van deze repeater te coderen in flood-pad/lusdetectietags. 0=1 byte (256 ID's, tot 64 hops), 1=2 bytes (65.000 ID's, tot 32 hops), 2=3 bytes (16 miljoen ID's, tot 21 hops). Versies 1.13 en ouder gebruiken multi-byte paden – alleen na het activeren van het netwerk.", + "repeater_pathHashModeHelper": "Bytes die gebruikt worden om de ID van deze repeater te coderen in flood-pad/lusdetectietags. 0=1 byte (256 ID's, tot 64 hops), 1=2 bytes (65.000 ID's, tot 32 hops), 2=3 bytes (16 miljoen ID's, tot 21 hops). Firmware vóór v1.14 gebruikte altijd 1-byte paden; v1.14 en nieuwer kunnen worden ingesteld op 2- of 3-byte paden.", "repeater_txDelay": "Vertraging bij Flood TX", - "repeater_txDelayHelper": "Herzendinterval voor verkeer tijdens overstromingen, als een veelvoud van de tijd die het pakket nodig heeft (0-2, standaard 0.5). Een hoger getal betekent minder botsingen, maar ook een langere leveringstijd.", + "repeater_txDelayHelper": "Herzendinterval voor flood-verkeer, als een veelvoud van de tijd die het pakket nodig heeft (0-2, standaard 0.5). Een hoger getal betekent minder botsingen, maar ook een langere leveringstijd.", "repeater_directTxDelay": "Directe vertraging", "repeater_directTxDelayHelper": "De overzending van tijdslots voor directe (niet-massaal) verkeer, als een vermenigvuldigingsfactor van de tijd die een pakket nodig heeft (0-2, standaard 0,3).", "repeater_intThresh": "Grenswaarde voor interferentie", @@ -1117,8 +1183,8 @@ "repeater_agcResetInterval": "Interval voor het opnieuw instellen van AGC", "repeater_agcResetIntervalHelper": "Hoe vaak moet u de automatische gainregeling van de radio opnieuw instellen om terug te keren van een situatie waarin de gain vastzit? Elke seconde, of elke 4e seconde. Het uitschakelen van de periodieke reset (0) zorgt ervoor dat de gain niet automatisch wordt aangepast.", "repeater_actionsTitle": "Acties", - "repeater_sendAdvert": "Verzend advertentie over overstromingen", - "repeater_sendAdvertSubtitle": "Zend een advertentie over overstromingen uit via het netwerk.", + "repeater_sendAdvert": "Verzend flood-advertentie", + "repeater_sendAdvertSubtitle": "Zend een flood-advertentie uit via het netwerk.", "repeater_sendAdvertZeroHop": "Verzend een advertentie zonder tussenliggende stap", "repeater_sendAdvertZeroHopSubtitle": "Zend een advertentie met één enkele verbinding (zonder tussenliggende zenders).", "repeater_clockSync": "Synchroniseer klok nu", @@ -1417,7 +1483,7 @@ } }, "channelPath_unknownPath": "Onbekend", - "channelPath_floodPath": "Overstroming", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Direct", "channelPath_observedZeroOf": "0 van {total} sprongen", "@channelPath_observedZeroOf": { @@ -1689,8 +1755,8 @@ "appSettings_languageUk": "Oekraïens", "contacts_invalidAdvertFormat": "Ongeldige contactgegevens", "contacts_contactImportFailed": "Contact kon niet geïmporteerd worden.", - "contacts_zeroHopAdvert": "Zero Hop Reclame", - "contacts_floodAdvert": "Overstromingsadvertentie", + "contacts_zeroHopAdvert": "Zero-hop-advertentie", + "contacts_floodAdvert": "Flood-advertentie", "contacts_copyAdvertToClipboard": "Advert naar klembord kopiëren", "appSettings_languageRu": "Russisch", "appSettings_enableMessageTracing": "Berichttracking inschakelen", @@ -1699,7 +1765,7 @@ "contacts_addContactFromClipboard": "Contact uit klembord toevoegen", "contacts_contactImported": "Contact is geïmporteerd.", "contacts_zeroHopContactAdvertSent": "Contact verzonden via advertentie", - "contacts_contactAdvertCopied": "Reclame gekopieerd naar Klembord.", + "contacts_contactAdvertCopied": "Advertentie gekopieerd naar Klembord.", "contacts_contactAdvertCopyFailed": "Kopiëren van advertentie naar Clipboard is mislukt.", "contacts_ShareContact": "Contact naar Klembord kopiëren", "contacts_ShareContactZeroHop": "Contact delen via advertentie", @@ -2233,15 +2299,15 @@ "repeater_cliHelpGetAgcResetInterval": "Geeft het interval in seconden aan voor het resetten van de AGC (Automatic Gain Control).", "repeater_cliHelpGetMultiAcks": "Geeft aan of de modus \"dubbele bevestiging\" is ingeschakeld (1) of uitgeschakeld (0).", "repeater_cliHelpGetAllowReadOnly": "Geeft aan of er toegang is voor gastgebruikers zonder rechten.", - "repeater_cliHelpGetAdvertInterval": "Geeft de duur van de lokale reclame in minuten aan.", - "repeater_cliHelpGetFloodAdvertInterval": "Geeft de duur van de reclame-interval in uren aan.", + "repeater_cliHelpGetAdvertInterval": "Geeft de duur van het lokale advertentie-interval in minuten aan.", + "repeater_cliHelpGetFloodAdvertInterval": "Geeft de duur van het flood-advertentie-interval in uren aan.", "repeater_cliHelpGetGuestPassword": "Toont het ingestelde gastwachtwoord.", "repeater_cliHelpGetLat": "Toont de ingestelde breedtegraad.", "repeater_cliHelpGetLon": "Toont de ingestelde lengtegraad.", "repeater_cliHelpGetRxDelay": "Toont de basiswaarde van de rx-vertraging.", "repeater_cliHelpGetTxDelay": "Geeft de factor weer die de vertraging in de flood-modus bepaalt.", "repeater_cliHelpGetDirectTxDelay": "Geeft de factor voor de vertraging in de directe modus weer.", - "repeater_cliHelpGetFloodMax": "Toont het maximale aantal keer dat een overstroming heeft plaatsgevonden.", + "repeater_cliHelpGetFloodMax": "Toont het maximale aantal hops voor flood-pakketten.", "repeater_cliHelpGetOwnerInfo": "Toont de string met contactgegevens van de eigenaar.", "repeater_cliHelpGetPathHashMode": "Toont de modus voor het berekenen van de hash (0/1/2).", "repeater_cliHelpGetLoopDetect": "Geeft de gevoeligheid voor het detecteren van lusvorming weer.", @@ -2263,8 +2329,8 @@ "repeater_cliHelpSensorList": "Toont alle aangepaste instellingen voor sensoren, gegroepeerd op basis van een optionele startindex.", "repeater_cliHelpRegionDefault": "Toont het huidige standaard regio-bereik.", "repeater_cliHelpRegionDefaultSet": "Stelt de standaard regio-omvang in. Gebruik \"\" om deze te resetten.", - "repeater_cliHelpRegionListAllowed": "Lijst van gebieden waar doorstromen tijdens overstromingen is toegestaan.", - "repeater_cliHelpRegionListDenied": "Geeft een lijst van regio's die het verkeer tijdens overstromingen verbieden.", + "repeater_cliHelpRegionListAllowed": "Geeft een lijst van regio's die flood-verkeer toestaan.", + "repeater_cliHelpRegionListDenied": "Geeft een lijst van regio's die flood-verkeer verbieden.", "repeater_cliHelpStatsPackets": "(Alleen voor seriële verbindingen) Toont statistieken op pakketniveau.", "repeater_cliHelpStatsRadio": "(Alleen voor serienummers) Toont radio-statistieken.", "repeater_cliHelpStatsCore": "(Alleen voor seriële communicatie) Toont de belangrijkste firmware-statistieken.", @@ -2403,7 +2469,7 @@ "contacts_searchClose": "Zoeken", "routing_title": "Routeplanning", "routing_modeAuto": "Auto", - "routing_modeFlood": "Overstroming", + "routing_modeFlood": "Flood", "routing_modeManual": "Handleiding", "routing_modeAutoHint": "Selecteert automatisch het bekendste pad, en gebruikt een flood-algoritme als er geen bekend pad is.", "routing_modeFloodHint": "Uitzendingen via elke zender. De meest betrouwbare methode, maar vereist meer uitzendtijd.", @@ -2421,13 +2487,13 @@ "routing_qualityGood": "Een goede eerste stap", "routing_qualityFair": "Een goede eerste hop", "routing_qualityWorked": "Is geleverd", - "routing_qualityFlood": "Hears via een overstroming", + "routing_qualityFlood": "Gehoord via flood", "routing_qualityUntested": "Niet getest", "routing_neverWorked": "nooit bevestigd", "routing_deliveryCounts": "{successes} zijn behaald, {failures} zijn mislukt", - "routing_floodDelivery": "Levering bij overstroming", + "routing_floodDelivery": "Flood-levering", "pathEditor_title": "Pad creëren", - "pathEditor_hopCounter": "{count} van 64 hopgranen", + "pathEditor_hopCounter": "{count} van 64 hops", "pathEditor_noHops": "Er zijn nog geen hop toegevoegd. Klik op de onderstaande knoppen om ze in de juiste volgorde toe te voegen, of sla de bestelling op zonder hop om deze direct te versturen.", "pathEditor_addHops": "Voeg hop toe in de juiste volgorde.", "pathEditor_searchRepeaters": "Zoek naar herhaaldelijke zenders", @@ -2435,7 +2501,7 @@ "pathEditor_hexLabel": "Hex-voorkanten", "pathEditor_hexHelper": "Twee hex-tekens per stap, gescheiden door komma's", "pathEditor_invalidTokens": "Ongeldig: {tokens}", - "pathEditor_tooManyHops": "Maximaal 64 hopken", + "pathEditor_tooManyHops": "Maximaal 64 hops", "pathEditor_usePath": "Gebruik deze route.", "pathEditor_removeHop": "Verwijder de hop", "pathEditor_unknownHop": "Onbekend type zender", @@ -2540,5 +2606,261 @@ "pathMap_noLocation": "Geen locatie", "pathMap_followPacket": "Weergave vergrendelen op pakket", "pathMap_unfollowPacket": "Weergave ontgrendelen van pakket", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regio's", + "settings_regionSettingsSubtitle": "Beheer van opgeslagen regio's", + "settings_regionManagement_screenTitle": "Regionale Bestuur", + "settings_regionNameHint": "Regio naam invoeren", + "settings_regionAddRegion": "Regio toevoegen", + "settings_regionFetchRegions": "Haal regio's uit herhalers", + "settings_regionFetchRegionsFail": "Er zijn geen regio's gevonden", + "settings_regionFetchRegionsAlreadyExists": "Deze regio is al toegevoegd.", + "settings_regionName": "Regio Naam", + "settings_regionDeleted": "Regio verwijderd", + "settings_deleteRegion": "Regio verwijden", + "settings_deleteRegionConfirm": "Verwijder \"{region}\" uit de regio-lijst?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 bytes", + "repeater_pathHashModeOption2": "2 - 3 bytes", + "repeater_pathHashModeOption3": "3 - 4 bytes", + "appSettings_batteryLipoHv": "LiPo HV (3,0-4,35 V)", + "channels_regionSetTo": "Regio: {region}", + "channels_regionNotSet": "Regio: geen", + "channels_regionSelect_Title": "Kies een regio", + "channels_clearRegion": "Duidelijke regio", + "chat_sendImageLora": "Afbeelding verzenden via MeshCore", + "chat_imagePickFailed": "Kunde die afbeelding niet openen", + "chat_receivedGif": "Ontvangen van een GIF", + "repeater_keySettings": "Verander de Identiteitskies", + "repeater_keySettingsSubtitle": "Wijzig de openbare/private sleutelpaar", + "repeater_prvKey": "Geheime sleutel", + "repeater_prvKeyHelper": "Een nieuwe private sleutel voor de repeater, een 128-karakter lange hexadecimale string.", + "repeater_generatePrvKey": "Stel een willekeurige sleutelpaar op", + "repeater_stopGeneratingPrvKey": "Stop zoek naar sleutelpaar", + "repeater_pubKey": "Openbaar sleutel", + "repeater_pubKeyHelper": "Dit is de openbare sleutel die past bij de gegenereerde privésleutel. U kunt dit niet direct instellen.", + "repeater_pubKeyPrefix": "Verlangde voorvoegsel", + "repeater_pubKeyPrefixHelper": "Zoek een openbare sleutel die begint met deze hexadecimale cijfers. Verwacht aantal pogingen: {tries}.", + "imageMessages_enableTitle": "Bijbehorende afbeeldingen activeren", + "imageMessages_enableSubtitle": "Beeldjes verzenden via het netwerk. Vereist eenmalig afdaling van een beeldmodel.", + "imageMessages_modelSectionTitle": "Beeldmodel", + "imageMessages_downloadModel": "Download", + "imageMessages_cancelDownload": "Annuleren", + "imageMessages_removeModel": "Model verwijderen", + "imageMessages_modelReady": "Klaar", + "imageMessages_modelNotPublished": "Nog niet gepubliceerd — deze versie kan dit niet downloaden.", + "imageMessages_downloadFailed": "Het beeldmodel kon niet worden gedownload.", + "imageMessages_autoProcessTitle": "Beeldverwerking automatisch", + "imageMessages_autoProcessSubtitle": "Reconstrueer elk beeld direct nadat het binnenkomt. Het gebruikt ongeveer 2 GB geheugen voor elke keer; schakel het reconstrueren uit met een tik als je het niet nodig hebt.", + "imageSend_title": "Beeld verzenden", + "imageSend_cropNote": "Aangepast aan 512 × 512 · het aspectverhouding is niet behouden", + "imageSend_originalSize": "Oorspronkelijk", + "imageSend_onAirSize": "Op de lucht", + "imageSend_quality": "Kwaliteit", + "imageSend_qualityStandard": "Standaard", + "imageSend_qualityHigh": "Hoog", + "imageSend_packetsLabel": "Pakketten", + "imageSend_airtimeLabel": "Tijd op de lucht", + "imageSend_sizeLabel": "Belasting", + "imageSend_packetsCount": "{count} {count, plural, =1{pakket} other{pakketten}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Radio-instellingen onbekend", + "imageSend_radioUnknownBody": "Verbinding maken met een apparaat zodat de uitzendtijd kan worden berekend.", + "imageSend_longSendTitle": "Lange transmissie", + "imageSend_longSendBody": "Dit houdt de kanaal ongeveer voor {duration} stand.", + "imageSend_floodNote": "Flood-routing: elke repeater binnen bereik herzendsends elk pakket opnieuw, waardoor het kanaal langer bezig blijft dan dit.", + "imageSend_parityTitle": "Herstelpakket", + "imageSend_paritySubtitle": "Een extra pakje. Groepsberichten worden niet bevestigd, waardoor de ontvanger het beeld kan herstellen als een enkel pakket verloren gaat.", + "imageSend_send": "Stuur", + "imageSend_cancel": "Annuleren", + "imageSend_encodeFailed": "Dit beeld kon niet worden gecodeerd.", + "imageSend_codecDownloading": "Het beeldmodel wordt nog steeds gedownload.", + "imageSend_codecUnavailable": "Het verzenden van een afbeelding is niet mogelijk op dit apparaat.", + "imageSend_codecDisabled": "Boodschappen met afbeeldingen zijn uitgeschakeld in de instellingen.", + "imageSend_deviceUnsupported": "Dit radio kan geen beeldpakketten verzenden. Verbind een apparaat met de bijbehorende firmware versie 13 of nieuwer.", + "imageSend_directMessagesUnsupported": "Afbeeldingen worden verzonden als groepsgegevens, dus ze kunnen alleen naar een kanaal worden gestuurd — niet via een directe boodschap.", + "imageSend_tooLarge": "Die afbeelding werd gecodeerd in meer pakketten dan het mesh-formaat toelaat.", + "imageSend_sentConfirmation": "Afbeelding verzonden als {count} {count, plural, =1{pakket} other{pakketten}}.", + "imageSend_sendFailed": "Het beeld kon niet worden verzonden: {error}", + "imageSend_sendingProgress": "Beeld verzenden — pakket {sent} van {total}", + "receivedImage_senderPrefix": "Knipper {prefix}", + "receivedImage_incoming": "{received} van de {total} pakketten", + "receivedImage_queued": "Wachten op het ontcijferen", + "receivedImage_tapToDecode": "Tik om te decoderen", + "receivedImage_decoding": "Herstellen… ongeveer 1 seconde", + "receivedImage_incomplete": "Afbeelding onvolledig — {received} van {total} pakketten ontvangen", + "receivedImage_corrupt": "Afbeelding kon niet worden gereconstrueerd", + "receivedImage_decoderMissing": "Beeld ontvangen — beeldontcipheringsapparatuur is uitgeschakeld", + "receivedImage_evicted": "Afbeelding niet langer opgeslagen", + "receivedImage_retry": "Probeer het opnieuw", + "receivedImage_decodeAgain": "Decode opnieuw", + "receivedImage_openSettings": "Inricht", + "receivedImage_tapToProcess": "Tik om te verwerken", + "receivedImage_awaiting": "{bytes} bytes · {packets} {packets, plural, =1{pakket} other{pakketten}}", + "imageSend_secondsValue": "{seconds} seconden", + "imageSend_minutesSecondsValue": "{minutes} m {seconds} s", + "channels_noFreeSlots": "Alle kanaalslots zijn bezet", + "chat_longMessageRetryNote": "Meer dan 158 bytes: maximaal {count} keer verzonden", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "reaction_report": "Emoji-reacties", + "repeater_bridgeNote": "Alleen beschikbaar bij firmware gebouwd met een bridge (RS232 of ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Toont het maximale aantal hops voor flood-advertenties.", + "repeater_cliHelpGetFloodMaxUnscoped": "Toont het maximale aantal hops voor flood-pakketten zonder regio-scope.", + "repeater_cliHelpGetRadioFemRxGain": "Toont of de RX-versterking van de LoRa-frontendmodule aan staat.", + "repeater_cliHelpGetRadioFemTxGain": "Toont of de TX-versterking van de LoRa-frontendmodule aan staat.", + "repeater_cliHelpRegionDef": "Definieert een keten van regio's in één commando: elke naam wordt onder de vorige toegevoegd; \"name,parent\" voegt de naam toe en gaat dan verder onder de opgegeven bovenliggende regio. Antwoordt met de regiolijst.", + "repeater_cliHelpSetFloodMaxAdvert": "Stelt het maximale aantal hops in voor het doorsturen van flood-advertenties (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Stelt het maximale aantal hops in voor het doorsturen van flood-pakketten zonder regio-scope (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Schakelt de RX-versterking (LNA) van de LoRa-frontendmodule. Boards zonder deze module antwoorden met \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Schakelt de TX-versterking (PA) van de LoRa-frontendmodule. Boards zonder deze module antwoorden met \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Regio-laadmodus: verstuur per regel één regionaam, ingesprongen met spaties onder de bovenliggende regio (voeg F toe na de naam om flood toe te staan). Regels krijgen geen antwoord. Verstuur een lege regel om te voltooien en dan \"region save\" om het resultaat te bewaren.", + "repeater_cliRegionLoadEnd": "(einde van regio-laadmodus)", + "repeater_cliRegionLoadHint": "Regioregel, of leeg om te voltooien", + "repeater_frequencyInvalid": "Ongeldige frequentie (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Ontvangstfouten", + "repeater_txPowerRangeHelper": "-9 tot 30 dBm", + "room_postsPushed": "Verzonden posts", + "room_postsStored": "Opgeslagen posts", + "settings_publicKeyCopied": "Openbare sleutel gekopieerd", + "settings_radioSettingsNotApplied": "De radio heeft deze instellingen niet toegepast", + "urlImage_enable": "URL-afbeeldingen inschakelen", + "urlImage_possible": "Mogelijke URL-afbeelding; schakel dit in bij Instellingen." } diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index d68df31d..af576481 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Nieprawidłowa szerokość geograficzna lub długość geograficzna.", "settings_latitude": "Szerokość", "settings_longitude": "Długość", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatyczne ogłoszenie zero-hop przy aktualizacji GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Gdy lokalizacja GPS się zmieni, wyślij ogłoszenie zero-hop (wymaga lokalizacji w ogłoszeniu).", "settings_privacyMode": "Tryb prywatności", "settings_privacyModeSubtitle": "Ukryj imię/lokalizację w rozgłoszeniach", "settings_privacyModeToggle": "Włącz tryb prywatności, aby ukryć swoje imię i lokalizację w rozgłoszeniach.", @@ -199,7 +201,7 @@ "appSettings_pathsWillBeCleared": "Ścieżka zostanie wyczyszczona po 5 nieudanych próbach.", "appSettings_pathsWillNotBeCleared": "Ścieżka nie zostanie automatycznie wyczyszczona.", "appSettings_autoRouteRotation": "Automatyczna rotacja trasy", - "appSettings_autoRouteRotationSubtitle": "Przełączaj się między najlepszymi ścieżkami a trybem zalewowym.", + "appSettings_autoRouteRotationSubtitle": "Przełączaj się między najlepszymi ścieżkami a trybem flood.", "appSettings_autoRouteRotationEnabled": "Automatyczne obracanie tras włączone", "appSettings_autoRouteRotationDisabled": "Automatyczne obracanie tras wyłączone", "appSettings_battery": "Bateria", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Ostatnie 6 godzin", "appSettings_last24Hours": "Ostatnie 24 godziny", "appSettings_lastWeek": "Ostatni tydzień", + "appSettings_rasterTileSource": "Źródło kafelków rastrowych", + "appSettings_stadiaEndpoint": "Punkt końcowy Stadia", + "appSettings_stadiaApiKey": "Klucz API Stadia", + "appSettings_stadiaApiKeyRequired": "Wymagane do korzystania ze Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Skonfigurowano: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Wprowadź swój klucz API Stadia Maps. Aplikacja używa go do żądań kafelków rastrowych.", "appSettings_offlineMapCache": "Pamięć podręczna map offline", "appSettings_noAreaSelected": "Nie wybrano żadnego obszaru.", "appSettings_areaSelectedZoom": "Wybrany obszar (skala {minZoom}-{maxZoom})", @@ -480,6 +495,7 @@ } } }, + "chat_selectSendAction": "Wybierz czynność wysyłania", "chat_sendGif": "Wyślij GIF", "chat_reply": "Odpowiedz", "chat_addReaction": "Dodaj Reakcję", @@ -572,7 +588,7 @@ "chat_pathManagement": "Zarządzanie ścieżkami", "chat_routingMode": "Tryb routingu", "chat_autoUseSavedPath": "Automatyczne (użyj zapisanej ścieżki)", - "chat_forceFloodMode": "Wymuś tryb zalewowy", + "chat_forceFloodMode": "Wymuś tryb flood", "chat_recentAckPaths": "Ostatnie ścieżki ACK (naciśnij, aby użyć):", "chat_pathHistoryFull": "Historia ścieżek jest pełna. Usuń wpisy, aby dodać nowe.", "chat_hopSingular": "skok", @@ -595,7 +611,7 @@ "chat_clearPathSubtitle": "Wymuś ponowne wyznaczenie trasy przy następnym wysłaniu", "chat_pathCleared": "Ścieżka wyczyszczona. Następna wiadomość odnajdzie trasę.", "chat_floodModeSubtitle": "Użyj przełącznika routingu w pasku narzędzi.", - "chat_floodModeEnabled": "Tryb zalewowy włączony. Przełącz z powrotem ikoną routingu w pasku aplikacji.", + "chat_floodModeEnabled": "Tryb flood włączony. Przełącz z powrotem ikoną routingu w pasku aplikacji.", "chat_fullPath": "Pełna ścieżka", "chat_pathDetailsNotAvailable": "Szczegóły ścieżki jeszcze niedostępne. Spróbuj wysłać wiadomość, aby odświeżyć.", "chat_pathSetHops": "Ścieżka ustawiona: {hopCount} {hopCount, plural, =1{hop} other{hops}} - {status}", @@ -616,7 +632,7 @@ "chat_path": "Ścieżka", "chat_publicKey": "Klucz Publiczny", "chat_compressOutgoingMessages": "Kompresuj wychodzące wiadomości", - "chat_floodForced": "Zalew (wymuszony)", + "chat_floodForced": "Flood (wymuszony)", "chat_directForced": "Bezpośrednio (wymuszono)", "chat_hopsForced": "{count} skoków (wymuszonych)", "@chat_hopsForced": { @@ -626,7 +642,7 @@ } } }, - "chat_floodAuto": "Zalew (automatyczny)", + "chat_floodAuto": "Flood (automatyczny)", "chat_direct": "Bezpośrednio", "chat_poiShared": "Wspólny POI", "chat_unread": "Nieprzeczytane: {count}", @@ -779,6 +795,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -844,7 +910,7 @@ "login_routing": "Trasowanie", "login_routingMode": "Tryb routingu", "login_autoUseSavedPath": "Automatycznie (użyj zapisanej ścieżki)", - "login_forceFloodMode": "Wymuś tryb zalewowy", + "login_forceFloodMode": "Wymuś tryb flood", "login_managePaths": "Zarządzaj Ścieżkami", "login_login": "Zaloguj się", "login_attempt": "Próba {current}/{max}", @@ -917,7 +983,7 @@ "repeater_statusTitle": "Status przekaźnika", "repeater_routingMode": "Tryb routingu", "repeater_autoUseSavedPath": "Automatycznie (użyj zapisanej ścieżki)", - "repeater_forceFloodMode": "Wymuś tryb zalewowy", + "repeater_forceFloodMode": "Wymuś tryb flood", "repeater_pathManagement": "Zarządzanie ścieżkami", "repeater_refresh": "Odśwież", "repeater_statusRequestTimeout": "Przekroczono czas oczekiwania na status.", @@ -962,7 +1028,7 @@ } } }, - "repeater_packetTxTotal": "Razem: {total}, Zalew: {flood}, Bezpośrednio: {direct}", + "repeater_packetTxTotal": "Razem: {total}, Flood: {flood}, Bezpośrednio: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -976,7 +1042,7 @@ } } }, - "repeater_packetRxTotal": "Razem: {total}, Zalew: {flood}, Bezpośrednio: {direct}", + "repeater_packetRxTotal": "Razem: {total}, Flood: {flood}, Bezpośrednio: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -990,7 +1056,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Zalew: {flood}, Bezpośrednie: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Bezpośrednie: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1047,7 +1113,7 @@ } } }, - "repeater_floodAdvertInterval": "Interwał rozgłoszenia zalewowego", + "repeater_floodAdvertInterval": "Interwał rozgłoszenia flood", "repeater_floodAdvertIntervalHours": "{hours} godzin", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1112,14 +1178,14 @@ "repeater_ownerInfo": "Informacje o operatorze", "repeater_ownerInfoHelper": "Publiczne metadane dla tego urządzenia powielającego", "repeater_refreshOwnerInfo": "Aktualizacja danych dotyczących operatora", - "repeater_floodMax": "Maksymalna liczba skoków podczas powodzi", + "repeater_floodMax": "Maksymalna liczba skoków flood", "repeater_floodMaxHelper": "Maksymalna liczba pakietów, które mogą przemieszczać się w jednym strumieniu (0-64)", "repeater_advancedSettings": "Zaawansowany", "repeater_advancedSettingsSubtitle": "Regulowane pokrętła dla doświadczonych operatorów", "repeater_pathHashMode": "Tryb haszujący ścieżkę", - "repeater_pathHashModeHelper": "Bity wykorzystywane do kodowania identyfikatora tego urządzenia w tagach ścieżek/detekcji pętli. 0=1 bity (256 identyfikatorów, do 64 skoków), 1=2 bity (65 000 identyfikatorów, do 32 skoków), 2=3 bity (1 600 000 identyfikatorów, do 21 skoków). Wersje 1.13 i wcześniejsze nie obsługują ścieżek wielobitowych – wykrywają tylko jedną, gdy sieć jest w wersji 1.14 lub nowszej.", + "repeater_pathHashModeHelper": "Bajty używane do kodowania identyfikatora tego repeatera w tagach ścieżki flood/wykrywania pętli. 0=1 bajt (256 identyfikatorów, do 64 skoków), 1=2 bajty (65 000 identyfikatorów, do 32 skoków), 2=3 bajty (16 milionów identyfikatorów, do 21 skoków). Firmware sprzed v1.14 zawsze używał ścieżek 1-bajtowych; v1.14 i nowsze można skonfigurować na ścieżki 2- lub 3-bajtowe.", "repeater_txDelay": "Opóźnienie w Flood, TX", - "repeater_txDelayHelper": "Ustawienie odstępu dla ruchu związanego z powodzią, jako mnożnik czasu przesyłania pakietu (0-2, domyślnie 0,5). Wyższe wartości oznaczają mniejszą liczbę kolizji, ale wolniejszą prędkość przesyłania.", + "repeater_txDelayHelper": "Ustawienie odstępu dla ruchu flood, jako mnożnik czasu przesyłania pakietu (0-2, domyślnie 0,5). Wyższe wartości oznaczają mniejszą liczbę kolizji, ale wolniejszą prędkość przesyłania.", "repeater_directTxDelay": "Bezpośrednie opóźnienie sygnału TX", "repeater_directTxDelayHelper": "Ustawienie odstępu dla ruchu bezpośredniego (bez rozgłaszania), jako mnożnika czasu przesyłania pakietu (0-2, domyślnie 0,3).", "repeater_intThresh": "Próg zakłóceń", @@ -1127,10 +1193,10 @@ "repeater_agcResetInterval": "Interwał resetowania AGC", "repeater_agcResetIntervalHelper": "Jak często należy resetować automatyczną regulację głośności radia, aby odzyskać z sytuacji, w której głośność jest ustawiona na stałe. Ustawienie \"0\" dezaktywuje okresowe resetowanie.", "repeater_actionsTitle": "Działania", - "repeater_sendAdvert": "Wysłać reklamę dotyczącą powodzi", - "repeater_sendAdvertSubtitle": "Wyemituj reklamę dotyczącą powodzi w sieci.", - "repeater_sendAdvertZeroHop": "Wysłać reklamę bez pośrednictwa", - "repeater_sendAdvertZeroHopSubtitle": "Napisz reklamę, która będzie transmitowana bezpośrednio (bez powtarzania).", + "repeater_sendAdvert": "Wysłać rozgłoszenie flood", + "repeater_sendAdvertSubtitle": "Wyemituj rozgłoszenie flood w sieci.", + "repeater_sendAdvertZeroHop": "Wysłać rozgłoszenie zero-hop", + "repeater_sendAdvertZeroHopSubtitle": "Wyemituj rozgłoszenie jednoskokowe (bez pośredników).", "repeater_clockSync": "Synchronizuj zegar", "repeater_clockSyncSubtitle": "Przekaż czas z telefonu do urządzenia powielającego", "repeater_actionSucceeded": "{action} zakończyło się pomyślnie", @@ -1227,7 +1293,7 @@ "repeater_cliHelpSetTx": "Ustawia moc transmisji LoRa w dBm. (zrestartuj, aby zastosować)", "repeater_cliHelpSetRepeat": "Włącza lub wyłącza rolę przekaźnika dla tego węzła.", "repeater_cliHelpSetAllowReadOnly": "(Serwer pokoju) Jeśli 'włączone', to logowanie z pustym hasłem będzie dozwolone, ale nie można publikować w pokoju (tylko czytać).", - "repeater_cliHelpSetFloodMax": "Ustawia maksymalną liczbę skoków pakietu zalewowego (jeśli >= max, pakiet nie jest przekierowywany)", + "repeater_cliHelpSetFloodMax": "Ustawia maksymalną liczbę skoków pakietu flood (jeśli >= max, pakiet nie jest przekierowywany)", "repeater_cliHelpSetIntThresh": "Ustawia Próg Interferencji (w dB). Domyślnie wynosi 14. Ustaw na 0, aby wyłączyć wykrywanie zakłóceń kanału.", "repeater_cliHelpSetAgcResetInterval": "Ustawia interwał do zresetowania automatycznego wzmocnienia (AGC). Ustaw na 0, aby wyłączyć.", "repeater_cliHelpSetMultiAcks": "Włącza lub wyłącza funkcję 'podwójnych potwierdzeń'.", @@ -1239,7 +1305,7 @@ "repeater_cliHelpSetLon": "Ustawia współrzędną długościową mapy rozgłoszeń. (stopnie dziesiętne)", "repeater_cliHelpSetRadio": "Ustawia nowe parametry radia i zapisuje je w preferencjach. Wymaga polecenia \"reboot\" do zastosowania.", "repeater_cliHelpSetRxDelay": "Ustawienia (eksperymentalne) bazowe (muszą być > 1, aby działać) do stosowania lekkiego opóźnienia dla odebranych pakietów, w oparciu o siłę sygnału/wynik. Ustaw na 0, aby wyłączyć.", - "repeater_cliHelpSetTxDelay": "Ustawia czynnik mnożony przez czas utrzymania w trybie zalewowym dla pakietu oraz z wykorzystaniem losowego systemu slotów, aby opóźnić jego przesyłanie (zmniejszając prawdopodobieństwo kolizji).", + "repeater_cliHelpSetTxDelay": "Ustawia czynnik mnożony przez czas utrzymania w trybie flood dla pakietu oraz z wykorzystaniem losowego systemu slotów, aby opóźnić jego przesyłanie (zmniejszając prawdopodobieństwo kolizji).", "repeater_cliHelpSetDirectTxDelay": "Taki sam jak txdelay, ale dla stosowania losowej opóźnienia przy przekazywaniu pakietów w trybie bezpośrednim.", "repeater_cliHelpSetBridgeEnabled": "Włącz/Wyłącz mostek.", "repeater_cliHelpSetBridgeDelay": "Ustaw czas opóźnienia przed ponownym wysyłaniem pakietów.", @@ -1255,13 +1321,13 @@ "repeater_cliHelpLogErase": "Usuwa logi pakietów z systemu plików.", "repeater_cliHelpNeighbors": "Wyświetla listę innych węzłów przekaźnikowych usłyszanych przez rozgłoszenia zero-hop. Każda linia to: id-prefix-hex:timestamp:snr-times-4", "repeater_cliHelpNeighborRemove": "Usuwa pierwszy pasujący wpis (z prefiksem pubkey (hex)) z listy sąsiadów.", - "repeater_cliHelpRegion": "(tylko port szeregowy) Wyświetla wszystkie zdefiniowane regiony i aktualne uprawnienia do zalewu.", + "repeater_cliHelpRegion": "(tylko port szeregowy) Wyświetla wszystkie zdefiniowane regiony i aktualne uprawnienia flood.", "repeater_cliHelpRegionLoad": "UWAGA: to jest specjalne wywołanie wielokomendowe. Każda następna komenda jest nazwą regionu (wcięta spacjami, aby wskazywać hierarchię nadrzędną, z minimum jedną spacją). Zakończona wysłaniem pustej linii/komendy.", "repeater_cliHelpRegionGet": "Wyszukuje region o podanej nazwie prefiksu (lub \"\" dla zakresu globalnego). Odpowiada \"-> region-name (parent-name) 'F'\"", "repeater_cliHelpRegionPut": "Dodaje lub aktualizuje definicję regionu z podaną nazwą.", "repeater_cliHelpRegionRemove": "Usuwa definicję regionu o podanej nazwie. (musi się dokładnie zgadzać i nie może mieć podregionów).", - "repeater_cliHelpRegionAllowf": "Ustawia uprawnienia 'F' (zalewowe) dla podanego regionu. ('' dla zakresu globalnego/starszego)", - "repeater_cliHelpRegionDenyf": "Usuwa uprawnienie 'F' (zalewowe) dla podanej strefy. (ZALECANE: na tym etapie NIE zaleca się używania tego na globalnym/starszym zakresie!!).", + "repeater_cliHelpRegionAllowf": "Ustawia uprawnienia 'F' (flood) dla podanego regionu. ('' dla zakresu globalnego/starszego)", + "repeater_cliHelpRegionDenyf": "Usuwa uprawnienie 'F' (flood) dla podanej strefy. (ZALECANE: na tym etapie NIE zaleca się używania tego na globalnym/starszym zakresie!!).", "repeater_cliHelpRegionHome": "Odpowiada z aktualnej 'home' region. (Uwaga: nie zostało jeszcze zastosowane, zarezerwowane na przyszłość).", "repeater_cliHelpRegionHomeSet": "Ustawia region 'domowe'.", "repeater_cliHelpRegionSave": "Zapisuje listę/mapę regionów do pamięci.", @@ -1427,7 +1493,7 @@ } }, "channelPath_unknownPath": "Nieznane", - "channelPath_floodPath": "Zalew", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Bezpośrednio", "channelPath_observedZeroOf": "0 z {total} skoków", "@channelPath_observedZeroOf": { @@ -1702,7 +1768,7 @@ "appSettings_enableMessageTracingSubtitle": "Pokaż szczegółowe metadane trasowania i czasu dla wiadomości", "contacts_contactImportFailed": "Kontakt nie został zaimportowany.", "contacts_zeroHopAdvert": "Rozgłoszenie zero-hop", - "contacts_floodAdvert": "Rozgłoszenie zalewowe", + "contacts_floodAdvert": "Rozgłoszenie flood", "contacts_copyAdvertToClipboard": "Kopiuj rozgłoszenie do schowka", "contacts_clipboardEmpty": "Schowek jest pusty.", "contacts_invalidAdvertFormat": "Nieprawidłowe dane kontaktowe", @@ -1763,7 +1829,7 @@ "settings_gpxExportChat": "Lokalizacje towarzyszy", "settings_gpxExportShareText": "Dane mapy wyeksportowane z meshcore-open", "settings_gpxExportShareSubject": "Eksport danych mapy GPX meshcore-open", - "pathTrace_someHopsNoLocation": "Jeden lub więcej z chmieli nie ma określonej lokalizacji!", + "pathTrace_someHopsNoLocation": "Jeden lub więcej skoków nie ma określonej lokalizacji!", "map_pathTraceCancelled": "Śledzenie ścieżki anulowano.", "map_runTrace": "Uruchom ślad ścieżki", "pathTrace_clearTooltip": "Wyczyść ścieżkę", @@ -2069,7 +2135,7 @@ "settings_allowAll": "Zezwalaj na wszystko", "settings_telemetryLocationMode": "Tryb położenia telemetrycznego", "settings_telemetryEnvironmentMode": "Tryb środowiska telemetrycznego", - "settings_advertLocation": "Lokalizacja reklamowa", + "settings_advertLocation": "Lokalizacja rozgłoszenia", "settings_advertLocationSubtitle": "Uwzględnij lokalizację w ogłoszeniu", "settings_denyAll": "Odmów wszystkim", "settings_privacySubtitle": "Kontroluj jakie informacje są udostępniane.", @@ -2239,7 +2305,7 @@ "repeater_sensors": "Czujniki", "repeater_cliHelpPowerOff": "Wyłącza urządzenie. (oczekiwanie na brak reakcji)", "repeater_cliHelpClkReboot": "Przywraca zegar do znanego punktu odniesienia i resetuje urządzenie.", - "repeater_cliHelpAdvertZeroHop": "Wysyła reklamę, która dociera bezpośrednio do sąsiadów (bez pośrednictwa).", + "repeater_cliHelpAdvertZeroHop": "Wysyła rozgłoszenie, które dociera bezpośrednio do sąsiadów (bez pośrednictwa).", "repeater_cliHelpStartOta": "Rozpoczyna aktualizację oprogramowania przez sieć (bezpośrednio z urządzenia).", "repeater_cliHelpTime": "Ustawia zegar urządzenia na określone sekundy od epoki Unix. Zegar nie może się cofać.", "repeater_cliHelpBoard": "Wyświetla informacje o producencie płyty głównej / identyfikator sprzętu.", @@ -2270,15 +2336,15 @@ "repeater_cliHelpGetAgcResetInterval": "Pokazuje interwał resetowania AGC w sekundach.", "repeater_cliHelpGetMultiAcks": "Pokazuje, czy tryb podwójnego potwierdzania jest włączony (1) czy wyłączony (0).", "repeater_cliHelpGetAllowReadOnly": "Pokazuje, czy dostęp dla gości jest ograniczony do odczytu tylko.", - "repeater_cliHelpGetAdvertInterval": "Pokazuje czas trwania lokalnej reklamy w minutach.", - "repeater_cliHelpGetFloodAdvertInterval": "Pokazuje interwał reklamowy dotyczący powodzi w godzinach.", + "repeater_cliHelpGetAdvertInterval": "Pokazuje interwał lokalnego rozgłoszenia w minutach.", + "repeater_cliHelpGetFloodAdvertInterval": "Pokazuje interwał rozgłoszenia flood w godzinach.", "repeater_cliHelpGetGuestPassword": "Wyświetla ustawione hasło dla gościa.", "repeater_cliHelpGetLat": "Pokazuje ustawioną szerokość geograficzną.", "repeater_cliHelpGetLon": "Pokazuje ustawioną długość geograficzną.", "repeater_cliHelpGetRxDelay": "Pokazuje bazową wartość opóźnienia RX.", - "repeater_cliHelpGetTxDelay": "Pokazuje współczynnik opóźnienia transmisji w trybie zalewowym.", + "repeater_cliHelpGetTxDelay": "Pokazuje współczynnik opóźnienia transmisji w trybie flood.", "repeater_cliHelpGetDirectTxDelay": "Pokazuje współczynnik opóźnienia w trybie bezpośrednim.", - "repeater_cliHelpGetFloodMax": "Pokazuje maksymalną liczbę skoków spowodowanych powodzią.", + "repeater_cliHelpGetFloodMax": "Pokazuje maksymalną liczbę skoków flood.", "repeater_cliHelpGetOwnerInfo": "Wyświetla ciąg znaków zawierający dane kontaktowe właściciela.", "repeater_cliHelpGetPathHashMode": "Pokazuje tryb haszujący ścieżkę (0/1/2).", "repeater_cliHelpGetLoopDetect": "Pokazuje czułość detekcji pętli.", @@ -2300,8 +2366,8 @@ "repeater_cliHelpSensorList": "Wyświetla wszystkie ustawienia dla niestandardowych czujników, podzielone na strony, z opcjonalnym indeksem początkowym.", "repeater_cliHelpRegionDefault": "Pokazuje aktualny domyślny zakres regionu.", "repeater_cliHelpRegionDefaultSet": "Ustawia domyślny zakres regionu. Użyj wartości \"\", aby go zresetować.", - "repeater_cliHelpRegionListAllowed": "Wymienia regiony, w których dopuszczony jest ruch związany z powodzami.", - "repeater_cliHelpRegionListDenied": "Wymienia regiony, w których ruch związany z powodziami jest ograniczony.", + "repeater_cliHelpRegionListAllowed": "Wymienia regiony, w których dozwolony jest ruch flood.", + "repeater_cliHelpRegionListDenied": "Wymienia regiony, w których ruch flood jest zabroniony.", "repeater_cliHelpStatsPackets": "(Tylko dla serialu) Prezentuje statystyki na poziomie pakietów.", "repeater_cliHelpStatsRadio": "(Tylko serial) Prezentuje statystyki dotyczące nadawania radiowego.", "repeater_cliHelpStatsCore": "(Tylko wersja serialowa) Wyświetla podstawowe statystyki o oprogramowaniu.", @@ -2441,7 +2507,7 @@ "contacts_searchClose": "Zaawansowane wyszukiwanie", "routing_title": "Planowanie tras", "routing_modeAuto": "Samochód", - "routing_modeFlood": "Powódź", + "routing_modeFlood": "Flood", "routing_modeManual": "Instrukcja obsługi", "routing_modeAutoHint": "Automatycznie wybiera najpopularniejszą ścieżkę, a w przypadku braku znanej, przechodzi do trybu \"przepływu\".", "routing_modeFloodHint": "Transmisje za pośrednictwem każdego repeatera. Najbardziej niezawodna metoda, ale zużywa więcej czasu transmisji.", @@ -2463,11 +2529,11 @@ "routing_qualityUntested": "Nieużywany", "routing_lastWorked": "pracował {when}", "routing_neverWorked": "nigdy nie zostało potwierdzone", - "routing_floodDelivery": "Dostawa w przypadku powodzi", + "routing_floodDelivery": "Dostawa flood", "pathEditor_title": "Stworzenie ścieżki", - "pathEditor_hopCounter": "{count} z 64 rodzajów chmielu", - "pathEditor_noHops": "Na razie nie dodano żadnych chmielu. Aby dodać je w odpowiedniej kolejności, kliknij w odpowiednie przyciski poniżej, lub zapisz przepis bez chmielu, aby wysłać go bezpośrednio.", - "pathEditor_addHops": "Dodawaj chmiel zgodnie z kolejnością.", + "pathEditor_hopCounter": "{count} z 64 skoków", + "pathEditor_noHops": "Nie dodano jeszcze żadnych skoków. Stuknij przekaźniki poniżej, aby dodać je w kolejności, lub zapisz bez skoków, aby wysłać bezpośrednio.", + "pathEditor_addHops": "Dodawaj skoki w kolejności.", "pathEditor_searchRepeaters": "Funkcje powtarzania", "pathEditor_advancedHex": "Zaawansowane: ścieżka w formacie szesnastkowym", "pathEditor_hexLabel": "Prefiksy heksadecymalne", @@ -2475,7 +2541,7 @@ "pathEditor_invalidTokens": "Nieprawidłowe: {tokens}", "pathEditor_tooManyHops": "Maksymalnie 64 hopów", "pathEditor_usePath": "Użyj tej ścieżki.", - "pathEditor_removeHop": "Usuń dziką psiankę", + "pathEditor_removeHop": "Usuń skok", "pathEditor_unknownHop": "Nieznany repeater", "map_zoomIn": "Przybliż", "routing_deliveryCounts": "{successes} delivered, {failures} failed", @@ -2578,5 +2644,261 @@ "pathMap_noLocation": "Brak lokalizacji", "pathMap_followPacket": "Śledź pakiet", "pathMap_unfollowPacket": "Przestań śledzić pakiet", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regiony", + "settings_regionSettingsSubtitle": "Zarządzanie zapisanymi regionami", + "settings_regionManagement_screenTitle": "Zarządzanie Regionami", + "settings_regionNameHint": "Wprowadź nazwę regionu", + "settings_regionAddRegion": "Dodaj region", + "settings_regionFetchRegions": "Pobierz regiony z repeaterów", + "settings_regionFetchRegionsFail": "Nie znaleziono żadnych regionów", + "settings_regionFetchRegionsAlreadyExists": "Ten region został już dodany", + "settings_regionName": "Nazwa Regionu", + "settings_regionDeleted": "Region usunięto", + "settings_deleteRegion": "Usuń Region", + "settings_deleteRegionConfirm": "Czy usunąć \"{region}\" z listy regionów?", + "settings_infoHardware": "Sprzęt", + "settings_infoFirmware": "Oprogramowanie wbudowane", + "repeater_pathHashModeOption0": "0 - 1 bajt", + "repeater_pathHashModeOption1": "1 - 2 bity", + "repeater_pathHashModeOption2": "2 - 3 bajty", + "repeater_pathHashModeOption3": "3 - 4 bajty", + "appSettings_batteryLipoHv": "Bateria LiPo HV (3,0-4,35 V)", + "channels_regionSetTo": "Region: {region}", + "channels_regionNotSet": "Region: brak", + "channels_regionSelect_Title": "Wybierz region", + "channels_clearRegion": "Przejrzyste obszar", + "chat_sendImageLora": "Wyślij obraz przez MeshCore", + "chat_imagePickFailed": "Nie mogłem otworzyć tego obrazu", + "chat_receivedGif": "Otrzymano GIF", + "repeater_keySettings": "Zmiana kluczy tożsamości", + "repeater_keySettingsSubtitle": "Zmień parę kluczy publiczną/prywatną", + "repeater_prvKey": "Klucz prywatny", + "repeater_prvKeyHelper": "Nowy klucz prywatny dla wzmacniacza, 128-znakowa string hexadecyimalny.", + "repeater_generatePrvKey": "Wygeneruj losowy klucz parowy", + "repeater_stopGeneratingPrvKey": "Przerwij wyszukiwanie kluczowego paru", + "repeater_pubKey": "Klucz publiczny", + "repeater_pubKeyHelper": "To jest klucz publiczny, który odpowiada wygenerowanemu kluczowi prywatnemu. Nie można go ustawić bezpośrednio.", + "repeater_pubKeyPrefix": "Pożądane przedrostek", + "repeater_pubKeyPrefixHelper": "Znajdź klucz publiczny, który zaczyna się od tych cyfr hex. Oczekiwana liczba prób: {tries}.", + "imageMessages_enableTitle": "Włącz wiadomości ze zdjęciami", + "imageMessages_enableSubtitle": "Przesyłaj zdjęcia przez siatkę. Wymaga jednorazowego pobrania modelu obrazu.", + "imageMessages_modelSectionTitle": "Model obrazowy", + "imageMessages_downloadModel": "Pobierz", + "imageMessages_cancelDownload": "Anuluj", + "imageMessages_removeModel": "Usuń model", + "imageMessages_modelReady": "Gotowy", + "imageMessages_modelNotPublished": "Nie opublikowane — ten build nie może tego pobrać.", + "imageMessages_downloadFailed": "Model obrazowy nie mógł zostać pobrany.", + "imageMessages_autoProcessTitle": "Obrazki są przetwarzane automatycznie.", + "imageMessages_autoProcessSubtitle": "Odbuduj każde zdjęcie, jak tylko przyjdzie. Zużywa około 2 GB pamięci za każdą drugą sekundę; wyłącz odbudowywanie jednym dotknięciem.", + "imageSend_title": "Wyślij obraz", + "imageSend_cropNote": "Zmniejszone do 512 × 512 · proporcje nie zostały zachowane", + "imageSend_originalSize": "Oryginalny", + "imageSend_onAirSize": "W eterze", + "imageSend_quality": "Jakość", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Wysoko", + "imageSend_packetsLabel": "Pakiet", + "imageSend_airtimeLabel": "Czas w eterze", + "imageSend_sizeLabel": "Payload", + "imageSend_packetsCount": "{count} {count, plural, =1{pakiet} other{pakietów}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Ustawienia radia nieznane", + "imageSend_radioUnknownBody": "Połącz urządzenie, aby można było obliczyć czas trwania transmisji.", + "imageSend_longSendTitle": "Długa transmisja", + "imageSend_longSendBody": "Ten kanał będzie dostępny przez około {duration}.", + "imageSend_floodNote": "Przepływ pakietów: każdy retransmitujący w zasięgu przekazuje każdy pakiet, przez co kanał pozostaje zajęty dłużej niż ten czas.", + "imageSend_parityTitle": "Pakiet odzysku", + "imageSend_paritySubtitle": "Jedna dodatkowa paczka. Wiadomości grupowe nie są potwierdzane, dzięki czemu odbiorca może odbudować obraz, jeśli zostanie utracona pojedyncza paczka.", + "imageSend_send": "Wyślij", + "imageSend_cancel": "Anuluj", + "imageSend_encodeFailed": "Ten obraz nie mógł zostać zakodowany.", + "imageSend_codecDownloading": "Model obrazowy jest nadal pobierany.", + "imageSend_codecUnavailable": "Wysyłanie obrazu nie jest dostępne na tym urządzeniu.", + "imageSend_codecDisabled": "Wiadomości ze zdjęciami są wyłączone w ustawieniach.", + "imageSend_deviceUnsupported": "Ten radiodysk nie może wysyłać pakietów obrazu. Podłącz urządzenie z oprogramowaniem firmware 13 lub nowszym.", + "imageSend_directMessagesUnsupported": "Obrazy są przesyłane jako dane grupowe, więc można je wysłać tylko do kanału — nie w wiadomości prywatnej.", + "imageSend_tooLarge": "Obraz zakodowany do więcej pakietów niż pozwala format siatki.", + "imageSend_sentConfirmation": "Obraz wysłany jako {count} {count, plural, =1{pakiet} other{pakietów}}.", + "imageSend_sendFailed": "Obraz nie mogł zostać wysłany: {error}", + "imageSend_sendingProgress": "Wysyłanie obrazu — pakiet {sent} z {total}", + "receivedImage_senderPrefix": "Węzeł {prefix}", + "receivedImage_incoming": "Otrzymano: {received} z {total} pakietów", + "receivedImage_queued": "Oczekiwanie na rozszyfrowanie", + "receivedImage_tapToDecode": "Kliknij, aby odszyfrować", + "receivedImage_decoding": "Odtwarzanie… około 1 sekundy", + "receivedImage_incomplete": "Obraz niepełny — {received} z {total} pakietów dotarło", + "receivedImage_corrupt": "Obraz nie może zostać zrekonstruowany", + "receivedImage_decoderMissing": "Otrzymano obraz — dekodowanie obrazu jest nieprawidłowe.", + "receivedImage_evicted": "Obraz nie jest już przechowywany", + "receivedImage_retry": "Spróbuj ponownie", + "receivedImage_decodeAgain": "Zdekoduj ponownie", + "receivedImage_openSettings": "Ustaw", + "receivedImage_tapToProcess": "Kliknij, aby przetworzyć", + "receivedImage_awaiting": "{bytes} bajtów · {packets} {packets, plural, =1{pakiet} other{pakiety}}", + "imageSend_secondsValue": "{seconds} sekund", + "imageSend_minutesSecondsValue": "{minutes} minut {seconds} sekundy", + "channels_noFreeSlots": "Wszystkie miejsca na kanały są zajęte", + "chat_longMessageRetryNote": "Powyżej 158 bajtów: wysyłane maksymalnie {count} razy", + "reaction_report": "Reakcje Emoji", + "repeater_bridgeNote": "Dostępne tylko w firmware zbudowanym z mostkiem (RS232 lub ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Pokazuje maksymalną liczbę skoków dla rozgłoszeń flood.", + "repeater_cliHelpGetFloodMaxUnscoped": "Pokazuje maksymalną liczbę skoków dla pakietów flood bez przypisanego regionu.", + "repeater_cliHelpGetRadioFemRxGain": "Pokazuje, czy wzmocnienie RX modułu front-end LoRa jest włączone.", + "repeater_cliHelpGetRadioFemTxGain": "Pokazuje, czy wzmocnienie TX modułu front-end LoRa jest włączone.", + "repeater_cliHelpRegionDef": "Definiuje łańcuch regionów w jednej komendzie: każda nazwa jest dodawana pod poprzednią; \"name,parent\" dodaje nazwę, a następnie kontynuuje pod podanym regionem nadrzędnym. Odpowiada listą regionów.", + "repeater_cliHelpSetFloodMaxAdvert": "Ustawia maksymalną liczbę skoków przy przekazywaniu rozgłoszeń flood (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Ustawia maksymalną liczbę skoków przy przekazywaniu pakietów flood bez przypisanego regionu (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Przełącza wzmocnienie RX (LNA) modułu front-end LoRa. Płytki bez tej funkcji odpowiadają \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Przełącza wzmocnienie TX (PA) modułu front-end LoRa. Płytki bez tej funkcji odpowiadają \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Tryb wczytywania regionów: wysyłaj po jednej nazwie regionu w linii, wcięte spacjami pod regionem nadrzędnym (dodaj F po nazwie, aby zezwolić na flood). Linie nie otrzymują odpowiedzi. Wyślij pustą linię, aby zakończyć, a następnie \"region save\", aby zachować wynik.", + "repeater_cliRegionLoadEnd": "(koniec wczytywania regionów)", + "repeater_cliRegionLoadHint": "Linia regionu lub pusta, aby zakończyć", + "repeater_frequencyInvalid": "Nieprawidłowa częstotliwość (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Błędy Odbioru", + "repeater_txPowerRangeHelper": "-9 do 30 dBm", + "room_postsPushed": "Wysłane Posty", + "room_postsStored": "Posty", + "settings_publicKeyCopied": "Skopiowano klucz publiczny", + "settings_radioSettingsNotApplied": "Radio nie zastosowało tych ustawień", + "urlImage_enable": "Włącz obrazy z URL", + "urlImage_possible": "Możliwy obraz z URL; włącz go w Ustawieniach.", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 43187cc9..dac37b0c 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Latitude ou longitude inválidos.", "settings_latitude": "Latitude", "settings_longitude": "Longitude", + "settings_autoZeroHopAdvertOnGpsUpdate": "Anúncio zero-hop automático na atualização do GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Quando a localização GPS mudar, enviar um anúncio zero-hop (requer localização no anúncio).", "settings_privacyMode": "Modo de Privacidade", "settings_privacyModeSubtitle": "Esconder nome/localização em anúncios", "settings_privacyModeToggle": "Ative o modo de privacidade para ocultar seu nome e localização em anúncios.", @@ -108,7 +110,7 @@ "settings_actions": "Ações", "settings_deleteAllPaths": "Delete All Paths", "settings_deleteAllPathsSubtitle": "Clear all path data from contacts.", - "settings_sendAdvertisement": "Enviar Publicidade", + "settings_sendAdvertisement": "Enviar Anúncio", "settings_sendAdvertisementSubtitle": "Presença de transmissão agora", "settings_advertisementSent": "Anúncio enviado", "settings_syncTime": "Tempo de Sincronização", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Últimos 6 horas", "appSettings_last24Hours": "Últimas 24 horas", "appSettings_lastWeek": "Da última semana", + "appSettings_rasterTileSource": "Fonte de blocos raster", + "appSettings_stadiaEndpoint": "Endpoint da Stadia", + "appSettings_stadiaApiKey": "Chave da API Stadia", + "appSettings_stadiaApiKeyRequired": "Obrigatório para usar o Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Configurado: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Insira sua chave da API Stadia Maps. O aplicativo a usa para solicitações de blocos raster.", "appSettings_offlineMapCache": "Cache de Mapa Offline", "appSettings_noAreaSelected": "Nenhuma área selecionada", "appSettings_areaSelectedZoom": "Área selecionada (zoom {minZoom}-{maxZoom})", @@ -470,6 +485,7 @@ } } }, + "chat_selectSendAction": "Selecionar ação de envio", "chat_sendGif": "Enviar GIF", "chat_reply": "Responder", "chat_addReaction": "Adicionar Reação", @@ -565,8 +581,8 @@ "chat_forceFloodMode": "Modo de Inundação Forçado", "chat_recentAckPaths": "Rotas de ACK Recentes (toque para usar):", "chat_pathHistoryFull": "O histórico está cheio. Remova entradas para adicionar novas.", - "chat_hopSingular": "pule", - "chat_hopPlural": "salta", + "chat_hopSingular": "salto", + "chat_hopPlural": "saltos", "chat_hopsCount": "{count} {count, plural, =1{salto} other{saltos}}", "@chat_hopsCount": { "placeholders": { @@ -769,6 +785,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1107,7 +1173,7 @@ "repeater_advancedSettings": "Avançado", "repeater_advancedSettingsSubtitle": "Controles de ajuste para operadores experientes", "repeater_pathHashMode": "Modo de hash de caminho", - "repeater_pathHashModeHelper": "Bytes utilizados para codificar o ID deste repetidor nas tags de caminho/detecção de loop. 0=1 byte (256 IDs, até 64 saltos), 1=2 bytes (65.000 IDs, até 32 saltos), 2=3 bytes (16 milhões de IDs, até 21 saltos). As versões 1.13 e anteriores do firmware não suportam caminhos multi-byte — apenas funcionam uma vez após a ativação da rede (a partir da versão 1.14+).", + "repeater_pathHashModeHelper": "Bytes usados para codificar o ID deste repetidor nas tags de caminho flood/detecção de loop. 0=1 byte (256 IDs, até 64 saltos), 1=2 bytes (65.000 IDs, até 32 saltos), 2=3 bytes (16 milhões de IDs, até 21 saltos). O firmware anterior à v1.14 sempre usava caminhos de 1 byte; v1.14 e versões mais recentes podem ser configuradas para caminhos de 2 ou 3 bytes.", "repeater_txDelay": "Atraso na entrega em Flood, TX", "repeater_txDelayHelper": "Ajuste de espaçamento para tráfego de inundações, como um multiplicador do tempo de transmissão (0-2, padrão 0,5). Quanto maior, menos colisões, mas uma entrega mais lenta.", "repeater_directTxDelay": "Atraso direto no sinal TX", @@ -1222,7 +1288,7 @@ "repeater_cliHelpSetAgcResetInterval": "Define o intervalo para resetar o Controlador de Ganho Automático. Defina como 0 para desativar.", "repeater_cliHelpSetMultiAcks": "Habilita ou desabilita a funcionalidade de \"double ACKs\".", "repeater_cliHelpSetAdvertInterval": "Define o intervalo do timer em minutos para enviar um pacote de anúncio local (sem salto). Defina como 0 para desativar.", - "repeater_cliHelpSetFloodAdvertInterval": "Define o intervalo do timer em horas para enviar um pacote de anúncio em massa. Defina como 0 para desativar.", + "repeater_cliHelpSetFloodAdvertInterval": "Define o intervalo do timer em horas para enviar um pacote de anúncio de inundação. Defina como 0 para desativar.", "repeater_cliHelpSetGuestPassword": "Define/atualiza a senha do convidado. (para repetidores, os logins de convidados podem enviar a solicitação \"Obter Estatísticas\")", "repeater_cliHelpSetName": "Define o nome do anúncio.", "repeater_cliHelpSetLat": "Define a latitude do mapa de anúncios. (graus decimais)", @@ -1250,8 +1316,8 @@ "repeater_cliHelpRegionGet": "Procura região com o prefixo de nome dado (ou \"\\\" para o âmbito global). Responde com \"-> nome-região (nome-pai) 'F'\"", "repeater_cliHelpRegionPut": "Adiciona ou atualiza uma definição de região com o nome fornecido.", "repeater_cliHelpRegionRemove": "Remove uma definição de região com o nome fornecido. (deve corresponder exatamente e não ter regiões filhas)", - "repeater_cliHelpRegionAllowf": "Define a permissão de 'F'luido para a região especificada. ('' para o escopo global/legado)", - "repeater_cliHelpRegionDenyf": "Remove a permissão de \"F\"luido para a região especificada. (NOTA: neste momento NÃO é aconselhável usar isso no escopo global/legado!!)", + "repeater_cliHelpRegionAllowf": "Define a permissão de 'F'lood para a região especificada. ('' para o escopo global/legado)", + "repeater_cliHelpRegionDenyf": "Remove a permissão de \"F\"lood para a região especificada. (NOTA: neste momento NÃO é aconselhável usar isso no escopo global/legado!!)", "repeater_cliHelpRegionHome": "Responde com a região 'home' atual. (Observação aplicada em nenhum lugar ainda, reservado para o futuro)", "repeater_cliHelpRegionHomeSet": "Define a região 'casa'.", "repeater_cliHelpRegionSave": "Persiste a lista/mapa de regiões para o armazenamento.", @@ -1468,7 +1534,7 @@ } } }, - "channelPath_noHopDetailsAvailable": "Não estão disponíveis detalhes de voo para este pacote.", + "channelPath_noHopDetailsAvailable": "Não estão disponíveis detalhes de salto para este pacote.", "channelPath_unknownRepeater": "Repetidor Desconhecido", "listFilter_tooltip": "Filtrar e ordenar", "listFilter_sortBy": "Ordenar por", @@ -1725,7 +1791,7 @@ "settings_gpxExportAllContacts": "Todos os locais de contatos", "settings_gpxExportShareText": "Dados do mapa exportados do meshcore-open", "settings_gpxExportShareSubject": "meshcore-open exportação de dados de mapa GPX", - "pathTrace_someHopsNoLocation": "Um ou mais dos lúpulos estão sem localização!", + "pathTrace_someHopsNoLocation": "Um ou mais dos saltos estão sem localização!", "map_runTrace": "Executar Traçado de Caminho", "map_pathTraceCancelled": "Rastreamento de caminho cancelado.", "pathTrace_clearTooltip": "Limpar caminho", @@ -2233,8 +2299,8 @@ "repeater_cliHelpGetAgcResetInterval": "Mostra o intervalo de reinicialização do AGC em segundos.", "repeater_cliHelpGetMultiAcks": "Indica se o modo de confirmação dupla está ativado (1) ou desativado (0).", "repeater_cliHelpGetAllowReadOnly": "Indica se o acesso somente de leitura para os convidados está habilitado.", - "repeater_cliHelpGetAdvertInterval": "Indica o intervalo de publicidade local em minutos.", - "repeater_cliHelpGetFloodAdvertInterval": "Mostra o intervalo de tempo da publicidade relacionada às inundações, em horas.", + "repeater_cliHelpGetAdvertInterval": "Indica o intervalo de anúncio local em minutos.", + "repeater_cliHelpGetFloodAdvertInterval": "Mostra o intervalo do anúncio de inundação, em horas.", "repeater_cliHelpGetGuestPassword": "Mostra a senha de convidado configurada.", "repeater_cliHelpGetLat": "Mostra a latitude configurada.", "repeater_cliHelpGetLon": "Mostra a longitude configurada.", @@ -2263,8 +2329,8 @@ "repeater_cliHelpSensorList": "Lista todas as configurações de sensores personalizadas, organizadas em páginas a partir de um índice de início opcional.", "repeater_cliHelpRegionDefault": "Mostra o escopo de região padrão atual.", "repeater_cliHelpRegionDefaultSet": "Define o escopo regional padrão. Use \"\" para limpar.", - "repeater_cliHelpRegionListAllowed": "Lista as regiões que permitem o tráfego em áreas de risco de inundações.", - "repeater_cliHelpRegionListDenied": "Lista as regiões que restringem o tráfego em áreas de risco de inundações.", + "repeater_cliHelpRegionListAllowed": "Lista as regiões que permitem o tráfego por inundação.", + "repeater_cliHelpRegionListDenied": "Lista as regiões que negam o tráfego por inundação.", "repeater_cliHelpStatsPackets": "(Apenas para séries) Apresenta estatísticas em nível de pacotes.", "repeater_cliHelpStatsRadio": "(Apenas para transmissões em série) Exibe estatísticas de rádio.", "repeater_cliHelpStatsCore": "(Apenas para dispositivos em série) Exibe estatísticas básicas do firmware.", @@ -2426,9 +2492,9 @@ "routing_neverWorked": "nunca confirmado", "routing_floodDelivery": "Entrega em áreas afetadas por inundações", "pathEditor_title": "Criar Caminho", - "pathEditor_hopCounter": "{count} de 64 gramas de lúpulo", - "pathEditor_noHops": "Ainda não há lúpulos adicionados. Clique nos repetidores abaixo para adicioná-los na ordem desejada, ou salve sem adicionar lúpulos para enviar diretamente.", - "pathEditor_addHops": "Adicione os lúpulos na seguinte ordem.", + "pathEditor_hopCounter": "{count} de 64 saltos", + "pathEditor_noHops": "Ainda não há saltos adicionados. Clique nos repetidores abaixo para adicioná-los na ordem desejada, ou salve sem adicionar saltos para enviar diretamente.", + "pathEditor_addHops": "Adicione os saltos na seguinte ordem.", "pathEditor_searchRepeaters": "Encontrar repetidores", "pathEditor_advancedHex": "Avançado: caminho hexadecimal bruto", "pathEditor_hexLabel": "Prefixos hexadecimais", @@ -2438,7 +2504,7 @@ "pathEditor_tooManyHops": "Máximo de 64 saltos", "routing_deliveryCounts": "{successes} delivered, {failures} failed", "pathEditor_usePath": "Utilize este caminho.", - "pathEditor_removeHop": "Remova o lúpulo", + "pathEditor_removeHop": "Remova o salto", "pathEditor_unknownHop": "Repetidor desconhecido", "map_zoomIn": "Ampliar", "map_zoomOut": "Ampliar", @@ -2540,5 +2606,260 @@ "pathMap_noLocation": "Sem localização", "pathMap_followPacket": "Fixar vista no pacote", "pathMap_unfollowPacket": "Liberar vista do pacote", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regiões", + "settings_regionSettingsSubtitle": "Gerenciar regiões armazenadas", + "settings_regionManagement_screenTitle": "Gestão de Região", + "settings_regionNameHint": "Nome da região", + "settings_regionAddRegion": "Adicionar região", + "settings_regionFetchRegions": "Regiões de obtenção a partir de repetidores", + "settings_regionFetchRegionsFail": "Nenhuma região foi encontrada", + "settings_regionFetchRegionsAlreadyExists": "Esta região já foi adicionada", + "settings_regionName": "Nome da Região", + "settings_regionDeleted": "Região excluída", + "settings_deleteRegion": "Excluir Região", + "settings_deleteRegionConfirm": "Remover \"{region}\" da lista de regiões?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 bytes", + "repeater_pathHashModeOption2": "2 - 3 bytes", + "repeater_pathHashModeOption3": "3 - 4 bytes", + "appSettings_batteryLipoHv": "LiPo HV (3,0-4,35V)", + "channels_regionSetTo": "Região: {region}", + "channels_regionNotSet": "Região: nenhuma", + "channels_regionSelect_Title": "Escolha uma região", + "channels_clearRegion": "Região desimpedida", + "chat_sendImageLora": "Enviar imagem via MeshCore", + "chat_imagePickFailed": "Não consegui abrir essa imagem", + "chat_receivedGif": "Recebi um GIF", + "repeater_keySettings": "Alterar Chaves de Identidade", + "repeater_keySettingsSubtitle": "Altere a chave pública/chave privada", + "repeater_prvKey": "Chave privada", + "repeater_prvKeyHelper": "Uma nova chave privada para o repetidor, uma string hexadecimal de 128 caracteres.", + "repeater_generatePrvKey": "Gere um par de chaves aleatório", + "repeater_stopGeneratingPrvKey": "Interrompa a busca por par de chaves", + "repeater_pubKey": "Chave pública", + "repeater_pubKeyHelper": "Esta é a chave pública que acompanha a chave privada gerada. Você não pode definir isso diretamente.", + "repeater_pubKeyPrefix": "Prefixo desejado", + "repeater_pubKeyPrefixHelper": "Encontre uma chave pública que comece com esses dígitos hexadecimais. Número esperado de tentativas: {tries}.", + "imageMessages_enableTitle": "Mensagens de imagem", + "imageMessages_enableSubtitle": "Envie as imagens pela malha. Requer o download de um modelo de imagem único.", + "imageMessages_modelSectionTitle": "Modelo de imagem", + "imageMessages_downloadModel": "Download", + "imageMessages_cancelDownload": "Cancelar", + "imageMessages_removeModel": "Remover modelo", + "imageMessages_modelReady": "Pronto", + "imageMessages_modelNotPublished": "Ainda não publicado — esta versão não pode baixá-lo.", + "imageMessages_downloadFailed": "O modelo de imagem não pôde ser baixado.", + "imageMessages_autoProcessTitle": "Processar imagens automaticamente", + "imageMessages_autoProcessSubtitle": "Reconstrua cada imagem assim que ela chegar. Utiliza cerca de 2 GB de memória por segundo; dispense a reconstrução com um toque.", + "imageSend_title": "Enviar imagem", + "imageSend_cropNote": "Redimensionado para 512 × 512 · a proporção de aspecto não foi preservada", + "imageSend_originalSize": "Texto Original", + "imageSend_onAirSize": "Ao ar", + "imageSend_quality": "Qualidade", + "imageSend_qualityStandard": "Padrão", + "imageSend_qualityHigh": "Alto", + "imageSend_packetsLabel": "Pacotes", + "imageSend_airtimeLabel": "Tempo em transmissão", + "imageSend_sizeLabel": "Carga útil", + "imageSend_packetsCount": "{count} {count, plural, =1{pacote} other{pacotes}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Configurações de rádio desconhecidas", + "imageSend_radioUnknownBody": "Conecte-se a um dispositivo para que o horário de transmissão possa ser calculado.", + "imageSend_longSendTitle": "Transmissão longa", + "imageSend_longSendBody": "Isso manterá o canal por cerca de {duration}.", + "imageSend_floodNote": "Roteamento de inundação: cada repetidor na faixa retransmite cada pacote, fazendo com que o canal permaneça ocupado por mais tempo do que isso.", + "imageSend_parityTitle": "Pacote de recuperação", + "imageSend_paritySubtitle": "Um pacote extra. As mensagens em grupo não são reconhecidas, assim permitindo que o destinatário reconstrua a imagem caso um pacote seja perdido.", + "imageSend_send": "Enviar", + "imageSend_cancel": "Cancelar", + "imageSend_encodeFailed": "Esta imagem não pode ser codificada.", + "imageSend_codecDownloading": "O modelo de imagem ainda está baixando.", + "imageSend_codecUnavailable": "O envio de imagem não está disponível neste dispositivo.", + "imageSend_codecDisabled": "As mensagens de imagem estão desativadas nas configurações.", + "imageSend_deviceUnsupported": "Este rádio não pode enviar pacotes de imagem. Conecte um dispositivo com firmware companheiro versão 13 ou superior.", + "imageSend_directMessagesUnsupported": "As imagens viajam como dados em grupo, portanto, só podem ser enviadas para um canal — não em mensagem direta.", + "imageSend_tooLarge": "Essa imagem foi codificada em mais pacotes do que o formato de malha permite.", + "imageSend_sentConfirmation": "Imagem enviada como {count} {count, plural, =1{pacote} other{pacotes}}.", + "imageSend_sendFailed": "A imagem não pôde ser enviada: {error}", + "imageSend_sendingProgress": "Envio da imagem — pacote {sent} de {total}", + "receivedImage_senderPrefix": "Nó {prefix}", + "receivedImage_incoming": "{received} de {total} pacotes", + "receivedImage_queued": "Aguardando para decodificar", + "receivedImage_tapToDecode": "Toque para decodificar", + "receivedImage_decoding": "Reconstruindo… cerca de 1 segundo", + "receivedImage_incomplete": "Imagem incompleta — {received} de {total} pacotes chegaram", + "receivedImage_corrupt": "A imagem não pôde ser reconstruída", + "receivedImage_decoderMissing": "Imagem recebida — decodificação de imagem incorreta", + "receivedImage_evicted": "Imagem não armazenada", + "receivedImage_retry": "Tente novamente", + "receivedImage_decodeAgain": "Decodifique novamente", + "receivedImage_openSettings": "Configurar", + "receivedImage_tapToProcess": "Toque para processar", + "receivedImage_awaiting": "{bytes} bytes · {packets} {packets, plural, =1{pacote} other{pacotes}}", + "imageSend_secondsValue": "{seconds} segundos", + "imageSend_minutesSecondsValue": "{minutes} min {seconds} s", + "channels_noFreeSlots": "Todos os slots de canal estão em uso", + "chat_longMessageRetryNote": "Mais de 158 bytes: enviado no máximo {count} vezes", + "reaction_report": "Reações com Emoji", + "repeater_bridgeNote": "Disponível apenas em firmware compilado com uma ponte (RS232 ou ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Mostra o número máximo de saltos para os anúncios de inundação.", + "repeater_cliHelpGetFloodMaxUnscoped": "Mostra o número máximo de saltos para pacotes de inundação sem escopo regional.", + "repeater_cliHelpGetRadioFemRxGain": "Mostra se o ganho RX do módulo frontal de LoRa está ativado.", + "repeater_cliHelpGetRadioFemTxGain": "Mostra se o ganho TX do módulo frontal de LoRa está ativado.", + "repeater_cliHelpRegionDef": "Define uma cadeia de regiões em um único comando: cada nome é adicionado sob o anterior; \"name,parent\" adiciona o nome e continua sob o pai indicado. Responde com a lista de regiões.", + "repeater_cliHelpSetFloodMaxAdvert": "Define o número máximo de saltos para encaminhar anúncios de inundação (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Define o número máximo de saltos para encaminhar pacotes de inundação sem escopo regional (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Ativa ou desativa o ganho RX (LNA) do módulo frontal de LoRa. Placas sem esse módulo respondem \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Ativa ou desativa o ganho TX (PA) do módulo frontal de LoRa. Placas sem esse módulo respondem \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Modo de carregamento de regiões: envie um nome de região por linha, indentado com espaços sob sua região pai (adicione F após o nome para permitir inundação). As linhas não recebem resposta. Envie uma linha vazia para terminar e depois \"region save\" para salvar o resultado.", + "repeater_cliRegionLoadEnd": "(fim do carregamento de regiões)", + "repeater_cliRegionLoadHint": "Linha de região, ou vazia para terminar", + "repeater_frequencyInvalid": "Frequência inválida (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Erros de Recepção", + "repeater_txPowerRangeHelper": "-9 a 30 dBm", + "room_postsPushed": "Publicações Enviadas", + "room_postsStored": "Publicações", + "settings_publicKeyCopied": "Chave pública copiada", + "settings_radioSettingsNotApplied": "O rádio não aplicou estas configurações", + "urlImage_enable": "Ativar imagens de URL", + "urlImage_possible": "Possível imagem de URL; ative-a em Configurações.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 8a8f85aa..0915a29b 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -77,6 +77,8 @@ "settings_locationIntervalInvalid": "Интервал должен составлять не менее 60 секунд и не более 86400 секунд.", "settings_latitude": "Широта", "settings_longitude": "Долгота", + "settings_autoZeroHopAdvertOnGpsUpdate": "Авто-анонс без хопов при обновлении GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Когда GPS-местоположение меняется, отправлять анонс без хопов (требуется геопозиция в анонсе).", "settings_privacyMode": "Режим конфиденциальности", "settings_privacyModeSubtitle": "Скрыть имя/позицию в анонсировании", "settings_privacyModeToggle": "Включите режим конфиденциальности, чтобы скрыть свое имя и местоположение в анонсировании.", @@ -147,7 +149,7 @@ "appSettings_languageRu": "Русский", "appSettings_notifications": "Уведомления", "appSettings_enableNotifications": "Включить уведомления", - "appSettings_enableNotificationsSubtitle": "Получать уведомления о сообщениях и оповещениях", + "appSettings_enableNotificationsSubtitle": "Получать уведомления о сообщениях и анонсах", "appSettings_notificationPermissionDenied": "Разрешение на уведомления отклонено", "appSettings_notificationsEnabled": "Уведомления включены", "appSettings_notificationsDisabled": "Уведомления отключены", @@ -190,6 +192,19 @@ "appSettings_last6Hours": "Последние 6 часов", "appSettings_last24Hours": "Последние 24 часа", "appSettings_lastWeek": "Последнюю неделю", + "appSettings_rasterTileSource": "Источник растровых тайлов", + "appSettings_stadiaEndpoint": "Конечная точка Stadia", + "appSettings_stadiaApiKey": "Ключ API Stadia", + "appSettings_stadiaApiKeyRequired": "Требуется для использования Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Настроено: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Введите свой ключ API Stadia Maps. Приложение использует его для запросов растровых тайлов.", "appSettings_offlineMapCache": "Кэш офлайн-карты", "appSettings_noAreaSelected": "Область не выбрана", "appSettings_areaSelectedZoom": "Область выбрана (масштаб {minZoom}–{maxZoom})", @@ -200,7 +215,7 @@ "appSettings_appDebugLoggingDisabled": "Журнал отладки приложения отключён", "contacts_title": "Контакты", "contacts_noContacts": "Контактов пока нет", - "contacts_contactsWillAppear": "Контакты появятся, когда устройства начнут рассылать оповещения", + "contacts_contactsWillAppear": "Контакты появятся, когда устройства начнут рассылать анонсы", "contacts_searchContacts": "Поиск контактов...", "contacts_noUnreadContacts": "Нет непрочитанных контактов", "contacts_noContactsFound": "Контакты или группы не найдены", @@ -301,6 +316,7 @@ "chat_messageDeleted": "Сообщение удалено", "chat_retryingMessage": "Повтор отправки сообщения", "chat_retryCount": "Попытка {current}/{max}", + "chat_selectSendAction": "Выберите действие отправки", "chat_sendGif": "Отправить GIF", "chat_reply": "Ответить", "chat_addReaction": "Добавить реакцию", @@ -438,6 +454,56 @@ "mapCache_downloadTilesButton": "Загрузить плитки", "mapCache_clearCacheButton": "Очистить кэш", "mapCache_failedDownloads": "Неудачных загрузок: {count}", + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "С {north}, Ю {south}, В {east}, З {west}", "time_justNow": "Только что", "time_minutesAgo": "{minutes} мин назад", @@ -557,7 +623,7 @@ "repeater_guestAccess": "Гостевой доступ", "repeater_guestAccessSubtitle": "Разрешить гостевой доступ только для чтения", "repeater_privacyMode": "Режим конфиденциальности", - "repeater_privacyModeSubtitle": "Скрывать имя/местоположение в оповещениях", + "repeater_privacyModeSubtitle": "Скрывать имя/местоположение в анонсах", "repeater_advertisementSettings": "Настройки анонсирования", "repeater_localAdvertInterval": "Интервал локальных анонсирований", "repeater_localAdvertIntervalMinutes": "{minutes} минут", @@ -626,9 +692,9 @@ "repeater_cliHelpSetAdvertInterval": "Устанавливает интервал (в минутах) отправки локального (нулевой хоп) анонсирования. Установите 0, чтобы отключить.", "repeater_cliHelpSetFloodAdvertInterval": "Устанавливает интервал (в часах) отправки анонсирований рассылкой. Установите 0, чтобы отключить.", "repeater_cliHelpSetGuestPassword": "Устанавливает/обновляет гостевой пароль. (для репитеров гости могут отправлять запрос «Get Stats»)", - "repeater_cliHelpSetName": "Устанавливает имя в оповещениях.", - "repeater_cliHelpSetLat": "Устанавливает широту для карты в оповещениях. (десятичные градусы)", - "repeater_cliHelpSetLon": "Устанавливает долготу для карты в оповещениях. (десятичные градусы)", + "repeater_cliHelpSetName": "Устанавливает имя анонса.", + "repeater_cliHelpSetLat": "Устанавливает широту для карты анонса. (десятичные градусы)", + "repeater_cliHelpSetLon": "Устанавливает долготу для карты анонса. (десятичные градусы)", "repeater_cliHelpSetRadio": "Устанавливает полностью новые параметры радио и сохраняет их в настройки. Требуется команда «reboot» для применения.", "repeater_cliHelpSetRxDelay": "Устанавливает (экспериментально) базовую задержку (>1 для эффекта) для принятых пакетов на основе качества сигнала. Установите 0, чтобы отключить.", "repeater_cliHelpSetTxDelay": "Устанавливает множитель времени в эфире для пакета в режиме рассылки и применяет случайную задержку перед пересылкой (чтобы уменьшить коллизии).", @@ -645,7 +711,7 @@ "repeater_cliHelpLogStart": "Начинает запись пакетов в файловую систему.", "repeater_cliHelpLogStop": "Останавливает запись пакетов в файловую систему.", "repeater_cliHelpLogErase": "Удаляет журналы пакетов из файловой системы.", - "repeater_cliHelpNeighbors": "Показывает список других репитеров, услышанных через оповещения нулевого хопа. Каждая строка: префикс-id-в-hex:временная-метка:snr×4", + "repeater_cliHelpNeighbors": "Показывает список других репитеров, услышанных через анонсы нулевого хопа. Каждая строка: префикс-id-в-hex:временная-метка:snr×4", "repeater_cliHelpNeighborRemove": "Удаляет первую подходящую запись (по префиксу публичного ключа в hex) из списка соседей.", "repeater_cliHelpRegion": "(только через последовательный порт) Показывает все определённые регионы и текущие права на рассылку.", "repeater_cliHelpRegionLoad": "ПРИМЕЧАНИЕ: это специальная многострочная команда. Каждая следующая строка — имя региона (с отступом пробелами для указания иерархии, минимум один пробел). Завершается пустой строкой.", @@ -859,20 +925,20 @@ "contacts_contactImported": "Контакт был импортирован", "contacts_contactImportFailed": "Контакт не удалось импортировать", "contacts_invalidAdvertFormat": "Недействительные контактные данные", - "contacts_zeroHopAdvert": "Реклама Zero Hop", + "contacts_zeroHopAdvert": "Анонс без хопов", "appSettings_languageUk": "Українська", "appSettings_enableMessageTracing": "Включить трассировку сообщений", "appSettings_enableMessageTracingSubtitle": "Показывать подробные метаданные о маршрутизации и времени для сообщений", - "contacts_floodAdvert": "Рекламный поток", + "contacts_floodAdvert": "Анонс рассылкой", "contacts_clipboardEmpty": "Буфер обмена пуст.", - "contacts_copyAdvertToClipboard": "Копировать рекламу в буфер обмена", + "contacts_copyAdvertToClipboard": "Копировать анонс в буфер обмена", "contacts_ShareContact": "Копировать контакт в буфер обмена", "contacts_zeroHopContactAdvertFailed": "Не удалось отправить контакт.", - "contacts_contactAdvertCopied": "Реклама скопирована в буфер обмена.", - "contacts_contactAdvertCopyFailed": "Копирование рекламы в буфер обмена не удалось.", + "contacts_contactAdvertCopied": "Анонс скопирован в буфер обмена.", + "contacts_contactAdvertCopyFailed": "Копирование анонса в буфер обмена не удалось.", "contacts_addContactFromClipboard": "Добавить контакт из буфера обмена", - "contacts_ShareContactZeroHop": "Поделиться контактом по объявлению", - "contacts_zeroHopContactAdvertSent": "Отправлено сообщение по объявлению.", + "contacts_ShareContactZeroHop": "Поделиться контактом по анонсу", + "contacts_zeroHopContactAdvertSent": "Контакт отправлен анонсом.", "notification_activityTitle": "Активность MeshCore", "notification_messagesCount": "{count} {count, plural, =1{сообщение} few{сообщения} many{сообщений} other{сообщений}}", "notification_channelMessagesCount": "{count} {count, plural, =1{сообщение канала} few{сообщения канала} many{сообщений канала} other{сообщений канала}}", @@ -894,7 +960,7 @@ "settings_gpxExportNoContacts": "Нет контактов для экспорта.", "settings_gpxExportShareText": "Данные карты экспортированы из meshcore-open", "settings_gpxExportShareSubject": "meshcore-open экспорт данных карты GPX", - "pathTrace_someHopsNoLocation": "Одному или нескольким хмелям не указано местоположение!", + "pathTrace_someHopsNoLocation": "У одного или нескольких хопов не указано местоположение!", "map_tapToAdd": "Нажимайте на узлы, чтобы добавить их в путь.", "map_removeLast": "Удалить последний", "map_pathTraceCancelled": "Отмена трассировки пути", @@ -1200,8 +1266,8 @@ "settings_privacySubtitle": "Контролируйте, какую информацию делиться.", "settings_telemetryLocationMode": "Режим местоположения телеметрии", "settings_telemetryEnvironmentMode": "Режим среды телеметрии", - "settings_advertLocation": "Местоположение рекламы", - "settings_advertLocationSubtitle": "Включить местоположение в объявление", + "settings_advertLocation": "Местоположение анонса", + "settings_advertLocationSubtitle": "Включить местоположение в анонс", "settings_allowAll": "Разрешить все", "settings_privacySettingsDescription": "Выберите, какую информацию ваше устройство будет делиться с другими.", "settings_denyAll": "Отклонить все", @@ -1473,14 +1539,14 @@ "repeater_ownerInfo": "Информация о операторе", "repeater_ownerInfoHelper": "Общая метаинформация для этого ретранслятора", "repeater_refreshOwnerInfo": "Обновить информацию о операторе", - "repeater_floodMax": "Максимальное количество прыжков при наводнении", + "repeater_floodMax": "Максимальное количество хопов при рассылке", "repeater_floodMaxHelper": "Максимальное количество пакетов, которые могут быть отправлены в одном потоке (0-64)", "repeater_advancedSettings": "Продвинутый", "repeater_advancedSettingsSubtitle": "Регуляторы для опытных операторов", "repeater_pathHashMode": "Режим хеширования пути", - "repeater_pathHashModeHelper": "Байты, используемые для кодирования идентификатора этого ретранслятора в тегах для обнаружения потоков/циклов. 0 = 1 байт (256 идентификаторов, до 64 переходов), 1 = 2 байта (65 000 идентификаторов, до 32 переходов), 2 = 3 байта (1 600 000 идентификаторов, до 21 перехода). Версии прошивки v1.13 и более ранние версии не поддерживают многобайтовые пути — они поднимаются только после того, как ваша сеть будет обновлена до версии v1.14 и выше.", + "repeater_pathHashModeHelper": "Байты, используемые для кодирования идентификатора этого ретранслятора в тегах flood-маршрута/обнаружения циклов. 0 = 1 байт (256 идентификаторов, до 64 хопов), 1 = 2 байта (65 000 идентификаторов, до 32 хопов), 2 = 3 байта (16 миллионов идентификаторов, до 21 хопа). Прошивки до v1.14 всегда использовали 1-байтовые маршруты; v1.14 и новее можно настроить на 2- или 3-байтовые маршруты.", "repeater_txDelay": "Задержка в работе системы Flood TX", - "repeater_txDelayHelper": "Передача с увеличенным интервалом для трафика во время наводнения, в качестве коэффициента, умножающего время передачи пакета (от 0 до 2, по умолчанию 0,5). Более высокое значение означает меньшее количество столкновений, но более медленную передачу.", + "repeater_txDelayHelper": "Задержка повторной передачи для трафика при рассылке (flood), в качестве коэффициента, умножающего время передачи пакета (от 0 до 2, по умолчанию 0,5). Более высокое значение означает меньшее количество столкновений, но более медленную передачу.", "repeater_directTxDelay": "Прямая задержка сигнала TX", "repeater_directTxDelayHelper": "Передача промежуточных данных для прямого (немассового) трафика, в качестве коэффициента, равного времени передачи пакета (от 0 до 2, по умолчанию 0,3).", "repeater_intThresh": "Пороговое значение помех", @@ -1488,10 +1554,10 @@ "repeater_agcResetInterval": "Интервал сброса AGC", "repeater_agcResetIntervalHelper": "Как часто следует сбрасывать автоматическую регулировку усиления радио, чтобы вернуться к нормальному состоянию после заклинивания? Интервал сброса составляет несколько секунд, кратный 4. Отключение периодического сброса осуществляется с помощью параметра 0.", "repeater_actionsTitle": "Действия", - "repeater_sendAdvert": "Отправить объявление о наводнении", - "repeater_sendAdvertSubtitle": "Разместите рекламу о наводнении в эфире по всей сети.", - "repeater_sendAdvertZeroHop": "Опубликуйте рекламу, не требующую промежуточного распространения.", - "repeater_sendAdvertZeroHopSubtitle": "Разместите рекламу, распространяемую одним способом (без использования ретрансляторов).", + "repeater_sendAdvert": "Отправить анонс рассылкой", + "repeater_sendAdvertSubtitle": "Разошлите анонс рассылкой по всей сети.", + "repeater_sendAdvertZeroHop": "Опубликуйте анонс, не требующий промежуточного распространения.", + "repeater_sendAdvertZeroHopSubtitle": "Разместите анонс, распространяемый одним способом (без использования ретрансляторов).", "repeater_clockSync": "Синхронизировать время сейчас", "repeater_clockSyncSubtitle": "Установите время на вашем телефоне, чтобы оно совпадало со временем ретранслятора.", "repeater_actionSucceeded": "{action} succeeded", @@ -1588,7 +1654,7 @@ "repeater_sensors": "Датчики", "repeater_cliHelpPowerOff": "Отключает устройство. (ожидается отсутствие ответа).", "repeater_cliHelpClkReboot": "Сбрасывает часы до известной эпохи и перезапускает устройство.", - "repeater_cliHelpAdvertZeroHop": "Отправляет рекламу, распространяемую только среди ближайших соседей (без промежуточных узлов).", + "repeater_cliHelpAdvertZeroHop": "Отправляет анонс, распространяемый только среди ближайших соседей (без промежуточных узлов).", "repeater_cliHelpStartOta": "Запускает обновление прошивки по воздуху на поддерживаемых устройствах.", "repeater_cliHelpTime": "Устанавливает время устройства в соответствии с заданными секундами от начала эпохи Unix. Время не может сброситься назад.", "repeater_cliHelpBoard": "Отображает информацию о производителе платы / идентификатор аппаратного обеспечения.", @@ -1599,7 +1665,7 @@ "repeater_cliHelpSetDutyCycle": "Устанавливает максимальный допустимый цикл передачи данных в процентах (от 1 до 100). Внутренне корректирует коэффициент времени передачи.", "repeater_cliHelpSetPrvKey": "(Только для серийного использования) Заменяет приватный ключ, идентифицирующий устройство. Требуется перезагрузка для применения. Генерирует новый публичный ключ.", "repeater_cliHelpSetRadioRxGain": "(Только для SX126x) Переключает усиление RX для повышения чувствительности при больших токах потребления.", - "repeater_cliHelpSetOwnerInfo": "Указывает строку с контактной информацией владельца, которая должна быть включена в объявления. Используйте '|' для переносов строк.", + "repeater_cliHelpSetOwnerInfo": "Указывает строку с контактной информацией владельца, которая должна быть включена в анонсы. Используйте '|' для переносов строк.", "repeater_cliHelpSetPathHashMode": "Устанавливает режим хеширования пути. 0 = устаревший, 1 = стандартный, 2 = строгий. Влияет на то, как определяются маршруты.", "repeater_cliHelpSetLoopDetect": "Устанавливает чувствительность обнаружения циклов маршрутизации: \"выключено\", \"минимальная\", \"умеренная\" или \"строгая\".", "repeater_cliHelpSetFreq": "(Только для настройки) Быстро устанавливает только частоту. Требуется перезагрузка. Рекомендуется использовать функцию \"настройка радио\" для полного набора параметров.", @@ -1619,15 +1685,15 @@ "repeater_cliHelpGetAgcResetInterval": "Отображает интервал сброса автоматической регулировки усиления в секундах.", "repeater_cliHelpGetMultiAcks": "Показывает, включен ли режим двойной подтверждения (1) или выключен (0).", "repeater_cliHelpGetAllowReadOnly": "Отображает, разрешен ли доступ для чтения только для гостей.", - "repeater_cliHelpGetAdvertInterval": "Отображает продолжительность рекламного блока в минутах.", - "repeater_cliHelpGetFloodAdvertInterval": "Отображает интервал времени показа рекламного ролика в часах.", + "repeater_cliHelpGetAdvertInterval": "Отображает интервал локального анонсирования в минутах.", + "repeater_cliHelpGetFloodAdvertInterval": "Отображает интервал анонсирования рассылкой (flood) в часах.", "repeater_cliHelpGetGuestPassword": "Отображает установленный пароль для гостя.", "repeater_cliHelpGetLat": "Отображает заданную широту.", "repeater_cliHelpGetLon": "Отображает заданную долготу.", "repeater_cliHelpGetRxDelay": "Отображает базовое значение задержки.", - "repeater_cliHelpGetTxDelay": "Отображает коэффициент задержки при работе в режиме затопления.", + "repeater_cliHelpGetTxDelay": "Отображает коэффициент задержки при работе в режиме рассылки (flood).", "repeater_cliHelpGetDirectTxDelay": "Отображает коэффициент задержки в режиме прямого подключения.", - "repeater_cliHelpGetFloodMax": "Отображает максимальное количество переходов при затоплении.", + "repeater_cliHelpGetFloodMax": "Отображает максимальное количество хопов при рассылке.", "repeater_cliHelpGetOwnerInfo": "Отображает строку с контактной информацией владельца.", "repeater_cliHelpGetPathHashMode": "Отображает режим работы с хэшем пути (0/1/2).", "repeater_cliHelpGetLoopDetect": "Отображает чувствительность к обнаружению циклов.", @@ -1649,8 +1715,8 @@ "repeater_cliHelpSensorList": "Перечисляет все пользовательские настройки датчиков, разбитые на страницы с возможностью указания начального индекса.", "repeater_cliHelpRegionDefault": "Отображает текущий область действия по умолчанию.", "repeater_cliHelpRegionDefaultSet": "Устанавливает значение региона по умолчанию. Используйте \"\", чтобы сбросить значение.", - "repeater_cliHelpRegionListAllowed": "Перечисляет регионы, где разрешено движение транспорта во время наводнений.", - "repeater_cliHelpRegionListDenied": "Перечисляет регионы, где запрещено движение транспорта во время наводнений.", + "repeater_cliHelpRegionListAllowed": "Перечисляет регионы, где разрешена рассылка (flood).", + "repeater_cliHelpRegionListDenied": "Перечисляет регионы, где запрещена рассылка (flood).", "repeater_cliHelpStatsPackets": "(Только для серийной версии) Отображает статистику на уровне пакетов.", "repeater_cliHelpStatsRadio": "(Только для серий) Отображает статистику радио.", "repeater_cliHelpStatsCore": "(Только для серийного оборудования) Отображает основные статистические данные прошивки.", @@ -1706,7 +1772,7 @@ "contacts_searchClose": "Закрыть поиск", "routing_title": "Маршрутизация", "routing_modeAuto": "Авто", - "routing_modeFlood": "Наводнение", + "routing_modeFlood": "Рассылка", "routing_modeManual": "Инструкция", "routing_modeAutoHint": "Автоматически выбирает наиболее известный путь, и если такой путь неизвестен, использует алгоритм поиска пути.", "routing_modeFloodHint": "Передача сигнала через все ретрансляторы. Самый надежный способ, но требует больше времени на передачу.", @@ -1720,18 +1786,18 @@ "routing_knownPaths": "Известные маршруты", "routing_knownPathsHint": "Создайте маршрут для переключения на этот пункт.", "routing_inUse": "В эксплуатации", - "routing_qualityStrong": "Сильный первый скачок", + "routing_qualityStrong": "Сильный первый хоп", "routing_qualityGood": "Хорошее начало", "routing_qualityFair": "Первый хороший урожай", "routing_qualityWorked": "Осуществлено", "routing_qualityFlood": "Узнал из новостей, распространяющихся в интернете.", "routing_qualityUntested": "Непроверенный", "routing_neverWorked": "никогда не было подтверждено", - "routing_floodDelivery": "Доставка при затоплении", + "routing_floodDelivery": "Доставка рассылкой", "pathEditor_title": "Создать маршрут", - "pathEditor_hopCounter": "{count} из 64 хмеля", - "pathEditor_noHops": "На данный момент хмель еще не добавлен. Чтобы добавить его, нажмите на соответствующие кнопки ниже в нужном порядке, или сохраните рецепт без хмеля, чтобы отправить его напрямую.", - "pathEditor_addHops": "Добавляйте хмель в соответствии с указанным порядком.", + "pathEditor_hopCounter": "{count} из 64 хопов", + "pathEditor_noHops": "Пока не добавлено ни одного хопа. Нажимайте на репитеры ниже, чтобы добавлять их по порядку, или сохраните маршрут без хопов, чтобы отправить напрямую.", + "pathEditor_addHops": "Добавляйте хопы по порядку", "pathEditor_searchRepeaters": "Поиск повторителей", "pathEditor_advancedHex": "Продвинутый уровень: прямой путь в шестнадцатеричном формате", "pathEditor_hexLabel": "Префиксы шестнадцатеричной системы", @@ -1741,7 +1807,7 @@ "routing_deliveryCounts": "{successes} delivered, {failures} failed", "pathEditor_tooManyHops": "Максимальное количество ингредиентов – 64", "pathEditor_usePath": "Используйте этот путь", - "pathEditor_removeHop": "Удалить хмель", + "pathEditor_removeHop": "Удалить хоп", "pathEditor_unknownHop": "Неизвестный ретранслятор", "map_zoomIn": "Увеличить масштаб", "map_zoomOut": "Увеличить масштаб", @@ -1843,5 +1909,260 @@ "pathMap_noLocation": "Нет координат", "pathMap_followPacket": "Следить за пакетом", "pathMap_unfollowPacket": "Не следить за пакетом", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Регионы", + "settings_regionSettingsSubtitle": "Управление сохранёнными регионами", + "settings_regionManagement_screenTitle": "Управление регионами", + "settings_regionNameHint": "Введите название региона", + "settings_regionAddRegion": "Добавить регион", + "settings_regionFetchRegions": "Извлекать регионы с ретрансляторов", + "settings_regionFetchRegionsFail": "Не были найдены никакие регионы", + "settings_regionFetchRegionsAlreadyExists": "Этот регион уже был добавлен", + "settings_regionName": "Название региона", + "settings_regionDeleted": "Регион удалён", + "settings_deleteRegion": "Удалить регион", + "settings_deleteRegionConfirm": "Удалить \"{region}\" из списка регионов?", + "settings_infoHardware": "Оборудование", + "settings_infoFirmware": "Производственное программное обеспечение", + "repeater_pathHashModeOption0": "0 - 1 байт", + "repeater_pathHashModeOption1": "1 - 2 байта", + "repeater_pathHashModeOption2": "2 - 3 байта", + "repeater_pathHashModeOption3": "3 - 4 байта", + "appSettings_batteryLipoHv": "LiPo HV (3,0–4,35 В)", + "channels_regionSetTo": "РЕГИОН: {region}", + "channels_regionNotSet": "Регион: отсутствует", + "channels_regionSelect_Title": "Выберите регион", + "channels_clearRegion": "Чистый регион", + "chat_sendImageLora": "Отправить изображение через MeshCore", + "chat_imagePickFailed": "Не удалось открыть это изображение", + "chat_receivedGif": "Получен GIF", + "repeater_keySettings": "Изменить ключи идентичности", + "repeater_keySettingsSubtitle": "Измените пару публичных/частных ключей", + "repeater_prvKey": "Личный ключ", + "repeater_prvKeyHelper": "Для повторителя генерируется новый приватный ключ — шестнадцатеричная строка из 128 символов.", + "repeater_generatePrvKey": "Сгенерируйте случайный ключ-пару", + "repeater_stopGeneratingPrvKey": "Прервать поиск ключной пары", + "repeater_pubKey": "Публичный ключ", + "repeater_pubKeyHelper": "Это публичный ключ, который соответствует сгенерированному приватному ключу. Вы не можете установить его напрямую.", + "repeater_pubKeyPrefix": "Желаемый префикс", + "repeater_pubKeyPrefixHelper": "Найдите публичный ключ, начинающийся этими шестнадцатеричными цифрами. Ожидаемое количество попыток: {tries}.", + "imageMessages_enableTitle": "Включить изображения в сообщения", + "imageMessages_enableSubtitle": "Отправьте изображения через сеть. Требуется однократная загрузка шаблона изображения.", + "imageMessages_modelSectionTitle": "Модель изображения", + "imageMessages_downloadModel": "Скачать", + "imageMessages_cancelDownload": "Отмена", + "imageMessages_removeModel": "Удалить модель", + "imageMessages_modelReady": "Готов", + "imageMessages_modelNotPublished": "Пока не опубликовано — эта сборка не может скачать это.", + "imageMessages_downloadFailed": "Модель изображения не удалось скачать.", + "imageMessages_autoProcessTitle": "Автоматически обрабатывать изображения", + "imageMessages_autoProcessSubtitle": "Примерно каждое изображение реконструируйте сразу после его поступления. Для этого на каждый раз используется около 2 ГБ памяти; отключите реконструкцию касанием.", + "imageSend_title": "Отправьте изображение", + "imageSend_cropNote": "Меняется размер на 512 × 512 · соотношение сторон не сохраняется", + "imageSend_originalSize": "Оригинал", + "imageSend_onAirSize": "В эфире", + "imageSend_quality": "Качество", + "imageSend_qualityStandard": "Стандарт", + "imageSend_qualityHigh": "Высота", + "imageSend_packetsLabel": "Пакеты", + "imageSend_airtimeLabel": "Время на эфире", + "imageSend_sizeLabel": "Пакет", + "imageSend_packetsCount": "{count} {count, plural, one{пакет} few{пакета} many{пакетов} other{пакета}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Настройки радио неизвестны", + "imageSend_radioUnknownBody": "Подключитесь к устройству, чтобы можно было рассчитать время эфирного времени.", + "imageSend_longSendTitle": "Долгая передача", + "imageSend_longSendBody": "Это будет поддерживать канал примерно {duration}.", + "imageSend_floodNote": "Руководство по маршрутизации потоков: каждый ретрансатор в зоне перераспределяет каждый пакет, поэтому канал остаётся занятным дольше, чем это.", + "imageSend_parityTitle": "Пакет восстановления", + "imageSend_paritySubtitle": "Один дополнительный пакет. Групповые сообщения не подтверждаются, поэтому это позволяет получателю восстановить изображение, если один пакет потерян.", + "imageSend_send": "Отправить", + "imageSend_cancel": "Отмена", + "imageSend_encodeFailed": "Это изображение не может быть закодировано.", + "imageSend_codecDownloading": "Модель изображения всё ещё загружается.", + "imageSend_codecUnavailable": "Отправка изображения на этом устройстве недоступна.", + "imageSend_codecDisabled": "В настройках отключены сообщения с изображениями.", + "imageSend_deviceUnsupported": "Это радио не может отправлять пакеты изображений. Подключите устройство, работающее на прошивке-компаньоне версии 13 или выше.", + "imageSend_directMessagesUnsupported": "Изображения передаются как групповые данные, поэтому их можно отправлять только в канал, а не в личное сообщение.", + "imageSend_tooLarge": "Изображение было закодировано в больше пакетов, чем позволяет формат сетки.", + "imageSend_sentConfirmation": "Изображение отправлено как {count} {count, plural, =1{пакет} other{пакетов}}.", + "imageSend_sendFailed": "Изображение не может быть отправлено: {error}", + "imageSend_sendingProgress": "Отправка изображения — пакет {sent} из {total}", + "receivedImage_senderPrefix": "Узел {prefix}", + "receivedImage_incoming": "{received} из {total} пакетов", + "receivedImage_queued": "Ожидание расшифровки", + "receivedImage_tapToDecode": "Нажмите для декодирования", + "receivedImage_decoding": "Реконструкция… примерно за 1 секунду", + "receivedImage_incomplete": "Отсутствует изображение — {received} из {total} пакетов пришло", + "receivedImage_corrupt": "Изображение не может быть восстановлено", + "receivedImage_decoderMissing": "Получен изображение — декодирование изображения неправильное", + "receivedImage_evicted": "Изображение больше не сохраняется", + "receivedImage_retry": "Попробуйте снова", + "receivedImage_decodeAgain": "Декодируйте снова", + "receivedImage_openSettings": "Настройте", + "receivedImage_tapToProcess": "Нажмите для обработки", + "receivedImage_awaiting": "{bytes} байт · {packets} {packets, plural, =1{пакет} other{пакетов}}", + "imageSend_secondsValue": "{seconds} секунд", + "imageSend_minutesSecondsValue": "{minutes} м {seconds} с", + "channels_noFreeSlots": "Нет свободных слотов для каналов", + "chat_longMessageRetryNote": "Более 158 байт: отправляется не более {count} раз", + "reaction_report": "Реакции", + "repeater_bridgeNote": "Доступно только на прошивке, собранной с мостом (RS232 или ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Показывает максимальное число хопов для анонсов, рассылаемых по сети (flood).", + "repeater_cliHelpGetFloodMaxUnscoped": "Показывает максимальное число хопов для пакетов рассылки (flood) без региональной области.", + "repeater_cliHelpGetRadioFemRxGain": "Показывает, включено ли усиление RX на входном модуле LoRa.", + "repeater_cliHelpGetRadioFemTxGain": "Показывает, включено ли усиление TX на входном модуле LoRa.", + "repeater_cliHelpRegionDef": "Задаёт цепочку регионов одной командой: каждое имя добавляется под предыдущим; \"name,parent\" добавляет имя и продолжает под указанным родителем. В ответ возвращается список регионов.", + "repeater_cliHelpSetFloodMaxAdvert": "Задаёт максимальное число хопов для пересылки анонсов, рассылаемых по сети (flood) (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Задаёт максимальное число хопов для пересылки пакетов рассылки (flood) без региональной области (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Переключает усиление RX (LNA) входного модуля LoRa. Платы без него отвечают \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Переключает усиление TX (PA) входного модуля LoRa. Платы без него отвечают \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Режим загрузки регионов: отправляйте по одному имени региона на строку, с отступом пробелами под родителем (добавьте F после имени, чтобы разрешить рассылку по сети). Строки не получают ответа. Отправьте пустую строку, чтобы завершить, затем \"region save\", чтобы сохранить результат.", + "repeater_cliRegionLoadEnd": "(конец загрузки регионов)", + "repeater_cliRegionLoadHint": "Строка региона или пусто для завершения", + "repeater_frequencyInvalid": "Недопустимая частота (150-2500 МГц)", + "repeater_frequencyRangeHelper": "150-2500 МГц", + "repeater_recvErrors": "Ошибки приёма", + "repeater_txPowerRangeHelper": "от -9 до 30 dBm", + "room_postsPushed": "Отправлено публикаций", + "room_postsStored": "Публикации", + "settings_publicKeyCopied": "Публичный ключ скопирован", + "settings_radioSettingsNotApplied": "Радиомодуль не применил эти настройки", + "urlImage_enable": "Показывать изображения по URL", + "urlImage_possible": "Возможно изображение по URL; включите это в настройках.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index f6852078..b09dbaad 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -100,17 +100,19 @@ "settings_locationInvalid": "Neplatná šírka alebo dĺžka.", "settings_latitude": "Súradnica", "settings_longitude": "Dĺžka", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatický zero-hop inzerát pri aktualizácii GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Keď sa GPS poloha zmení, odoslať zero-hop inzerát (vyžaduje polohu v inzeráte).", "settings_privacyMode": "Režim ochrany súkromia", - "settings_privacyModeSubtitle": "Skryť meno/poloha v reklamách", - "settings_privacyModeToggle": "Prepínač súkromného režimu skryje vaše meno a polohu v reklamách.", + "settings_privacyModeSubtitle": "Skryť meno/poloha v inzerátoch", + "settings_privacyModeToggle": "Prepínač súkromného režimu skryje vaše meno a polohu v inzerátoch.", "settings_privacyModeEnabled": "Ochranný režim je povolený.", "settings_privacyModeDisabled": "Ochranný režim je vypnutý", "settings_actions": "Možné akcie", "settings_deleteAllPaths": "Delete All Paths", "settings_deleteAllPathsSubtitle": "Clear all path data from contacts.", - "settings_sendAdvertisement": "Odoslať reklamu", + "settings_sendAdvertisement": "Odoslať inzerát", "settings_sendAdvertisementSubtitle": "Momentálne priezornejšie.", - "settings_advertisementSent": "Reklama odeslaná", + "settings_advertisementSent": "Inzerát odoslaný", "settings_syncTime": "Čas synchronizácie", "settings_syncTimeSubtitle": "Nastaviť hodiny zariadenia na čas telefónu", "settings_timeSynchronized": "Čas synchronizovaný", @@ -191,7 +193,7 @@ "appSettings_messageNotificationsSubtitle": "Zobraziť upozornenie pri prijímaní nových správ", "appSettings_channelMessageNotifications": "Notifikácie z kanálov", "appSettings_channelMessageNotificationsSubtitle": "Zobraziť upozornenie pri prijímaní správ z kanálu", - "appSettings_advertisementNotifications": "Upozornenia na reklamy", + "appSettings_advertisementNotifications": "Upozornenia na inzeráty", "appSettings_advertisementNotificationsSubtitle": "Zobraziť upozornenie, keď sa objavia nové uzly.", "appSettings_messaging": "Správy", "appSettings_clearPathOnMaxRetry": "Vyčisti cestu na Max Retry", @@ -199,7 +201,7 @@ "appSettings_pathsWillBeCleared": "Cesty budú vymazané po 5 neúspešných pokusoch.", "appSettings_pathsWillNotBeCleared": "Cesty sa automaticky nevymazávajú.", "appSettings_autoRouteRotation": "Automatické prechodové trasy", - "appSettings_autoRouteRotationSubtitle": "Striedajte sa medzi najlepšími trasami a režimom povodňovej analýzy.", + "appSettings_autoRouteRotationSubtitle": "Striedajte sa medzi najlepšími trasami a flood režimom.", "appSettings_autoRouteRotationEnabled": "Automatické otáčanie trasy povolené", "appSettings_autoRouteRotationDisabled": "Automatické prekladanie trás pozastavené", "appSettings_battery": "Batéria", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Posledné 6 hodín", "appSettings_last24Hours": "Posledných 24 hodín", "appSettings_lastWeek": "Minul týždeň", + "appSettings_rasterTileSource": "Zdroj rastrových dlaždíc", + "appSettings_stadiaEndpoint": "Koncový bod Stadia", + "appSettings_stadiaApiKey": "Kľúč API Stadia", + "appSettings_stadiaApiKeyRequired": "Vyžaduje sa na používanie Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Nakonfigurované: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Zadajte svoj kľúč API pre Stadia Maps. Aplikácia ho používa na požiadavky na rastrové dlaždice.", "appSettings_offlineMapCache": "Offline Mapa Pamäť", "appSettings_noAreaSelected": "Neoznačila sa žiadna oblasť", "appSettings_areaSelectedZoom": "Vyberená oblasť (zoom {minZoom}-{maxZoom})", @@ -260,7 +275,7 @@ "appSettings_appDebugLoggingDisabled": "Zabudované ladenie aplikácie je vypnuté.", "contacts_title": "Kontakty", "contacts_noContacts": "Zatiaľ žiadne kontakty.", - "contacts_contactsWillAppear": "Kontakty sa zobrazia, keď zariadenia spúšťajú reklamu.", + "contacts_contactsWillAppear": "Kontakty sa zobrazia, keď zariadenia vysielajú inzerát.", "contacts_searchContacts": "Vyhľadávajte kontakty...", "contacts_noUnreadContacts": "Žiadne neprečítané kontakty", "contacts_noContactsFound": "Neboli nájdených žiadnych kontaktov ani skupiny.", @@ -470,6 +485,7 @@ } } }, + "chat_selectSendAction": "Vybrať akciu odoslania", "chat_sendGif": "Odoslať GIF", "chat_reply": "Odpovedať", "chat_addReaction": "Pridať Reakciu", @@ -562,7 +578,7 @@ "chat_pathManagement": "Správa ciest", "chat_routingMode": "Režim trasy", "chat_autoUseSavedPath": "Použiť uloženú cestu", - "chat_forceFloodMode": "Zavrieť režim núdzového povodňového režimu", + "chat_forceFloodMode": "Zavrieť núdzový flood režim", "chat_recentAckPaths": "Nedávne cesty ACK (klepni na použitie):", "chat_pathHistoryFull": "História ciest je plná. Odstráňte záznamy, aby ste mohli pridať nové.", "chat_hopSingular": "Skok", @@ -606,7 +622,7 @@ "chat_path": "Cesta", "chat_publicKey": "Verejný kľúč", "chat_compressOutgoingMessages": "Komprimovať odoslané správy", - "chat_floodForced": "Povodňová (nutená)", + "chat_floodForced": "Flood (vynútený)", "chat_directForced": "Priame (donútené)", "chat_hopsForced": "{count} skokov (nutené)", "@chat_hopsForced": { @@ -616,7 +632,7 @@ } } }, - "chat_floodAuto": "Povod (automaticky)", + "chat_floodAuto": "Flood (automaticky)", "chat_direct": "Priamo", "chat_poiShared": "Zdieľané body záujmu", "chat_unread": "Nezriadené: {count}", @@ -769,6 +785,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -834,7 +900,7 @@ "login_routing": "Rútiace", "login_routingMode": "Režim trasy", "login_autoUseSavedPath": "Použiť uloženú cestu", - "login_forceFloodMode": "Zavrieť režim núdzového povodňového režimu", + "login_forceFloodMode": "Zavrieť núdzový flood režim", "login_managePaths": "Spravovať Cesty", "login_login": "Prihlásiť", "login_attempt": "Skúšaj {current}/{max}", @@ -907,7 +973,7 @@ "repeater_statusTitle": "Status opakého zboru", "repeater_routingMode": "Režim trasy", "repeater_autoUseSavedPath": "Použiť uloženú cestu", - "repeater_forceFloodMode": "Zavrieť režim núdzového povodňového režimu", + "repeater_forceFloodMode": "Zavrieť núdzový flood režim", "repeater_pathManagement": "Správa trás", "repeater_refresh": "Obnoviť", "repeater_statusRequestTimeout": "Požiadavka stavu zlyhala.", @@ -952,7 +1018,7 @@ } } }, - "repeater_packetTxTotal": "Celkem: {total}, Povodňový režim: {flood}, Priamy: {direct}", + "repeater_packetTxTotal": "Celkem: {total}, Flood: {flood}, Priamy: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -966,7 +1032,7 @@ } } }, - "repeater_packetRxTotal": "Celkem: {total}, Povodňový režim: {flood}, Priamy: {direct}", + "repeater_packetRxTotal": "Celkem: {total}, Flood: {flood}, Priamy: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -980,7 +1046,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Pond: {flood}, Priamy: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Priamy: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1026,9 +1092,9 @@ "repeater_guestAccess": "Prístup pre hostí", "repeater_guestAccessSubtitle": "Umožniť prístup hosta iba na čítanie.", "repeater_privacyMode": "Režim ochrany súkromia", - "repeater_privacyModeSubtitle": "Skryť meno/poloha v reklamách", - "repeater_advertisementSettings": "Nastavenia reklamy", - "repeater_localAdvertInterval": "Lokálna reklamná časová obdoba", + "repeater_privacyModeSubtitle": "Skryť meno/poloha v inzerátoch", + "repeater_advertisementSettings": "Nastavenia inzerátov", + "repeater_localAdvertInterval": "Lokálna inzertná časová obdoba", "repeater_localAdvertIntervalMinutes": "{minutes} minút", "@repeater_localAdvertIntervalMinutes": { "placeholders": { @@ -1037,7 +1103,7 @@ } } }, - "repeater_floodAdvertInterval": "Interval reklamnej povodňovej reklamy", + "repeater_floodAdvertInterval": "Interval flood inzerátu", "repeater_floodAdvertIntervalHours": "{hours} hodín", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1046,7 +1112,7 @@ } } }, - "repeater_encryptedAdvertInterval": "Šifrovaný reklamný interval", + "repeater_encryptedAdvertInterval": "Šifrovaný inzertný interval", "repeater_dangerZone": "Nebezpečná zóna", "repeater_rebootRepeater": "Restart Repetér", "repeater_rebootRepeaterSubtitle": "Resetovať vysielací prístroj", @@ -1102,14 +1168,14 @@ "repeater_ownerInfo": "Informácie o poskytovateľovi", "repeater_ownerInfoHelper": "Veľké dátové informácie pre tento vysielací zdroj", "repeater_refreshOwnerInfo": "Zísť informácie o operátore", - "repeater_floodMax": "Maximálny počet skokov pri povodni", + "repeater_floodMax": "Maximálny počet skokov flood", "repeater_floodMaxHelper": "Maximálny počet paketov, ktoré môžu preletieť cez jeden hop (0-64)", "repeater_advancedSettings": "Pokročilé", "repeater_advancedSettingsSubtitle": "Ovládacie knopy pre skúsených operátorov", "repeater_pathHashMode": "Režim hashovania cesty", - "repeater_pathHashModeHelper": "Byty použité na zakódovanie ID tohto opakovača v tagoch pre trasu/detekciu slučky. 0 = 1 bytu (256 ID, až 64 skokov), 1 = 2 byty (65 000 ID, až 32 skokov), 2 = 3 byty (16 miliónov ID, až 21 skokov). Verzie 1.13 a staršie nepodporujú viacbytové trasy – fungujú len, keď je sieť aktivovaná.", + "repeater_pathHashModeHelper": "Bajty použité na zakódovanie ID tohto opakovača v tagoch flood trasy/detekcie slučky. 0=1 bajt (256 ID, až 64 skokov), 1=2 bajty (65 000 ID, až 32 skokov), 2=3 bajty (16 miliónov ID, až 21 skokov). Firmvér pred v1.14 vždy používal 1-bajtové trasy; v1.14 a novšie možno nakonfigurovať na 2- alebo 3-bajtové trasy.", "repeater_txDelay": "Zpoždanie v Flood, TX", - "repeater_txDelayHelper": "Nastavenie pre opakované vysielanie pre dopravu počas povodní, ako násobok času, ktorý paket využije (0-2, výchoce hodnota 0,5). Vyššia hodnota znamená menej kolízii, ale pomalšie doručovanie.", + "repeater_txDelayHelper": "Nastavenie pre opakované vysielanie pre flood dopravu, ako násobok času, ktorý paket využije (0-2, výchoce hodnota 0,5). Vyššia hodnota znamená menej kolízii, ale pomalšie doručovanie.", "repeater_directTxDelay": "Priame oneskorenie TX", "repeater_directTxDelayHelper": "Nastavenie pre retransmisiu pre priame (nie pre plnú sieť), ako násobok času prenosu paketov (0-2, výchoce 0,3).", "repeater_intThresh": "Hranica, pri ktorej dochádza k rušeniu", @@ -1117,10 +1183,10 @@ "repeater_agcResetInterval": "Interval reštartu AGC", "repeater_agcResetIntervalHelper": "Ako často by ste mali reštartovať automatické ovládanie zosilnenia, aby ste sa vrátili do normálneho stavu, ak je zosilnenie zablokované? Nastavenie „4.0“ vypne pravidelné reštarty.", "repeater_actionsTitle": "Opatrenia", - "repeater_sendAdvert": "Odoslať inzerát o povodňovej situácii", - "repeater_sendAdvertSubtitle": "Zverejnite reklamu na povodňu prostredníctvom siete.", - "repeater_sendAdvertZeroHop": "Odoslať reklamu bez prenosu", - "repeater_sendAdvertZeroHopSubtitle": "Zverejnite reklamnú správu, ktorá sa prenáša len raz (bez prenosov).", + "repeater_sendAdvert": "Odoslať flood inzerát", + "repeater_sendAdvertSubtitle": "Zverejnite flood inzerát v sieti.", + "repeater_sendAdvertZeroHop": "Odoslať inzerát bez prenosu", + "repeater_sendAdvertZeroHopSubtitle": "Zverejnite inzerát, ktorý sa prenáša len raz (bez prenosov).", "repeater_clockSync": "Synchronizujte hodiny teraz", "repeater_clockSyncSubtitle": "Nastavte čas na vašom telefóne, aby odpovedal na volania z vysielacieho zariadenia.", "repeater_actionSucceeded": "{action} succeeded", @@ -1205,9 +1271,9 @@ "repeater_cliQuickGetTx": "Zísť TX", "repeater_cliQuickNeighbors": "Súsezný", "repeater_cliQuickVersion": "Verzia", - "repeater_cliQuickAdvertise": "Reklama", + "repeater_cliQuickAdvertise": "Inzerát", "repeater_cliQuickClock": "Hodiny", - "repeater_cliHelpAdvert": "Odosiela reklamnú balíček.", + "repeater_cliHelpAdvert": "Odosiela inzertný balíček.", "repeater_cliHelpReboot": "Resetuje zariadenie. (pozor, môže dôjsť k 'Timeoutu', čo je normálne)", "repeater_cliHelpClock": "Zobrazuje aktuálny čas podľa hodiniek zariadenia.", "repeater_cliHelpPassword": "Nastaví nový administrátorský prístupový údaj pre zariadenie.", @@ -1221,15 +1287,15 @@ "repeater_cliHelpSetIntThresh": "Nastavuje hranicu ruživeho ladenia (v dB). Predvolené je 14. Nastavením na 0 sa vypne detekcia ruživeho ladenia kanálu.", "repeater_cliHelpSetAgcResetInterval": "Nastavuje interval na reštartovanie Auto Gain Controlleru. Nastavenie na 0 vypne funkciu.", "repeater_cliHelpSetMultiAcks": "Povolí alebo pozastaví funkciiu \"dvojité potvrdenia\".", - "repeater_cliHelpSetAdvertInterval": "Nastavuje interval časovača v minútach na odošle miestny (bezprostredný) reklamný paket. Nastavenie na 0 vypne funkciu.", - "repeater_cliHelpSetFloodAdvertInterval": "Nastavuje interval časovača v hodinách na odeslanie reklamnej vlne. Nastavenie na 0 vypne.", + "repeater_cliHelpSetAdvertInterval": "Nastavuje interval časovača v minútach na odoslanie miestneho (bezprostredného) inzertného paketu. Nastavenie na 0 vypne funkciu.", + "repeater_cliHelpSetFloodAdvertInterval": "Nastavuje interval časovača v hodinách na odoslanie flood inzerátu. Nastavenie na 0 vypne.", "repeater_cliHelpSetGuestPassword": "Nastavuje/aktualizuje heslo hosťa. (pre opakované pripojenia môžu hosťovské prihlásenia posielať požadanie \"Get Stats\")", - "repeater_cliHelpSetName": "Nastaví názov reklamy.", - "repeater_cliHelpSetLat": "Nastaví geografickú šírku reklamnej mapy. (desatinné stupne)", - "repeater_cliHelpSetLon": "Nastavuje longitudinu reklamnej mapy. (desatinné stupne)", + "repeater_cliHelpSetName": "Nastaví názov inzerátu.", + "repeater_cliHelpSetLat": "Nastaví geografickú šírku mapy inzerátu. (desatinné stupne)", + "repeater_cliHelpSetLon": "Nastavuje longitúdu mapy inzerátu. (desatinné stupne)", "repeater_cliHelpSetRadio": "Nastavuje úplne nové parametre rádia a uloží ich do preferencií. Požaduje príkaz \"reboot\" na aplikáciu.", "repeater_cliHelpSetRxDelay": "Nastavenia (experimentálne) základné (musi byť > 1 pre účel) na aplikáciu mierneho onesenia prijatých paketov, na základe signálu/skóre. Nastavenie na 0 vypne.", - "repeater_cliHelpSetTxDelay": "Nastavuje faktor násobený časom na vzduchu pre paket v režime povodňovej vlny a s náhodným systémom slotov, aby sa oneskorene jeho prenosovanie (s cieľom znížiť pravdepodobnosť kolízii).", + "repeater_cliHelpSetTxDelay": "Nastavuje faktor násobený časom na vzduchu pre paket v režime flood a s náhodným systémom slotov, aby sa oneskorene jeho prenosovanie (s cieľom znížiť pravdepodobnosť kolízii).", "repeater_cliHelpSetDirectTxDelay": "Podobne ako txdelay, ale pre aplikáciu náhodného oneskorenia pri preposlaní paketov v režime priameho prenosu.", "repeater_cliHelpSetBridgeEnabled": "Aktivovať/Zatvárať most.", "repeater_cliHelpSetBridgeDelay": "Nastaviť odklad pred retransmisiou paketov.", @@ -1243,9 +1309,9 @@ "repeater_cliHelpLogStart": "Začína protokolovanie balíkov do systému súborov.", "repeater_cliHelpLogStop": "Zastaví protokolovanie paketov do systémového súboru.", "repeater_cliHelpLogErase": "Odstráni záznamy z balíkov z systému súborov.", - "repeater_cliHelpNeighbors": "Zobrazuje zoznam iných repeaterových uzlov zasielaných cez zero-hop reklamy. Každý riadok je id-prefix-hex:timestamp:snr-times-4", + "repeater_cliHelpNeighbors": "Zobrazuje zoznam iných repeaterových uzlov zasielaných cez zero-hop inzeráty. Každý riadok je id-prefix-hex:timestamp:snr-times-4", "repeater_cliHelpNeighborRemove": "Odstráni prvú zhodujúcu položku (podľa prefixu pubkey (hex)) z zoznamu susedov.", - "repeater_cliHelpRegion": "(len sériál) Zobrazuje všetky definované regióny a aktuálne povolenia pre povodňové situácie.", + "repeater_cliHelpRegion": "(len sériál) Zobrazuje všetky definované regióny a aktuálne povolenia pre flood.", "repeater_cliHelpRegionLoad": "Poznámka: toto je špeciálna multi-príkázová inštancia. Každé nasledujúce príkaza je názov oblasti (zapustený s medzerami na indikáciu hierarchického pomeru, s minimálne jednou medzerou). Ukončené odeslaním prázdnej platnej linky/príkazu.", "repeater_cliHelpRegionGet": "Hľadá región s daným príponou názvu (alebo \"\\\" pre globálny rozsah). Odpovedá \"-> región-název (rodič-název) 'F'\"", "repeater_cliHelpRegionPut": "Pridá alebo aktualizuje definíciu regiónu s daným menom.", @@ -1259,8 +1325,8 @@ "repeater_cliHelpGpsOnOff": "Prepínač stavu GPS napájania.", "repeater_cliHelpGpsSync": "Synchronizuje čas uzla s GPS hodinami.", "repeater_cliHelpGpsSetLoc": "Nastaví polohu uzla na GPS súradnice a uloží preferencie.", - "repeater_cliHelpGpsAdvert": "Poskytuje konfiguráciu reklamy pre uzol:\n- žiadna: nezahrňte polohu do reklám\n- zdieľať: zdieľajte GPS polohu (z SensorManager)\n- nastavenia: zobrazujte polohu uloženú v nastaveniach", - "repeater_cliHelpGpsAdvertSet": "Nastavuje konfiguráciu reklamy na zadané miesto.", + "repeater_cliHelpGpsAdvert": "Poskytuje konfiguráciu inzerátu pre uzol:\n- žiadna: nezahrňte polohu do inzerátov\n- zdieľať: zdieľajte GPS polohu (z SensorManager)\n- nastavenia: zobrazujte polohu uloženú v nastaveniach", + "repeater_cliHelpGpsAdvertSet": "Nastavuje konfiguráciu inzerátu na zadané miesto.", "repeater_commandsListTitle": "Zoznam príkazov", "repeater_commandsListNote": "Poznámka: pre rôzne príkazy \"set ...\" existuje aj príkaz \"get ...\".", "repeater_general": "Obecné", @@ -1417,7 +1483,7 @@ } }, "channelPath_unknownPath": "Neznáme", - "channelPath_floodPath": "Povodňová", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Priamo", "channelPath_observedZeroOf": "0 z {total} skokov", "@channelPath_observedZeroOf": { @@ -1690,8 +1756,8 @@ "appSettings_languageUk": "Ukrajinská", "contacts_contactImportFailed": "Kontakt sa nepodarilo importovať.", "contacts_zeroHopAdvert": "Inzerát Zero Hop", - "contacts_floodAdvert": "Inzerát povodní", - "contacts_copyAdvertToClipboard": "Kopírovať reklamu do schránky", + "contacts_floodAdvert": "Flood inzerát", + "contacts_copyAdvertToClipboard": "Kopírovať inzerát do schránky", "contacts_invalidAdvertFormat": "Neplatné kontaktné údaje", "appSettings_languageRu": "Ruština", "appSettings_enableMessageTracing": "Povoliť sledovanie správ", @@ -1725,7 +1791,7 @@ "settings_gpxExportChat": "Lokácie sprievodcov", "settings_gpxExportShareText": "Mapové údaje exportované z meshcore-open", "settings_gpxExportShareSubject": "meshcore-open export dát GPX mapových údajov", - "pathTrace_someHopsNoLocation": "Jedna alebo viac chmeľov chýba lokalita!", + "pathTrace_someHopsNoLocation": "Jedna alebo viac skokov chýba lokalita!", "pathTrace_clearTooltip": "Zmazať cestu", "map_tapToAdd": "Kliknite na uzly, aby ste ich pridali k ceste.", "map_removeLast": "Odstrániť posledný", @@ -2202,7 +2268,7 @@ "repeater_sensors": "Senzory", "repeater_cliHelpPowerOff": "Vypína zariadenie. (neočakáva sa žiadna odpoveď)", "repeater_cliHelpClkReboot": "Resetuje hodiny na známu epochu a reštartuje zariadenie.", - "repeater_cliHelpAdvertZeroHop": "Rozosiela reklamu, ktorá sa prenáša len medzi susednými zariadeniami (bez prenosu cez iné siete).", + "repeater_cliHelpAdvertZeroHop": "Rozosiela inzerát, ktorý sa prenáša len medzi susednými zariadeniami (bez prenosu cez iné siete).", "repeater_cliHelpStartOta": "Spustí aktualizáciu firmvéru prostredníctvom diaľkového prenosu na podporovaných doskách.", "repeater_cliHelpTime": "Nastavuje časovník zariadenia na zadané sekundy od Unix epochy. Časovník sa nedá otáčať dozadu.", "repeater_cliHelpBoard": "Zobrazuje informácie o výrobcom dosky / identifikátor hardvéru.", @@ -2213,7 +2279,7 @@ "repeater_cliHelpSetDutyCycle": "Nastavuje maximálnu povolenú frekvenciu prenosu ako percento (1-100). Internálne upravuje faktor času prenosu.", "repeater_cliHelpSetPrvKey": "(Používa sa len v sériovej verzii) Nahradí privátny kľúč, ktorý identifikuje zariadenie. Po aplikácii je potrebné zariadenie reštartovať. Generuje nový verejný kľúč.", "repeater_cliHelpSetRadioRxGain": "(iba pre SX126x) Zapína zvýšený zisk prijímania pre zlepšenie citlivosti pri vyššom príkonu.", - "repeater_cliHelpSetOwnerInfo": "Definuje reťazec s informáciami o kontaktnom osobě, ktorý je zahrnutý v reklamách. Používajte '|' pre nové riadky.", + "repeater_cliHelpSetOwnerInfo": "Definuje reťazec s informáciami o kontaktnom osobě, ktorý je zahrnutý v inzerátoch. Používajte '|' pre nové riadky.", "repeater_cliHelpSetPathHashMode": "Nastavuje režim hashovania cesty. 0 = starý režim, 1 = štandardný režim, 2 = striktný režim. Ovplyvňuje, ako sa prekladajú trasy.", "repeater_cliHelpSetLoopDetect": "Nastavuje citlivosť detekcie slučky routovania: vypnutá, minimálna, stredná alebo prísna.", "repeater_cliHelpSetFreq": "(Používa sa len v sériovej verzii) Rýchlo nastavuje len frekvenciu. Je potrebné reštartovať. Pre úplné nastavenie rádia preferujte funkciu \"nastavenie rádia\".", @@ -2233,15 +2299,15 @@ "repeater_cliHelpGetAgcResetInterval": "Zobrazuje interval reštartovania AGC v sekundách.", "repeater_cliHelpGetMultiAcks": "Ukazuje, či je režim dvojité potvrdenie zapnutý (1) alebo vypnutý (0).", "repeater_cliHelpGetAllowReadOnly": "Ukazuje, či je povolená len čítacia funkcia pre hostí.", - "repeater_cliHelpGetAdvertInterval": "Zobrazuje čas trvania miestnej reklamnej pauzy v minútach.", - "repeater_cliHelpGetFloodAdvertInterval": "Zobrazuje časový interval reklamy počas záplavy v hodinách.", + "repeater_cliHelpGetAdvertInterval": "Zobrazuje interval miestneho inzerátu v minútach.", + "repeater_cliHelpGetFloodAdvertInterval": "Zobrazuje časový interval flood inzerátu v hodinách.", "repeater_cliHelpGetGuestPassword": "Zobrazuje nastavené heslo pre hosta.", "repeater_cliHelpGetLat": "Zobrazuje nastavenú šírku.", "repeater_cliHelpGetLon": "Zobrazuje nastavenú dĺžku.", "repeater_cliHelpGetRxDelay": "Zobrazuje základnú hodnotu rxdelay.", - "repeater_cliHelpGetTxDelay": "Ukazuje faktor zpoždenia pre režim povodňovej komunikácie.", + "repeater_cliHelpGetTxDelay": "Ukazuje faktor zpoždenia pre režim flood.", "repeater_cliHelpGetDirectTxDelay": "Zobrazuje faktor zloženia pri priamej modulácii.", - "repeater_cliHelpGetFloodMax": "Zobrazuje maximálny počet opakovaní povodňového stavu.", + "repeater_cliHelpGetFloodMax": "Zobrazuje maximálny počet skokov flood.", "repeater_cliHelpGetOwnerInfo": "Zobrazuje reťazec s kontaktnými údajmi vlastníka.", "repeater_cliHelpGetPathHashMode": "Zobrazuje režim hashovania cesty (0/1/2).", "repeater_cliHelpGetLoopDetect": "Ukazuje citlivosť na detekciu slučiek.", @@ -2263,8 +2329,8 @@ "repeater_cliHelpSensorList": "Zobrazuje všetky nastavenia pre špecifické senzory, zoradené podľa voliteľného indexu začiatku.", "repeater_cliHelpRegionDefault": "Zobrazuje aktuálnu rozsiahku, ktorá je nastavená ako výchozí.", "repeater_cliHelpRegionDefaultSet": "Nastavuje výchoce rozsiahku regiónu. Použite \"\", aby ju vymazal.", - "repeater_cliHelpRegionListAllowed": "Zoznam oblastí, ktoré umožňujú premávku počas povodní.", - "repeater_cliHelpRegionListDenied": "Zoznam oblastí, ktoré zakazujú premávku v dôsledku povodní.", + "repeater_cliHelpRegionListAllowed": "Zoznam oblastí, ktoré umožňujú premávku flood.", + "repeater_cliHelpRegionListDenied": "Zoznam oblastí, ktoré zakazujú premávku flood.", "repeater_cliHelpStatsPackets": "(Len pre sériové záznamy) Zobrazuje štatistiky na úrovni paketov.", "repeater_cliHelpStatsRadio": "(Len pre sériu) Zobrazuje údaje o rádiových staniciach.", "repeater_cliHelpStatsCore": "(Len pre sériové modely) Zobrazuje základné štatistiky firmvéru.", @@ -2403,7 +2469,7 @@ "contacts_searchClose": "Zavrieť vyhľadávanie", "routing_title": "Navigácia", "routing_modeAuto": "Auto", - "routing_modeFlood": "Povodňová vlna", + "routing_modeFlood": "Flood", "routing_modeManual": "Ručná príručka", "routing_modeAutoHint": "Automaticky vyberá najznámejší trasa, a ak žiadna nie je známa, použije náhodnú trasu.", "routing_modeFloodHint": "Prenos prostredníctvom všetkých opakovačov. Najspoľahlivejší spôsob, ale vyžaduje viac času vysielania.", @@ -2421,14 +2487,14 @@ "routing_qualityGood": "Úspešný prvý krok", "routing_qualityFair": "Prvá, spravodlivá fáza", "routing_qualityWorked": "Dosiahnutý úspech", - "routing_qualityFlood": "Zistil som to z informácií, ktoré som získal v dôsledku povodňovej situácie.", + "routing_qualityFlood": "Zistil som to z informácií, ktoré som získal cez flood.", "routing_qualityUntested": "Neotestované", "routing_neverWorked": "nikedy nebolo potvrdené", - "routing_floodDelivery": "Doručenie v prípade povodní", + "routing_floodDelivery": "Doručenie cez flood", "pathEditor_title": "Vytvorenie cesty", - "pathEditor_hopCounter": "{count} z 64 chmelových zŕš", - "pathEditor_noHops": "Zatiaľ žiadne chmel. Kliknite na opakované, aby ste ich pridali postupne, alebo uložte bez chmelu, aby ste ho mohli poslať priamo.", - "pathEditor_addHops": "Pridávajte chmel podľa zadaného poriadku.", + "pathEditor_hopCounter": "{count} z 64 skokov", + "pathEditor_noHops": "Zatiaľ žiadne skoky. Kliknite na opakovače nižšie, aby ste ich pridali postupne, alebo uložte bez skokov, aby ste správu mohli poslať priamo.", + "pathEditor_addHops": "Pridávajte skoky podľa zadaného poriadku.", "pathEditor_searchRepeaters": "Hľadať opakované", "pathEditor_advancedHex": "Pokročilé: pôvodná hexová cesta", "pathEditor_hexLabel": "Prefiksy pre hexadecimálne čísla", @@ -2438,7 +2504,7 @@ "routing_deliveryCounts": "{successes} delivered, {failures} failed", "pathEditor_tooManyHops": "Maximálne 64 krokov", "pathEditor_usePath": "Použite túto cestu", - "pathEditor_removeHop": "Odstráňte chmel", + "pathEditor_removeHop": "Odstráňte skok", "pathEditor_unknownHop": "Neznáme zariadenie na opakované vysielanie", "map_zoomIn": "Zväčšiť", "map_zoomOut": "Zmenť zamer zblízka", @@ -2540,5 +2606,261 @@ "pathMap_noLocation": "Bez polohy", "pathMap_followPacket": "Uzamknúť pohľad na paket", "pathMap_unfollowPacket": "Odomknúť pohľad od paketu", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regiony", + "settings_regionSettingsSubtitle": "Zohľať uložené regiony", + "settings_regionManagement_screenTitle": "Regiónne vedenie", + "settings_regionNameHint": "Vstuptejte název regionu", + "settings_regionAddRegion": "Dodajte region", + "settings_regionFetchRegions": "Odberanie regionov z repeaterov", + "settings_regionFetchRegionsFail": "Nebylo našli žiadné regiony", + "settings_regionFetchRegionsAlreadyExists": "Tento oblast je už dodán", + "settings_regionName": "Regionné název", + "settings_regionDeleted": "Regionu zníteno", + "settings_deleteRegion": "Vyniknúcia regionu", + "settings_deleteRegionConfirm": "Odstraniť {region} z listy regionov?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byt", + "repeater_pathHashModeOption1": "1 - 2 bity", + "repeater_pathHashModeOption2": "2 - 3 bity", + "repeater_pathHashModeOption3": "3 - 4 bity", + "appSettings_batteryLipoHv": "LiPo HV (3.0-4.35V)", + "channels_regionSetTo": "Region: {region}", + "channels_regionNotSet": "Region: žiadné", + "channels_regionSelect_Title": "Vyberte region", + "channels_clearRegion": "Jasný údajný oblasť", + "chat_sendImageLora": "Odoslať obrázok cez MeshCore", + "chat_imagePickFailed": "Nesmiela jsem otvoriť tento obrázok", + "chat_receivedGif": "Odeslaný GIF", + "repeater_keySettings": "Zmena identititačných klíčov", + "repeater_keySettingsSubtitle": "Zmena prehľadného/osobného klíčového zbraň", + "repeater_prvKey": "Prívatná klíč", + "repeater_prvKeyHelper": "Nová prívna klíčová číslo pre repeater, 128-znáčlový šestnáctorýč.", + "repeater_generatePrvKey": "Vytvorenie príma kľúčového paru", + "repeater_stopGeneratingPrvKey": "Prerušenie hľadania klíčového paru", + "repeater_pubKey": "Public key", + "repeater_pubKeyHelper": "Táto je veľká klíč, ktorý sa vztahuje s generovaným manéčným klíčom. Nemožné je to ustanovit priateľne.", + "repeater_pubKeyPrefix": "Požadovaný prefiks", + "repeater_pubKeyPrefixHelper": "Zahľadnite sa veľkú publicenu klíču, ktorá začíná tými šestícih štiastkami. Očekivané potrebné pokusy: {tries}.", + "imageMessages_enableTitle": "Zabezpečte zobrazi", + "imageMessages_enableSubtitle": "Odeslanie obrazov pre mšťanie. Potrebujete jednorazové stáhnutie modelu obrazov.", + "imageMessages_modelSectionTitle": "Model v kínajme", + "imageMessages_downloadModel": "Stáhnie", + "imageMessages_cancelDownload": "Zastavenie", + "imageMessages_removeModel": "Vyhniť model", + "imageMessages_modelReady": "Čiačný", + "imageMessages_modelNotPublished": "Nesprávne vypisáné — tento prechovka nie môže jej stáhnuť.", + "imageMessages_downloadFailed": "Model s obrázkom nemôžno sťažovať.", + "imageMessages_autoProcessTitle": "Automaticky prepojiť slučaje.", + "imageMessages_autoProcessSubtitle": "Rekonstruujte každý obraz tak, ako pridá. Používajete okolo 2 GB pamäti pre drugú hodinu; odložte rekonstrukciu tým kliknutím.", + "imageSend_title": "Vyslat obraz", + "imageSend_cropNote": "Zmeneno na 512 × 512 · vzorýst nie byl zachovan", + "imageSend_originalSize": "Výborný text:\n\n\"Language is the road map of a culture. It tells us where to go as a society and helps us understand the world around us. Learning a new language opens up new perspectives and opportunities, allowing us to connect with people from different backgrounds and build bridges between cultures.\"\n\nSlovenská preklada:\n\n\"Jazyk je cesta pre zručnosti a odráža kultúru. Dá nám uvedomi, dokádať, kúdy sa pohladneme a pomáha našej společnosti poradiť sa v rôznych okolnosti a porozumieť o svetu kolem nás. Nauka nového jazyka otviera nové perspektívy a možnosti, čo pohybuje našu schopnosť sa spoluprávať s ľudmi z rôznych okolnosti a budovať mosty medzi kultúry.\"", + "imageSend_onAirSize": "V prúce", + "imageSend_quality": "Kvalita", + "imageSend_qualityStandard": "Stándard", + "imageSend_qualityHigh": "Vysoká", + "imageSend_packetsLabel": "Pakety", + "imageSend_airtimeLabel": "Čas na anteni", + "imageSend_sizeLabel": "Základ", + "imageSend_packetsCount": "{count} {count, plural, =1{paket} other{paketov}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Nastavenia radio nezná", + "imageSend_radioUnknownBody": "Zkonečte s určým prijemcem, aby sa mohlo výpočet času, ktorý je v prúbežu.", + "imageSend_longSendTitle": "Dlouhá transmisia", + "imageSend_longSendBody": "Tento dôvod udrží kanál priamo na {duration}.", + "imageSend_floodNote": "Flood routing: každý repeater v rozsahu zrňa každý paket, takže kanál zostá zajetší dlouše, než tu.", + "imageSend_parityTitle": "Poučný paket pre očudenie", + "imageSend_paritySubtitle": "Jedný dodatný paket. Skúsené súhlasy nie sa uznávaú, takže to umožňuje prechovávaču opraviť obraz, pokiaľ sa jedný paket niebyl ztrácený.", + "imageSend_send": "Odeslať", + "imageSend_cancel": "Zastavenie", + "imageSend_encodeFailed": "Tento obráz nie byla byla schována.", + "imageSend_codecDownloading": "Model prehľadovania prebeža stále stále stále prechádza.", + "imageSend_codecUnavailable": "Zobrazenie nie je dostupný na tomto zariadení.", + "imageSend_codecDisabled": "Zobrazy s prešteľkami sú v nastavení vypnené.", + "imageSend_deviceUnsupported": "Tento radiok nie môže odeslať obrazové pakety. Podeďte správne určité zařízení s oprogramovaním spolupráce 13 alebo novším.", + "imageSend_directMessagesUnsupported": "Obrazy sa prechádzajú jako skupinové údaje, preto sa ich môžu odeslať len na kanál — nie v príbeh sa.", + "imageSend_tooLarge": "Tento obraz byl skodyrovany do viac paketov, ako umožňuje si sítka format.", + "imageSend_sentConfirmation": "Obrázok odoslaný ako {count} {count, plural, =1{paket} other{paketov}}.", + "imageSend_sendFailed": "Obraz nemôžlo odeslať: {error}", + "imageSend_sendingProgress": "Vysyťanie obrazu — pakét {sent} z {total}", + "receivedImage_senderPrefix": "Vęzlo {prefix}", + "receivedImage_incoming": "Otrzymané {received} z {total} pakotí", + "receivedImage_queued": "Čekanie na dekódovanie", + "receivedImage_tapToDecode": "Kliknite, aby dekódovať", + "receivedImage_decoding": "Rekonstrukcia… o čoľve 1 s", + "receivedImage_incomplete": "Obraz nieješťajný — {received} z {total} paciek príšlo", + "receivedImage_corrupt": "Obraz nemôžu byť prepojený", + "receivedImage_decoderMissing": "Otrzymaná slúba — dekódovanie slúby je vypadejce", + "receivedImage_evicted": "Obraz nemá uložený", + "receivedImage_retry": "Zkôr to opítajte", + "receivedImage_decodeAgain": "Zdeľte sa znovu", + "receivedImage_openSettings": "Založte", + "receivedImage_tapToProcess": "Ukliknite, aby sa príjomili", + "receivedImage_awaiting": "{bytes} bajtov · {packets} {packets, plural, =1{paket} other{paketov}}", + "imageSend_secondsValue": "{seconds} s", + "imageSend_minutesSecondsValue": "{minutes} min {seconds} s", + "channels_noFreeSlots": "Všetky miesta pre kanály sú obsadené", + "chat_longMessageRetryNote": "Nad 158 bajtov: odoslané najviac {count}-krát", + "reaction_report": "Emoji reakcie", + "repeater_bridgeNote": "Dostupné len vo firmvéri zostavenom s mostom (RS232 alebo ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Zobrazuje maximálny počet skokov pre flood inzeráty.", + "repeater_cliHelpGetFloodMaxUnscoped": "Zobrazuje maximálny počet skokov pre flood pakety bez priradeného regiónu.", + "repeater_cliHelpGetRadioFemRxGain": "Zobrazuje, či je zapnuté RX zosilnenie LoRa front-end modulu.", + "repeater_cliHelpGetRadioFemTxGain": "Zobrazuje, či je zapnuté TX zosilnenie LoRa front-end modulu.", + "repeater_cliHelpRegionDef": "Definuje reťazec regiónov v jednom príkaze: každý názov sa pridá pod predchádzajúci; \"name,parent\" pridá názov a potom pokračuje pod zadaným nadradeným regiónom. Odpovie zoznamom regiónov.", + "repeater_cliHelpSetFloodMaxAdvert": "Nastavuje maximálny počet skokov pri preposielaní flood inzerátov (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Nastavuje maximálny počet skokov pri preposielaní flood paketov bez priradeného regiónu (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Prepína RX zosilnenie (LNA) LoRa front-end modulu. Dosky bez neho odpovedia \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Prepína TX zosilnenie (PA) LoRa front-end modulu. Dosky bez neho odpovedia \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Režim načítania regiónov: pošlite po jednom názve regiónu na riadok, odsadenom medzerami pod jeho nadradeným regiónom (pridaním F za názov povolíte flood). Riadky nedostanú odpoveď. Prázdnym riadkom ukončite a potom príkazom \"region save\" výsledok uložte.", + "repeater_cliRegionLoadEnd": "(koniec načítania regiónov)", + "repeater_cliRegionLoadHint": "Riadok regiónu, alebo prázdny na ukončenie", + "repeater_frequencyInvalid": "Neplatná frekvencia (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Chyby príjmu", + "repeater_txPowerRangeHelper": "-9 až 30 dBm", + "room_postsPushed": "Odoslané príspevky", + "room_postsStored": "Príspevky", + "settings_publicKeyCopied": "Verejný kľúč skopírovaný", + "settings_radioSettingsNotApplied": "Rádio tieto nastavenia neuplatnilo", + "urlImage_enable": "Povoliť obrázky z URL", + "urlImage_possible": "Možný obrázok z URL; povoľte ho v Nastaveniach.", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index e423ab67..c22326e3 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -100,6 +100,8 @@ "settings_locationInvalid": "Neveljavna zemeljska širina ali dolžina.", "settings_latitude": "Širina", "settings_longitude": "Dolžina", + "settings_autoZeroHopAdvertOnGpsUpdate": "Samodejni zero-hop oglas ob posodobitvi GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Ko se GPS lokacija spremeni, pošlji zero-hop oglas (zahteva lokacijo v oglasu).", "settings_privacyMode": "Zasebnost", "settings_privacyModeSubtitle": "Skrita imena/lokacije v oglasih", "settings_privacyModeToggle": "Omogoči način zasebnosti, da skrijemo tvoje ime in lokacijo v oglasih.", @@ -240,6 +242,19 @@ "appSettings_last6Hours": "Zadnjih 6 ur", "appSettings_last24Hours": "Zadnjih 24 ur", "appSettings_lastWeek": "Prejšnji teden", + "appSettings_rasterTileSource": "Vir rastrskih ploščic", + "appSettings_stadiaEndpoint": "Končna točka Stadia", + "appSettings_stadiaApiKey": "Ključ API Stadia", + "appSettings_stadiaApiKeyRequired": "Obvezno za uporabo Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Nastavljeno: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Vnesite svoj ključ API za Stadia Maps. Aplikacija ga uporablja za zahteve rastrskih ploščic.", "appSettings_offlineMapCache": "Shramba zemljevidov brez povezave", "appSettings_noAreaSelected": "Območje ni izbrano", "appSettings_areaSelectedZoom": "Izbrano območje (povečava {minZoom}-{maxZoom})", @@ -470,6 +485,7 @@ } } }, + "chat_selectSendAction": "Izberite dejanje pošiljanja", "chat_sendGif": "Pošlji GIF", "chat_reply": "Odgovori", "chat_addReaction": "Dodaj reakcijo", @@ -562,7 +578,7 @@ "chat_pathManagement": "Upravljanje poti", "chat_routingMode": "Navodilo za usmerjevalni način", "chat_autoUseSavedPath": "Avto (uporabi shranjeno pot)", - "chat_forceFloodMode": "Nasilje obvezati v način", + "chat_forceFloodMode": "Vsili flood način", "chat_recentAckPaths": "Nedavni poti ACK (tap za uporabo):", "chat_pathHistoryFull": "Zapiske o poti so popolni. Izbriši vnose, da dodaš nove.", "chat_hopSingular": "skok", @@ -606,7 +622,7 @@ "chat_path": "Pot", "chat_publicKey": "Ključ javnega tipa", "chat_compressOutgoingMessages": "Stisnite izhodne sporočila", - "chat_floodForced": "Porolni (nasilje).", + "chat_floodForced": "Flood (vsiljeno)", "chat_directForced": "Nezglašen (nasilje)", "chat_hopsForced": "{count} skoki (nasilje)", "@chat_hopsForced": { @@ -616,7 +632,7 @@ } } }, - "chat_floodAuto": "Preplavljenje (avtomatizirano)", + "chat_floodAuto": "Flood (samodejno)", "chat_direct": "Neposredni", "chat_poiShared": "Deljeno točke MN", "chat_unread": "Nerešeno: {count}", @@ -769,6 +785,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -834,7 +900,7 @@ "login_routing": "Usmerjanje", "login_routingMode": "Navodilo za usmerjevalni način", "login_autoUseSavedPath": "Avto (uporabi shranjeno pot)", - "login_forceFloodMode": "Nasilje obvezati v način", + "login_forceFloodMode": "Vsili flood način", "login_managePaths": "Upravljajte Potniške Proti", "login_login": "Prijava", "login_attempt": "Poskušajo {current}/{max}", @@ -907,7 +973,7 @@ "repeater_statusTitle": "Status ponovitelja", "repeater_routingMode": "Navodilo za usmerjevalni način", "repeater_autoUseSavedPath": "Avto (uporabi shranjeno pot)", - "repeater_forceFloodMode": "Nasilje obvezati v način", + "repeater_forceFloodMode": "Vsili flood način", "repeater_pathManagement": "Upravljanje poti", "repeater_refresh": "Ponovno obnavljati", "repeater_statusRequestTimeout": "Zahtev statusa je iztekla.", @@ -952,7 +1018,7 @@ } } }, - "repeater_packetTxTotal": "Skupno: {total}, Poplava: {flood}, Neposredno: {direct}", + "repeater_packetTxTotal": "Skupno: {total}, Flood: {flood}, Neposredno: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -966,7 +1032,7 @@ } } }, - "repeater_packetRxTotal": "Skupno: {total}, Poplava: {flood}, Neposredno: {direct}", + "repeater_packetRxTotal": "Skupno: {total}, Flood: {flood}, Neposredno: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -980,7 +1046,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Prah: {flood}, Neposredni: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Neposredni: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -1037,7 +1103,7 @@ } } }, - "repeater_floodAdvertInterval": "Razpon Obvestil o Poplavah", + "repeater_floodAdvertInterval": "Razpon Flood Oglasov", "repeater_floodAdvertIntervalHours": "{hours} ur", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1107,9 +1173,9 @@ "repeater_advancedSettings": "Napredno", "repeater_advancedSettingsSubtitle": "Gumbi za nastavljanje za izkušene uporabnike", "repeater_pathHashMode": "Način ustvarjanja hash-a poti", - "repeater_pathHashModeHelper": "Biti, ki so bila uporabljena za kodiranje ID-ja tega releja v oznakah za zaznavanje pot/kroga, imajo naslednje velikosti: 0=1 bit (256 ID-jev, do 64 skokov), 1=2 biti (65.000 ID-jev, do 32 skokov), 2=3 biti (16 milijonov ID-jev, do 21 skokov). V različicah 1.13 in starejših se ustvarjajo večbitne poti – vendar se to zgodi šele, ko je omrežje vklopljeno v različicah 1.14 in kasnejših.", - "repeater_txDelay": "Zatemnitevanje zaradi poplav v Texasu", - "repeater_txDelayHelper": "Uporaba intervalov za ponovno pošiljanje v primeru prometa zaradi poplav, kot pomnožnik časovne trajanje paketa (0-2, privzeto 0,5). Veje vrednost = manjše kolizije, vendar počasnejše dostavo.", + "repeater_pathHashModeHelper": "Bajti, uporabljeni za kodiranje ID-ja tega repetitorja v oznakah flood poti/zaznavanja zank. 0=1 bajt (256 ID-jev, do 64 skokov), 1=2 bajta (65.000 ID-jev, do 32 skokov), 2=3 bajti (16 milijonov ID-jev, do 21 skokov). Vdelana programska oprema pred v1.14 je vedno uporabljala 1-bajtne poti; v1.14 in novejše je mogoče nastaviti na 2- ali 3-bajtne poti.", + "repeater_txDelay": "Flood TX zakasnitev", + "repeater_txDelayHelper": "Uporaba intervalov za ponovno pošiljanje v primeru flood prometa, kot pomnožnik časovne trajanje paketa (0-2, privzeto 0,5). Veje vrednost = manjše kolizije, vendar počasnejše dostavo.", "repeater_directTxDelay": "Neposredni časovno odlašanje", "repeater_directTxDelayHelper": "Razdalja za ponovno pošiljanje za neposredno (neobvezen) promet, kot pomnožnik časovne trajanja paketa (0-2, privzeto 0,3).", "repeater_intThresh": "Meja, pri kateri nastane motnja", @@ -1117,8 +1183,8 @@ "repeater_agcResetInterval": "Interval ponovne kalibracije AGC", "repeater_agcResetIntervalHelper": "Kako pogosto je treba ponovno nastaviti samodejno regulacijo občutljivosti, da se vrnete v normalno stanje? Interval je nastavljen na nekaj sekund, natančno na 4. 0 izklopi periodično ponovno nastavljanje.", "repeater_actionsTitle": "Dejanja", - "repeater_sendAdvert": "Pošlji oglas o poplavah", - "repeater_sendAdvertSubtitle": "Razpustite oglas o poplavah preko omrežja.", + "repeater_sendAdvert": "Pošlji flood oglas", + "repeater_sendAdvertSubtitle": "Razpošlji flood oglas preko omrežja.", "repeater_sendAdvertZeroHop": "Pošlji oglas, ki ne potrebuje posrednika.", "repeater_sendAdvertZeroHopSubtitle": "Premejte oglas, ki uporablja eno povezavo (brez posrednikov).", "repeater_clockSync": "Sinerizirajte uro zdaj", @@ -1217,19 +1283,19 @@ "repeater_cliHelpSetTx": "Nastavi moč LoRa oddajanja v dBm. (za ponovni zagon za uporabo)", "repeater_cliHelpSetRepeat": "Omogoči ali onemogoči vlogo ponovitelja za tono.", "repeater_cliHelpSetAllowReadOnly": "(Osebni strežnik) Če je 'vklopljeno', potem bo dovoljeno prijavo z praznim geslom, vendar ne bo mogoče objaviti v sobo. (samo branje).", - "repeater_cliHelpSetFloodMax": "Nastavi največjo število skokov za vstopne poplave (če je >= maks, paket ni usmerjen)", + "repeater_cliHelpSetFloodMax": "Nastavi največje število skokov za vhodni flood paket (če je >= maks, paket ni posredovan)", "repeater_cliHelpSetIntThresh": "Nastavi Prag Interferencij (v dB). Privzeto je 14. Nastavi na 0 za onemogočitev zaznavanja interferenc kanalov.", "repeater_cliHelpSetAgcResetInterval": "Nastavi časovno razdaljo za ponovni zagon nadzornika Avtomatske uteži. Nastavi na 0 za onemogočanje.", "repeater_cliHelpSetMultiAcks": "Omogoči ali onemogoči funkcijo \"dvojakih potrdil\".", "repeater_cliHelpSetAdvertInterval": "Nastavi časovno obmesto v minutah za pošiljanje lokalnega (brezposrednega) napovednega paketa. Nastavi na 0 za onemogočiti.", - "repeater_cliHelpSetFloodAdvertInterval": "Nastavi časovno obmesto v urah za pošiljanje plovilnega oglasnega paketa. Nastavi na 0 za onemogočanje.", + "repeater_cliHelpSetFloodAdvertInterval": "Nastavi časovno obmesto v urah za pošiljanje flood oglasnega paketa. Nastavi na 0 za onemogočanje.", "repeater_cliHelpSetGuestPassword": "Nastavi/posodobi geslo gosta. (za ponovitve lahko gostov prijavi pošiljajo zahtevo \"Get Stats\")", "repeater_cliHelpSetName": "Nastavi ime oglasnika.", "repeater_cliHelpSetLat": "Nastavi zemljepisno širino oglaševalskega zemljevida (desetdeljne).", "repeater_cliHelpSetLon": "Nastavi zemljevidno širino oglasnika. (desetdelne stopnje)", "repeater_cliHelpSetRadio": "Nastavi popolnoma nove radijske parametre in jih shranjuje v nastavitve. Za uporabo je potrebna \"restart\" ukaz.", "repeater_cliHelpSetRxDelay": "Nastavitve (eksperimentalne) osnova (mora biti > 1 za učinkovanje) za uporabo rahle zakasnitve prejetih paketov, glede na moč signala/rezultat. Nastavite na 0 za onemogočanje.", - "repeater_cliHelpSetTxDelay": "Nastavi faktor, ki se množi s časom delovanja za paket v načinu poplavnega režima in z randomiziranim sistemom slotov, da odvrne njegovo posredovanje. (da se zmanjša verjetnost kolizij)", + "repeater_cliHelpSetTxDelay": "Nastavi faktor, ki se množi s časom delovanja za paket v flood načinu in z randomiziranim sistemom slotov, da odvrne njegovo posredovanje. (da se zmanjša verjetnost kolizij)", "repeater_cliHelpSetDirectTxDelay": "Ima podobno vrednost kot txdelay, vendar jo lahko uporabite za dodajanje naknadnega zamika pri posredovanju paketov v režimu neposredne prevodi.", "repeater_cliHelpSetBridgeEnabled": "Omogoči/Preklopi most.", "repeater_cliHelpSetBridgeDelay": "Nastavi zamik pred ponovnim poslanjem paketov.", @@ -1245,7 +1311,7 @@ "repeater_cliHelpLogErase": "Izbriše pakete zapisov iz datotek sistema.", "repeater_cliHelpNeighbors": "Prikaže seznam drugih ponovnih knopov, do katerih je prišlo preko brezposrednih oglasov. Vsaka vrstica je id-prefix-hex:timestamp:snr-times-4", "repeater_cliHelpNeighborRemove": "Izbriše prvo ustreznu postavko (po predpomnilku pubkey (heks),) iz seznama sosedov.", - "repeater_cliHelpRegion": "(Serija samo) Navaja vse definirane regije in trenutne poplave dovolilnosti.", + "repeater_cliHelpRegion": "(Serija samo) Navaja vse definirane regije in trenutna dovoljenja za flood.", "repeater_cliHelpRegionLoad": "Opomba: to je posebna več ukazna pozivna operacija. Vsak naslednji ukaz je ime regije (z lezijami za prikaz hierarhije, z enim ustvarjenim razmislom). Zaključena s pošiljanjem praznega reda/ukaza.", "repeater_cliHelpRegionGet": "Išče regijo s podanimi imenimi prefiksom (ali \"\\\" za globalni obseg). Odgovori se s \"-> regija-ime (rodič-ime) 'F'\"", "repeater_cliHelpRegionPut": "Dodaja ali posodobi regijsko definicijo s podanim imenom.", @@ -1417,7 +1483,7 @@ } }, "channelPath_unknownPath": "Neznano", - "channelPath_floodPath": "Prebivalstvo", + "channelPath_floodPath": "Flood", "channelPath_directPath": "Neposredni", "channelPath_observedZeroOf": "0 iz {total} skokov", "@channelPath_observedZeroOf": { @@ -1489,7 +1555,7 @@ } } }, - "repeater_neighborsSubtitle": "Pogledati nič sosednjih hopjev.", + "repeater_neighborsSubtitle": "Pogledati nič sosednjih skokov.", "repeater_neighbors": "Sosedi", "neighbors_receivedData": "Prejeto podatke o sosedih", "neighbors_requestTimedOut": "Sosedi zahtevajo izklop po dogovoru.", @@ -1692,8 +1758,8 @@ "appSettings_enableMessageTracingSubtitle": "Prikaži podrobne metapodatke o usmerjanju in časovnem usklajevanju sporočil", "contacts_contactImported": "Kontakt je bil uvožen.", "contacts_contactImportFailed": "Kontakt ni bil uspešno uvožen.", - "contacts_zeroHopAdvert": "Reklama brez posrednikov", - "contacts_floodAdvert": "Poplavna oglás", + "contacts_zeroHopAdvert": "Oglas brez posrednikov", + "contacts_floodAdvert": "Flood oglas", "contacts_invalidAdvertFormat": "Neveljavni kontaktne podatke", "contacts_clipboardEmpty": "Odložišče je prazno.", "contacts_copyAdvertToClipboard": "Kopiraj oglas v odložišče", @@ -1725,7 +1791,7 @@ "settings_gpxExportNoContacts": "Ni stikov za izvoz.", "settings_gpxExportNotAvailable": "Ni podprto na vašem napravi/operacijskem sistemu", "settings_gpxExportShareSubject": "meshcore-open izvoz podatkov GPX karte", - "pathTrace_someHopsNoLocation": "Ena ali več hmelju manjka lokacija!", + "pathTrace_someHopsNoLocation": "Enemu ali več skokom manjka lokacija!", "map_tapToAdd": "Pritisnite na vozlišča, da jih dodate poti.", "map_removeLast": "Odstrani Zadnji", "map_runTrace": "Zaženi sledenje poti", @@ -2232,15 +2298,15 @@ "repeater_cliHelpGetAgcResetInterval": "Prikazuje interval ponovne kalibracije AGC v sekundah.", "repeater_cliHelpGetMultiAcks": "Pokaže, ali je vklopljen način dvojnega potrdila (1) ali je izklopljen (0).", "repeater_cliHelpGetAllowReadOnly": "Pokaže, ali je omogočen le brani dostop za goste.", - "repeater_cliHelpGetAdvertInterval": "Prikazuje časovno obdobje lokalne reklame v minutah.", - "repeater_cliHelpGetFloodAdvertInterval": "Prikaže časovno obdobje, ko se prikazuje oglas o poplavah, v urah.", + "repeater_cliHelpGetAdvertInterval": "Prikazuje časovno obdobje lokalnega oglasa v minutah.", + "repeater_cliHelpGetFloodAdvertInterval": "Prikaže časovno obdobje flood oglasa, v urah.", "repeater_cliHelpGetGuestPassword": "Prikaže nastavljeno geslo za gostitelja.", "repeater_cliHelpGetLat": "Prikaže določeno zemljepisno širino.", "repeater_cliHelpGetLon": "Prikaže določeno merilo dolžine.", "repeater_cliHelpGetRxDelay": "Prikazuje osnovno vrednost RX odlašanja.", - "repeater_cliHelpGetTxDelay": "Prikazuje faktor zamude v načinu delovanja pri plavlju.", + "repeater_cliHelpGetTxDelay": "Prikazuje faktor zamude v flood načinu.", "repeater_cliHelpGetDirectTxDelay": "Prikazuje faktor odlašanja signala v režimu neposredne komunikacije.", - "repeater_cliHelpGetFloodMax": "Prikazuje največjo število, kolikokrat lahko voda doseže najvišjo višino.", + "repeater_cliHelpGetFloodMax": "Prikazuje največje število skokov za flood.", "repeater_cliHelpGetOwnerInfo": "Prikazuje niz z informacijami o lastniku.", "repeater_cliHelpGetPathHashMode": "Prikaže način delovanja z hashjem poti (0/1/2).", "repeater_cliHelpGetLoopDetect": "Prikazuje občutljivost na zaznavanje ciklov.", @@ -2262,8 +2328,8 @@ "repeater_cliHelpSensorList": "Navaja vse nastavitve za uporabniške senzorje, razvrščene po želeni začetni indeksu.", "repeater_cliHelpRegionDefault": "Prikaže trenutno privzeto območje.", "repeater_cliHelpRegionDefaultSet": "Določi privzeto območje. Za izbris uporabite \"\".", - "repeater_cliHelpRegionListAllowed": "Navaja regije, ki dovoljujejo promet v času poplav.", - "repeater_cliHelpRegionListDenied": "Navaja regije, ki preprečujejo promet zaradi poplav.", + "repeater_cliHelpRegionListAllowed": "Navaja regije, ki dovoljujejo flood promet.", + "repeater_cliHelpRegionListDenied": "Navaja regije, ki preprečujejo flood promet.", "repeater_cliHelpStatsPackets": "(Samo za serijske povezave) Prikazuje statistiko na nivoju paketov.", "repeater_cliHelpStatsRadio": "(Samo za serije) Prikazuje statistične podatke o radiju.", "repeater_cliHelpStatsCore": "(Samo za serijske naprave) Prikazuje osnovne statistične podatke.", @@ -2403,7 +2469,7 @@ "contacts_searchClose": "Izklopi iskanje", "routing_title": "Navigacija", "routing_modeAuto": "Avto", - "routing_modeFlood": "Poplavo", + "routing_modeFlood": "Flood", "routing_modeManual": "Navodilo", "routing_modeAutoHint": "Samodejno izbere najbolj poznano pot, in sicer, ko ni na voljo nobena.", "routing_modeFloodHint": "Prenosi preko vseh repetitorjev. Najzanesljivejši način, vendar zahteva več časa.", @@ -2421,15 +2487,15 @@ "routing_qualityGood": "Prva uspešna faza", "routing_qualityFair": "Prva, uspešna faza", "routing_qualityWorked": "Izpolnil", - "routing_qualityFlood": "Slišano preko poplave", + "routing_qualityFlood": "Slišano prek flooda", "routing_qualityUntested": "Ne preizkušen", "routing_lastWorked": "delal/a {when}", "routing_neverWorked": "nikoli ni bilo potrjeno", - "routing_floodDelivery": "Dostava zaradi poplave", + "routing_floodDelivery": "Dostava prek flooda", "pathEditor_title": "Izgradnja poti", - "pathEditor_hopCounter": "{count} od 64 različnih sort hropa", - "pathEditor_noHops": "Še niso dodani hmelji. Za dodajanje hmelja v vrstnem redu kliknite na povezavo spodaj, ali pa shranite brez dodanega hmelja, da ga lahko posredujete neposredno.", - "pathEditor_addHops": "Dodajte suho travo v skladu s postopkom.", + "pathEditor_hopCounter": "{count} od 64 skokov", + "pathEditor_noHops": "Še niso dodani skoki. Za dodajanje skokov v vrstnem redu kliknite na ponovitelje spodaj, ali pa shranite brez dodanih skokov, da ga lahko posredujete neposredno.", + "pathEditor_addHops": "Dodajte skoke v vrstnem redu.", "pathEditor_searchRepeaters": "Iskanje ponovitev", "pathEditor_advancedHex": "Napredno: surovi šestnajstni pot", "pathEditor_hexLabel": "Predfiks za heksadecimalno šifro", @@ -2437,7 +2503,7 @@ "pathEditor_invalidTokens": "Neveljaven: {tokens}", "pathEditor_tooManyHops": "Največ 64 hopov", "pathEditor_usePath": "Uporabite to poto", - "pathEditor_removeHop": "Odstranite hmelj", + "pathEditor_removeHop": "Odstranite skok", "pathEditor_unknownHop": "Neznani ponovitelj", "map_zoomIn": "Povečaj", "routing_deliveryCounts": "{successes} delivered, {failures} failed", @@ -2540,5 +2606,261 @@ "pathMap_noLocation": "Brez lokacije", "pathMap_followPacket": "Zakleni pogled na paket", "pathMap_unfollowPacket": "Odkleni pogled od paketa", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regioni", + "settings_regionSettingsSubtitle": "Upravljanje opisanih regionov", + "settings_regionManagement_screenTitle": "Regijonsko upravljanje", + "settings_regionNameHint": "Naslov občine", + "settings_regionAddRegion": "Dodaj region", + "settings_regionFetchRegions": "Pobražujte izvajne področja iz ponavljalnikov", + "settings_regionFetchRegionsFail": "Nižnih občin ni izkrali", + "settings_regionFetchRegionsAlreadyExists": "Taj oblasi je več pomanjkan.", + "settings_regionName": "Naziv Regiona", + "settings_regionDeleted": "Oblikačena regija", + "settings_deleteRegion": "Prihoda Region", + "settings_deleteRegionConfirm": "Ostani {region} iz listy regionov?", + "settings_infoHardware": "Hardver", + "settings_infoFirmware": "Pravilnik", + "repeater_pathHashModeOption0": "0 - 1 bajt", + "repeater_pathHashModeOption1": "1 - 2 bite", + "repeater_pathHashModeOption2": "2 - 3 bite", + "repeater_pathHashModeOption3": "3 - 4 bite", + "appSettings_batteryLipoHv": "LiPo HV (3,0–4,35 V)", + "channels_regionSetTo": "Osebno: {region}", + "channels_regionNotSet": "Region: brak", + "channels_regionSelect_Title": "Vablajte region", + "channels_clearRegion": "Jasna regija", + "chat_sendImageLora": "Pošlji sliko prek MeshCore", + "chat_imagePickFailed": "Nispeval sem tega ta slik", + "chat_receivedGif": "Otrvljen GIF", + "repeater_keySettings": "Zmeničke ključe identitete", + "repeater_keySettingsSubtitle": "Zamenjajte publican ali privatni ključni par", + "repeater_prvKey": "Privarna ključa", + "repeater_prvKeyHelper": "Nova privatna ključa za prekaznik, 128- znakovni šestnastik.", + "repeater_generatePrvKey": "Sporočna ključna para", + "repeater_stopGeneratingPrvKey": "Prekajanje odkrivanja ključne paro", + "repeater_pubKey": "Public key (publična ključa)", + "repeater_pubKeyHelper": "Taj je publicna ključ, ki pomeni pripovedno privatno ključ. Ne možeš to vrediti direktno.", + "repeater_pubKeyPrefix": "Poželana prefiks", + "repeater_pubKeyPrefixHelper": "Najdi publicen ključ, ki začne s tih hexnih čitov. Očekivani pokusi: {tries}.", + "imageMessages_enableTitle": "Pozivni izkričile slike", + "imageMessages_enableSubtitle": "Prešli vzorce pre mrežo. Potrebno je jednokratno stworiti model vzorca.", + "imageMessages_modelSectionTitle": "Obrazni model", + "imageMessages_downloadModel": "Storba", + "imageMessages_cancelDownload": "Odločite", + "imageMessages_removeModel": "Ubrani model", + "imageMessages_modelReady": "Gotov", + "imageMessages_modelNotPublished": "Jo še niso izdana — ta izdelka te ne može prebaviti.", + "imageMessages_downloadFailed": "Obrazni model ne može biti preuzet.", + "imageMessages_autoProcessTitle": "Avtomatizirane slike", + "imageMessages_autoProcessSubtitle": "Katero je oblikovanje svega oblikov, ko se pošteva. Za drugo okolo časa se koristi ok. 2 GB pamične prostore; odločite se za oblikovanje s tukom.", + "imageSend_title": "Sločaji slik", + "imageSend_cropNote": "Zadovoljno izmenjeno na 512 × 512 · vzorovni odnos ne ohranjen", + "imageSend_originalSize": "Original text:\n\nThe early bird catches the worm.\n\nTranslation:\n\nPojdi prvi, zlati v kroku.", + "imageSend_onAirSize": "Na vodi", + "imageSend_quality": "Kakovost", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Vysoko", + "imageSend_packetsLabel": "Pakete", + "imageSend_airtimeLabel": "Čas v eteru", + "imageSend_sizeLabel": "Napravo", + "imageSend_packetsCount": "{count} {count, plural, =1{paket} other{paketov}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Naslušniki radio neznane", + "imageSend_radioUnknownBody": "Poučajte se na stroj, da se lahko izračunuje čas v prikazu.", + "imageSend_longSendTitle": "Dluga preposlana", + "imageSend_longSendBody": "Ovo bo ohranilo kanal prihodno za obliko {duration}.", + "imageSend_floodNote": "Flood usmerjanje: vsak ponovitelj v dosegu znova odda vsak paket, zato je kanal zaseden dlje kot to.", + "imageSend_parityTitle": "Pobavni paket zdržbe", + "imageSend_paritySubtitle": "Jedna dodatna paczka. Grupni izjasi ne izvajajo potvarnosti, pa ta izdelka omogoča preuzimanju ponovno izgleda, če je zgubjen pojedni paket.", + "imageSend_send": "Posyłaj", + "imageSend_cancel": "Odločite", + "imageSend_encodeFailed": "Ovo slikovo ne more biti zakodirano.", + "imageSend_codecDownloading": "Obrazni model še pospeva preborjanje.", + "imageSend_codecUnavailable": "Poslanje slike nema na tem zelo naročnem naročnem.", + "imageSend_codecDisabled": "Obrazi s pomanjkanjem so v nastavnih.", + "imageSend_deviceUnsupported": "Taj radio ne može posredovati slike pakuete. Prepoštijo izbirni napravnik s kompanijskimi programi na čevem 13 ali novšejšim.", + "imageSend_directMessagesUnsupported": "Obrazy se pojavijo kot skupnih podatkov, pa lahko ih poslujejo samo na kanal — ne v prilogih.", + "imageSend_tooLarge": "Taj slik je zakodiran v viših pakotnih od športne formate, ki omogoča mrežni format.", + "imageSend_sentConfirmation": "Slika poslana kot {count} {count, plural, =1{paket} other{paketov}}.", + "imageSend_sendFailed": "Obraz ne može biti poslany: {error}", + "imageSend_sendingProgress": "Prekazivanje izkaza — paket {sent} od {total}", + "receivedImage_senderPrefix": "Vrtitev {prefix}", + "receivedImage_incoming": "Otrteno od {received} na {total} poslovanih potokov", + "receivedImage_queued": "Čekanje, da se dekodira", + "receivedImage_tapToDecode": "Kliknite, da razkrivete", + "receivedImage_decoding": "Ostvarjanje… o prihodnosti za okolo 1 s", + "receivedImage_incomplete": "Obraz nije kompletan — {received} od {total} poslaničev je prishodil", + "receivedImage_corrupt": "Obraz ne more lahko rekonstruirati", + "receivedImage_decoderMissing": "Otrgena slika — dekodirana slika je izključena", + "receivedImage_evicted": "Obraz ni več niso zakajiren", + "receivedImage_retry": "Pokušajte znova", + "receivedImage_decodeAgain": "Dekodiraj ponovno", + "receivedImage_openSettings": "Nastavite", + "receivedImage_tapToProcess": "Kliknij za obravnavanje", + "receivedImage_awaiting": "{bytes} bajtov · {packets} {packets, plural, =1{paket} other{paketov}}", + "imageSend_secondsValue": "{seconds} s", + "imageSend_minutesSecondsValue": "{minutes} m {seconds} s", + "channels_noFreeSlots": "Vsa mesta za kanale so zasedena", + "chat_longMessageRetryNote": "Nad 158 bajtov: poslano največ {count}-krat", + "reaction_report": "Emoji reakcije", + "repeater_bridgeNote": "Na voljo samo v vdelani programski opremi, zgrajeni z mostom (RS232 ali ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Prikaže največje število skokov za flood oglase.", + "repeater_cliHelpGetFloodMaxUnscoped": "Prikaže največje število skokov za flood pakete brez določenega regijskega obsega.", + "repeater_cliHelpGetRadioFemRxGain": "Prikaže, ali je RX ojačanje LoRa front-end modula vklopljeno.", + "repeater_cliHelpGetRadioFemTxGain": "Prikaže, ali je TX ojačanje LoRa front-end modula vklopljeno.", + "repeater_cliHelpRegionDef": "Definira verigo regij z enim ukazom: vsako ime se doda pod prejšnje; \"name,parent\" doda ime in nato nadaljuje pod navedeno nadrejeno regijo. Odgovori s seznamom regij.", + "repeater_cliHelpSetFloodMaxAdvert": "Nastavi največje število skokov za posredovanje flood oglasov (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Nastavi največje število skokov za posredovanje flood paketov brez določenega regijskega obsega (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Preklopi RX ojačanje (LNA) LoRa front-end modula. Plošče brez njega odgovorijo z \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Preklopi TX ojačanje (PA) LoRa front-end modula. Plošče brez njega odgovorijo z \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Način nalaganja regij: pošljite eno ime regije na vrstico, zamaknjeno s presledki pod nadrejeno regijo (dodajte F za imenom, da dovolite flood). Vrstice ne prejmejo odgovora. Pošljite prazno vrstico za konec, nato pa \"region save\", da shranite rezultat.", + "repeater_cliRegionLoadEnd": "(konec nalaganja regij)", + "repeater_cliRegionLoadHint": "Vrstica regije ali prazna vrstica za konec", + "repeater_frequencyInvalid": "Neveljavna frekvenca (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Napake sprejema", + "repeater_txPowerRangeHelper": "-9 do 30 dBm", + "room_postsPushed": "Poslane objave", + "room_postsStored": "Objave", + "settings_publicKeyCopied": "Javni ključ kopiran", + "settings_radioSettingsNotApplied": "Radio teh nastavitev ni uveljavil", + "urlImage_enable": "Omogoči slike iz URL", + "urlImage_possible": "Mogoča slika iz URL; omogočite jo v Nastavitvah.", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 5366d0e0..09b98b84 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -17,13 +17,13 @@ "common_unknownDevice": "Okänd enhet", "common_save": "Spara", "common_delete": "Radera", - "common_close": "Stänga", + "common_close": "Stäng", "common_edit": "Redigera", "common_add": "Lägg till", "common_settings": "Inställningar", "common_disconnect": "Koppla från", "common_connected": "Ansluten", - "common_disconnected": "Ansluten", + "common_disconnected": "Frånkopplad", "common_create": "Skapa", "common_continue": "Fortsätt", "common_share": "Dela", @@ -35,7 +35,7 @@ "common_disable": "Inaktivera", "common_autoRefresh": "Automatisk uppdatering", "common_interval": "Intervall", - "common_reboot": "Start om", + "common_reboot": "Starta om", "common_loading": "Laddar...", "common_notAvailable": "—", "common_voltageValue": "{volts} V", @@ -56,7 +56,7 @@ }, "scanner_title": "MeshCore – Öppen version", "scanner_scanning": "Söker efter enheter...", - "scanner_connecting": "Anslutning...", + "scanner_connecting": "Ansluter...", "scanner_disconnecting": "Anslutning bryts...", "scanner_notConnected": "Inte ansluten", "scanner_connectedTo": "Ansluten till {deviceName}", @@ -82,9 +82,9 @@ "device_quickSwitch": "Snabb växling", "device_meshcore": "MeshCore", "settings_title": "Inställningar", - "settings_deviceInfo": "Enhetens information", + "settings_deviceInfo": "Enhetsinformation", "settings_appSettings": "Appinställningar", - "settings_appSettingsSubtitle": "Meddelanden, notiser och kartinställningar", + "settings_appSettingsSubtitle": "Notifieringar, meddelanden och kartinställningar", "settings_nodeSettings": "Nodinställningar", "settings_nodeName": "Nodnamn", "settings_nodeNameNotSet": "Inte angivet", @@ -94,36 +94,38 @@ "settings_radioSettingsSubtitle": "Frekvens, effekt, spridningsfaktor", "settings_radioSettingsUpdated": "Radioinställningarna har uppdaterats", "settings_location": "Plats", - "settings_locationSubtitle": "GPS koordinater", + "settings_locationSubtitle": "GPS-koordinater", "settings_locationUpdated": "Plats uppdaterad", "settings_locationBothRequired": "Ange både latitud och longitud.", "settings_locationInvalid": "Ogiltig latitud eller longitud.", "settings_latitude": "Latitud", - "settings_longitude": "Längdgrad", + "settings_longitude": "Longitud", + "settings_autoZeroHopAdvertOnGpsUpdate": "Automatisk nollhoppsannons vid GPS-uppdatering", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "När GPS-positionen ändras skickas en nollhoppsannons (kräver plats i annonsen).", "settings_privacyMode": "Privatläge", "settings_privacyModeSubtitle": "Dölj namn/plats i annonser", "settings_privacyModeToggle": "Aktivera privatläge för att dölja ditt namn och din plats i annonser.", "settings_privacyModeEnabled": "Privatläget är aktiverat", "settings_privacyModeDisabled": "Privatläge är avstängt", "settings_actions": "Åtgärder", - "settings_deleteAllPaths": "Delete All Paths", - "settings_deleteAllPathsSubtitle": "Clear all path data from contacts.", - "settings_sendAdvertisement": "Skicka Annons", - "settings_sendAdvertisementSubtitle": "Sändning finns nu", + "settings_deleteAllPaths": "Radera alla rutter", + "settings_deleteAllPathsSubtitle": "Rensa all ruttdata från kontakter.", + "settings_sendAdvertisement": "Skicka annons", + "settings_sendAdvertisementSubtitle": "Sänd din närvaro nu", "settings_advertisementSent": "Annons skickad", - "settings_syncTime": "Synkroniseringstid", + "settings_syncTime": "Synkronisera tid", "settings_syncTimeSubtitle": "Ställ enheten till telefonens tid", "settings_timeSynchronized": "Tidssynkroniserat", "settings_refreshContacts": "Uppdatera Kontakter", "settings_refreshContactsSubtitle": "Ladda om kontaktlistan från enheten", "settings_rebootDevice": "Starta om enheten", - "settings_rebootDeviceSubtitle": "Starta MeshCore-enheten", + "settings_rebootDeviceSubtitle": "Starta om MeshCore-enheten", "settings_rebootDeviceConfirm": "Är du säker på att du vill starta om enheten? Du kommer att bli avkopplad.", "settings_debug": "Felsök", "settings_bleDebugLog": "BLE-felsökning", "settings_bleDebugLogSubtitle": "BLE-kommandon, svar och rådata", - "settings_appDebugLog": "Appfelsökning", - "settings_appDebugLogSubtitle": "Applikations felsökningsmeddelanden", + "settings_appDebugLog": "Appens felsökningslogg", + "settings_appDebugLogSubtitle": "Felsökningsmeddelanden från appen", "settings_about": "Om", "settings_aboutVersion": "MeshCore Open version {version}", "@settings_aboutVersion": { @@ -133,21 +135,21 @@ } } }, - "settings_aboutLegalese": "2024 MeshCore Öppen Källkodsprojekt", - "settings_aboutDescription": "En öppen källkods Flutter-klient för MeshCore LoRa meshnätverksenheter.", + "settings_aboutLegalese": "2026 MeshCore Open Source Project", + "settings_aboutDescription": "En Flutter-klient med öppen källkod för MeshCore-enheter i LoRa-meshnät.", "settings_infoName": "Namn", "settings_infoId": "ID", "settings_infoStatus": "Status", "settings_infoBattery": "Batteri", - "settings_infoPublicKey": "Allmänt nyckel", - "settings_infoContactsCount": "Kontakterantal", - "settings_infoChannelCount": "Kanalantal", + "settings_infoPublicKey": "Publik nyckel", + "settings_infoContactsCount": "Antal kontakter", + "settings_infoChannelCount": "Antal kanaler", "settings_presets": "Fördefinierade inställningar", "settings_frequency": "Frekvens (MHz)", "settings_frequencyHelper": "300,0 - 2500,0", "settings_frequencyInvalid": "Ogiltig frekvens (300-2500 MHz)", "settings_bandwidth": "Bandbredd", - "settings_spreadingFactor": "Spreadingfaktor", + "settings_spreadingFactor": "Spridningsfaktor", "settings_codingRate": "Kodningsgrad", "settings_txPower": "TX-effekt (dBm)", "settings_txPowerHelper": "0 – 22", @@ -164,42 +166,42 @@ "appSettings_appearance": "Utseende", "appSettings_theme": "Tema", "appSettings_themeSystem": "Systemstandard", - "appSettings_themeLight": "Ljus", - "appSettings_themeDark": "Mörk", + "appSettings_themeLight": "Ljust", + "appSettings_themeDark": "Mörkt", "appSettings_language": "Språk", "appSettings_languageSystem": "Systemstandard", "appSettings_languageEn": "Engelska", "appSettings_languageFr": "Franska", "appSettings_languageEs": "Spanska", - "appSettings_languageDe": "Tyskt", - "appSettings_languagePl": "Polsk", + "appSettings_languageDe": "Tyska", + "appSettings_languagePl": "Polska", "appSettings_languageSl": "Sloveniska", "appSettings_languagePt": "Portugisiska", "appSettings_languageIt": "Italienska", "appSettings_languageZh": "Kinesiska", "appSettings_languageSv": "Svenska", "appSettings_languageNl": "Nederländska", - "appSettings_languageSk": "Sloveniska", + "appSettings_languageSk": "Slovakiska", "appSettings_languageBg": "Bulgariska", - "appSettings_notifications": "Meddelanden", - "appSettings_enableNotifications": "Aktivera Notifikationer", - "appSettings_enableNotificationsSubtitle": "Ta emot notiser för meddelanden och reklam", + "appSettings_notifications": "Notifieringar", + "appSettings_enableNotifications": "Aktivera notifieringar", + "appSettings_enableNotificationsSubtitle": "Ta emot notifieringar för meddelanden och annonser", "appSettings_notificationPermissionDenied": "Tillåtelse för notifikationer nekad", - "appSettings_notificationsEnabled": "Notifikationer aktiverade", - "appSettings_notificationsDisabled": "Meddelanden är avstängda", - "appSettings_messageNotifications": "Meddelandekrav", - "appSettings_messageNotificationsSubtitle": "Visa notis när nya meddelanden tas emot", - "appSettings_channelMessageNotifications": "Kanalmeddelandena", - "appSettings_channelMessageNotificationsSubtitle": "Visa notis när meddelanden i kanal mottas", - "appSettings_advertisementNotifications": "Annonsmeddelanden", - "appSettings_advertisementNotificationsSubtitle": "Visa notis när nya noder upptäcks", + "appSettings_notificationsEnabled": "Notifieringar aktiverade", + "appSettings_notificationsDisabled": "Notifieringar inaktiverade", + "appSettings_messageNotifications": "Meddelandenotifieringar", + "appSettings_messageNotificationsSubtitle": "Visa en notifiering när nya meddelanden tas emot", + "appSettings_channelMessageNotifications": "Kanalnotifieringar", + "appSettings_channelMessageNotificationsSubtitle": "Visa en notifiering när kanalmeddelanden tas emot", + "appSettings_advertisementNotifications": "Annonsnotifieringar", + "appSettings_advertisementNotificationsSubtitle": "Visa en notifiering när nya noder upptäcks", "appSettings_messaging": "Meddelanden", - "appSettings_clearPathOnMaxRetry": "Rensa Vägen på Max Försök", - "appSettings_clearPathOnMaxRetrySubtitle": "Återställ kontaktväg efter 5 misslyckade försök att skicka", - "appSettings_pathsWillBeCleared": "Sökvägar kommer att tömmas efter 5 misslyckade försök.", - "appSettings_pathsWillNotBeCleared": "Sökvägar kommer inte att rensas automatiskt.", - "appSettings_autoRouteRotation": "Automatisk Rutväxling", - "appSettings_autoRouteRotationSubtitle": "Blixtra mellan bästa vägar och flödesläge", + "appSettings_clearPathOnMaxRetry": "Rensa rutt efter maximalt antal försök", + "appSettings_clearPathOnMaxRetrySubtitle": "Återställ kontaktens rutt efter 5 misslyckade sändningsförsök", + "appSettings_pathsWillBeCleared": "Rutter rensas efter 5 misslyckade försök", + "appSettings_pathsWillNotBeCleared": "Rutter rensas inte automatiskt", + "appSettings_autoRouteRotation": "Automatisk ruttrotation", + "appSettings_autoRouteRotationSubtitle": "Växla mellan de bästa rutterna och flood-läge", "appSettings_autoRouteRotationEnabled": "Automatisk ruttrotation är aktiverad", "appSettings_autoRouteRotationDisabled": "Automatisk ruttrotation är avstängd", "appSettings_battery": "Batteri", @@ -217,8 +219,8 @@ "appSettings_batteryLifepo4": "LiFePO4 (2,6–3,65V)", "appSettings_batteryLipo": "LiPo (3,0-4,2V)", "appSettings_mapDisplay": "Kartvisning", - "appSettings_showRepeaters": "Visa återuppslag", - "appSettings_showRepeatersSubtitle": "Visa återspelsnoder på kartan", + "appSettings_showRepeaters": "Visa repeaters", + "appSettings_showRepeatersSubtitle": "Visa repeaternoder på kartan", "appSettings_showChatNodes": "Visa Chattnoder", "appSettings_showChatNodesSubtitle": "Visa chattnoder på kartan", "appSettings_showOtherNodes": "Visa andra noder", @@ -233,13 +235,26 @@ } } }, - "appSettings_mapTimeFilter": "Karttid Filter", + "appSettings_mapTimeFilter": "Tidsfilter för kartan", "appSettings_showNodesDiscoveredWithin": "Visa noder som upptäckts inom:", - "appSettings_allTime": "Totalen", + "appSettings_allTime": "Alla tider", "appSettings_lastHour": "Sista timmen", "appSettings_last6Hours": "De senaste 6 timmarna", "appSettings_last24Hours": "De senaste 24 timmarna", "appSettings_lastWeek": "Förra veckan", + "appSettings_rasterTileSource": "Källa för rasterplattor", + "appSettings_stadiaEndpoint": "Stadia-slutpunkt", + "appSettings_stadiaApiKey": "Stadia API-nyckel", + "appSettings_stadiaApiKeyRequired": "Krävs för att använda Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Konfigurerad: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Ange din Stadia Maps API-nyckel. Appen använder den för förfrågningar om rasterplattor.", "appSettings_offlineMapCache": "Offline Kartcache", "appSettings_noAreaSelected": "Ingen area markerad", "appSettings_areaSelectedZoom": "Område markerat (zoom {minZoom}-{maxZoom})", @@ -261,7 +276,7 @@ "contacts_title": "Kontakter", "contacts_noContacts": "Inga kontakter ännu", "contacts_contactsWillAppear": "Kontakter kommer att visas när enheter annonserar.", - "contacts_searchContacts": "Sök kontakter...", + "contacts_searchContacts": "Sök {number}{str} kontakter…", "contacts_noUnreadContacts": "Inga oinlästa kontakter", "contacts_noContactsFound": "Inga kontakter eller grupper hittades.", "contacts_deleteContact": "Ta bort Kontakt", @@ -273,9 +288,9 @@ } } }, - "contacts_manageRepeater": "Hantera Upprepare", - "contacts_roomLogin": "Rum Inloggning", - "contacts_openChat": "Öppna Chatt", + "contacts_manageRepeater": "Hantera repeater", + "contacts_roomLogin": "Inloggning på rumsserver", + "contacts_openChat": "Öppna chatt", "contacts_editGroup": "Redigera Grupp", "contacts_deleteGroup": "Ta bort Grupp", "contacts_deleteGroupConfirm": "Ta bort {groupName}?", @@ -341,7 +356,7 @@ } } }, - "channels_public": "Offentligt", + "channels_public": "Publik", "channels_private": "Privat", "channels_editChannel": "Redigera kanal", "channels_muteChannel": "Tysta kanal", @@ -366,11 +381,11 @@ "channels_addChannel": "Lägg till kanal", "channels_channelIndexLabel": "Kanalindex", "channels_channelName": "Kanalnamn", - "channels_usePublicChannel": "Använd Publikkanal", - "channels_standardPublicPsk": "Standard allmän PSK", - "channels_pskHex": "PSK (heks)", + "channels_usePublicChannel": "Använd publik kanal", + "channels_standardPublicPsk": "Standard-PSK för publik kanal", + "channels_pskHex": "PSK (hex)", "channels_generateRandomPsk": "Generera slumpmässig PSK", - "channels_enterChannelName": "Ange en kanalnamn", + "channels_enterChannelName": "Ange ett kanalnamn", "channels_pskMustBe32Hex": "PSK måste vara 32 hexadecimala tecken", "channels_channelAdded": "Kanalen \"{name}\" har lagts till", "@channels_channelAdded": { @@ -413,10 +428,10 @@ } } }, - "channels_publicChannelAdded": "Allmänt kanal tillagd", + "channels_publicChannelAdded": "Publik kanal har lagts till", "channels_sortBy": "Sortera efter", "channels_sortManual": "Manuell", - "channels_sortAZ": "A-Z", + "channels_sortAZ": "A-Ö", "channels_sortLatestMessages": "Senaste meddelanden", "channels_sortUnread": "Oläst", "chat_noMessages": "Inga meddelanden ännu", @@ -470,10 +485,12 @@ } } }, + "chat_selectSendAction": "Välj sändningsåtgärd", "chat_sendGif": "Skicka GIF", "chat_reply": "Svara", "chat_addReaction": "Lägg till reaktion", "chat_me": "Mig", + "reaction_report": "Emoji-reaktioner", "emojiCategorySmileys": "Emojis", "emojiCategoryGestures": "Gestikuleringar", "emojiCategoryHearts": "Hjärtan", @@ -493,7 +510,7 @@ "debugLog_bleCopied": "BLE-logg kopierad", "debugLog_noEntries": "Inga felsökningsloggar ännu", "debugLog_enableInSettings": "Aktivera appens felsökningsloggning i inställningarna", - "debugLog_frames": "Rammar", + "debugLog_frames": "Ramar", "debugLog_rawLogRx": "Rå Log-RX", "debugLog_noBleActivity": "Ingen BLE-aktivitet ännu", "debugFrame_length": "Ramstorlek: {count} byte", @@ -559,14 +576,14 @@ } }, "debugFrame_hexDump": "Hexdump:", - "chat_pathManagement": "Stigarhantering", + "chat_pathManagement": "Rutthantering", "chat_routingMode": "Ruttläge", "chat_autoUseSavedPath": "Automatisk (använd sparad sökväg)", - "chat_forceFloodMode": "Tvinga Översvämningsläge", - "chat_recentAckPaths": "Nyligen Ack-vägar (tryck för att använda):", + "chat_forceFloodMode": "Tvinga flood-läge", + "chat_recentAckPaths": "Nyligen bekräftade vägar (tryck för att använda):", "chat_pathHistoryFull": "Historisk sökväg är full. Ta bort poster för att lägga till nya.", - "chat_hopSingular": "hoppa", - "chat_hopPlural": "hoppar", + "chat_hopSingular": "hopp", + "chat_hopPlural": "hopp", "chat_hopsCount": "{count} {count, plural, =1{hopp} other{hopp} }", "@chat_hopsCount": { "placeholders": { @@ -576,19 +593,19 @@ } }, "chat_successes": "framgångar", - "chat_removePath": "Ta bort sökväg", - "chat_noPathHistoryYet": "Ingen historik ännu.\nSkicka ett meddelande för att upptäcka spår.", - "chat_pathActions": "Stigar:", - "chat_setCustomPath": "Ange anpassad sökväg", - "chat_setCustomPathSubtitle": "Ange ruttväg manuellt", - "chat_clearPath": "Rensa Vägen", + "chat_removePath": "Ta bort rutt", + "chat_noPathHistoryYet": "Ingen rutthistorik ännu.\nSkicka ett meddelande för att upptäcka rutter.", + "chat_pathActions": "Rutter:", + "chat_setCustomPath": "Ange anpassad rutt", + "chat_setCustomPathSubtitle": "Ange rutt manuellt", + "chat_clearPath": "Rensa Rutt", "chat_clearPathSubtitle": "Tvinga fram omstart vid nästa sändning", - "chat_pathCleared": "Routen är nu fri. Nästa meddelande kommer att upptäcka rutten igen.", + "chat_pathCleared": "Rutten rensades. Nästa meddelande kommer att upptäcka rutten på nytt.", "chat_floodModeSubtitle": "Använd routningsomkopplaren i appraden", - "chat_floodModeEnabled": "Översvämningsläge aktiverat. Stäng av via ruttikonen i appraden.", - "chat_fullPath": "Fullständig sökväg", - "chat_pathDetailsNotAvailable": "Stigaruppgifterna är ännu inte tillgängliga. Försök att skicka ett meddelande för att uppdatera.", - "chat_pathSetHops": "Sökväg inställd: {hopCount} {hopCount, plural, =1{hopp} other{hoppar}} - {status}", + "chat_floodModeEnabled": "Flood-läge aktiverat. Stäng av via ruttikonen i appraden.", + "chat_fullPath": "Fullständig rutt", + "chat_pathDetailsNotAvailable": "Ruttuppgifterna är ännu inte tillgängliga. Försök att skicka ett meddelande för att uppdatera.", + "chat_pathSetHops": "Rutt inställd: {hopCount} {hopCount, plural, =1{hopp} other{hoppar}} - {status}", "@chat_pathSetHops": { "placeholders": { "hopCount": { @@ -602,11 +619,11 @@ "chat_pathSavedLocally": "Sparat lokalt. Anslut för att synkronisera.", "chat_pathDeviceConfirmed": "Enheten bekräftad.", "chat_pathDeviceNotConfirmed": "Enheten har inte bekräftats ännu.", - "chat_type": "Skriv", - "chat_path": "Sökväg", - "chat_publicKey": "Allmänt nyckel", - "chat_compressOutgoingMessages": "Kryptera utgående meddelanden", - "chat_floodForced": "Översvämning (tvingad)", + "chat_type": "Typ", + "chat_path": "Rutt", + "chat_publicKey": "Publik nyckel", + "chat_compressOutgoingMessages": "Komprimera utgående meddelanden", + "chat_floodForced": "Flood (tvingad)", "chat_directForced": "Direkt (tvingad)", "chat_hopsForced": "{count} hopp (tvingat)", "@chat_hopsForced": { @@ -616,7 +633,7 @@ } } }, - "chat_floodAuto": "Översvämning (auto)", + "chat_floodAuto": "Flood (automatisk)", "chat_direct": "Direkt", "chat_poiShared": "Delad POI", "chat_unread": "Olästa: {count}", @@ -650,7 +667,7 @@ } } }, - "map_pinsCount": "Pinnar: {count}", + "map_pinsCount": "Markörer: {count}", "@map_pinsCount": { "placeholders": { "count": { @@ -658,13 +675,13 @@ } } }, - "map_chat": "Chat", - "map_repeater": "Återuppspelare", + "map_chat": "Chatt", + "map_repeater": "Repeater", "map_room": "Rum", "map_sensor": "Sensor", - "map_pinDm": "Lås (DM)", - "map_pinPrivate": "Lås (Privat)", - "map_pinPublic": "Anslå (Offentligt)", + "map_pinDm": "Markör (DM)", + "map_pinPrivate": "Markör (privat)", + "map_pinPublic": "Markör (offentlig)", "map_lastSeen": "Senast sedd", "map_disconnectConfirm": "Är du säker på att du vill koppla från enheten?", "map_from": "Från", @@ -690,22 +707,22 @@ "map_filterNodes": "Filtrera noder", "map_nodeTypes": "Nodtyper", "map_chatNodes": "Chatnoder", - "map_repeaters": "Upprepare", + "map_repeaters": "Repeatrar", "map_otherNodes": "Andra noder", "map_keyPrefix": "Nyckelprefix", "map_filterByKeyPrefix": "Filtrera efter nyckelprefix", - "map_publicKeyPrefix": "Allmänt nyckelprästegenskap", + "map_publicKeyPrefix": "Prefix för publik nyckel", "map_markers": "Markörer", "map_showSharedMarkers": "Visa delade markörer", - "map_lastSeenTime": "Senaste Visats Tid", + "map_lastSeenTime": "Senast sedd", "map_sharedPin": "Delad PIN", "map_joinRoom": "Gå med i rum", - "map_manageRepeater": "Hantera Upprepare", + "map_manageRepeater": "Hantera repeater", "mapCache_title": "Offline Kartcache", "mapCache_selectAreaFirst": "Välj ett område att cachera först", - "mapCache_noTilesToDownload": "Inga kuber att ladda ner för detta område", - "mapCache_downloadTilesTitle": "Ladda ner klick", - "mapCache_downloadTilesPrompt": "Ladda ner {count} kuber för offlineanvändning?", + "mapCache_noTilesToDownload": "Inga kartplattor att ladda ned för det här området", + "mapCache_downloadTilesTitle": "Ladda ned kartplattor", + "mapCache_downloadTilesPrompt": "Ladda ned {count} kartplattor för offlineanvändning?", "@mapCache_downloadTilesPrompt": { "placeholders": { "count": { @@ -713,8 +730,8 @@ } } }, - "mapCache_downloadAction": "Ladda ner", - "mapCache_cachedTiles": "Cache {count} kuber", + "mapCache_downloadAction": "Ladda ned", + "mapCache_cachedTiles": "{count} kartplattor cachelagrade", "@mapCache_cachedTiles": { "placeholders": { "count": { @@ -722,7 +739,7 @@ } } }, - "mapCache_cachedTilesWithFailed": "Cachelagda {downloaded} klickark ({failed} misslyckades)", + "mapCache_cachedTilesWithFailed": "{downloaded} kartplattor cachelagrade ({failed} misslyckades)", "@mapCache_cachedTilesWithFailed": { "placeholders": { "downloaded": { @@ -734,13 +751,13 @@ } }, "mapCache_clearOfflineCacheTitle": "Rensa offline-cache", - "mapCache_clearOfflineCachePrompt": "Ta bort alla cachemapplaner?", + "mapCache_clearOfflineCachePrompt": "Ta bort alla cachelagrade kartplattor?", "mapCache_offlineCacheCleared": "Offline-cache rensad", "mapCache_noAreaSelected": "Ingen area markerad", "mapCache_cacheArea": "Cacheområde", "mapCache_useCurrentView": "Använd Aktuell Visning", "mapCache_zoomRange": "Zoombegränsning", - "mapCache_estimatedTiles": "Uppskattat antal klick: {count}", + "mapCache_estimatedTiles": "Uppskattat antal kartplattor: {count}", "@mapCache_estimatedTiles": { "placeholders": { "count": { @@ -748,7 +765,7 @@ } } }, - "mapCache_downloadedTiles": "Ladda ner {completed} / {total}", + "mapCache_downloadedTiles": "Nedladdade {completed} / {total}", "@mapCache_downloadedTiles": { "placeholders": { "completed": { @@ -759,7 +776,7 @@ } } }, - "mapCache_downloadTilesButton": "Ladda ner klick", + "mapCache_downloadTilesButton": "Ladda ned kartplattor", "mapCache_clearCacheButton": "Rensa Cache", "mapCache_failedDownloads": "Misslyckade nedladdningar: {count}", "@mapCache_failedDownloads": { @@ -769,6 +786,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cachelagrade kartplattor", + "mapCache_cachedTileSummaryLabel": "Sammanfattning av cachelagrade kartplattor", + "mapCache_bulkDownloadDisabledForSource": "Massnedladdning för offlinebruk är inaktiverad för {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Massnedladdning för offlinebruk är inaktiverad för {source} i appens konfiguration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Källa: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cachelagrade kartplattor för källan: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cachelagrat i valt område/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Ungefärlig cachestorlek: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "N {north}, S {south}, E {east}, W {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -823,19 +890,19 @@ "time_allTime": "Alla tider", "dialog_disconnect": "Koppla från", "dialog_disconnectConfirm": "Är du säker på att du vill koppla från enheten?", - "login_repeaterLogin": "Återuppta Inloggning", - "login_roomLogin": "Rum Inloggning", + "login_repeaterLogin": "Repeaterinloggning", + "login_roomLogin": "Inloggning på rumsserver", "login_password": "Lösenord", "login_enterPassword": "Ange lösenord", "login_savePassword": "Spara lösenord", "login_savePasswordSubtitle": "Lösenord kommer att lagras säkert på enheten.", - "login_repeaterDescription": "Ange återuppspelarens lösenord för att komma åt inställningar och status.", + "login_repeaterDescription": "Ange repeaterns lösenord för gäst- eller administratörsåtkomst.", "login_roomDescription": "Ange rummets lösenord för att komma åt inställningar och status.", "login_routing": "Ruttning", "login_routingMode": "Ruttläge", - "login_autoUseSavedPath": "Automatisk (använd sparad sökväg)", - "login_forceFloodMode": "Tvinga Översvämningsläge", - "login_managePaths": "Hantera Sökvägar", + "login_autoUseSavedPath": "Automatisk (använd sparad rutt)", + "login_forceFloodMode": "Tvinga flood-läge", + "login_managePaths": "Hantera rutter", "login_login": "Logga in", "login_attempt": "Försök {current}/{max}", "@login_attempt": { @@ -859,7 +926,7 @@ "login_failedMessage": "Inloggning misslyckades. Antingen är lösenordet fel eller så går det inte att nå repeatern.", "common_reload": "Ladda om", "common_clear": "Rensa", - "path_currentPath": "Nuvarande sökväg: {path}", + "path_currentPath": "Nuvarande rutt: {path}", "@path_currentPath": { "placeholders": { "path": { @@ -867,7 +934,7 @@ } } }, - "path_usingHopsPath": "Använda {count} {count, plural, =1{hop} other{hops}} sökväg", + "path_usingHopsPath": "Använda {count} {count, plural, =1{hop} other{hops}} rutt", "@path_usingHopsPath": { "placeholders": { "count": { @@ -875,15 +942,15 @@ } } }, - "path_enterCustomPath": "Ange anpassad sökväg", - "path_currentPathLabel": "Nuvarande sökväg", + "path_enterCustomPath": "Ange anpassad rutt", + "path_currentPathLabel": "Aktuell rutt", "path_hexPrefixInstructions": "Ange 2-tecknets hex-prefett för varje hopp, åtskilda med komma.", "path_hexPrefixExample": "Exempel: A1,F2,3C (varje nod använder det första bytet av sitt publika nyckel)", "path_labelHexPrefixes": "Hexprefixer", "path_helperMaxHops": "Max 64 hopp. Varje prefix är 2 hex-tecken (1 byte)", "path_selectFromContacts": "Välj istället från kontakter:", - "path_noRepeatersFound": "Inga återuppspelare eller rumsservrar hittades.", - "path_customPathsRequire": "Anpassade sökvägar kräver mellansteg som kan vidarebefordra meddelanden.", + "path_noRepeatersFound": "Inga repeatrar eller rumsservrar hittades.", + "path_customPathsRequire": "Anpassade rutter kräver mellansteg som kan vidarebefordra meddelanden.", "path_invalidHexPrefixes": "Ogiltiga hex-prefikser: {prefixes}", "@path_invalidHexPrefixes": { "placeholders": { @@ -894,21 +961,21 @@ }, "path_tooLong": "Sökvägen är för lång. Max 64 hopp tillåtna.", "path_setPath": "Ange Sökväg", - "repeater_management": "Återuppspelarens Hantering", + "repeater_management": "Repeaterhantering", "repeater_managementTools": "Administrationsverktyg", "repeater_status": "Status", - "repeater_statusSubtitle": "Visa återspolningsstatus, statistik och grannar", + "repeater_statusSubtitle": "Visa repeaterstatus, statistik och grannar", "repeater_telemetry": "Telemetri", "repeater_telemetrySubtitle": "Visa telemetri för sensorer och systemstatistik", "repeater_cli": "Kommandoradgränssnitt", - "repeater_cliSubtitle": "Skicka kommandon till repetitorn", + "repeater_cliSubtitle": "Skicka kommandon till repeatern", "repeater_settings": "Inställningar", - "repeater_settingsSubtitle": "Konfigurera återspolarparametrar", - "repeater_statusTitle": "Återspelsstatus", + "repeater_settingsSubtitle": "Konfigurera repeaterparametrar", + "repeater_statusTitle": "Repeaterstatus", "repeater_routingMode": "Ruttläge", - "repeater_autoUseSavedPath": "Automatisk (använd sparad sökväg)", - "repeater_forceFloodMode": "Tvinga Översvämningsläge", - "repeater_pathManagement": "Stigarhantering", + "repeater_autoUseSavedPath": "Automatisk (använd sparad rutt)", + "repeater_forceFloodMode": "Tvinga flood-läge", + "repeater_pathManagement": "Rutthantering", "repeater_refresh": "Uppdatera", "repeater_statusRequestTimeout": "Statusförfrågan gick inte att hämta.", "repeater_errorLoadingStatus": "Fel vid inläsning av status: {error}", @@ -922,15 +989,15 @@ "repeater_systemInformation": "Systeminformation", "repeater_battery": "Batteri", "repeater_clockAtLogin": "Klocka (vid inloggning)", - "repeater_uptime": "Tillgänglighet", - "repeater_queueLength": "Köans längd", - "repeater_debugFlags": "Felsökningsflaggor", + "repeater_uptime": "Drifttid", + "repeater_queueLength": "Kölängd", + "repeater_debugFlags": "Debugflaggor", "repeater_radioStatistics": "Radiostatistik", "repeater_lastRssi": "Senaste RSSI", - "repeater_lastSnr": "Sista SNR", - "repeater_noiseFloor": "Ljudnivå", - "repeater_txAirtime": "TX Airtime", - "repeater_rxAirtime": "RX Airtime", + "repeater_lastSnr": "Senaste SNR", + "repeater_noiseFloor": "Brusgolv", + "repeater_txAirtime": "TX-sändningstid", + "repeater_rxAirtime": "RX-sändningstid", "repeater_packetStatistics": "Paketstatistik", "repeater_sent": "Skickat", "repeater_received": "Mottaget", @@ -952,7 +1019,7 @@ } } }, - "repeater_packetTxTotal": "Totalt: {total}, Översvämning: {flood}, Direkt: {direct}", + "repeater_packetTxTotal": "Totalt: {total}, Flood: {flood}, Direkt: {direct}", "@repeater_packetTxTotal": { "placeholders": { "total": { @@ -966,7 +1033,7 @@ } } }, - "repeater_packetRxTotal": "Totalt: {total}, Översvämning: {flood}, Direkt: {direct}", + "repeater_packetRxTotal": "Totalt: {total}, Flood: {flood}, Direkt: {direct}", "@repeater_packetRxTotal": { "placeholders": { "total": { @@ -980,7 +1047,7 @@ } } }, - "repeater_duplicatesFloodDirect": "Översvämning: {flood}, Direkt: {direct}", + "repeater_duplicatesFloodDirect": "Flood: {flood}, Direkt: {direct}", "@repeater_duplicatesFloodDirect": { "placeholders": { "flood": { @@ -999,36 +1066,36 @@ } } }, - "repeater_settingsTitle": "Återuppspelarens Inställningar", + "repeater_settingsTitle": "Repeaterinställningar", "repeater_basicSettings": "Grundinställningar", - "repeater_repeaterName": "Upprepare Namn", - "repeater_repeaterNameHelper": "Visa namn för denna återupprepare", - "repeater_adminPassword": "Adminlösenord", + "repeater_repeaterName": "Repeaternamn", + "repeater_repeaterNameHelper": "Visningsnamn för den här repeatern", + "repeater_adminPassword": "Administratörslösenord", "repeater_adminPasswordHelper": "Fullständig åtkomstlösenord", - "repeater_guestPassword": "Gästlösenhet", - "repeater_guestPasswordHelper": "Läs-skyddspassord", + "repeater_guestPassword": "Gästlösenord", + "repeater_guestPasswordHelper": "Lösenord för skrivskyddad åtkomst", "repeater_radioSettings": "Radioinställningar", "repeater_frequencyMhz": "Frekvens (MHz)", "repeater_frequencyHelper": "300–2500 MHz", - "repeater_txPower": "TX Effekt", + "repeater_txPower": "TX-effekt", "repeater_txPowerHelper": "1-30 dBm", "repeater_bandwidth": "Bandbredd", - "repeater_spreadingFactor": "Spreadingfaktor", + "repeater_spreadingFactor": "Spridningsfaktor", "repeater_codingRate": "Kodningsgrad", "repeater_locationSettings": "Platsinställningar", "repeater_latitude": "Latitud", "repeater_latitudeHelper": "Decimalgrader (t.ex. 37.7749)", - "repeater_longitude": "Längdgrad", + "repeater_longitude": "Longitud", "repeater_longitudeHelper": "Decimalgrader (t.ex. -122.4194)", "repeater_features": "Funktioner", - "repeater_packetForwarding": "Paketväxling", - "repeater_packetForwardingSubtitle": "Aktivera återuppspelaren för att vidarebefordra paket", + "repeater_packetForwarding": "Vidarebefordran av paket", + "repeater_packetForwardingSubtitle": "Låt repeatern vidarebefordra paket", "repeater_guestAccess": "Gäståtkomst", "repeater_guestAccessSubtitle": "Tillåt läsbehörigheter för gäster.", "repeater_privacyMode": "Privatläge", "repeater_privacyModeSubtitle": "Dölj namn/plats i annonser", "repeater_advertisementSettings": "Annonsinställningar", - "repeater_localAdvertInterval": "Lokalt Annonsintervall", + "repeater_localAdvertInterval": "Intervall för lokal annonsering", "repeater_localAdvertIntervalMinutes": "{minutes} minuter", "@repeater_localAdvertIntervalMinutes": { "placeholders": { @@ -1037,7 +1104,7 @@ } } }, - "repeater_floodAdvertInterval": "Översvämnadsannonsens tidsintervall", + "repeater_floodAdvertInterval": "Intervall för flood-annonsering", "repeater_floodAdvertIntervalHours": "{hours} timmar", "@repeater_floodAdvertIntervalHours": { "placeholders": { @@ -1046,16 +1113,16 @@ } } }, - "repeater_encryptedAdvertInterval": "Krypterad Annonsintervall", + "repeater_encryptedAdvertInterval": "Intervall för krypterad annonsering", "repeater_dangerZone": "Faraområde", - "repeater_rebootRepeater": "Starta Återuppspelaren", - "repeater_rebootRepeaterSubtitle": "Starta om repeternheten", + "repeater_rebootRepeater": "Starta om repeater", + "repeater_rebootRepeaterSubtitle": "Starta om repeatern", "repeater_rebootRepeaterConfirm": "Är du säker på att du vill starta om denna repeater?", "repeater_regenerateIdentityKey": "Generera Identitetsknyckel", "repeater_regenerateIdentityKeySubtitle": "Generera ny publik/privat nyckelpar", - "repeater_regenerateIdentityKeyConfirm": "Detta kommer att generera en ny identitet för återspelaren. Fortsätta?", + "repeater_regenerateIdentityKeyConfirm": "Detta genererar en ny identitet för repeatern. Fortsätta?", "repeater_eraseFileSystem": "Radera Filsystem", - "repeater_eraseFileSystemSubtitle": "Formatera återspelsfilsystemet", + "repeater_eraseFileSystemSubtitle": "Formatera repeaterns filsystem", "repeater_eraseFileSystemConfirm": "VARNING: Detta kommer att radera all data på repeatern. Detta kan inte ångras!", "repeater_eraseSerialOnly": "Rensa är endast tillgängligt via seriell konsol.", "repeater_commandSent": "Kommandot skickades: {command}", @@ -1078,13 +1145,13 @@ "repeater_settingsSaved": "Inställningarna sparades framgångsrikt.", "repeater_rxGain": "Ökad RX-vinst", "repeater_rxGainHelper": "Ökad känslighet, högre strömförbrukning (endast för SX1262/SX1268)", - "repeater_refreshRxGain": "Återställ förbättrad RX-signalstyrka", + "repeater_refreshRxGain": "Uppdatera förstärkt RX-gain", "repeater_multiAcks": "Flera bekräftelser", - "repeater_multiAcksSubtitle": "Bekräfta meddelanden via flera olika kanaler för bättre leverans.", - "repeater_refreshMultiAcks": "Återställ flera ACK-meddelanden", + "repeater_multiAcksSubtitle": "Kvittera meddelanden via flera rutter för säkrare leverans", + "repeater_refreshMultiAcks": "Uppdatera multi-ACK", "repeater_networkHealth": "Nätverkets hälsa", "repeater_loopDetect": "Identifiering av loopar", - "repeater_loopDetectHelper": "Skapa \"flödespaket\" som ser ut som att de bildar en loop (en återkommande krets).", + "repeater_loopDetectHelper": "Släpp flood-paket som ser ut att ingå i routingloopar", "repeater_loopDetectOff": "Av", "repeater_loopDetectMinimal": "Minimal", "repeater_loopDetectModerate": "Måttlig", @@ -1099,28 +1166,28 @@ } } }, - "repeater_ownerInfo": "Information om operatören", - "repeater_ownerInfoHelper": "Offentliga metadata för denna sändare", - "repeater_refreshOwnerInfo": "Uppdatera information om personal", - "repeater_floodMax": "Maximala mängden humle", - "repeater_floodMaxHelper": "Maximalt antal hopp en paket kan färdas (0-64)", + "repeater_ownerInfo": "Operatörsinformation", + "repeater_ownerInfoHelper": "Publik metadata för den här repeatern", + "repeater_refreshOwnerInfo": "Uppdatera operatörsinformation", + "repeater_floodMax": "Max antal flood-hopp", + "repeater_floodMaxHelper": "Maximalt antal hopp som ett flood-paket får färdas (0–64)", "repeater_advancedSettings": "Avancerad", "repeater_advancedSettingsSubtitle": "Ställjusteringsknappar för erfarna användare", - "repeater_pathHashMode": "Hash-läge för sökväg", - "repeater_pathHashModeHelper": "Byte används för att koda denna repeaters ID i taggar för att upptäcka loopar/flödesvägar. 0=1 byte (256 ID:n, upp till 64 hopp), 1=2 byte (65 000 ID:n, upp till 32 hopp), 2=3 byte (16 miljoner ID:n, upp till 21 hopp). Versioner 1.13 och äldre har stöd för multi-byte-vägar – endast en gång när nätverket är aktiverat (från och med version 1.14).", - "repeater_txDelay": "Försening i Flood TX", - "repeater_txDelayHelper": "Återöverföringsintervall för trafik under perioder med hög belastning, som en multiplikator av paketets överföringstid (0-2, standard 0,5). Högre värde = färre kollisioner, men långsammare leverans.", + "repeater_pathHashMode": "Läge för rutthash", + "repeater_pathHashModeHelper": "Byte som används för att koda repeaterns ID i flood-ruttens/loopdetekteringens taggar. 0=1 byte (256 ID:n, upp till 64 hopp), 1=2 byte (65K ID:n, upp till 32 hopp), 2=3 byte (16M ID:n, upp till 21 hopp). Firmware före v1.14 använde alltid 1-byte-rutter; v1.14 och senare kan konfigureras för 2- eller 3-byte-rutter.", + "repeater_txDelay": "Flood-TX-fördröjning", + "repeater_txDelayHelper": "Intervall mellan vidarebefordringar för flood-trafik, som en multiplikator av paketets sändningstid (0–2, standard 0,5). Högre = färre kollisioner men långsammare leverans.", "repeater_directTxDelay": "Direkt TX-fördröjning", - "repeater_directTxDelayHelper": "Återöverföringsintervall för direkt (icke-översvämmande) trafik, som en multiplikator av paketets överföringstid (0-2, standard 0,3).", + "repeater_directTxDelayHelper": "Intervall mellan vidarebefordringar för direkt trafik (icke-flood), som en multiplikator av paketets sändningstid (0–2, standard 0,3).", "repeater_intThresh": "Tröskelvärde för störning", "repeater_intThreshHelper": "Tröskelvärdet har ställts in så att den filtrerar bort störningar som överstiger detta värde. 0 stänger av – aktivera endast om du ser RX-fel i ett störningsfyllt frekvensområde.", "repeater_agcResetInterval": "Återställningsintervall för AGC", "repeater_agcResetIntervalHelper": "Hur ofta ska man återställa radioens automatiska förstärkning för att återhämta sig från ett tillstånd där förstärkningen är fast? Sekunder, inställda till en multipel av 4. 0 stänger av periodiska återställningar.", "repeater_actionsTitle": "Åtgärder", - "repeater_sendAdvert": "Skicka annons om översvämning", - "repeater_sendAdvertSubtitle": "Sänd en reklamfilm om översvämningar via nätverket.", - "repeater_sendAdvertZeroHop": "Skicka en annons som inte kräver någon mellanstopp", - "repeater_sendAdvertZeroHopSubtitle": "Sänd en reklamkampanj med en enda sändare (utan mellanliggande sändare).", + "repeater_sendAdvert": "Skicka flood-annonsering", + "repeater_sendAdvertSubtitle": "Sänd en flood-annonsering genom nätverket", + "repeater_sendAdvertZeroHop": "Skicka nollhoppsannons", + "repeater_sendAdvertZeroHopSubtitle": "Sänd en nollhoppsannons (inga vidarebefordringar)", "repeater_clockSync": "Synkronisera klockan nu", "repeater_clockSyncSubtitle": "Ställ din telefons tid till repeatern.", "repeater_actionSucceeded": "{action} lyckades", @@ -1142,7 +1209,7 @@ } } }, - "repeater_settingsSavedRebootNeeded": "Inställningar sparade – starta om repetern för att tillämpa dem", + "repeater_settingsSavedRebootNeeded": "Inställningarna har sparats — starta om repeatern för att tillämpa dem", "repeater_settingsPartialFailure": "Vissa inställningar misslyckades: {failures}", "@repeater_settingsPartialFailure": { "placeholders": { @@ -1159,12 +1226,12 @@ } } }, - "repeater_refreshBasicSettings": "Återställ Grundläggande Inställningar", - "repeater_refreshRadioSettings": "Återställ Radiosinställningar", - "repeater_refreshTxPower": "Återställ TX-effekt", - "repeater_refreshPacketForwarding": "Återställ Paketväxling", - "repeater_refreshGuestAccess": "Återställ Gäståtkomst", - "repeater_refreshPrivacyMode": "Återställ Sekretessläge", + "repeater_refreshBasicSettings": "Uppdatera grundinställningar", + "repeater_refreshRadioSettings": "Uppdatera radioinställningar", + "repeater_refreshTxPower": "Uppdatera TX-effekt", + "repeater_refreshPacketForwarding": "Uppdatera paketvidarebefordran", + "repeater_refreshGuestAccess": "Uppdatera gäståtkomst", + "repeater_refreshPrivacyMode": "Uppdatera privatläge", "repeater_refreshed": "{label} har uppdaterats", "@repeater_refreshed": { "placeholders": { @@ -1181,9 +1248,9 @@ } } }, - "repeater_cliTitle": "Återuppspelaren CLI", + "repeater_cliTitle": "Repeater-CLI", "repeater_debugNextCommand": "Felsök Nästa Kommando", - "repeater_commandHelp": "Hjälp", + "repeater_commandHelp": "Kommandohjälp", "repeater_clearHistory": "Rensa Historik", "repeater_noCommandsSent": "Inga kommandon skickats ännu", "repeater_typeCommandOrUseQuick": "Skriv en kommando nedan eller använd snabba kommandon", @@ -1215,21 +1282,21 @@ "repeater_cliHelpClearStats": "Återställer olika statistikräknare till noll.", "repeater_cliHelpSetAf": "Ställer in lufttidsfaktor.", "repeater_cliHelpSetTx": "Ställer LoRa-sändningseffekten i dBm. (starta om för att tillämpa)", - "repeater_cliHelpSetRepeat": "Aktiverar eller inaktiverar återuppspelarens roll för denna nod.", - "repeater_cliHelpSetAllowReadOnly": "(Rumserver) Om 'på', så tillåts login med tomt lösenord, men kan inte Posta till rummet. (bara läsa).", - "repeater_cliHelpSetFloodMax": "Ställer in det maximala antalet hopp för inkommande översvämning (om >= max, skickas inte paketet).", + "repeater_cliHelpSetRepeat": "Aktiverar eller inaktiverar repeaterrollen för den här noden.", + "repeater_cliHelpSetAllowReadOnly": "(Rumsserver) Om detta är på tillåts inloggning med tomt lösenord, men det går inte att posta till rummet (endast läsning).", + "repeater_cliHelpSetFloodMax": "Anger maximalt antal hopp för inkommande flood-paket (om >= max vidarebefordras inte paketet).", "repeater_cliHelpSetIntThresh": "Ställer Interferensgränsen (i dB). Standardvärdet är 14. Ställ in den på 0 för att inaktivera detektion av kanalinterferens.", "repeater_cliHelpSetAgcResetInterval": "Ställer in intervallet för att återställa Auto Gain-kontrollen. Ställ in till 0 för att inaktivera.", "repeater_cliHelpSetMultiAcks": "Aktiverar eller inaktiverar funktionen 'dubbla ACKs'.", - "repeater_cliHelpSetAdvertInterval": "Ställer in tidsintervallen i minuter för att skicka ett lokalt (utan-hopp) annonseringspaket. Ställs till 0 för att inaktivera.", - "repeater_cliHelpSetFloodAdvertInterval": "Ställer in tidsintervallen i timmar för att skicka ett flödesannonspaket. Ställ in på 0 för att inaktivera.", - "repeater_cliHelpSetGuestPassword": "Ställer in/uppdaterar gästlösenordet. (för återvändare kan gästloggar skicka \"Get Stats\"-förfrågan)", - "repeater_cliHelpSetName": "Ställer in annonstexterna namn.", + "repeater_cliHelpSetAdvertInterval": "Anger tidsintervallet i minuter för att skicka ett lokalt nollhopps-annonseringspaket. Ange 0 för att inaktivera.", + "repeater_cliHelpSetFloodAdvertInterval": "Anger tidsintervallet i timmar för att skicka ett flood-annonseringspaket. Ange 0 för att inaktivera.", + "repeater_cliHelpSetGuestPassword": "Anger/uppdaterar gästlösenordet. (För repeatrar kan gästinloggningar skicka begäran \"Get Stats\".)", + "repeater_cliHelpSetName": "Anger namnet som används i annonseringen.", "repeater_cliHelpSetLat": "Ställer in annonskartans latitud. (decimalgrader)", "repeater_cliHelpSetLon": "Ställer in annonskartans longitud (decimalgrader).", "repeater_cliHelpSetRadio": "Ställer helt nya radioparametrar och sparar dem i inställningar. Kräver en \"omstart\" för att tillämpa.", "repeater_cliHelpSetRxDelay": "Ställer (experimentell) basvärde (måste vara > 1 för effekt) för att applicera en liten fördröjning på mottagna paket, baserat på signalstyrka/poäng. Ställ in på 0 för att inaktivera.", - "repeater_cliHelpSetTxDelay": "Ställer in en faktor som multipliceras med tid på luft för en översvämningsläge-paket och med ett slumpmässigt slot-system för att fördröja dess vidarebefordran (för att minska risken för kollisioner).", + "repeater_cliHelpSetTxDelay": "Anger en faktor som multipliceras med sändningstiden för ett paket i flood-läge och används med ett slumpmässigt slotsystem för att fördröja vidarebefordran (för att minska risken för kollisioner).", "repeater_cliHelpSetDirectTxDelay": "Samma som txdelay, men för att applicera en slumpmässig fördröjning vid vidarebefordran av direktlägespaket.", "repeater_cliHelpSetBridgeEnabled": "Aktivera/Inaktivera brygga.", "repeater_cliHelpSetBridgeDelay": "Ställ in fördröjning innan paket åter sänder.", @@ -1243,9 +1310,9 @@ "repeater_cliHelpLogStart": "Starta paketloggning till filsystem.", "repeater_cliHelpLogStop": "Stoppar paketloggning till filsystem.", "repeater_cliHelpLogErase": "Raderar pakets loggar från filsystemet.", - "repeater_cliHelpNeighbors": "Visar en lista över andra repeaternoder som hörts via noll-hop-annonser. Varje rad är id-prefix-hex:tidsstämpel:snr-g撮-4", + "repeater_cliHelpNeighbors": "Visar en lista över andra repeaternoder som hörts via nollhoppsannonser. Varje rad är id-prefix-hex:timestamp:snr-times-4.", "repeater_cliHelpNeighborRemove": "Tar bort det första matchande inlägget (genom pubkey-prefiks (hex)) från grannlistan.", - "repeater_cliHelpRegion": "(Serien endast) Listar alla definierade regioner och aktuella översvämningsbehörigheter.", + "repeater_cliHelpRegion": "(Endast seriell anslutning) Listar alla definierade regioner och aktuella behörigheter för flood-trafik.", "repeater_cliHelpRegionLoad": "MEDDELANDE: detta är ett specialkommando med flera kommandon. Varje efterföljande kommando är ett regionsnamn (indenterat med blanksteg för att indikera en hierarkisk relation, med minst ett blanksteg). Avslutas genom att skicka en tom rad/kommando.", "repeater_cliHelpRegionGet": "Söker efter region med given namnprefiks (eller \"\" för det globala scopet). Svarar med \"-> regionnamn (föräldernamn) 'F'\"", "repeater_cliHelpRegionPut": "Lägger till eller uppdaterar en regionsdefinition med det angivna namnet.", @@ -1260,15 +1327,15 @@ "repeater_cliHelpGpsSync": "Synkroniserar nätverks tid med GPS-klockan.", "repeater_cliHelpGpsSetLoc": "Ställer nodens position till GPS-koordinater och sparar inställningar.", "repeater_cliHelpGpsAdvert": "Ger platsannonskonfigurationen för noden:\n- ingen: inkludera inte plats i annonser\n- dela: dela gps-plats (från SensorManager)\n- inställningar: annonsera platsen som sparats i inställningar", - "repeater_cliHelpGpsAdvertSet": "Ställer in annonsplatskonfiguration.", + "repeater_cliHelpGpsAdvertSet": "Anger konfigurationen för plats i annonser.", "repeater_commandsListTitle": "Inställningslista", "repeater_commandsListNote": "OBS: för de olika \"set ...\" -kommandon finns det även ett \"get ...\" -kommando.", "repeater_general": "Allmänt", "repeater_settingsCategory": "Inställningar", "repeater_bridge": "Bro", "repeater_logging": "Logga", - "repeater_neighborsRepeaterOnly": "Grannar (Endast återspelare)", - "repeater_regionManagementRepeaterOnly": "Regionhantering (endast återuppspelare)", + "repeater_neighborsRepeaterOnly": "Grannar (endast repeater)", + "repeater_regionManagementRepeaterOnly": "Regionhantering (endast repeater)", "repeater_regionNote": "Regionkommandon har införts för att hantera regiondefinitioner och behörigheter.", "repeater_gpsManagement": "GPS Hantering", "repeater_gpsNote": "GPS-kommando har introducerats för att hantera platsrelaterade ämnen.", @@ -1332,7 +1399,7 @@ "telemetry_voltageLabel": "Spänning", "telemetry_mcuTemperatureLabel": "MCU Temperatur", "telemetry_temperatureLabel": "Temperatur", - "telemetry_currentLabel": "Aktuell", + "telemetry_currentLabel": "Ström", "telemetry_batteryValue": "{percent}% / {volts}V", "@telemetry_batteryValue": { "placeholders": { @@ -1371,18 +1438,18 @@ } } }, - "channelPath_title": "Paketväg", + "channelPath_title": "Paketrutt", "channelPath_viewMap": "Visa karta", - "channelPath_otherObservedPaths": "Övriga observerade stigar", - "channelPath_repeaterHops": "Återupptagningssteg", - "channelPath_noHopDetails": "Detaljer för denna paket är inte angivna.", + "channelPath_otherObservedPaths": "Andra observerade rutter", + "channelPath_repeaterHops": "Repeaterhopp", + "channelPath_noHopDetails": "Hoppdetaljer anges inte för det här paketet.", "channelPath_messageDetails": "Meddelandets detaljer", "channelPath_senderLabel": "Avsändare", "channelPath_timeLabel": "Tid", "channelPath_repeatsLabel": "Upprepa", - "channelPath_pathLabel": "Sökväg {index}", + "channelPath_pathLabel": "Rutt {index}", "channelPath_observedLabel": "Observerat", - "channelPath_observedPathTitle": "Observerad bana {index} • {hops}", + "channelPath_observedPathTitle": "Observerad rutt {index} • {hops}", "@channelPath_observedPathTitle": { "placeholders": { "index": { @@ -1416,8 +1483,8 @@ } } }, - "channelPath_unknownPath": "Okänt", - "channelPath_floodPath": "Översvämning", + "channelPath_unknownPath": "Okänd", + "channelPath_floodPath": "Flood-trafik", "channelPath_directPath": "Direkt", "channelPath_observedZeroOf": "0 av {total} hopp", "@channelPath_observedZeroOf": { @@ -1438,9 +1505,9 @@ } } }, - "channelPath_mapTitle": "Sökvägskarta", - "channelPath_noRepeaterLocations": "Inga återupprepningsplatser finns tillgängliga för denna väg.", - "channelPath_primaryPath": "Sökväg {index} (Primär)", + "channelPath_mapTitle": "Ruttkarta", + "channelPath_noRepeaterLocations": "Inga repeaterpositioner är tillgängliga för den här rutten.", + "channelPath_primaryPath": "Rutt {index} (primär)", "@channelPath_primaryPath": { "placeholders": { "index": { @@ -1455,8 +1522,8 @@ } } }, - "channelPath_pathLabelTitle": "Sökväg", - "channelPath_observedPathHeader": "Observerad Sökväg", + "channelPath_pathLabelTitle": "Rutt", + "channelPath_observedPathHeader": "Observerad rutt", "channelPath_selectedPathLabel": "{label} • {prefixes}", "@channelPath_selectedPathLabel": { "placeholders": { @@ -1469,17 +1536,17 @@ } }, "channelPath_noHopDetailsAvailable": "Inga hoppdetaljer finns tillgängliga för detta paket.", - "channelPath_unknownRepeater": "Okänt Upprepare", + "channelPath_unknownRepeater": "Okänd repeater", "listFilter_tooltip": "Filtrera och sortera", "listFilter_sortBy": "Sortera efter", "listFilter_latestMessages": "Senaste meddelanden", - "listFilter_heardRecently": "Hörts nyligen", - "listFilter_az": "A-Z", + "listFilter_heardRecently": "Nyligen hörd", + "listFilter_az": "A-Ö", "listFilter_filters": "Filteralternativ", "listFilter_all": "Alla", "listFilter_users": "Användare", - "listFilter_repeaters": "Upprepare", - "listFilter_roomServers": "Rumservrar", + "listFilter_repeaters": "Repeatrar", + "listFilter_roomServers": "Rumsservrar", "listFilter_unreadOnly": "Endast oinlästa", "listFilter_newGroup": "Ny grupp", "@neighbors_errorLoading": { @@ -1490,20 +1557,20 @@ } }, "repeater_neighbors": "Grannar", - "repeater_neighborsSubtitle": "Visa noll hoppgrannar.", + "repeater_neighborsSubtitle": "Visa nollhoppsgrannar.", "neighbors_receivedData": "Mottagna grannars data", - "neighbors_requestTimedOut": "Grannar begär tidsinställd utskick.", + "neighbors_requestTimedOut": "Tidsgränsen för grannförfrågan överskreds.", "neighbors_errorLoading": "Fel vid inläsning av grannar: {error}", - "neighbors_repeatersNeighbors": "Upprepar grannar", + "neighbors_repeatersNeighbors": "Repeatergrannar", "neighbors_noData": "Inga grannuppgifter finns tillgängliga.", "channels_createPrivateChannel": "Skapa en privat kanal", - "channels_joinPrivateChannel": "Gå med i en Privat Kanal", - "channels_joinPrivateChannelDesc": "Ange en hemlig nyckel manuellt.", - "channels_createPrivateChannelDesc": "Skyddat med en hemlig nyckel.", - "channels_joinPublicChannel": "Gå med i den Offentliga Kanalen", - "channels_joinPublicChannelDesc": "Vem som helst kan gå med i denna kanal.", - "channels_joinHashtagChannel": "Gå med i en Hashtagkanal", - "channels_joinHashtagChannelDesc": "Väldigt enkelt att gå med i hashtag-kanaler.", + "channels_joinPrivateChannel": "Gå med i en privat kanal", + "channels_joinPrivateChannelDesc": "Skriv in nyckeln manuellt.", + "channels_createPrivateChannelDesc": "Säkrad med en hemlig nyckel.", + "channels_joinPublicChannel": "Gå med i den publika kanalen", + "channels_joinPublicChannelDesc": "Alla kan gå med i den här kanalen.", + "channels_joinHashtagChannel": "Gå med i en hashtagkanal", + "channels_joinHashtagChannelDesc": "Vem som helst kan gå med i hashtagkanaler.", "channels_scanQrCode": "Skanna en QR-kod", "channels_scanQrCodeComingSoon": "Kommer snart", "channels_enterHashtag": "Ange hashtag", @@ -1528,8 +1595,8 @@ "settings_locationGPSEnableSubtitle": "Aktivera automatiska uppdateringar av platsen med hjälp av GPS.", "settings_locationIntervalSec": "Interval för GPS (Sekunder)", "settings_locationIntervalInvalid": "Intervalet måste vara minst 60 sekunder och mindre än 86400 sekunder.", - "contacts_manageRoom": "Hantera Rumserver", - "room_management": "Rumserverhantering", + "contacts_manageRoom": "Hantera rumsserver", + "room_management": "Rumsserverhantering", "@community_joinConfirmation": { "placeholders": { "name": { @@ -1588,7 +1655,7 @@ }, "community_create": "Skapa Gemenskap", "community_createDesc": "Skapa en ny gemenskap och dela via QR-kod.", - "common_ok": "Okej", + "common_ok": "OK", "community_title": "Gemenskap", "community_join": "Gå med", "community_joinTitle": "Gå med i gemenskapen", @@ -1596,9 +1663,9 @@ "community_scanQr": "Skanna Gemenskapens QR", "community_scanInstructions": "Rikta kameran mot en QR-kod i communityn", "community_showQr": "Visa QR-kod", - "community_publicChannel": "Föreningens Offentliga", + "community_publicChannel": "Publik communitykanal", "community_name": "Gemenskapens namn", - "community_enterName": "Ange communities namn", + "community_enterName": "Ange communityns namn", "community_created": "Community \"{name}\" har skapats", "community_joined": "Medlem i communityn \"{name}\"", "community_qrTitle": "Dela Gemenskap", @@ -1608,8 +1675,8 @@ "community_invalidQrCode": "Ogiltig community QR-kod", "community_alreadyMember": "Är redan medlem", "community_alreadyMemberMessage": "Du är redan medlem av \"{name}\".", - "community_addPublicChannel": "Lägg till Gemenskapskanal (Offentlig)", - "community_addPublicChannelHint": "Lägg automatiskt till den offentliga kanalen för denna community", + "community_addPublicChannel": "Lägg till publik communitykanal", + "community_addPublicChannelHint": "Lägg automatiskt till den publika kanalen för den här communityn", "community_noCommunities": "Inga gemenskaper har anslutats ännu", "community_scanOrCreate": "Skanna en QR-kod eller skapa en community för att komma igång", "community_manageCommunities": "Hantera Gemenskaper", @@ -1662,7 +1729,7 @@ }, "community_regenerate": "Regenerera", "community_regenerateSecretConfirm": "Regenerera den hemliga nyckeln för \"{name}\"? Alla medlemmar måste scanna den nya QR-koden för att fortsätta kommunicera.", - "community_secretRegenerated": "Lösenord återskapad för \"{name}\"", + "community_secretRegenerated": "Hemligheten har genererats om för “{name}”", "community_regenerateSecret": "Regenerera hemlig kod", "community_scanToUpdateSecret": "Skanna den nya QR-koden för att uppdatera hemligheten för \"{name}\"", "community_secretUpdated": "Hemlighet uppdaterad för \"{name}\"", @@ -1675,27 +1742,27 @@ } }, "pathTrace_you": "Du", - "pathTrace_failed": "Sökvägsföljning misslyckades.", - "pathTrace_notAvailable": "Path trace ej tillgänglig.", - "pathTrace_refreshTooltip": "Uppdatera Path Trace", - "contacts_pathTrace": "Spårning", - "contacts_ping": "Ping", - "contacts_repeaterPathTrace": "Vägspårning till repeater", + "pathTrace_failed": "Ruttspårningen misslyckades.", + "pathTrace_notAvailable": "Ruttspårning är inte tillgänglig.", + "pathTrace_refreshTooltip": "Uppdatera ruttspårning.", + "contacts_pathTrace": "Ruttspårning", + "contacts_ping": "Pinga", + "contacts_repeaterPathTrace": "Ruttspårning till repeater", "contacts_repeaterPing": "Ping-repeater", - "contacts_roomPathTrace": "Vägspårning till rumserver", - "contacts_roomPing": "Ping rumsserver", + "contacts_roomPathTrace": "Ruttspårning till rumsserver", + "contacts_roomPing": "Pinga rumsserver", "contacts_chatTraceRoute": "Spåra rutt", "contacts_pathTraceTo": "Spåra rutt till {name}", "contacts_clipboardEmpty": "Urklipp är tomt.", "appSettings_languageRu": "Ryska", "contacts_contactImportFailed": "Kontakt kunde inte importeras.", - "contacts_zeroHopAdvert": "Reklam med nollhopp", - "contacts_floodAdvert": "Översvämningsannons", + "contacts_zeroHopAdvert": "Nollhoppsannons", + "contacts_floodAdvert": "Flood-annonsering", "contacts_copyAdvertToClipboard": "Kopiera annons till urklipp", "contacts_invalidAdvertFormat": "Ogiltiga kontaktuppgifter", "appSettings_languageUk": "Ukrainska", "appSettings_enableMessageTracing": "Aktivera meddelandespårning", - "appSettings_enableMessageTracingSubtitle": "Visa detaljerade metadata om dirigering och tidsinställningar för meddelanden", + "appSettings_enableMessageTracingSubtitle": "Visa detaljerad routing- och tidsmetadata för meddelanden", "contacts_addContactFromClipboard": "Lägg till kontakt från urklipp", "contacts_contactImported": "Kontakt har importerats.", "contacts_zeroHopContactAdvertSent": "Skickat kontakt via annons.", @@ -1711,34 +1778,34 @@ "notification_newTypeDiscovered": "Ny {contactType} upptäckt", "notification_receivedNewMessage": "Nytt meddelande mottaget", "settings_gpxExportAll": "Exportera alla kontakter till GPX", - "settings_gpxExportRepeatersSubtitle": "Exporterar repeater / roomserver med plats till GPX-fil.", + "settings_gpxExportRepeatersSubtitle": "Exporterar repeatrar/rumsservrar med position till en GPX-fil.", "settings_gpxExportSuccess": "Har exporterat GPX-fil med framgång", "settings_gpxExportNoContacts": "Inga kontakter att exportera.", "settings_gpxExportNotAvailable": "Stöds inte på din enhet/operativsystem", "settings_gpxExportRepeatersRoom": "Repeater- och rumsserverplatser", - "settings_gpxExportRepeaters": "Exportera repeater / rumsservrar till GPX", + "settings_gpxExportRepeaters": "Exportera repeatrar/rumsservrar till GPX", "settings_gpxExportAllSubtitle": "Exporterar alla kontakter med en plats till GPX-fil.", - "settings_gpxExportContacts": "Exportera följeslagare till GPX", - "settings_gpxExportContactsSubtitle": "Exporterar följeslagare med en plats till GPX-fil.", - "settings_gpxExportChat": "Medhjälparplatser", + "settings_gpxExportContacts": "Exportera Companion-kontakter till GPX", + "settings_gpxExportContactsSubtitle": "Exporterar Companion-enheter med position till en GPX-fil.", + "settings_gpxExportChat": "Companion-positioner", "settings_gpxExportError": "Det uppstod ett fel när data exporterades.", "settings_gpxExportAllContacts": "Alla kontakters platser", "settings_gpxExportShareSubject": "meshcore-open export av GPX-kartdata", "settings_gpxExportShareText": "Kartdata exporterad från meshcore-open", - "pathTrace_someHopsNoLocation": "En eller flera av humlen saknar en plats!", - "pathTrace_clearTooltip": "Rensa väg", - "map_pathTraceCancelled": "Sökvägsspårning avbruten.", - "map_runTrace": "Kör spårsökning", - "map_tapToAdd": "Tryck på noder för att lägga till dem i banan.", + "pathTrace_someHopsNoLocation": "Ett eller flera hopp saknar position!", + "pathTrace_clearTooltip": "Rensa rutt", + "map_pathTraceCancelled": "Ruttspårningen avbröts.", + "map_runTrace": "Kör ruttspårning", + "map_tapToAdd": "Tryck på noder för att lägga till dem i rutten.", "map_removeLast": "Ta bort sista", "scanner_enableBluetooth": "Aktivera Bluetooth", "scanner_bluetoothOffMessage": "Vänligen aktivera Bluetooth för att söka efter enheter.", "scanner_chromeRequired": "Chrome-webbläsare krävs", - "scanner_chromeRequiredMessage": "Denna webbapplikation kräver Google Chrome oder en Chromium-baserader webbläsare för Bluetooth-stöd.", + "scanner_chromeRequiredMessage": "Den här webbappen kräver Google Chrome eller en Chromium-baserad webbläsare för Bluetooth-stöd.", "scanner_bluetoothOff": "Bluetooth är avstängt", "snrIndicator_lastSeen": "Senast sedd", - "snrIndicator_nearByRepeaters": "Närliggande uppreparstationer", - "chat_ShowAllPaths": "Visa alla vägar", + "snrIndicator_nearByRepeaters": "Närliggande repeatrar", + "chat_ShowAllPaths": "Visa alla rutter", "settings_clientRepeatSubtitle": "Låt enheten repetera nätpaket för andra användare.", "settings_clientRepeat": "Upprepa utan elnät", "settings_clientRepeatFreqWarning": "För att kunna kommunicera utanför elnätet krävs frekvenserna 433, 869 eller 918 MHz.", @@ -1746,8 +1813,8 @@ "appSettings_unitsTitle": "Enheter", "appSettings_unitsMetric": "Metriskt (m/km)", "appSettings_unitsImperial": "Imperialt (ft / mi)", - "map_lineOfSight": "Synlinje", - "map_losScreenTitle": "Synlinje", + "map_lineOfSight": "Siktlinje", + "map_losScreenTitle": "Siktlinje", "losSelectStartEnd": "Välj start- och slutnoder för LOS.", "losRunFailed": "Synlinjekontroll misslyckades: {error}", "@losRunFailed": { @@ -1762,7 +1829,7 @@ "losMenuTitle": "LOS-menyn", "losMenuSubtitle": "Tryck på noder eller tryck länge på kartan för anpassade punkter", "losShowDisplayNodes": "Visa displaynoder", - "losCustomPoints": "Anpassade poäng", + "losCustomPoints": "Anpassade punkter", "losCustomPointLabel": "Anpassad {index}", "@losCustomPointLabel": { "placeholders": { @@ -1797,7 +1864,7 @@ }, "losRun": "Kör LOS", "losNoElevationData": "Inga höjddata", - "losProfileClear": "{distance} {distanceUnit}, rensa LOS, min clearance {clearance} {heightUnit}", + "losProfileClear": "{distance} {distanceUnit}, fri siktlinje, minsta frigång {clearance} {heightUnit}", "@losProfileClear": { "placeholders": { "distance": { @@ -1833,7 +1900,7 @@ }, "losStatusChecking": "LOS: kollar...", "losStatusNoData": "LOS: inga data", - "losStatusSummary": "LOS: {clear}/{total} rensa, {blocked} blockerad, {unknown} okänd", + "losStatusSummary": "LOS: {clear}/{total} fria, {blocked} blockerade, {unknown} okända", "@losStatusSummary": { "placeholders": { "clear": { @@ -1926,26 +1993,26 @@ }, "contacts_unread": "Oläst", "contacts_searchContactsNoNumber": "Sök kontakter...", - "contacts_searchRepeaters": "Sök {number}{str} upprepningsenheter...", + "contacts_searchRepeaters": "Sök {number}{str} repeaters…", "contacts_searchFavorites": "Sök {number}{str} Favoriter...", "contacts_searchUsers": "Sök {number}{str} användare...", - "contacts_searchRoomServers": "Sök {number}{str} Room-servrar...", + "contacts_searchRoomServers": "Sök {number}{str} rumsservrar…", "settings_contactSettingsSubtitle": "Inställningar för hur kontakter läggs till.", "settings_contactSettings": "Kontaktinställningar", "contactsSettings_autoAddTitle": "Automatisk upptäckt", "contactsSettings_otherTitle": "Andra inställningar relaterade till kontakt", - "contactsSettings_autoAddUsersSubtitle": "Tillåt kompanjonen att automatiskt lägga till upptäckta användare", - "contactsSettings_autoAddRepeatersTitle": "Lägg till upprepande enheter automatiskt", - "contactsSettings_autoAddRoomServersSubtitle": "Tillåt kompanjonen att automatiskt lägga till upptäckta rumsservrar.", + "contactsSettings_autoAddUsersSubtitle": "Tillåt Companion-enheten att automatiskt lägga till upptäckta användare.", + "contactsSettings_autoAddRepeatersTitle": "Lägg till repeatrar automatiskt", + "contactsSettings_autoAddRoomServersSubtitle": "Tillåt Companion-enheten att automatiskt lägga till upptäckta rumsservrar.", "contactsSettings_autoAddSensorsTitle": "Lägg till sensorer automatiskt", "contactsSettings_autoAddUsersTitle": "Lägg till användare automatiskt", "contactsSettings_title": "Kontaktinställningar", - "contactsSettings_autoAddSensorsSubtitle": "Tillåt kompanjonen att automatiskt lägga till upptäckta sensorer.", - "contactsSettings_overwriteOldestTitle": "Skriv över äldst", - "contactsSettings_autoAddRepeatersSubtitle": "Tillåt kompanjonen att automatiskt lägga till upptäckta repeater.", + "contactsSettings_autoAddSensorsSubtitle": "Tillåt Companion-enheten att automatiskt lägga till upptäckta sensorer.", + "contactsSettings_overwriteOldestTitle": "Skriv över äldsta", + "contactsSettings_autoAddRepeatersSubtitle": "Tillåt Companion-enheten att automatiskt lägga till upptäckta repeatrar.", "contactsSettings_autoAddRoomServersTitle": "Lägg automatiskt till rumsservrar", "discoveredContacts_noMatching": "Inga matchande kontakter", - "discoveredContacts_searchHint": "Sök uppfunna kontakter", + "discoveredContacts_searchHint": "Sök bland upptäckta kontakter", "discoveredContacts_deleteContact": "Ta bort kontakt", "discoveredContacts_Title": "Upptäckta kontakter", "discoveredContacts_contactAdded": "Kontakt tillagd", @@ -1969,13 +2036,13 @@ "usbErrorInvalidPort": "Välj en giltig USB-enhet.", "usbErrorBusy": "En annan förfrågan om USB-anslutning är redan pågående.", "usbErrorNotConnected": "Ingen USB-enhet är ansluten.", - "usbErrorOpenFailed": "Misslyckades med att öppna det valda USB-enheten.", - "usbErrorConnectFailed": "Kunde inte ansluta till det valda USB-enheten.", + "usbErrorOpenFailed": "Det gick inte att öppna den valda USB-enheten.", + "usbErrorConnectFailed": "Det gick inte att ansluta till den valda USB-enheten.", "usbErrorUnsupported": "USB-seriell kommunikation stöds inte på denna plattform.", "usbErrorAlreadyActive": "En USB-anslutning är redan aktiv.", "usbErrorNoDeviceSelected": "Ingen USB-enhet valdes.", "usbErrorPortClosed": "USB-anslutningen är inte aktiv.", - "usbFallbackDeviceName": "Web-serieenhet", + "usbFallbackDeviceName": "Web Serial-enhet", "@usbConnectionFailed": { "placeholders": { "error": { @@ -1987,7 +2054,7 @@ "usbStatus_notConnected": "Välj en USB-enhet", "usbConnectionFailed": "Fel vid USB-anslutning: {error}", "usbStatus_searching": "Söker efter USB-enheter...", - "usbErrorConnectTimedOut": "Anslutningen har tidsutgått. Se till att enheten har rätt USB-firmware.", + "usbErrorConnectTimedOut": "Anslutningen tog för lång tid. Kontrollera att enheten har USB Companion-firmware.", "@tcpStatus_connectingTo": { "placeholders": { "endpoint": { @@ -2006,14 +2073,14 @@ "tcpHostLabel": "IP-adress", "tcpScreenTitle": "Anslut via TCP", "connectionChoiceTcpLabel": "TCP", - "tcpPortLabel": "Hamn", + "tcpPortLabel": "Port", "tcpPortHint": "5000", "tcpStatus_notConnected": "Ange slutpunkt och anslut", "tcpStatus_connectingTo": "Anslutning till {endpoint}...", "tcpErrorHostRequired": "IP-adress krävs.", "tcpErrorPortInvalid": "Porten måste vara mellan 1 och 65535.", "tcpErrorUnsupported": "TCP-transport fungerar inte på denna plattform.", - "tcpErrorTimedOut": "TCP-anslutningen har tidsut gått.", + "tcpErrorTimedOut": "Tidsgränsen för TCP-anslutningen överskreds.", "tcpConnectionFailed": "Fel vid TCP-anslutning: {error}", "map_showDiscoveryContacts": "Visa Discovery-kontakter", "map_setAsMyLocation": "Ange som min plats", @@ -2030,9 +2097,9 @@ "settings_privacy": "Inställningar för sekretess", "settings_allowAll": "Tillåt alla", "settings_privacySubtitle": "Kontrollera vilken information som delas.", - "settings_telemetryEnvironmentMode": "Telemetri miljöläge", + "settings_telemetryEnvironmentMode": "Telemetriläge för miljö", "settings_telemetryBaseMode": "Telemetribasläge", - "settings_telemetryLocationMode": "Telemetritillstånd för plats", + "settings_telemetryLocationMode": "Telemetriläge för position", "settings_advertLocation": "Annonsplacering", "contact_info": "Kontaktinformation", "contact_settings": "Kontaktinställningar", @@ -2049,21 +2116,21 @@ "contact_teleBaseSubtitle": "Tillåt delning av batterinivå och grundläggande telemetri", "contact_teleLoc": "Telemetridata plats", "contact_teleLocSubtitle": "Tillåt delning av platsdata", - "appSettings_initialRouteWeightSubtitle": "Initial vikt för nyligen upptäckta vägar", - "appSettings_maxRouteWeight": "Maximalt tillåtet vikt för rutten", - "appSettings_maxRouteWeightSubtitle": "Maximal vikt som en leveransväg kan ackumulera från framgångsrika leveranser.", + "appSettings_initialRouteWeightSubtitle": "Startvikt för nyligen upptäckta rutter", + "appSettings_maxRouteWeight": "Maximal ruttvikt", + "appSettings_maxRouteWeightSubtitle": "Maximal vikt som en rutt kan samla efter lyckade leveranser", "appSettings_initialRouteWeight": "Initial vikt för rutt", "appSettings_routeWeightSuccessIncrement": "Ökning av vikt för framgång", - "appSettings_routeWeightSuccessIncrementSubtitle": "Vikt läggs till en väg efter en lyckad leverans.", + "appSettings_routeWeightSuccessIncrementSubtitle": "Vikt som läggs till en rutt efter en lyckad leverans", "appSettings_routeWeightFailureDecrement": "Minskning av vikten för misslyckande", - "appSettings_routeWeightFailureDecrementSubtitle": "Vikt som tagits bort från en väg efter ett misslyckat leveransförsök", + "appSettings_routeWeightFailureDecrementSubtitle": "Vikt som tas bort från en rutt efter en misslyckad leverans", "appSettings_maxMessageRetries": "Maximalt antal försök", "appSettings_maxMessageRetriesSubtitle": "Antal försök att skicka om ett meddelande innan det markeras som misslyckat.", "path_routeWeight": "{weight}/{max}", "settings_telemetryModeUpdated": "Telemetri-läge uppdaterat", "settings_multiAck": "Flera bekräftelser", "map_showOverlaps": "Repeater-nyckelöverlappningar", - "map_runTraceWithReturnPath": "Gå tillbaka på samma väg", + "map_runTraceWithReturnPath": "Återvänd längs samma rutt.", "@radioStats_noiseFloor": { "placeholders": { "noiseDbm": { @@ -2108,25 +2175,25 @@ }, "appSettings_jumpToOldestUnreadSubtitle": "När du öppnar en chatt med oinlästa meddelanden, scrolla till det första oinlästa meddelandet istället för det senaste.", "chat_sendCooldown": "Vänligen vänta en stund innan du skickar igen.", - "appSettings_jumpToOldestUnread": "Gå direkt till det äldsta, obesvarade meddelandet", - "appSettings_languageHu": "Ungerskt", + "appSettings_jumpToOldestUnread": "Gå till äldsta olästa", + "appSettings_languageHu": "Ungerska", "appSettings_languageJa": "Japanska", "appSettings_languageKo": "Koreanska", "radioStats_tooltip": "Radio- och mesh-statistik", - "radioStats_screenTitle": "Radiostation", + "radioStats_screenTitle": "Radiostatistik", "radioStats_notConnected": "Anslut till en enhet för att visa radiostatistik.", - "radioStats_firmwareTooOld": "Radio statistik kräver kompatibel firmware version 8 eller senare.", + "radioStats_firmwareTooOld": "Radiostatistik kräver Companion-firmware v8 eller senare.", "radioStats_waiting": "Väntar på data…", "radioStats_noiseFloor": "Bakgrundsnivå: {noiseDbm} dBm", "radioStats_lastRssi": "Senaste RSSI-värde: {rssiDbm} dBm", "radioStats_lastSnr": "Senaste SNR: {snr} dB", "radioStats_txAir": "TX-tid (total): {seconds} sekunder", "radioStats_rxAir": "RX-tid (total): {seconds} s", - "radioStats_chartCaption": "Ljudnivå (dBm) baserat på de senaste mätningarna.", + "radioStats_chartCaption": "Brusgolv (dBm) för de senaste mätningarna.", "radioStats_stripNoise": "Bakgrundsnivå: {noiseDbm} dBm", "radioStats_stripWaiting": "Hämtar radiostatistik…", - "radioStats_settingsTile": "Radiostation", - "radioStats_settingsSubtitle": "Bakgrundsnivå, RSSI, SNR och tillgänglig tid", + "radioStats_settingsTile": "Radiostatistik", + "radioStats_settingsSubtitle": "Brusgolv, RSSI, SNR och sändningstid", "@translation_downloadFailed": { "placeholders": { "error": { @@ -2140,16 +2207,16 @@ "translation_composerTitle": "Översätt innan du skickar", "translation_composerSubtitle": "Styr standardtillståndet för kompositorns översättningsikon.", "translation_autoIncomingTitle": "Översätt meddelanden automatiskt", - "translation_autoIncomingSubtitle": "Översätter meddelanden automatiskt för aviseringar och för chattar eller kanaler.", + "translation_autoIncomingSubtitle": "Översätter meddelanden automatiskt för notifieringar samt för chattar och kanaler.", "translation_translateMessage": "Översätt meddelande", - "translation_targetLanguage": "Målmedvetet språk", + "translation_targetLanguage": "Målspråk", "translation_useAppLanguage": "Använd appens språk", "translation_downloadedModelLabel": "Nedladdad modell", - "translation_presetModelLabel": "Fördefinierat Hugging Face-modell", - "translation_manualUrlLabel": "Manualens URL", + "translation_presetModelLabel": "Fördefinierad Hugging Face-modell", + "translation_manualUrlLabel": "Manuell modell-URL", "translation_downloadModel": "Ladda ner modellen", "translation_downloading": "Nedladdning...", - "translation_working": "Arbeta...", + "translation_working": "Arbetar…", "translation_stop": "Stopp", "translation_mergingChunks": "Slå samman de nedladdade delarna till en slutlig fil...", "translation_downloadedModels": "Nedladdade modeller", @@ -2193,20 +2260,20 @@ }, "repeater_clockSyncAfterLoginSubtitle": "Automatiskt skicka \"klocksynkronisering\" efter en lyckad inloggning.", "repeater_clockSyncAfterLogin": "Synkronisera klockan efter inloggning", - "repeater_guest": "Information om repetorer", + "repeater_guest": "Repeaterinformation", "chat_sendMessage": "Skicka meddelande", "repeater_guestTools": "Gästverktyg", - "room_guest": "Information om servern", + "room_guest": "Rumsserverinformation", "repeater_getCategory": "Hämta värden", "repeater_powerMgmt": "Effektstyrning", "repeater_sensors": "Sensorer", "repeater_cliHelpPowerOff": "Stänger av enheten. (ingen respons förväntas)", "repeater_cliHelpClkReboot": "Återställer klockan till en känd tidpunkt och startar om enheten.", - "repeater_cliHelpAdvertZeroHop": "Skickar en annons som når endast direkt grannar (endast närmaste grannar).", + "repeater_cliHelpAdvertZeroHop": "Skickar en nollhoppsannons (endast direkta grannar).", "repeater_cliHelpStartOta": "Startar en firmware-uppdatering via luft, på kompatibla enheter.", "repeater_cliHelpTime": "Ställer enheten till den angivna Unix-epokens tid. Klockan kan inte gå bakåt.", "repeater_cliHelpBoard": "Visar tillverkaren av moderkortet / hårdvaru-identifieraren.", - "repeater_cliHelpDiscoverNeighbors": "Skickar en förfrågan om att upptäcka närliggande noder. (Endast för repetrar)", + "repeater_cliHelpDiscoverNeighbors": "Skickar en begäran om nodupptäckt till närliggande grannar. (Endast repeater.)", "repeater_cliHelpPowersaving": "Visar om energisparläget är aktiverat eller avstängt.", "repeater_cliHelpPowersavingOnOff": "Aktiverar eller inaktiverar energisparläget (om det stöds).", "repeater_cliHelpErase": "(Endast för seriell kommunikation) Formaterar enhetens filsystem. Raderar alla inställningar och kontakter.", @@ -2215,16 +2282,16 @@ "repeater_cliHelpSetRadioRxGain": "(Endast SX126x) Aktiverar förstärkt mottagargain för förbättrad känslighet vid högre strömförbrukning.", "repeater_cliHelpSetOwnerInfo": "Anger kontaktinformationen som ska inkluderas i annonserna. Använd '|' för att separera olika fält.", "repeater_cliHelpSetPathHashMode": "Definierar läget för hash-baserad ruttning. 0 = äldre läge, 1 = standard, 2 = strikt. Påverkar hur ruttvägar matchas.", - "repeater_cliHelpSetLoopDetect": "Ställer in känsligheten för att detektera loopar i routningen: av, minimal, måttlig eller strikt.", + "repeater_cliHelpSetLoopDetect": "Ställer in känsligheten för detektering av routingloopar: av, minimal, måttlig eller strikt.", "repeater_cliHelpSetFreq": "(Endast för seriell kommunikation) Ställer snabbt bara frekvensen. Kräver omstart. Föredrar \"ställ radio\" för att få full kontroll över radioinställningarna.", "repeater_cliHelpSetBridgeChannel": "(Endast ESPNow-brygga) Anger WiFi-kanalen (1-14) som används av bryggan.", "repeater_cliHelpGetName": "Visar det konfigurerade nodnamnet.", - "repeater_cliHelpGetRole": "Visar firmware-funktionen (Repeater, Room Server, etc.).", + "repeater_cliHelpGetRole": "Visar firmware-rollen (repeater, rumsserver osv.).", "repeater_cliHelpGetPublicKey": "Visar enhetens publika nyckel.", "repeater_cliHelpGetPrvKey": "(Endast för seriell användning) Visar enheters privata nyckel. Behandla detta som en hemlighet.", "repeater_cliHelpGetRepeat": "Visar om funktionen för att vidarebefordra paket (som en repeater) är aktiverad eller inaktiverad.", "repeater_cliHelpGetTx": "Visar aktuell TX-effekt i dBm.", - "repeater_cliHelpGetFreq": "Visar den konfigurerade radiovågen i MHz.", + "repeater_cliHelpGetFreq": "Visar den konfigurerade radiofrekvensen i MHz.", "repeater_cliHelpGetRadio": "Visar alla radioparametrar: frekvens, bandbredd, spridningsfaktor, kodningshastighet.", "repeater_cliHelpGetRadioRxGain": "(Endast för SX126x) Visar RX:s förstärkningstillstånd.", "repeater_cliHelpGetAf": "Visar aktuell tidssats.", @@ -2233,19 +2300,19 @@ "repeater_cliHelpGetAgcResetInterval": "Visar återställningsintervallet för AGC i sekunder.", "repeater_cliHelpGetMultiAcks": "Visar om dubbelbekräftelseläget är aktiverat (1) eller avstängt (0).", "repeater_cliHelpGetAllowReadOnly": "Visar om gäst har tillåtelse att endast läsa.", - "repeater_cliHelpGetAdvertInterval": "Visar den lokala reklampausens längd i minuter.", - "repeater_cliHelpGetFloodAdvertInterval": "Visar tidsintervallet för reklamsegmentet under översvämningen, i timmar.", + "repeater_cliHelpGetAdvertInterval": "Visar intervallet för lokala annonseringar i minuter.", + "repeater_cliHelpGetFloodAdvertInterval": "Visar intervallet för flood-annonseringar i timmar.", "repeater_cliHelpGetGuestPassword": "Visar det angivna gästlösen.", "repeater_cliHelpGetLat": "Visar den angivna latituden.", "repeater_cliHelpGetLon": "Visar den angivna longituden.", "repeater_cliHelpGetRxDelay": "Visar grundvärdet för rxdelay.", - "repeater_cliHelpGetTxDelay": "Visar faktor för fördröjning i flödesläge.", + "repeater_cliHelpGetTxDelay": "Visar txdelay-faktorn för flood-läge.", "repeater_cliHelpGetDirectTxDelay": "Visar faktorn för fördröjning i direktläge.", - "repeater_cliHelpGetFloodMax": "Visar det maximala antalet gånger en översvämning har inträffat.", + "repeater_cliHelpGetFloodMax": "Visar maximalt antal flood-hopp.", "repeater_cliHelpGetOwnerInfo": "Visar strängen med kontaktinformation för ägaren.", - "repeater_cliHelpGetPathHashMode": "Visar hash-läge (0/1/2).", + "repeater_cliHelpGetPathHashMode": "Visar läget för rutthash (0/1/2).", "repeater_cliHelpGetLoopDetect": "Visar känsligheten för att detektera loopar.", - "repeater_cliHelpGetAcl": "(Endast för serier) Visar åtkomstkontrollinställningarna för en repeater.", + "repeater_cliHelpGetAcl": "Visar åtkomstkontrollposterna på en repeater. (Endast seriell anslutning.)", "repeater_cliHelpGetBridgeEnabled": "Visar om bron är aktiverad.", "repeater_cliHelpGetBridgeDelay": "Visar fördröjningen i bron i millisekunder.", "repeater_cliHelpGetBridgeSource": "Visar om bron skickar RX- eller TX-paket.", @@ -2254,24 +2321,24 @@ "repeater_cliHelpGetBridgeSecret": "(Endast ESPNow-brygga) Visar bryggans delade hemlighet.", "repeater_cliHelpGetBootloaderVer": "(Endast för NRF52) Visar versionen av bootloadern.", "repeater_cliHelpGetAdcMultiplier": "Visar ADC-multiplikatorn (skalning av batterispänning).", - "repeater_cliHelpGetPwrMgtSupport": "Anger om styrelsen har stöd för energihantering.", + "repeater_cliHelpGetPwrMgtSupport": "Anger om kortet har stöd för strömhantering.", "repeater_cliHelpGetPwrMgtSource": "Visar aktuell strömkälla: extern eller batteri.", "repeater_cliHelpGetPwrMgtBootReason": "Visar de senaste orsakerna till återställning och avstängning.", "repeater_cliHelpGetPwrMgtBootMv": "Visar batterispänningen vid start i millivolt (mV).", - "repeater_cliHelpSensorGet": "Läser en anpassad sensorinställning via tangentbordet.", + "repeater_cliHelpSensorGet": "Läser en anpassad sensorinställning via nyckel.", "repeater_cliHelpSensorSet": "Skapar en anpassad inställning för en sensor.", "repeater_cliHelpSensorList": "Visar alla anpassade sensorinställningar, sorterade från ett valfritt startindex.", "repeater_cliHelpRegionDefault": "Visar det aktuella standardområde.", "repeater_cliHelpRegionDefaultSet": "Definierar standardområde. Använd \"\" för att återställa till standard.", - "repeater_cliHelpRegionListAllowed": "Lista områden där det är tillåtet med trafik under översvämningsförhållanden.", - "repeater_cliHelpRegionListDenied": "Listar områden där trafik på grund av översvämningar är förbjuden.", + "repeater_cliHelpRegionListAllowed": "Listar regioner som tillåter flood-trafik.", + "repeater_cliHelpRegionListDenied": "Listar regioner som blockerar flood-trafik.", "repeater_cliHelpStatsPackets": "(Endast för seriell kommunikation) Visar statistik på paketnivå.", - "repeater_cliHelpStatsRadio": "(Enbart för serier) Visar radiostatistik.", + "repeater_cliHelpStatsRadio": "(Endast seriell anslutning) Visar radiostatistik.", "repeater_cliHelpStatsCore": "(Enbart för seriell kommunikation) Visar grundläggande firmware-statistik.", - "common_done": "Done", - "background_serviceTitle": "MeshCore running", - "background_serviceText": "Keeping BLE connected", - "appSettings_translationModelDeleted": "Deleted {name}", + "common_done": "Klar", + "background_serviceTitle": "MeshCore körs", + "background_serviceText": "Håller BLE-anslutningen aktiv", + "appSettings_translationModelDeleted": "Tog bort {name}", "@appSettings_translationModelDeleted": { "placeholders": { "name": { @@ -2279,7 +2346,7 @@ } } }, - "appSettings_translationModelDeleteFailed": "Failed to delete: {error}", + "appSettings_translationModelDeleteFailed": "Det gick inte att ta bort: {error}", "@appSettings_translationModelDeleteFailed": { "placeholders": { "error": { @@ -2287,7 +2354,7 @@ } } }, - "channels_channelUpdateFailed": "Failed to update channel: {error}", + "channels_channelUpdateFailed": "Det gick inte att uppdatera kanalen: {error}", "@channels_channelUpdateFailed": { "placeholders": { "error": { @@ -2295,19 +2362,19 @@ } } }, - "map_type": "Type", - "map_path": "Path", - "map_location": "Location", - "map_estLocation": "Est. Location", - "map_publicKey": "Public Key", - "map_publicKeyPrefixHint": "e.g. ab12", - "contact_typeChat": "Chat", + "map_type": "Typ", + "map_path": "Rutt", + "map_location": "Plats", + "map_estLocation": "Uppskattad plats", + "map_publicKey": "Publik nyckel", + "map_publicKeyPrefixHint": "t.ex. ab12", + "contact_typeChat": "Chatt", "contact_typeRepeater": "Repeater", - "contact_typeRoom": "Room", + "contact_typeRoom": "Rum", "contact_typeSensor": "Sensor", - "contact_typeUnknown": "Unknown", + "contact_typeUnknown": "Okänd", "channels_via": "via {path}", - "chat_score": "Score", + "chat_score": "Poäng", "map_sharedAt": "Delad", "@losBlockedSpotChip": { "placeholders": { @@ -2345,12 +2412,12 @@ } }, "losBlockedSpotChip": "{distance} {distanceUnit} • {obstruction} {heightUnit}", - "losBlockedSpotsTitle": "Reserverade platser", - "losSelectedObstructionTitle": "Vald hinder", + "losBlockedSpotsTitle": "Blockerade punkter", + "losSelectedObstructionTitle": "Valt hinder", "losBlockedSpotsHint": "Klicka på en markerad plats för att framhäva den på kartan.", - "losSelectedObstructionDetails": "Blocked by {obstruction} {heightUnit}, {distanceFromA} from A and {distanceFromB} from B ({distanceUnit}).", + "losSelectedObstructionDetails": "Blockerad av {obstruction} {heightUnit}, {distanceFromA} från A och {distanceFromB} från B ({distanceUnit}).", "chat_markAsUnread": "Markera som oläst", - "settings_companionDebugLog": "Följande felsökningslogg", + "settings_companionDebugLog": "Companion-felsökningslogg", "chat_newMessages": "Nya meddelanden", "settings_companionDebugLogSubtitle": "BLE/TCP/USB-kommandon, svar och rådata", "repeater_chanUtil": "Användning av kanal", @@ -2392,57 +2459,57 @@ } } }, - "messageStatus_sent": "Sen", - "messageStatus_delivered": "Levererad", + "messageStatus_sent": "Skickat", + "messageStatus_delivered": "Levererat", "common_undo": "Ångra", - "messageStatus_pending": "Skicka", + "messageStatus_pending": "Skickar", "messageStatus_failed": "Misslyckades med att skicka", "messageStatus_repeated": "Hördes upprepade gånger", "contacts_moreOptions": "Fler alternativ", "contacts_searchOpen": "Sök efter kontakter", - "contacts_searchClose": "Avancerad sökning", + "contacts_searchClose": "Stäng sökning", "routing_title": "Ruttplanering", - "routing_modeAuto": "Bil", - "routing_modeFlood": "Översvämning", - "routing_modeManual": "Instruktioner", - "routing_modeAutoHint": "Väljer automatiskt den bästa kända vägen, och använder en \"flooding\"-strategi om ingen väg är känd.", - "routing_modeFloodHint": "Sändningar via alla repetrar. Det mest pålitliga alternativet, men kräver mer sändtid.", - "routing_modeManualHint": "Skickar alltid den exakta väg du har angivit.", + "routing_modeAuto": "Automatisk", + "routing_modeFlood": "Flood-trafik", + "routing_modeManual": "Manuell", + "routing_modeAutoHint": "Väljer automatiskt den bästa kända rutten och använder flood när ingen rutt är känd.", + "routing_modeFloodHint": "Sänder via alla repeatrar. Mest tillförlitligt, men använder mer sändningstid.", + "routing_modeManualHint": "Skickar alltid längs exakt den rutt du anger.", "routing_currentRoute": "Nuvarande rutt", - "routing_directNoHops": "Direkt – utan mellanliggande routrar", - "routing_noPathYet": "Ingen väg hittad ännu. Nästa meddelande skickas tills en rutt har upptäckts.", - "routing_floodBroadcast": "Sändas via alla repetrar", - "routing_editPath": "Redigera sökväg", - "routing_forgetPath": "Glöm vägen", - "routing_knownPaths": "Kända vägar", - "routing_knownPathsHint": "Välj en väg för att byta till den.", + "routing_directNoHops": "Direkt — inga repeaterhopp", + "routing_noPathYet": "Ingen rutt ännu. Nästa meddelande floodas tills en rutt hittas.", + "routing_floodBroadcast": "Sänd via varje repeater", + "routing_editPath": "Redigera rutt", + "routing_forgetPath": "Glöm rutt", + "routing_knownPaths": "Kända rutter", + "routing_knownPathsHint": "Tryck på en rutt för att byta till den.", "routing_inUse": "I användning", - "routing_qualityStrong": "En stark start", - "routing_qualityGood": "Bra första steg", + "routing_qualityStrong": "Starkt första hopp", + "routing_qualityGood": "Bra första hopp", "routing_qualityFair": "Bra första hopp", "routing_qualityWorked": "Har levererat", - "routing_qualityFlood": "Fått information via nyhetsflöde", + "routing_qualityFlood": "Hörd via flood", "routing_qualityUntested": "Ej testat", - "routing_lastWorked": "arbetade {when}", + "routing_lastWorked": "fungerade {when}", "routing_neverWorked": "aldrig bekräftat", - "routing_floodDelivery": "Leverans vid översvämningsområde", - "pathEditor_title": "Skapa väg", - "pathEditor_hopCounter": "{count} av 64 humlor", - "pathEditor_noHops": "Inga humle än. Använd knapparna nedan för att lägga till dem i rätt ordning, eller spara utan humle för att skicka direkt.", - "pathEditor_addHops": "Tillsätt humlen i rätt ordning.", - "pathEditor_searchRepeaters": "Sök efter återupptagna samtal", - "pathEditor_advancedHex": "Avancerat: rå hex-sökväg", + "routing_floodDelivery": "Flood-leverans", + "pathEditor_title": "Skapa rutt", + "pathEditor_hopCounter": "{count} av 64 hopp", + "pathEditor_noHops": "Inga hopp ännu. Tryck på repeaters nedan för att lägga till dem i ordning, eller spara utan hopp för att skicka direkt.", + "pathEditor_addHops": "Lägg till hopp i ordning", + "pathEditor_searchRepeaters": "Sök repeaters", + "pathEditor_advancedHex": "Avancerat: rå rutt i hexformat", "pathEditor_hexLabel": "Hex-prefikser", - "pathEditor_hexHelper": "Två hex-tecken per steg, separerade med kommatecken.", + "pathEditor_hexHelper": "Två hextecken per hopp, separerade med kommatecken", "pathEditor_invalidTokens": "Ogiltigt: {tokens}", - "pathEditor_tooManyHops": "Maximalt 64 humlörter", - "pathEditor_usePath": "Använd denna väg", - "pathEditor_removeHop": "Ta bort humlen", - "pathEditor_unknownHop": "Okänd förstärkare", + "pathEditor_tooManyHops": "Maximalt 64 hopp", + "pathEditor_usePath": "Använd den här rutten", + "pathEditor_removeHop": "Ta bort hopp", + "pathEditor_unknownHop": "Okänd repeater", "map_zoomIn": "Zooma in", - "routing_deliveryCounts": "{successes} delivered, {failures} failed", + "routing_deliveryCounts": "{successes} levererade, {failures} misslyckade", "map_zoomOut": "Zooma ut", - "map_centerMap": "Kartöversikt", + "map_centerMap": "Centrera kartan", "chrome_bluetoothRequiresChromium": "Web Bluetooth kräver en Chromium-baserad webbläsare.", "channels_communityShortId": "ID: {id}...", "pathTrace_legendGpsConfirmed": "GPS-verifierat", @@ -2524,21 +2591,276 @@ "pathMap_animationOn": "Visa paketanimering", "pathMap_animationOff": "Dölj paketanimering", "pathMap_hopOf": "Hopp {current} av {total}", - "pathMap_observedPaths": "Observerade vägar: {count}", + "pathMap_observedPaths": "Observerade rutter: {count}", "pathMap_primary": "Primär", "pathMap_alternate": "Alternativ {index}", "pathMap_hopCount": "{count, plural, =1{1 hopp} other{{count} hopp}}", "pathMap_legendShared": "Delat segment", "pathMap_legendEstimated": "Uppskattat segment", - "pathMap_sharedNodeCount": "Används av {count} vägar", - "pathMap_partialAnimation": "{count, plural, =1{1 hopp saknar position — den visade vägen är ofullständig} other{{count} hopp saknar position — den visade vägen är ofullständig}}", + "pathMap_sharedNodeCount": "Används av {count} rutter", + "pathMap_partialAnimation": "{count, plural, =1{1 hopp saknar position — den visade rutten är ofullständig} other{{count} hopp saknar position — den visade rutten är ofullständig}}", "pathMap_showAllPaths": "Visa allt", - "pathMap_hidePath": "Dölj väg", - "pathMap_showPath": "Visa väg", + "pathMap_hidePath": "Dölj rutt", + "pathMap_showPath": "Visa rutt", "pathMap_collapsePanel": "Fäll ihop panel", "pathMap_expandPanel": "Expandera panel", "pathMap_noLocation": "Ingen position", "pathMap_unfollowPacket": "Lås upp vy från paket", "pathMap_followPacket": "Lås vy till paket", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Regioner", + "settings_regionSettingsSubtitle": "Hämtade regioner", + "settings_regionManagement_screenTitle": "Regionhantering", + "settings_regionNameHint": "Ange regionnamn", + "settings_regionAddRegion": "Lägg till region", + "settings_regionFetchRegions": "Hämta regioner från repeaters", + "settings_regionFetchRegionsFail": "Ingen region hittades", + "settings_regionFetchRegionsAlreadyExists": "Den här regionen har redan lagts till", + "settings_regionName": "Regionnamn", + "settings_regionDeleted": "Regionen har tagits bort", + "settings_deleteRegion": "Radera region", + "settings_deleteRegionConfirm": "Ta bort “{region}” från regionlistan?", + "settings_infoHardware": "Hardware", + "settings_infoFirmware": "Firmware", + "repeater_pathHashModeOption0": "0 - 1 byte", + "repeater_pathHashModeOption1": "1 - 2 byte", + "repeater_pathHashModeOption2": "2 - 3 byte", + "repeater_pathHashModeOption3": "3 - 4 byte", + "appSettings_batteryLipoHv": "LiPo HV (3,0-4,35 V)", + "channels_regionSetTo": "Region: {region}", + "channels_regionNotSet": "Region: ingen", + "channels_regionSelect_Title": "Välj en region", + "channels_clearRegion": "Rensa region", + "chat_sendImageLora": "Skicka bild via MeshCore", + "chat_imagePickFailed": "Kunde inte öppna bilden", + "chat_receivedGif": "Mottagit en GIF", + "repeater_keySettings": "Ändra identitetsnyckel", + "repeater_keySettingsSubtitle": "Ändra det publika/privata nyckelparet", + "repeater_prvKey": "Privat nyckel", + "repeater_prvKeyHelper": "En ny privat nyckel för repeatern, en hexsträng med 128 tecken.", + "repeater_generatePrvKey": "Generera ett slumpmässigt nyckelpar", + "repeater_stopGeneratingPrvKey": "Avbryt sökning efter nyckelpar", + "repeater_pubKey": "Publik nyckel", + "repeater_pubKeyHelper": "Det här är den publika nyckeln som hör till den genererade privata nyckeln. Den kan inte anges direkt.", + "repeater_pubKeyPrefix": "Önskad prefix", + "repeater_pubKeyPrefixHelper": "Hitta en publik nyckel som börjar med dessa hexsiffror. Förväntat antal försök: {tries}.", + "imageMessages_enableTitle": "Aktivera bildmeddelanden", + "imageMessages_enableSubtitle": "Skicka bilder över meshnätet. Kräver en engångsnedladdning av bildmodellen.", + "imageMessages_modelSectionTitle": "Bildmodell", + "imageMessages_downloadModel": "Ladda ned", + "imageMessages_cancelDownload": "Avbryt", + "imageMessages_removeModel": "Ta bort modellen", + "imageMessages_modelReady": "Färdig", + "imageMessages_modelNotPublished": "Inte publicerad ännu — den här versionen kan inte ladda ned den.", + "imageMessages_downloadFailed": "Bildmodellen kunde inte laddas ner.", + "imageMessages_autoProcessTitle": "Bearbeta bilder automatiskt", + "imageMessages_autoProcessSubtitle": "Rekonstruera varje bild så snart den kommer. Använder cirka 2 GB minne i ungefär en sekund varje gång; låt detta vara avstängt om du hellre vill rekonstruera med ett tryck.", + "imageSend_title": "Skicka bild", + "imageSend_cropNote": "Storleksändrad till 512 × 512 · bildförhållandet bevaras inte", + "imageSend_originalSize": "Original", + "imageSend_onAirSize": "Överförd storlek", + "imageSend_quality": "Kvalitet", + "imageSend_qualityStandard": "Standard", + "imageSend_qualityHigh": "Hög", + "imageSend_packetsLabel": "Paket", + "imageSend_airtimeLabel": "Sändningstid", + "imageSend_sizeLabel": "Nyttolast", + "imageSend_packetsCount": "{count} {count, plural, =1{paket} other{paket}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Radioindikatorer inte kända", + "imageSend_radioUnknownBody": "Anslut till en enhet så att sändningstiden kan beräknas.", + "imageSend_longSendTitle": "Lång överföring", + "imageSend_longSendBody": "Det här kommer att hålla kanalen upptagen i ungefär {duration}.", + "imageSend_floodNote": "Flood-routing: varje repeater inom räckvidd sänder om varje paket, så kanalen hålls upptagen längre än så här.", + "imageSend_parityTitle": "Lägg till återställningspaket", + "imageSend_paritySubtitle": "Ett extra paket. Gruppmeddelanden kvitteras inte, så mottagaren kan återskapa bilden om ett enda paket går förlorat.", + "imageSend_send": "Sänd", + "imageSend_cancel": "Avbryt", + "imageSend_encodeFailed": "Denna bild kan inte kodas.", + "imageSend_codecDownloading": "Bildmodellen laddas fortfarande ned.", + "imageSend_codecUnavailable": "Bildsändning är inte tillgänglig på den här enheten.", + "imageSend_codecDisabled": "Bildmeddelanden är avstängda i inställningarna.", + "imageSend_deviceUnsupported": "Den här radion kan inte skicka bildpaket. Anslut en enhet med Companion-firmware 13 eller senare.", + "imageSend_directMessagesUnsupported": "Bilder skickas som gruppdata och kan därför bara skickas till en kanal — inte som direktmeddelande.", + "imageSend_tooLarge": "Bilden kodades till mer paket än meshformaten tillåter.", + "imageSend_sentConfirmation": "Bilden skickades som {count} {count, plural, =1{paket} other{paket}}.", + "imageSend_sendFailed": "Bilden kunde inte skickas: {error}", + "imageSend_sendingProgress": "Skickar bild — paket {sent} av {total}", + "receivedImage_senderPrefix": "Nod {prefix}", + "receivedImage_incoming": "{received} av {total} paket", + "receivedImage_queued": "Väntar på avkodning", + "receivedImage_tapToDecode": "Tryck för att avkoda", + "receivedImage_decoding": "Rekonstruktion… om 1 sekund", + "receivedImage_incomplete": "Bilden är ofullständig — {received} av {total} paket kom fram", + "receivedImage_corrupt": "Bilden kunde inte rekonstrueras", + "receivedImage_decoderMissing": "Bild mottagen — bildavkodning är avstängd", + "receivedImage_evicted": "Bild inte lagrad längre", + "receivedImage_retry": "Försök igen", + "receivedImage_decodeAgain": "Avkoda igen", + "receivedImage_openSettings": "Konfigurera", + "receivedImage_tapToProcess": "Tryck för att bearbeta", + "receivedImage_awaiting": "{bytes} byte · {packets} {packets, plural, =1{paket} other{paket}}", + "imageSend_secondsValue": "{seconds} sekunder", + "imageSend_minutesSecondsValue": "{minutes} min {seconds} s", + "channels_noFreeSlots": "Alla kanalplatser är upptagna", + "chat_longMessageRetryNote": "Över 158 byte: skickas högst {count} gånger", + "@chat_longMessageRetryNote": { + "description": "Shown under the DM composer when the message is too long for the firmware's later retry attempts", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "repeater_bridgeNote": "Endast tillgängligt på firmware byggd med en brygga (RS232 eller ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Visar det maximala antalet hopp för flood-annonser.", + "repeater_cliHelpGetFloodMaxUnscoped": "Visar det maximala antalet hopp för flood-paket utan regionscope.", + "repeater_cliHelpGetRadioFemRxGain": "Visar om LoRa-frontändmodulens RX-gain är påslagen.", + "repeater_cliHelpGetRadioFemTxGain": "Visar om LoRa-frontändmodulens TX-gain är påslagen.", + "repeater_cliHelpRegionDef": "Definierar en kedja av regioner i ett kommando: varje namn läggs till under det föregående; \"name,parent\" lägger till namnet och fortsätter sedan under den angivna föräldern. Svarar med regionlistan.", + "repeater_cliHelpSetFloodMaxAdvert": "Anger det maximala antalet hopp för vidarebefordran av flood-annonser (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Anger det maximala antalet hopp för vidarebefordran av flood-paket utan regionscope (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Växlar LoRa-frontändmodulens RX-gain (LNA). Kort utan denna modul svarar \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Växlar LoRa-frontändmodulens TX-gain (PA). Kort utan denna modul svarar \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Regionladdningsläge: skicka ett regionnamn per rad, indraget med blanksteg under sin förälder (lägg till F efter namnet för att tillåta flood). Rader får inget svar. Skicka en tom rad för att avsluta, och sedan \"region save\" för att spara resultatet.", + "repeater_cliRegionLoadEnd": "(slut på regionladdning)", + "repeater_cliRegionLoadHint": "Regionrad, eller tom för att avsluta", + "repeater_frequencyInvalid": "Ogiltig frekvens (150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "Mottagningsfel", + "repeater_txPowerRangeHelper": "-9 till 30 dBm", + "room_postsPushed": "Skickade inlägg", + "room_postsStored": "Inlägg", + "settings_publicKeyCopied": "Publik nyckel kopierad", + "settings_radioSettingsNotApplied": "Radion tillämpade inte dessa inställningar", + "urlImage_enable": "Aktivera URL-bilder", + "urlImage_possible": "Möjlig URL-bild; aktivera den i Inställningar." } diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 8f82d3d6..5ffaf809 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -101,6 +101,8 @@ "settings_locationInvalid": "Некоректна широта або довгота.", "settings_latitude": "Широта", "settings_longitude": "Довгота", + "settings_autoZeroHopAdvertOnGpsUpdate": "Автооголошення без хопів при оновленні GPS", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "Коли GPS-локація змінюється, надсилати оголошення без хопів (потрібна геопозиція в оголошенні).", "settings_privacyMode": "Режим приватності", "settings_privacyModeSubtitle": "Приховати ім'я/геопозицію в оголошеннях", "settings_privacyModeToggle": "Увімкніть режим приватності, щоб приховати своє ім'я та геопозицію в оголошеннях.", @@ -242,6 +244,19 @@ "appSettings_last6Hours": "Останні 6 годин", "appSettings_last24Hours": "Останні 24 години", "appSettings_lastWeek": "Минулий тиждень", + "appSettings_rasterTileSource": "Джерело растрових тайлів", + "appSettings_stadiaEndpoint": "Кінцева точка Stadia", + "appSettings_stadiaApiKey": "Ключ API Stadia", + "appSettings_stadiaApiKeyRequired": "Потрібно для використання Stadia Maps", + "appSettings_stadiaApiKeyConfigured": "Налаштовано: {maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "Введіть свій ключ API Stadia Maps. Програма використовує його для запитів растрових тайлів.", "appSettings_offlineMapCache": "Офлайн-кеш карти", "appSettings_noAreaSelected": "Область не вибрано", "appSettings_areaSelectedZoom": "Вибрана область (зум {minZoom}-{maxZoom})", @@ -473,6 +488,7 @@ } } }, + "chat_selectSendAction": "Виберіть дію надсилання", "chat_sendGif": "Надіслати GIF", "chat_reply": "Відповісти", "chat_addReaction": "Додати реакцію", @@ -779,6 +795,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "Пн {north}, Пд {south}, Сх {east}, Зх {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1112,14 +1178,14 @@ "repeater_ownerInfo": "Інформація про оператора", "repeater_ownerInfoHelper": "Публічні метадані для цього ретранслятора", "repeater_refreshOwnerInfo": "Оновити інформацію про оператора", - "repeater_floodMax": "Максимальна кількість стрибків під час повені", + "repeater_floodMax": "Максимальна кількість переходів під час поширення через всю мережу (flood)", "repeater_floodMaxHelper": "Максимальна кількість хмелю, яку може містити один пакет (0-64)", "repeater_advancedSettings": "Просунутий", "repeater_advancedSettingsSubtitle": "Регулювальні ручки для досвідчених операторів", "repeater_pathHashMode": "Режим хешування шляху", - "repeater_pathHashModeHelper": "Байти, що використовуються для кодування ідентифікатора цього ретранслятора в тегах для виявлення потоків/петлі. 0=1 байт (256 ідентифікаторів, до 64 перехідів), 1=2 байти (65 000 ідентифікаторів, до 32 перехідів), 2=3 байти (16 мільйонів ідентифікаторів, до 21 переходу). Версії 1.13 та старіші не підтримують багатобайтні шляхи — вони активуються лише після того, як мережа буде оновлена до версії 1.14+.", + "repeater_pathHashModeHelper": "Байти, що використовуються для кодування ідентифікатора цього ретранслятора в тегах flood-шляху/виявлення петель. 0=1 байт (256 ідентифікаторів, до 64 переходів), 1=2 байти (65 000 ідентифікаторів, до 32 переходів), 2=3 байти (16 мільйонів ідентифікаторів, до 21 переходу). Прошивки до v1.14 завжди використовували 1-байтові шляхи; v1.14 і новіші можна налаштувати на 2- або 3-байтові шляхи.", "repeater_txDelay": "Затримка у Flood, штат Техас", - "repeater_txDelayHelper": "Повторне надсилання з урахуванням навантаження від потоків транспорту, як множник від часу передачі пакета (0-2, за замовчуванням 0,5). Чим вище значення, тим менше конфліктів, але повільніше передавання.", + "repeater_txDelayHelper": "Затримка повторного надсилання для трафіку через всю мережу (flood), як множник від часу передачі пакета (0-2, за замовчуванням 0,5). Чим вище значення, тим менше конфліктів, але повільніше передавання.", "repeater_directTxDelay": "Пряме затримка TX", "repeater_directTxDelayHelper": "Відновлення інтервалів для прямого (немасового) трафіку, як множник часу передачі пакета (від 0 до 2, за замовчуванням 0,3).", "repeater_intThresh": "Порогове значення перешкод", @@ -1127,10 +1193,10 @@ "repeater_agcResetInterval": "Інтервал перезавантаження AGC", "repeater_agcResetIntervalHelper": "Як часто потрібно скидати автоматичне регулювання гучності радіо, щоб відновити нормальну роботу після ситуації, коли гучність була заблокована. Кожні кілька секунд, зменшуючи значення до кратного 4. Вимкнення періодичного скидання.", "repeater_actionsTitle": "Дії", - "repeater_sendAdvert": "Надіслати рекламу щодо повені", - "repeater_sendAdvertSubtitle": "Розповсюдити рекламу про надзвичайну ситуацію (повен) через мережу.", - "repeater_sendAdvertZeroHop": "Надіслати рекламу без посередників", - "repeater_sendAdvertZeroHopSubtitle": "Розповсюдити рекламу з однією переадресацією (без повторного розповсюдження)", + "repeater_sendAdvert": "Надіслати оголошення через всю мережу (flood)", + "repeater_sendAdvertSubtitle": "Розповсюдити оголошення через всю мережу (flood).", + "repeater_sendAdvertZeroHop": "Надіслати оголошення без ретрансляції", + "repeater_sendAdvertZeroHopSubtitle": "Розповсюдити оголошення лише на один перехід (без ретрансляторів)", "repeater_clockSync": "Синхронізувати годинник зараз", "repeater_clockSyncSubtitle": "Передайте час вашого телефону на ретранслятор.", "repeater_actionSucceeded": "{action} succeeded", @@ -1701,7 +1767,7 @@ "contacts_contactImported": "Контакт було імпортовано.", "contacts_contactImportFailed": "Контакт не вдалось імпортувати", "contacts_zeroHopAdvert": "Оголошення без ретрансляції", - "contacts_floodAdvert": "Оголошення з ретрансляцією", + "contacts_floodAdvert": "Оголошення через всю мережу (flood)", "contacts_copyAdvertToClipboard": "Копіювати оголошення", "contacts_clipboardEmpty": "Буфер обміну порожній", "appSettings_languageRu": "Російська", @@ -2211,7 +2277,7 @@ "repeater_sensors": "Датчики", "repeater_cliHelpPowerOff": "Вмикає живлення пристрою. (очікується відсутність відповіді)", "repeater_cliHelpClkReboot": "Скидає годинник до відомої епохи та перезавантажує пристрій.", - "repeater_cliHelpAdvertZeroHop": "Надсилає рекламу, яка не проходить через інші мережі (лише до безпосередніх сусідів).", + "repeater_cliHelpAdvertZeroHop": "Надсилає оголошення, яке не проходить через інші мережі (лише до безпосередніх сусідів).", "repeater_cliHelpStartOta": "Запускає оновлення прошивки безпосередньо через повітря на сумісних платах.", "repeater_cliHelpTime": "Встановлює час пристрою відповідно до заданих секунд від початку епохи Unix. Час не може відкачуватися назад.", "repeater_cliHelpBoard": "Показує виробника/ідентифікатор обладнання.", @@ -2242,15 +2308,15 @@ "repeater_cliHelpGetAgcResetInterval": "Показує інтервал перезавантаження AGC у секундах.", "repeater_cliHelpGetMultiAcks": "Показує, чи увімкнено режим подвійного підтвердження (1) або вимкнено (0).", "repeater_cliHelpGetAllowReadOnly": "Показує, чи дозволено лише читання для гостей.", - "repeater_cliHelpGetAdvertInterval": "Показує тривалість місцевої рекламної паузи в хвилинах.", - "repeater_cliHelpGetFloodAdvertInterval": "Показує інтервал часу між рекламними роликами про повені, виражений у годинах.", + "repeater_cliHelpGetAdvertInterval": "Показує тривалість інтервалу локальних оголошень у хвилинах.", + "repeater_cliHelpGetFloodAdvertInterval": "Показує інтервал оголошень через всю мережу (flood), виражений у годинах.", "repeater_cliHelpGetGuestPassword": "Відображає налаштований пароль для гостей.", "repeater_cliHelpGetLat": "Відображає задану широту.", "repeater_cliHelpGetLon": "Відображає задану довготу.", "repeater_cliHelpGetRxDelay": "Відображає базове значення rxdelay.", - "repeater_cliHelpGetTxDelay": "Показує коефіцієнт затримки сигналу у режимі затоплення.", + "repeater_cliHelpGetTxDelay": "Показує коефіцієнт затримки сигналу в режимі «через всю мережу» (flood).", "repeater_cliHelpGetDirectTxDelay": "Показує коефіцієнт затримки сигналу в режимі прямого зв'язку.", - "repeater_cliHelpGetFloodMax": "Показує максимальну кількість підйомів, спричинених повенем.", + "repeater_cliHelpGetFloodMax": "Показує максимальну кількість переходів під час пересилання через всю мережу (flood).", "repeater_cliHelpGetOwnerInfo": "Відображає рядок з контактною інформацією власника.", "repeater_cliHelpGetPathHashMode": "Відображає режим хешування шляху (0/1/2).", "repeater_cliHelpGetLoopDetect": "Демонструє чутливість до виявлення циклів.", @@ -2272,8 +2338,8 @@ "repeater_cliHelpSensorList": "Перераховує всі налаштування користувацьких датчиків, розділені на сторінки, починаючи з опціонального індексу початку.", "repeater_cliHelpRegionDefault": "Показує поточний область дії за замовчуванням.", "repeater_cliHelpRegionDefaultSet": "Встановлює значення регіону за замовчуванням. Використовуйте \"\", щоб очистити.", - "repeater_cliHelpRegionListAllowed": "Перелік регіонів, де дозволено рух транспорту під час повені.", - "repeater_cliHelpRegionListDenied": "Перелік регіонів, які забороняють рух транспорту під час повені.", + "repeater_cliHelpRegionListAllowed": "Перелік регіонів, де дозволено поширення через всю мережу (flood).", + "repeater_cliHelpRegionListDenied": "Перелік регіонів, де заборонено поширення через всю мережу (flood).", "repeater_cliHelpStatsPackets": "(Тільки для серійного використання) Відображає статистику на рівні пакетів.", "repeater_cliHelpStatsRadio": "(Тільки для серій) Відображає радіостатистику.", "repeater_cliHelpStatsCore": "(Тільки для серійного використання) Відображає основні статистичні дані про програмне забезпечення.", @@ -2383,9 +2449,9 @@ "contacts_searchClose": "Закрити пошук", "routing_title": "Маршрутизація", "routing_modeAuto": "Автомобіль", - "routing_modeFlood": "Повені", + "routing_modeFlood": "Через всю мережу", "routing_modeManual": "Інструкція", - "routing_modeAutoHint": "Автоматично обирає найкращий відомий шлях, та у разі відсутності відомого шляху, використовує алгоритм \"занурення\".", + "routing_modeAutoHint": "Автоматично обирає найкращий відомий шлях, а за відсутності відомого шляху використовує режим «через всю мережу» (flood).", "routing_modeFloodHint": "Передавання через усі ретранслятори. Найбільш надійний спосіб, але потребує більше часу.", "routing_modeManualHint": "Завжди доставляє точно за вказаним вами маршрутом.", "routing_currentRoute": "Поточний маршрут", @@ -2397,18 +2463,18 @@ "routing_knownPaths": "Відомі маршрути", "routing_knownPathsHint": "Виберіть опцію, щоб переключитися на неї.", "routing_inUse": "У робочому стані", - "routing_qualityStrong": "Сильний перший стрибок", + "routing_qualityStrong": "Сильний перший перехід", "routing_qualityGood": "Чудова перша спроба", "routing_qualityFair": "Перший, але вдалий, крок", "routing_qualityWorked": "Доставлено", - "routing_qualityFlood": "Дізнався через новини", + "routing_qualityFlood": "Отримано через всю мережу (flood)", "routing_qualityUntested": "Не протестовано", "routing_neverWorked": "ніколи не підтверджено", - "routing_floodDelivery": "Доставка під час повені", + "routing_floodDelivery": "Доставка через всю мережу (flood)", "pathEditor_title": "Створити маршрут", "pathEditor_hopCounter": "{count} з 64 штук хмелю", - "pathEditor_noHops": "Ще не додано хміль. Натисніть на відповідні кнопки, щоб додати його в потрібному порядку, або збережіть рецепт без хмілю, щоб відправити його безпосередньо.", - "pathEditor_addHops": "Додавайте хміль у наступній послідовності.", + "pathEditor_noHops": "Ще не додано жодного переходу. Натисніть на відповідні кнопки нижче, щоб додати їх у потрібному порядку, або збережіть шлях без переходів, щоб надіслати напряму.", + "pathEditor_addHops": "Додавайте переходи в потрібному порядку.", "pathEditor_searchRepeaters": "Пошук повторювачів", "pathEditor_advancedHex": "Просунутий рівень: пряма шлях у форматі шестнадцяткової системи.", "pathEditor_hexLabel": "Префікси для шестнадцяткової системи числення", @@ -2418,7 +2484,7 @@ "routing_deliveryCounts": "{successes} delivered, {failures} failed", "pathEditor_tooManyHops": "Максимум 64 хмелеві колоди", "pathEditor_usePath": "Використовуйте цей шлях", - "pathEditor_removeHop": "Видалити хміль", + "pathEditor_removeHop": "Видалити перехід", "pathEditor_unknownHop": "Невідомий ретранслятор", "map_zoomIn": "Увійти в режим збільшення", "map_zoomOut": "Видалити зум", @@ -2520,5 +2586,260 @@ "pathMap_noLocation": "Без геопозиції", "pathMap_followPacket": "Прив'язати вигляд до пакету", "pathMap_unfollowPacket": "Відв'язати вигляд від пакету", - "pathMap_gpsCount": "{confirmed}/{total} GPS" + "pathMap_gpsCount": "{confirmed}/{total} GPS", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "Ріси", + "settings_regionSettingsSubtitle": "Управляти збережених регіонів", + "settings_regionManagement_screenTitle": "Рégіональний управління", + "settings_regionNameHint": "Назва регіону", + "settings_regionAddRegion": "Добачить регіон", + "settings_regionFetchRegions": "Збираємо регіони з репітерів", + "settings_regionFetchRegionsFail": "Ні відкриті регіони", + "settings_regionFetchRegionsAlreadyExists": "Цей регіон вже було доданий", + "settings_regionName": "Ріонна назва", + "settings_regionDeleted": "Ріон витертений", + "settings_deleteRegion": "Видалення регіону", + "settings_deleteRegionConfirm": "Вирішіть \"{region}\" з списку регіонів?", + "settings_infoHardware": "Оборудовання", + "settings_infoFirmware": "Програмне вміст (фirmware)", + "repeater_pathHashModeOption0": "0 - 1 байт", + "repeater_pathHashModeOption1": "1 - 2 байти", + "repeater_pathHashModeOption2": "2 - 3 байти", + "repeater_pathHashModeOption3": "3 - 4 байта", + "appSettings_batteryLipoHv": "ЛиPo HV (3,0-4,35 В)", + "channels_regionSetTo": "Ріон: {region}", + "channels_regionNotSet": "Ріон: нема", + "channels_regionSelect_Title": "Вybірте регіон", + "channels_clearRegion": "Чистя зона", + "chat_sendImageLora": "Надіслати зображення через MeshCore", + "chat_imagePickFailed": "Неможливо відкрити це изображення", + "chat_receivedGif": "Підймовано GIF", + "repeater_keySettings": "Зміна ключів ідентифікації", + "repeater_keySettingsSubtitle": "Замініть публічний/приватний ключ", + "repeater_prvKey": "Приватний ключ", + "repeater_prvKeyHelper": "Нова приватна ключ для репітера, 128-символова штучна штука в шестнадцатеричному форматі.", + "repeater_generatePrvKey": "Синхронізujте ключовий пару", + "repeater_stopGeneratingPrvKey": "Прервити шук ключового пару", + "repeater_pubKey": "Публічна ключ", + "repeater_pubKeyHelper": "Це публична ключ, який пов'язано з створеною приватною ключом. Ви не можете встановлювати його напрямую.", + "repeater_pubKeyPrefix": "Високорейтингове прикінання", + "repeater_pubKeyPrefixHelper": "Найдіть відповідний открытий ключ, який починається ціми шестнадцатыми цифрами. Ожидається кількість потрібних попыток: {tries}.", + "imageMessages_enableTitle": "Підтримка зображень для посилання", + "imageMessages_enableSubtitle": "Пошукуєте изображення через сеть. Вимagaєте однократне скачання моделю изображення.", + "imageMessages_modelSectionTitle": "Модель для зображень", + "imageMessages_downloadModel": "Скачання", + "imageMessages_cancelDownload": "Завершити", + "imageMessages_removeModel": "Видалим модель", + "imageMessages_modelReady": "Готово", + "imageMessages_modelNotPublished": "Щоб не було опубліковано — це версія не дозволяє зробити скачання.", + "imageMessages_downloadFailed": "Модель для зображень не можна сказати.", + "imageMessages_autoProcessTitle": "Автоматично оброблювати obraзи", + "imageMessages_autoProcessSubtitle": "Кожна картинка повинні бути відтворена на мій момент прибуття. Використовує приблизно 2 ГБ пам'яті на кожен раз; відключіть від відтворення за допомогою кlikу.", + "imageSend_title": "Нашкоду зовні\n\n(or more naturally, depending on context)\n\nПошукуєте изображення", + "imageSend_cropNote": "Манітовано до 512 × 512 · соотношення варість не зберігається", + "imageSend_originalSize": "Оригінал", + "imageSend_onAirSize": "На ері", + "imageSend_quality": "Качество", + "imageSend_qualityStandard": "Стандарт", + "imageSend_qualityHigh": "Висок", + "imageSend_packetsLabel": "Пакети", + "imageSend_airtimeLabel": "Час на ері", + "imageSend_sizeLabel": "Підлог", + "imageSend_packetsCount": "{count} {count, plural, one{пакет} few{пакети} many{пакетів} other{пакета}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "Настройки радио неизвестні", + "imageSend_radioUnknownBody": "Залучіться до пристрою, щоб можна було розрахунювати час в етері.", + "imageSend_longSendTitle": "Длуга передача", + "imageSend_longSendBody": "Це забезпечить канал на approximativno {duration} хвилин.", + "imageSend_floodNote": "Поширення через всю мережу (flood): кожен ретранслятор у діапазоні пересилає кожен пакет, тому канал залишається зайнятим довше, ніж зазначено тут.", + "imageSend_parityTitle": "Пакет відновлення", + "imageSend_paritySubtitle": "Один дополний пакет. Групові посилання не відповідають, тому це дозволяє відвідувачу відтворити зображення, якщо один пакет втрачений.", + "imageSend_send": "Пошутить", + "imageSend_cancel": "Завершити", + "imageSend_encodeFailed": "Це изображення не може бути кодировано.", + "imageSend_codecDownloading": "Модель для відтворення изображень ще збирається.", + "imageSend_codecUnavailable": "Постій для відправлення изображень на цьому пристрої не доступний.", + "imageSend_codecDisabled": "Пictesovani posyly wyключені в настройках.", + "imageSend_deviceUnsupported": "Цей радіопередач не може отправляти пакети зображень. Зконнете пристрої, що працює з обладнанням керемонітом компаньєр 13 або новшим.", + "imageSend_directMessagesUnsupported": "Фотографії передаються як дані групою, тому їх можна відправляти лише на канал — не в прямому посилання.", + "imageSend_tooLarge": "Це изображення кодує більше пакітів, ніж дозволяє формат сети.", + "imageSend_sentConfirmation": "Зображення надіслано як {count} {count, plural, =1{пакет} other{пакетів}}.", + "imageSend_sendFailed": "Изображення не можна відправити: {error}", + "imageSend_sendingProgress": "Пошускаємо изображення — пакет {sent} з {total}", + "receivedImage_senderPrefix": "Нод {prefix}", + "receivedImage_incoming": "Підходяче: {received} з {total} пакітів", + "receivedImage_queued": "Очікування розслівання коду", + "receivedImage_tapToDecode": "Кliknite для декодування", + "receivedImage_decoding": "Повноювання… за прибуття 1 с.", + "receivedImage_incomplete": "Образок не повний — {received} з {total} пакітів прибавлено", + "receivedImage_corrupt": "Obraz не можна відтворити", + "receivedImage_decoderMissing": "Під час приємки — розшифровка зображення не вдалося.", + "receivedImage_evicted": "Изображення не зберігається", + "receivedImage_retry": "Попробуй ще раз", + "receivedImage_decodeAgain": "Декодуй ще раз", + "receivedImage_openSettings": "Заведіть", + "receivedImage_tapToProcess": "Кликніть для обробки", + "receivedImage_awaiting": "{bytes} байтів · {packets} {packets, plural, =1{пакет} other{пакетів}}", + "imageSend_secondsValue": "{seconds} секунди", + "imageSend_minutesSecondsValue": "{minutes} хв {seconds} с", + "channels_noFreeSlots": "Немає вільних слотів для каналів", + "chat_longMessageRetryNote": "Понад 158 байтів: надсилається не більше {count} разів", + "reaction_report": "Реакції", + "repeater_bridgeNote": "Доступно лише для прошивки, зібраної з мостом (RS232 або ESP-NOW).", + "repeater_cliHelpGetFloodMaxAdvert": "Показує максимальну кількість переходів для оголошень через всю мережу (flood).", + "repeater_cliHelpGetFloodMaxUnscoped": "Показує максимальну кількість переходів для пакетів через всю мережу (flood) без визначеної області.", + "repeater_cliHelpGetRadioFemRxGain": "Показує, чи увімкнено підсилення RX вхідного модуля LoRa.", + "repeater_cliHelpGetRadioFemTxGain": "Показує, чи увімкнено підсилення TX вхідного модуля LoRa.", + "repeater_cliHelpRegionDef": "Визначає ланцюжок регіонів однією командою: кожне ім’я додається під попереднім; \"name,parent\" додає ім’я і продовжує під вказаним батьківським регіоном. У відповідь повертає список регіонів.", + "repeater_cliHelpSetFloodMaxAdvert": "Встановлює максимальну кількість переходів для пересилання оголошень через всю мережу (flood) (0-64).", + "repeater_cliHelpSetFloodMaxUnscoped": "Встановлює максимальну кількість переходів для пересилання пакетів через всю мережу (flood) без визначеної області регіону (0-64).", + "repeater_cliHelpSetRadioFemRxGain": "Перемикає підсилення RX (LNA) вхідного модуля LoRa. Плати без нього відповідають \"Error: unsupported\".", + "repeater_cliHelpSetRadioFemTxGain": "Перемикає підсилення TX (PA) вхідного модуля LoRa. Плати без нього відповідають \"Error: unsupported\".", + "repeater_cliRegionLoadActive": "Режим завантаження регіонів: надсилайте по одному імені регіону в рядку, з відступом пробілами під батьківським регіоном (додайте F після імені, щоб дозволити поширення через всю мережу). Рядки не отримують відповіді. Надішліть порожній рядок, щоб завершити, а потім \"region save\", щоб зберегти результат.", + "repeater_cliRegionLoadEnd": "(кінець завантаження регіонів)", + "repeater_cliRegionLoadHint": "Рядок регіону або порожній рядок для завершення", + "repeater_frequencyInvalid": "Некоректна частота (150-2500 МГц)", + "repeater_frequencyRangeHelper": "150-2500 МГц", + "repeater_recvErrors": "Помилки прийому", + "repeater_txPowerRangeHelper": "від -9 до 30 dBm", + "room_postsPushed": "Надіслано публікацій", + "room_postsStored": "Публікації", + "settings_publicKeyCopied": "Публічний ключ скопійовано", + "settings_radioSettingsNotApplied": "Радіомодуль не застосував ці налаштування", + "urlImage_enable": "Показувати зображення за URL", + "urlImage_possible": "Можливе зображення за URL; увімкніть це в Налаштуваннях.", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index e7129d19..64b8aa68 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -105,9 +105,11 @@ "settings_locationIntervalInvalid": "间隔时间必须至少为 60 秒,但不超过 86400 秒。", "settings_latitude": "纬度", "settings_longitude": "经度", + "settings_autoZeroHopAdvertOnGpsUpdate": "GPS 更新时自动发送零跳广播", + "settings_autoZeroHopAdvertOnGpsUpdateSubtitle": "当 GPS 位置变化时,发送零跳广播(需要在广播中包含位置)。", "settings_privacyMode": "隐私模式", - "settings_privacyModeSubtitle": "在广告中隐藏姓名/位置", - "settings_privacyModeToggle": "切换隐私模式以在广告中隐藏姓名和位置,保护个人信息。", + "settings_privacyModeSubtitle": "在广播中隐藏姓名/位置", + "settings_privacyModeToggle": "切换隐私模式以在广播中隐藏姓名和位置,保护个人信息。", "settings_privacyModeEnabled": "隐私模式已启用", "settings_privacyModeDisabled": "隐私模式已关闭", "settings_actions": "操作", @@ -254,6 +256,19 @@ "appSettings_last6Hours": "过去6小时", "appSettings_last24Hours": "过去24小时", "appSettings_lastWeek": "上周", + "appSettings_rasterTileSource": "栅格瓦片源", + "appSettings_stadiaEndpoint": "Stadia 端点", + "appSettings_stadiaApiKey": "Stadia API 密钥", + "appSettings_stadiaApiKeyRequired": "使用 Stadia Maps 时必需", + "appSettings_stadiaApiKeyConfigured": "已配置:{maskedKey}", + "@appSettings_stadiaApiKeyConfigured": { + "placeholders": { + "maskedKey": { + "type": "String" + } + } + }, + "appSettings_stadiaApiKeyDialogDescription": "请输入你的 Stadia Maps API 密钥。该应用会使用它来请求栅格瓦片。", "appSettings_offlineMapCache": "离线地图缓存", "appSettings_noAreaSelected": "未选择任何区域", "appSettings_areaSelectedZoom": "已选择区域(缩放 {minZoom} - {maxZoom})", @@ -497,6 +512,7 @@ } } }, + "chat_selectSendAction": "选择发送操作", "chat_sendGif": "发送 GIF", "chat_reply": "回复", "chat_addReaction": "添加表情", @@ -796,6 +812,56 @@ } } }, + "mapCache_cachedTilesLabel": "Cached tiles", + "mapCache_cachedTileSummaryLabel": "Cached tile summary", + "mapCache_bulkDownloadDisabledForSource": "Offline bulk downloads are disabled for {source}.", + "@mapCache_bulkDownloadDisabledForSource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_bulkDownloadDisabledInConfig": "Offline bulk downloads are disabled for {source} in this app configuration.", + "@mapCache_bulkDownloadDisabledInConfig": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summarySource": "Source: {source}", + "@mapCache_summarySource": { + "placeholders": { + "source": { + "type": "String" + } + } + }, + "mapCache_summaryCachedTilesForSource": "Cached tiles for source: {count}", + "@mapCache_summaryCachedTilesForSource": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryCachedInSelection": "Cached in selected area/zoom: {count}", + "@mapCache_summaryCachedInSelection": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mapCache_summaryApproxCacheSize": "Approx cache size: {size}", + "@mapCache_summaryApproxCacheSize": { + "placeholders": { + "size": { + "type": "String" + } + } + }, "mapCache_boundsLabel": "北 {north}, 南 {south}, 东 {east}, 西 {west}", "@mapCache_boundsLabel": { "placeholders": { @@ -1114,7 +1180,7 @@ "repeater_refreshMultiAcks": "刷新多个确认", "repeater_networkHealth": "网络健康", "repeater_loopDetect": "循环检测", - "repeater_loopDetectHelper": "创建看起来像路由环的“洪水包”", + "repeater_loopDetectHelper": "创建看起来像路由环的“泛洪包”", "repeater_loopDetectOff": "离开", "repeater_loopDetectMinimal": "最少", "repeater_loopDetectModerate": "适度的", @@ -1132,14 +1198,14 @@ "repeater_ownerInfo": "运营商信息", "repeater_ownerInfoHelper": "此复播器的公共元数据", "repeater_refreshOwnerInfo": "刷新操作员信息", - "repeater_floodMax": "最大跳跃次数", - "repeater_floodMaxHelper": "一个洪水包中,最大可以传输的跳数 (0-64)", + "repeater_floodMax": "最大跳数", + "repeater_floodMaxHelper": "一个泛洪包中,最大可以传输的跳数 (0-64)", "repeater_advancedSettings": "高级", "repeater_advancedSettingsSubtitle": "高级操作员使用的调节旋钮", "repeater_pathHashMode": "路径哈希模式", - "repeater_pathHashModeHelper": "用于编码此复用器的 ID 的字节数,在“洪流路径/环检测”标签中使用。 0=1 字节(256 个 ID,最多 64 个跳跃),1=2 字节(65K 个 ID,最多 32 个跳跃),2=3 字节(16M 个 ID,最多 21 个跳跃)。 v1.13 及更早版本的固件会使用多字节路径——只有在您的网络升级到 v1.14 或更高版本后才会生效。", - "repeater_txDelay": "洪水(德克萨斯州)延误", - "repeater_txDelayHelper": "对于洪水流量,重新传输间隔应设置为包的传输时间(0-2,默认值为0.5)的倍数。 较高的值意味着更少的冲突,但传输速度会变慢。", + "repeater_pathHashModeHelper": "用于在洪泛路径/环路检测标签中编码此中继器 ID 的字节数。0=1 字节(256 个 ID,最多 64 跳),1=2 字节(65K 个 ID,最多 32 跳),2=3 字节(16M 个 ID,最多 21 跳)。v1.14 之前的固件始终使用 1 字节路径;v1.14 及更新版本可配置为 2 或 3 字节路径。", + "repeater_txDelay": "泛洪 TX 延迟", + "repeater_txDelayHelper": "对于泛洪流量,重新传输间隔应设置为包的传输时间(0-2,默认值为0.5)的倍数。 较高的值意味着更少的冲突,但传输速度会变慢。", "repeater_directTxDelay": "直接的 TX 延迟", "repeater_directTxDelayHelper": "对于直接(非广播)流量,重新传输间隔应设置为包的传输时间(0-2,默认值为0.3)的倍数。", "repeater_intThresh": "干扰阈值", @@ -1147,10 +1213,10 @@ "repeater_agcResetInterval": "AGC 恢复间隔", "repeater_agcResetIntervalHelper": "为了从失控的增益状态中恢复,应该多久重置收音机的自动增益控制?设置为“秒”,每次重置间隔为4秒。将此选项设置为“0”将禁用周期性重置。", "repeater_actionsTitle": "行动", - "repeater_sendAdvert": "发布防洪广告", - "repeater_sendAdvertSubtitle": "通过网络播放防洪广告", - "repeater_sendAdvertZeroHop": "发送零跳广告", - "repeater_sendAdvertZeroHopSubtitle": "进行单跳广告广播(不使用中继)", + "repeater_sendAdvert": "发送泛洪广播", + "repeater_sendAdvertSubtitle": "向整个网络发送泛洪广播", + "repeater_sendAdvertZeroHop": "发送零跳广播", + "repeater_sendAdvertZeroHopSubtitle": "发送单跳广播(不使用中继)", "repeater_clockSync": "现在同步时钟", "repeater_clockSyncSubtitle": "将手机的时间设置为与中继器同步", "repeater_actionSucceeded": "{action} 成功", @@ -2036,8 +2102,8 @@ "settings_privacySettingsDescription": "选择您的设备与他人共享的信息。", "settings_telemetryBaseMode": "遥测基础模式", "settings_telemetryLocationMode": "遥测位置模式", - "settings_advertLocation": "广告位置", - "settings_advertLocationSubtitle": "在广告中包含位置", + "settings_advertLocation": "广播位置", + "settings_advertLocationSubtitle": "在广播中包含位置", "settings_allowByContact": "按联系人标志允许", "settings_denyAll": "拒绝所有", "settings_privacy": "隐私设置", @@ -2207,7 +2273,7 @@ "repeater_sensors": "传感器", "repeater_cliHelpPowerOff": "关闭设备。(不应有任何响应)", "repeater_cliHelpClkReboot": "将时钟重置为已知的时间点,并重启设备。", - "repeater_cliHelpAdvertZeroHop": "发送无中继广告(仅限于邻居)。", + "repeater_cliHelpAdvertZeroHop": "发送无中继广播(仅限于邻居)。", "repeater_cliHelpStartOta": "在支持的板上启动通过空中进行固件更新。", "repeater_cliHelpTime": "将设备时钟设置为给定的 Unix 纪元秒。时钟不能倒退。", "repeater_cliHelpBoard": "显示制造商/硬件标识。", @@ -2218,7 +2284,7 @@ "repeater_cliHelpSetDutyCycle": "设定允许的最大传输时段百分比(1-100)。内部调整空闲时间因子。", "repeater_cliHelpSetPrvKey": "(仅适用于序列号)替换设备身份私钥。需要重启才能应用。生成一个新的公钥。", "repeater_cliHelpSetRadioRxGain": "(仅适用于 SX126x 芯片) 启用增强型 RX 增益,以在较高电流下提高灵敏度。", - "repeater_cliHelpSetOwnerInfo": "设置广告中包含的联系人信息字符串。使用 '|' 作为换行符。", + "repeater_cliHelpSetOwnerInfo": "设置广播中包含的联系人信息字符串。使用 '|' 作为换行符。", "repeater_cliHelpSetPathHashMode": "设置路径哈希模式。 0 = 传统模式,1 = 标准模式,2 = 严格模式。 影响路由路径的匹配方式。", "repeater_cliHelpSetLoopDetect": "设置路由环检测的灵敏度:关闭、低、中、或高。", "repeater_cliHelpSetFreq": "(仅限串行模式)快速设置频率。需要重启。 建议使用“设置收音机参数”功能,以便设置完整的收音机参数。", @@ -2238,15 +2304,15 @@ "repeater_cliHelpGetAgcResetInterval": "显示 AGC 重置的间隔时间(以秒为单位)。", "repeater_cliHelpGetMultiAcks": "显示双重确认模式是否已启用(1)或已禁用(0)。", "repeater_cliHelpGetAllowReadOnly": "显示是否允许访客仅限查看权限。", - "repeater_cliHelpGetAdvertInterval": "显示本地广告的时间间隔,单位为分钟。", - "repeater_cliHelpGetFloodAdvertInterval": "显示洪水广告的播放时间间隔,以小时为单位。", + "repeater_cliHelpGetAdvertInterval": "显示本地广播的时间间隔,单位为分钟。", + "repeater_cliHelpGetFloodAdvertInterval": "显示泛洪广播的播放时间间隔,以小时为单位。", "repeater_cliHelpGetGuestPassword": "显示已配置的访客密码。", "repeater_cliHelpGetLat": "显示已配置的纬度。", "repeater_cliHelpGetLon": "显示已配置的经度。", "repeater_cliHelpGetRxDelay": "显示 rxdelay 的基本值。", - "repeater_cliHelpGetTxDelay": "显示洪水模式下的传输延迟系数。", + "repeater_cliHelpGetTxDelay": "显示泛洪模式下的传输延迟系数。", "repeater_cliHelpGetDirectTxDelay": "显示直接模式下的时延系数。", - "repeater_cliHelpGetFloodMax": "显示最大洪水传播次数。", + "repeater_cliHelpGetFloodMax": "显示最大泛洪跳数。", "repeater_cliHelpGetOwnerInfo": "显示所有者的联系信息。", "repeater_cliHelpGetPathHashMode": "显示哈希模式(0/1/2)。", "repeater_cliHelpGetLoopDetect": "显示循环检测的灵敏度。", @@ -2268,8 +2334,8 @@ "repeater_cliHelpSensorList": "列出所有自定义传感器设置,并按可选的起始索引进行分页显示。", "repeater_cliHelpRegionDefault": "显示当前默认的区域范围。", "repeater_cliHelpRegionDefaultSet": "设置默认的区域范围。使用 \"\" 可以清除。", - "repeater_cliHelpRegionListAllowed": "列出允许洪水交通的区域。", - "repeater_cliHelpRegionListDenied": "列出禁止洪水交通的区域。", + "repeater_cliHelpRegionListAllowed": "列出允许泛洪交通的区域。", + "repeater_cliHelpRegionListDenied": "列出禁止泛洪交通的区域。", "repeater_cliHelpStatsPackets": "(仅显示序列信息)显示数据包级别的统计信息。", "repeater_cliHelpStatsRadio": "(仅显示序列信息)显示收音机相关统计数据。", "repeater_cliHelpStatsCore": "(仅显示序列号)显示核心固件统计信息。", @@ -2408,9 +2474,9 @@ "contacts_searchClose": "高级搜索", "routing_title": "路由", "routing_modeAuto": "汽车", - "routing_modeFlood": "洪水", + "routing_modeFlood": "泛洪", "routing_modeManual": "手册", - "routing_modeAutoHint": "自动选择已知最佳路径,当没有已知路径时,则进行“洪水”搜索。", + "routing_modeAutoHint": "自动选择已知最佳路径,当没有已知路径时,则进行“泛洪”搜索。", "routing_modeFloodHint": "通过所有中继站进行广播。 这种方式最可靠,但占用更多的时间。", "routing_modeManualHint": "总是按照您设置的路径进行导航。", "routing_currentRoute": "当前路线", @@ -2426,22 +2492,22 @@ "routing_qualityGood": "不错的开端", "routing_qualityFair": "第一次尝试,结果良好", "routing_qualityWorked": "已完成", - "routing_qualityFlood": "通过新闻报道", + "routing_qualityFlood": "通过泛洪收到", "routing_qualityUntested": "未经测试", "routing_lastWorked": "工作于 {when}", "routing_neverWorked": "从未得到证实", - "routing_floodDelivery": "洪水配送", + "routing_floodDelivery": "泛洪配送", "pathEditor_title": "构建路径", - "pathEditor_noHops": "目前还没有添加任何啤酒花。点击下面的“添加”按钮,按顺序添加,或者直接保存,不添加任何啤酒花。", - "pathEditor_addHops": "按照顺序添加啤酒花", + "pathEditor_noHops": "目前还没有添加任何跳点。点击下面的“添加”按钮,按顺序添加,或者直接保存,不添加任何跳点。", + "pathEditor_addHops": "按照顺序添加跳点", "pathEditor_searchRepeaters": "重复搜索", "pathEditor_advancedHex": "高级:原始十六进制路径", "pathEditor_hexLabel": "十六进制前缀", - "pathEditor_hexHelper": "每次跳跃,使用两个十六进制字符,用逗号分隔。", + "pathEditor_hexHelper": "每跳使用两个十六进制字符,用逗号分隔。", "pathEditor_invalidTokens": "无效:{tokens}", - "pathEditor_tooManyHops": "最多 64 个跳跃", + "pathEditor_tooManyHops": "最多 64 跳", "pathEditor_usePath": "请使用此路径", - "pathEditor_removeHop": "去除啤酒花", + "pathEditor_removeHop": "去除跳点", "routing_deliveryCounts": "{successes} delivered, {failures} failed", "pathEditor_hopCounter": "{count} of 64 hops", "pathEditor_unknownHop": "未知的重复器", @@ -2545,5 +2611,260 @@ "pathMap_followPacket": "锁定视图跟随数据包", "pathMap_unfollowPacket": "解锁视图跟随", "pathMap_gpsCount": "{confirmed}/{total} GPS", - "pathMap_partialAnimation": "{count, plural, =1{1 跳无位置信息 — 显示的路径不完整} other{{count} 跳无位置信息 — 显示的路径不完整}}" + "pathMap_partialAnimation": "{count, plural, =1{1 跳无位置信息 — 显示的路径不完整} other{{count} 跳无位置信息 — 显示的路径不完整}}", + "@settings_deleteRegionConfirm": { + "placeholders": { + "region": { + "type": "String" + } + } + }, + "@channels_regionSetTo": { + "placeholders": { + "region": { + "type": "String", + "example": "de-mitte" + } + } + }, + "@chat_imagePickFailed": { + "description": "Shown when picking or reading a photo to send fails" + }, + "@repeater_pubKeyPrefixHelper": { + "placeholders": { + "tries": { + "type": "int" + } + } + }, + "@imageSend_packetsCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_range": { + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "@imageSend_longSendBody": { + "placeholders": { + "duration": { + "type": "String" + } + } + }, + "@imageSend_sentConfirmation": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "@imageSend_sendFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "@imageSend_sendingProgress": { + "placeholders": { + "sent": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_senderPrefix": { + "placeholders": { + "prefix": { + "type": "String" + } + } + }, + "@receivedImage_incoming": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_incomplete": { + "placeholders": { + "received": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "@receivedImage_awaiting": { + "placeholders": { + "bytes": { + "type": "int" + }, + "packets": { + "type": "int" + } + } + }, + "@imageSend_secondsValue": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, + "@imageSend_minutesSecondsValue": { + "placeholders": { + "minutes": { + "type": "String" + }, + "seconds": { + "type": "String" + } + } + }, + "settings_regionSettings": "地区", + "settings_regionSettingsSubtitle": "管理已存储的区域", + "settings_regionManagement_screenTitle": "区域管理", + "settings_regionNameHint": "区域名称", + "settings_regionAddRegion": "增加地区", + "settings_regionFetchRegions": "从中继器获取区域", + "settings_regionFetchRegionsFail": "未发现任何地区", + "settings_regionFetchRegionsAlreadyExists": "该地区已被添加", + "settings_regionName": "地区名称", + "settings_regionDeleted": "区域已删除", + "settings_deleteRegion": "删除区域", + "settings_deleteRegionConfirm": "从 {region} 列表中删除?", + "settings_infoHardware": "硬件", + "settings_infoFirmware": "固件", + "repeater_pathHashModeOption0": "0 - 1 字节", + "repeater_pathHashModeOption1": "1 - 2 字节", + "repeater_pathHashModeOption2": "2 - 3 字节", + "repeater_pathHashModeOption3": "3 - 4 字节", + "appSettings_batteryLipoHv": "锂多压电源(3.0-4.35伏)", + "channels_regionSetTo": "地区:{region}", + "channels_regionNotSet": "地区:无", + "channels_regionSelect_Title": "选择一个地区", + "channels_clearRegion": "无碍区域", + "chat_sendImageLora": "通过 MeshCore 发送图片", + "chat_imagePickFailed": "无法打开该图片", + "chat_receivedGif": "收到一个GIF", + "repeater_keySettings": "更改身份密钥", + "repeater_keySettingsSubtitle": "更换公钥/私钥对", + "repeater_prvKey": "私钥", + "repeater_prvKeyHelper": "中继器的新私钥,为一个128位的十六进制字符串。", + "repeater_generatePrvKey": "生成一个随机的密钥对", + "repeater_stopGeneratingPrvKey": "中断密钥对搜索", + "repeater_pubKey": "公钥", + "repeater_pubKeyHelper": "这是与生成的私钥配对的公钥。您不能直接设置此内容。", + "repeater_pubKeyPrefix": "期望的前缀", + "repeater_pubKeyPrefixHelper": "找到一组以这些十六进制数字开头的公钥。预计尝试次数:{tries}", + "imageMessages_enableTitle": "启用图片消息", + "imageMessages_enableSubtitle": "通过网格发送图像。需要一次性下载图像模型。", + "imageMessages_modelSectionTitle": "图像模型", + "imageMessages_downloadModel": "下载", + "imageMessages_cancelDownload": "取消", + "imageMessages_removeModel": "移除模型", + "imageMessages_modelReady": "准备就绪", + "imageMessages_modelNotPublished": "尚未发布——此版本无法下载该内容。", + "imageMessages_downloadFailed": "图像模型无法下载。", + "imageMessages_autoProcessTitle": "自动处理图像", + "imageMessages_autoProcessSubtitle": "每次图像到达后立即重建,每次需要约2GB的内存;若想关闭重建功能,可通过点击取消开启。", + "imageSend_title": "发送图片", + "imageSend_cropNote": "调整大小至512 × 512 · 宽高比未保留", + "imageSend_originalSize": "原文", + "imageSend_onAirSize": "直播中", + "imageSend_quality": "质量", + "imageSend_qualityStandard": "标准", + "imageSend_qualityHigh": "高", + "imageSend_packetsLabel": "数据包", + "imageSend_airtimeLabel": "播出时间", + "imageSend_sizeLabel": "有效载荷", + "imageSend_packetsCount": "{count} {count, plural, =1{个数据包} other{个数据包}}", + "imageSend_range": "{min}–{max}", + "imageSend_unknownValue": "—", + "imageSend_radioUnknownTitle": "无线电设置未知", + "imageSend_radioUnknownBody": "连接设备以计算播出时间。", + "imageSend_longSendTitle": "长距离传输", + "imageSend_longSendBody": "这将维持频道大约 {duration} 时间。", + "imageSend_floodNote": "泛洪路由:每个中继站都会转发每个数据包,因此信道比这段时间更长地处于繁忙状态。", + "imageSend_parityTitle": "恢复包", + "imageSend_paritySubtitle": "多一个数据包。群发消息不被确认,因此如果某个数据包丢失,接收方可以重新构建图像。", + "imageSend_send": "发送", + "imageSend_cancel": "取消", + "imageSend_encodeFailed": "此图像无法编码。", + "imageSend_codecDownloading": "图像模型仍在下载中。", + "imageSend_codecUnavailable": "此设备无法发送图片。", + "imageSend_codecDisabled": "图片消息在设置中已关闭。", + "imageSend_deviceUnsupported": "此无线电无法发送图像数据包。请连接运行伴侣固件13或更高版本的设备。", + "imageSend_directMessagesUnsupported": "图片作为群组数据传输,因此只能发送到频道,而不能直接发送给个人。", + "imageSend_tooLarge": "该图像编码的数据包数量超过了网格格式所允许的范围。", + "imageSend_sentConfirmation": "图像已作为 {count} {count, plural, =1{个数据包} other{个数据包}} 发送。", + "imageSend_sendFailed": "无法发送图片:{error}", + "imageSend_sendingProgress": "发送图像 — 已发送 {sent} 包含 {total}", + "receivedImage_senderPrefix": "节点 {prefix}", + "receivedImage_incoming": "已收到的 {received} 个包含在 {total} 个包裹中", + "receivedImage_queued": "等待解码", + "receivedImage_tapToDecode": "点击解锁", + "receivedImage_decoding": "重建……大约1秒", + "receivedImage_incomplete": "图片不完整 — {received} 已收到 {total} 个数据包", + "receivedImage_corrupt": "图像无法重建", + "receivedImage_decoderMissing": "收到图片 — 图像解码失败", + "receivedImage_evicted": "图片已不再存储", + "receivedImage_retry": "再试一次", + "receivedImage_decodeAgain": "重新解码", + "receivedImage_openSettings": "建立", + "receivedImage_tapToProcess": "点击处理", + "receivedImage_awaiting": "{bytes} 字节 · {packets} {packets, plural, =1{个数据包} other{个数据包}}", + "imageSend_secondsValue": "{seconds} 秒", + "imageSend_minutesSecondsValue": "{minutes} 分 {seconds} 秒", + "channels_noFreeSlots": "所有频道插槽都已被占用", + "chat_longMessageRetryNote": "超过158字节:最多发送 {count} 次", + "reaction_report": "表情反应", + "repeater_bridgeNote": "仅支持带有桥接功能(RS232 或 ESP-NOW)的固件。", + "repeater_cliHelpGetFloodMaxAdvert": "显示泛洪广播包的最大跳数。", + "repeater_cliHelpGetFloodMaxUnscoped": "显示无区域范围的泛洪数据包的最大跳数。", + "repeater_cliHelpGetRadioFemRxGain": "显示 LoRa 前端模块的 RX 增益是否已开启。", + "repeater_cliHelpGetRadioFemTxGain": "显示 LoRa 前端模块的 TX 增益是否已开启。", + "repeater_cliHelpRegionDef": "在一条命令中定义一条区域链:每个名称都添加在上一个名称之下;“name,parent”会添加该名称,然后在指定的父级下继续。回复区域列表。", + "repeater_cliHelpSetFloodMaxAdvert": "设置转发泛洪广播包时的最大跳数(0-64)。", + "repeater_cliHelpSetFloodMaxUnscoped": "设置转发无区域范围的泛洪数据包时的最大跳数(0-64)。", + "repeater_cliHelpSetRadioFemRxGain": "切换 LoRa 前端模块的 RX 增益(LNA)。不支持此功能的板卡会回复“Error: unsupported”。", + "repeater_cliHelpSetRadioFemTxGain": "切换 LoRa 前端模块的 TX 增益(PA)。不支持此功能的板卡会回复“Error: unsupported”。", + "repeater_cliRegionLoadActive": "区域加载模式:每行发送一个区域名称,并用空格缩进表示其位于父级之下(在名称后添加 F 可允许泛洪)。每行不会有回复。发送空行以结束,然后发送“region save”以保存结果。", + "repeater_cliRegionLoadEnd": "(区域加载结束)", + "repeater_cliRegionLoadHint": "区域行,或留空以结束", + "repeater_frequencyInvalid": "无效频率(150-2500 MHz)", + "repeater_frequencyRangeHelper": "150-2500 MHz", + "repeater_recvErrors": "接收错误", + "repeater_txPowerRangeHelper": "-9 至 30 dBm", + "room_postsPushed": "已推送的帖子", + "room_postsStored": "帖子", + "settings_publicKeyCopied": "公钥已复制", + "settings_radioSettingsNotApplied": "收音机未应用这些设置", + "urlImage_enable": "启用URL图片", + "urlImage_possible": "可能是URL图片,请在设置中启用。", + "@chat_longMessageRetryNote": { + "placeholders": { + "count": { + "type": "int" + } + } + } } diff --git a/lib/l10n/contact_localization.dart b/lib/l10n/contact_localization.dart index d8344a32..9f34e2ab 100644 --- a/lib/l10n/contact_localization.dart +++ b/lib/l10n/contact_localization.dart @@ -1,4 +1,5 @@ import '../connector/meshcore_protocol.dart'; +import '../helpers/path_helper.dart'; import '../models/contact.dart'; import 'app_localizations.dart'; @@ -23,14 +24,30 @@ extension ContactLocalization on Contact { } } - String pathLabel(AppLocalizations l10n) { + String pathLabel( + AppLocalizations l10n, { + int pathHashByteWidth = pathHashSize, + }) { if (pathOverride != null) { if (pathOverride! < 0) return l10n.chat_floodForced; if (pathOverride == 0) return l10n.chat_directForced; - return l10n.chat_hopsForced(pathOverride!); + return l10n.chat_hopsForced( + _displayHopCount(pathOverrideBytes, pathOverride!, pathHashByteWidth), + ); } if (pathLength < 0) return l10n.channelPath_floodPath; if (pathLength == 0) return l10n.chat_direct; - return l10n.chat_hopsCount(pathLength); + return l10n.chat_hopsCount( + _displayHopCount(path, pathLength, pathHashWidth), + ); + } + + int _displayHopCount( + List? pathBytes, + int storedHopCount, + int hashWidth, + ) { + if (pathBytes == null || pathBytes.isEmpty) return storedHopCount; + return PathHelper.splitPathBytes(pathBytes, hashWidth).length; } } diff --git a/lib/main.dart b/lib/main.dart index 1445bdde..82e9e0ac 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter/foundation.dart'; @@ -9,7 +11,13 @@ import 'screens/chrome_required_screen.dart'; import 'utils/platform_info.dart'; import 'connector/meshcore_connector.dart'; +import 'models/image_codec_support.dart'; import 'screens/scanner_screen.dart'; +import 'services/image_chunk_transport.dart'; +import 'services/image_codec_service.dart'; +import 'services/image_codec_settings_store.dart'; +import 'services/received_image_blob_store_factory.dart'; +import 'services/received_image_store.dart'; import 'services/storage_service.dart'; import 'services/message_retry_service.dart'; import 'services/path_history_service.dart'; @@ -26,6 +34,7 @@ import 'services/timeout_prediction_service.dart'; import 'storage/prefs_manager.dart'; import 'theme/mesh_theme.dart'; import 'utils/app_logger.dart'; +import 'widgets/image_send_codec_binding.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -51,15 +60,60 @@ void main() async { final bleDebugLogService = BleDebugLogService(); final appDebugLogService = AppDebugLogService(); final backgroundService = BackgroundService(); - final mapTileCacheService = MapTileCacheService(); + final mapTileCacheService = MapTileCacheService( + appSettingsService: appSettingsService, + ); final chatTextScaleService = ChatTextScaleService(); final translationService = TranslationService(appSettingsService); final uiViewStateService = UiViewStateService(); final timeoutPredictionService = TimeoutPredictionService(storage); - // Load settings + // Load settings before anything reads them. The image stack below takes its + // model registry and its "process automatically" default straight off + // `appSettingsService.settings`, so this cannot stay where it used to be + // (after the constructions) without those two starting out wrong. await appSettingsService.loadSettings(); + // ---- image messages (AEIC over GRP_DATA) -------------------------------- + // The codec owns the ONNX decoder; the store owns received-image state and + // the decode queue; the reassembler/transport pair is the receive path the + // connector feeds raw frames into. + final imageCodecService = ImageCodecService( + appSettingsService, + settingsStore: AppSettingsImageCodecStore(appSettingsService), + ); + final receivedImageStore = ReceivedImageStore( + // Without a file-backed store this silently falls back to memory and every + // received image — sidecar included — is gone at the next launch. + blobs: createReceivedImageBlobStore(), + decoder: ImageCodecServiceDecoder(imageCodecService), + processAutomatically: appSettingsService.settings.imageProcessAutomatically, + ); + // A decode peaks around 2.16 GiB, so the setting is the user's consent to + // spend it. Mirrored on every settings change; the store applies it to + // future arrivals only, so turning it on does not decode a backlog. + appSettingsService.addListener(() { + receivedImageStore.processAutomatically = + appSettingsService.settings.imageProcessAutomatically; + }); + // Availability/isBusy changes are the only thing that un-parks a decode + // queue that stopped because the codec was unusable or busy. + imageCodecService.addListener(receivedImageStore.notifyDecoderChanged); + final imageReassembler = ImageStreamReassembler(store: receivedImageStore); + final imageTransport = ImageChunkTransport( + reassembler: imageReassembler, + // The UI sends whole chunk sets through connector.sendImageChunks so it + // gets real inter-chunk pacing and per-chunk progress; this closure only + // keeps ImageChunkTransport.sendImage() usable on its own. + send: (blob, channelIndex) => connector.sendImageChunks( + [blob], + channelIndex: channelIndex, + interChunkDelay: Duration.zero, + ), + // Overwritten by onImageSenderPrefix as soon as SELF_INFO lands. + senderPrefix: 0, + ); + // Initialize app logger appLogger.initialize( appDebugLogService, @@ -77,6 +131,8 @@ void main() async { await chatTextScaleService.initialize(); await translationService.refreshDownloadedModels(); + await imageCodecService.refreshDownloadedModels(); + await receivedImageStore.load(); await uiViewStateService.initialize(); await timeoutPredictionService.initialize(); @@ -90,6 +146,12 @@ void main() async { appDebugLogService: appDebugLogService, backgroundService: backgroundService, timeoutPredictionService: timeoutPredictionService, + imageCodecService: imageCodecService, + imageTransport: imageTransport, + // ImageStreamReassembler.addChunk already forwards every outcome to the + // store together with the channel index (which ImageChunkOutcome itself + // does not carry), so onImageChunk would be a second, channel-blind path. + onImageSenderPrefix: (prefix) => imageReassembler.selfPrefix = prefix, ); await connector.loadContactCache(); @@ -114,10 +176,107 @@ void main() async { translationService: translationService, uiViewStateService: uiViewStateService, timeoutPredictionService: timeoutPredictionService, + imageCodecService: imageCodecService, + receivedImageStore: receivedImageStore, + imageReassembler: imageReassembler, ), ); } +/// [ReceivedImageDecoder] over [ImageCodecService]. +/// +/// Pure delegation. It exists so `received_image_store.dart` never imports +/// `image_codec_service.dart` (and so the store stays testable without an +/// 872 MB ONNX graph). +class ImageCodecServiceDecoder implements ReceivedImageDecoder { + final ImageCodecService service; + + const ImageCodecServiceDecoder(this.service); + + @override + ImageCodecAvailability get availability => service.availability; + + @override + bool get isBusy => service.isBusy; + + @override + Future decodeBitstream({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + }) => service.decodeBitstream( + bitstream: bitstream, + ratePoint: ratePoint, + resolution: resolution, + ); + + @override + void cancelCodecJob() => service.cancelCodecJob(); +} + +/// [ImageCodecSettingsStore] backed by [AppSettingsService]. +/// +/// Replaces `PrefsImageCodecSettingsStore` now that the five `imageCodec*` +/// fields live on [AppSettings]; the JSON keys were already the same, so a +/// user upgrading keeps their model registry only if it was written through +/// this adapter — the old standalone `image_codec_settings` blob is not +/// migrated, because a placeholder-URL build cannot have produced one. +class AppSettingsImageCodecStore implements ImageCodecSettingsStore { + final AppSettingsService _service; + + const AppSettingsImageCodecStore(this._service); + + @override + ImageCodecPreferences get preferences => _service.settings.imageCodec; + + @override + Future load() async { + // AppSettingsService.loadSettings() already ran in main(). + } + + @override + Future save(ImageCodecPreferences preferences) => + _service.setImageCodecPreferences(preferences); +} + +/// An [ImageReassembler] that (a) learns the local sender prefix after +/// SELF_INFO and (b) forwards every outcome to [ReceivedImageStore] together +/// with the channel index. +/// +/// Both exist because of upstream shapes this file cannot change: +/// * `ImageReassembler.selfPrefix` is `final`, but the local public key does +/// not exist until `RESP_CODE_SELF_INFO`, so a reassembler built here would +/// start with a null prefix and never be able to drop our own flood echo. +/// Overriding the getter is the smallest fix that does not touch the +/// transport; see the report's "needs from others". +/// * `ImageChunkOutcome` carries no channel index, so the connector's +/// `onImageChunk` callback cannot call `handleOutcome`, which requires one. +/// Intercepting `addChunk` — the only place the index is in scope — can. +class ImageStreamReassembler extends ImageReassembler { + final ReceivedImageStore store; + + int? _selfPrefix; + + ImageStreamReassembler({required this.store}) + : super(onFailed: ((failure) => unawaited(store.handleFailure(failure)))); + + @override + int? get selfPrefix => _selfPrefix; + + set selfPrefix(int? value) => _selfPrefix = value; + + @override + ImageChunkOutcome addChunk( + Uint8List blob, { + int channelIndex = 0, + DateTime? now, + }) { + final outcome = super.addChunk(blob, channelIndex: channelIndex, now: now); + unawaited(store.handleOutcome(outcome, channelIndex: channelIndex)); + return outcome; + } +} + void _registerThirdPartyLicenses() { LicenseRegistry.addLicense(() async* { yield const LicenseEntryWithLineBreaks( @@ -139,7 +298,7 @@ https://creativecommons.org/licenses/by/4.0/ }); } -class MeshCoreApp extends StatelessWidget { +class MeshCoreApp extends StatefulWidget { final MeshCoreConnector connector; final MessageRetryService retryService; final PathHistoryService pathHistoryService; @@ -152,6 +311,9 @@ class MeshCoreApp extends StatelessWidget { final TranslationService translationService; final UiViewStateService uiViewStateService; final TimeoutPredictionService timeoutPredictionService; + final ImageCodecService imageCodecService; + final ReceivedImageStore receivedImageStore; + final ImageStreamReassembler imageReassembler; const MeshCoreApp({ super.key, @@ -167,24 +329,83 @@ class MeshCoreApp extends StatelessWidget { required this.translationService, required this.uiViewStateService, required this.timeoutPredictionService, + required this.imageCodecService, + required this.receivedImageStore, + required this.imageReassembler, }); + @override + State createState() => _MeshCoreAppState(); +} + +/// How often abandoned image streams are swept. +/// +/// `ImageReassembler.evictExpired` otherwise only runs from `addChunk`, so a +/// sender that stops mid-image would leave its bubble stuck on "2 of 3 +/// packets" until some unrelated image arrived. +const Duration _kImageSweepInterval = Duration(seconds: 5); + +class _MeshCoreAppState extends State with WidgetsBindingObserver { + Timer? _imageSweepTimer; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _imageSweepTimer = Timer.periodic( + _kImageSweepInterval, + (_) => widget.imageReassembler.evictExpired(), + ); + } + + @override + void dispose() { + _imageSweepTimer?.cancel(); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + super.didChangeAppLifecycleState(state); + widget.receivedImageStore.setForeground(state == AppLifecycleState.resumed); + // ~2.7 GiB resident in a backgrounded app is a low-memory-killer kill, so + // unlike the translation stack the graph is dropped on background rather + // than held until the radio disconnects. + if (state == AppLifecycleState.paused || + state == AppLifecycleState.hidden) { + unawaited(widget.imageCodecService.handleMemoryPressure()); + unawaited(widget.receivedImageStore.handleMemoryPressure()); + } + } + + @override + void didHaveMemoryPressure() { + super.didHaveMemoryPressure(); + unawaited(widget.imageCodecService.handleMemoryPressure()); + unawaited(widget.receivedImageStore.handleMemoryPressure()); + } + @override Widget build(BuildContext context) { + final connector = widget.connector; + final storage = widget.storage; return MultiProvider( providers: [ ChangeNotifierProvider.value(value: connector), - ChangeNotifierProvider.value(value: retryService), - ChangeNotifierProvider.value(value: pathHistoryService), - ChangeNotifierProvider.value(value: appSettingsService), - ChangeNotifierProvider.value(value: bleDebugLogService), - ChangeNotifierProvider.value(value: appDebugLogService), - ChangeNotifierProvider.value(value: chatTextScaleService), - ChangeNotifierProvider.value(value: translationService), - ChangeNotifierProvider.value(value: uiViewStateService), + ChangeNotifierProvider.value(value: widget.retryService), + ChangeNotifierProvider.value(value: widget.pathHistoryService), + ChangeNotifierProvider.value(value: widget.appSettingsService), + ChangeNotifierProvider.value(value: widget.bleDebugLogService), + ChangeNotifierProvider.value(value: widget.appDebugLogService), + ChangeNotifierProvider.value(value: widget.chatTextScaleService), + ChangeNotifierProvider.value(value: widget.translationService), + ChangeNotifierProvider.value(value: widget.uiViewStateService), Provider.value(value: storage), - Provider.value(value: mapTileCacheService), - ChangeNotifierProvider.value(value: timeoutPredictionService), + ChangeNotifierProvider.value(value: widget.mapTileCacheService), + ChangeNotifierProvider.value(value: widget.timeoutPredictionService), + ChangeNotifierProvider.value(value: widget.imageCodecService), + ChangeNotifierProvider.value(value: widget.receivedImageStore), ], child: Consumer( builder: (context, settingsService, child) { diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 3fd0d05f..85fd35a2 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -1,3 +1,4 @@ +import 'image_codec_support.dart'; import 'translation_support.dart'; enum UnitSystem { metric, imperial } @@ -76,6 +77,7 @@ class Cyr2LatProfile { class AppSettings { static const Object _unset = Object(); + static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0'; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -87,20 +89,29 @@ class AppSettings { final String mapKeyPrefix; final bool mapShowMarkers; final bool mapShowGuessedLocations; + final bool mapClusterNodes; final bool enableMessageTracing; final Map? mapCacheBounds; final int mapCacheMinZoom; final int mapCacheMaxZoom; + final String mapRasterSourceId; + final String mapTileEndpointId; + final String? mapTileApiKey; final bool notificationsEnabled; final bool notifyOnNewMessage; final bool notifyOnNewChannelMessage; final bool notifyOnNewAdvert; + final bool autoSendZeroHopAdvertOnGpsUpdate; + final int gpsIntervalSeconds; final bool autoRouteRotationEnabled; final double maxRouteWeight; final double initialRouteWeight; final double routeWeightSuccessIncrement; final double routeWeightFailureDecrement; final int maxMessageRetries; + final bool channelMinHopsEnabled; + final int channelMinHops; + final int channelMinHopsRetries; final String themeMode; final String? languageOverride; // null = system default final bool appDebugLogEnabled; @@ -112,6 +123,29 @@ class AppSettings { final String tcpServerAddress; final int tcpServerPort; final bool jumpToOldestUnread; + final bool imageMessagesEnabled; + + /// Whether a received image is decoded as soon as it is reassembled. + /// + /// Off by default and deliberately so: a decode peaks around 2.16 GiB + /// resident and takes about a second, so an unattended chat must not be able + /// to trigger one per arriving image. When false, `ReceivedImageStore` parks + /// the arrival as a "Tap to process" placeholder instead of queueing it. + final bool imageProcessAutomatically; + + // ---- neural image codec (AEIC-SE) --------------------------------------- + // Structural twins of the translation block above; the JSON keys match + // ImageCodecPreferences.toJson so ImageCodecService reads them unchanged. + final bool imageCodecEnabled; + final String? imageCodecSelectedModelId; + final String? imageCodecModelSourceUrl; + + /// [AeicRatePoint.wireValue] of the composer's default rate point. + /// 4 == ft32, the only rate point this build ships. + final int imageCodecRatePoint; + + final List imageCodecDownloadedModels; + final bool translationEnabled; final bool autoTranslateIncomingMessages; final String? translationTargetLanguageCode; @@ -122,6 +156,26 @@ class AppSettings { final List cyr2latProfiles; final String selectedCyr2latProfileId; + /// The five `imageCodec*` fields as the value object `ImageCodecService` + /// consumes. Assembled rather than stored so the settings blob stays flat. + ImageCodecPreferences get imageCodec => ImageCodecPreferences( + enabled: imageCodecEnabled, + selectedModelId: imageCodecSelectedModelId, + modelSourceUrl: imageCodecModelSourceUrl, + ratePoint: imageCodecRatePoint, + downloadedModels: imageCodecDownloadedModels, + ); + + String get effectiveMapTileApiKey { + final apiKey = mapTileApiKey?.trim(); + if (apiKey == null || apiKey.isEmpty) { + return stadiaDemo; + } + return apiKey; + } + + bool get usesstadiaDemo => effectiveMapTileApiKey == stadiaDemo; + Map get cyr2latCharMap { final profile = cyr2latProfiles.firstWhere( (p) => p.id == selectedCyr2latProfileId, @@ -136,25 +190,34 @@ class AppSettings { this.mapShowChatNodes = true, this.mapShowOtherNodes = true, this.mapShowOverlaps = false, - this.mapTimeFilterHours = 0, // Default to all time + this.mapTimeFilterHours = 168, this.mapKeyPrefixEnabled = false, this.mapKeyPrefix = '', this.mapShowMarkers = true, this.mapShowGuessedLocations = true, - this.enableMessageTracing = true, + this.mapClusterNodes = true, + this.enableMessageTracing = false, this.mapCacheBounds, this.mapCacheMinZoom = 10, this.mapCacheMaxZoom = 15, + this.mapRasterSourceId = 'osm_auto', + this.mapTileEndpointId = 'standard_2x', + this.mapTileApiKey, this.notificationsEnabled = true, this.notifyOnNewMessage = true, this.notifyOnNewChannelMessage = true, this.notifyOnNewAdvert = true, + this.autoSendZeroHopAdvertOnGpsUpdate = false, + this.gpsIntervalSeconds = 900, this.autoRouteRotationEnabled = true, this.maxRouteWeight = 5.0, this.initialRouteWeight = 3.0, this.routeWeightSuccessIncrement = 0.5, this.routeWeightFailureDecrement = 0.2, this.maxMessageRetries = 5, + this.channelMinHopsEnabled = false, + this.channelMinHops = 2, + this.channelMinHopsRetries = 1, this.themeMode = 'system', this.languageOverride, this.appDebugLogEnabled = false, @@ -166,6 +229,13 @@ class AppSettings { this.tcpServerAddress = '', this.tcpServerPort = 0, this.jumpToOldestUnread = false, + this.imageMessagesEnabled = false, + this.imageProcessAutomatically = false, + this.imageCodecEnabled = false, + this.imageCodecSelectedModelId, + this.imageCodecModelSourceUrl, + this.imageCodecRatePoint = 4, + List? imageCodecDownloadedModels, this.translationEnabled = false, this.autoTranslateIncomingMessages = true, this.translationTargetLanguageCode, @@ -178,6 +248,7 @@ class AppSettings { }) : batteryChemistryByDeviceId = batteryChemistryByDeviceId ?? {}, batteryChemistryByRepeaterId = batteryChemistryByRepeaterId ?? {}, mutedChannels = mutedChannels ?? {}, + imageCodecDownloadedModels = imageCodecDownloadedModels ?? const [], translationDownloadedModels = translationDownloadedModels ?? const [], cyr2latProfiles = cyr2latProfiles ?? @@ -202,20 +273,30 @@ class AppSettings { 'map_key_prefix': mapKeyPrefix, 'map_show_markers': mapShowMarkers, 'map_show_guessed_locations': mapShowGuessedLocations, + 'map_cluster_nodes': mapClusterNodes, 'enable_message_tracing': enableMessageTracing, 'map_cache_bounds': mapCacheBounds, 'map_cache_min_zoom': mapCacheMinZoom, 'map_cache_max_zoom': mapCacheMaxZoom, + 'map_raster_source_id': mapRasterSourceId, + 'map_tile_endpoint_id': mapTileEndpointId, + 'map_tile_api_key': mapTileApiKey, 'notifications_enabled': notificationsEnabled, 'notify_on_new_message': notifyOnNewMessage, 'notify_on_new_channel_message': notifyOnNewChannelMessage, 'notify_on_new_advert': notifyOnNewAdvert, + 'auto_send_zero_hop_advert_on_gps_update': + autoSendZeroHopAdvertOnGpsUpdate, + 'gps_interval_seconds': gpsIntervalSeconds, 'auto_route_rotation_enabled': autoRouteRotationEnabled, 'max_route_weight': maxRouteWeight, 'initial_route_weight': initialRouteWeight, 'route_weight_success_increment': routeWeightSuccessIncrement, 'route_weight_failure_decrement': routeWeightFailureDecrement, 'max_message_retries': maxMessageRetries, + 'channel_min_hops_enabled': channelMinHopsEnabled, + 'channel_min_hops': channelMinHops, + 'channel_min_hops_retries': channelMinHopsRetries, 'theme_mode': themeMode, 'language_override': languageOverride, 'app_debug_log_enabled': appDebugLogEnabled, @@ -227,6 +308,15 @@ class AppSettings { 'tcp_server_address': tcpServerAddress, 'tcp_server_port': tcpServerPort, 'jump_to_oldest_unread': jumpToOldestUnread, + 'image_messages_enabled': imageMessagesEnabled, + 'image_process_automatically': imageProcessAutomatically, + 'image_codec_enabled': imageCodecEnabled, + 'image_codec_selected_model_id': imageCodecSelectedModelId, + 'image_codec_model_source_url': imageCodecModelSourceUrl, + 'image_codec_rate_point': imageCodecRatePoint, + 'image_codec_downloaded_models': imageCodecDownloadedModels + .map((model) => model.toJson()) + .toList(), 'translation_enabled': translationEnabled, 'auto_translate_incoming_messages': autoTranslateIncomingMessages, 'translation_target_language_code': translationTargetLanguageCode, @@ -258,23 +348,31 @@ class AppSettings { mapShowOtherNodes: json['map_show_other_nodes'] as bool? ?? true, mapShowOverlaps: json['map_show_overlaps'] as bool? ?? false, mapTimeFilterHours: - (json['map_time_filter_hours'] as num?)?.toDouble() ?? 0, + (json['map_time_filter_hours'] as num?)?.toDouble() ?? 168, mapKeyPrefixEnabled: json['map_key_prefix_enabled'] as bool? ?? false, mapKeyPrefix: json['map_key_prefix'] as String? ?? '', mapShowMarkers: json['map_show_markers'] as bool? ?? true, mapShowGuessedLocations: json['map_show_guessed_locations'] as bool? ?? true, - enableMessageTracing: json['enable_message_tracing'] as bool? ?? true, + mapClusterNodes: json['map_cluster_nodes'] as bool? ?? true, + enableMessageTracing: json['enable_message_tracing'] as bool? ?? false, mapCacheBounds: (json['map_cache_bounds'] as Map?)?.map( (key, value) => MapEntry(key.toString(), (value as num).toDouble()), ), mapCacheMinZoom: json['map_cache_min_zoom'] as int? ?? 10, mapCacheMaxZoom: json['map_cache_max_zoom'] as int? ?? 15, + mapRasterSourceId: json['map_raster_source_id'] as String? ?? 'osm_auto', + mapTileEndpointId: json['map_tile_endpoint_id'] as String? ?? 'standard', + mapTileApiKey: json['map_tile_api_key'] as String?, notificationsEnabled: json['notifications_enabled'] as bool? ?? true, notifyOnNewMessage: json['notify_on_new_message'] as bool? ?? true, notifyOnNewChannelMessage: json['notify_on_new_channel_message'] as bool? ?? true, notifyOnNewAdvert: json['notify_on_new_advert'] as bool? ?? true, + autoSendZeroHopAdvertOnGpsUpdate: + json['auto_send_zero_hop_advert_on_gps_update'] as bool? ?? false, + gpsIntervalSeconds: + (json['gps_interval_seconds'] as num?)?.toInt() ?? 900, autoRouteRotationEnabled: json['auto_route_rotation_enabled'] as bool? ?? true, maxRouteWeight: (json['max_route_weight'] as num?)?.toDouble() ?? 5.0, @@ -285,6 +383,9 @@ class AppSettings { routeWeightFailureDecrement: (json['route_weight_failure_decrement'] as num?)?.toDouble() ?? 0.2, maxMessageRetries: json['max_message_retries'] as int? ?? 5, + channelMinHopsEnabled: json['channel_min_hops_enabled'] as bool? ?? false, + channelMinHops: json['channel_min_hops'] as int? ?? 2, + channelMinHopsRetries: json['channel_min_hops_retries'] as int? ?? 1, themeMode: json['theme_mode'] as String? ?? 'system', languageOverride: json['language_override'] as String?, appDebugLogEnabled: json['app_debug_log_enabled'] as bool? ?? false, @@ -309,6 +410,23 @@ class AppSettings { tcpServerAddress: json['tcp_server_address'] as String? ?? '', tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, + imageMessagesEnabled: json['image_messages_enabled'] as bool? ?? false, + imageProcessAutomatically: + json['image_process_automatically'] as bool? ?? false, + imageCodecEnabled: json['image_codec_enabled'] as bool? ?? false, + imageCodecSelectedModelId: + json['image_codec_selected_model_id'] as String?, + imageCodecModelSourceUrl: json['image_codec_model_source_url'] as String?, + imageCodecRatePoint: json['image_codec_rate_point'] as int? ?? 4, + imageCodecDownloadedModels: + (json['image_codec_downloaded_models'] as List?) + ?.map( + (entry) => ImageCodecModelRecord.fromJson( + Map.from(entry as Map), + ), + ) + .toList() ?? + const [], translationEnabled: json['translation_enabled'] as bool? ?? false, autoTranslateIncomingMessages: json['auto_translate_incoming_messages'] as bool? ?? true, @@ -375,20 +493,29 @@ class AppSettings { String? mapKeyPrefix, bool? mapShowMarkers, bool? mapShowGuessedLocations, + bool? mapClusterNodes, bool? enableMessageTracing, Object? mapCacheBounds = _unset, int? mapCacheMinZoom, int? mapCacheMaxZoom, + String? mapRasterSourceId, + String? mapTileEndpointId, + Object? mapTileApiKey = _unset, bool? notificationsEnabled, bool? notifyOnNewMessage, bool? notifyOnNewChannelMessage, bool? notifyOnNewAdvert, + bool? autoSendZeroHopAdvertOnGpsUpdate, + int? gpsIntervalSeconds, bool? autoRouteRotationEnabled, double? maxRouteWeight, double? initialRouteWeight, double? routeWeightSuccessIncrement, double? routeWeightFailureDecrement, int? maxMessageRetries, + bool? channelMinHopsEnabled, + int? channelMinHops, + int? channelMinHopsRetries, String? themeMode, Object? languageOverride = _unset, bool? appDebugLogEnabled, @@ -400,6 +527,13 @@ class AppSettings { String? tcpServerAddress, int? tcpServerPort, bool? jumpToOldestUnread, + bool? imageMessagesEnabled, + bool? imageProcessAutomatically, + bool? imageCodecEnabled, + Object? imageCodecSelectedModelId = _unset, + Object? imageCodecModelSourceUrl = _unset, + int? imageCodecRatePoint, + List? imageCodecDownloadedModels, bool? translationEnabled, bool? autoTranslateIncomingMessages, Object? translationTargetLanguageCode = _unset, @@ -422,17 +556,27 @@ class AppSettings { mapShowMarkers: mapShowMarkers ?? this.mapShowMarkers, mapShowGuessedLocations: mapShowGuessedLocations ?? this.mapShowGuessedLocations, + mapClusterNodes: mapClusterNodes ?? this.mapClusterNodes, enableMessageTracing: enableMessageTracing ?? this.enableMessageTracing, mapCacheBounds: mapCacheBounds == _unset ? this.mapCacheBounds : mapCacheBounds as Map?, mapCacheMinZoom: mapCacheMinZoom ?? this.mapCacheMinZoom, mapCacheMaxZoom: mapCacheMaxZoom ?? this.mapCacheMaxZoom, + mapRasterSourceId: mapRasterSourceId ?? this.mapRasterSourceId, + mapTileEndpointId: mapTileEndpointId ?? this.mapTileEndpointId, + mapTileApiKey: mapTileApiKey == _unset + ? this.mapTileApiKey + : mapTileApiKey as String?, notificationsEnabled: notificationsEnabled ?? this.notificationsEnabled, notifyOnNewMessage: notifyOnNewMessage ?? this.notifyOnNewMessage, notifyOnNewChannelMessage: notifyOnNewChannelMessage ?? this.notifyOnNewChannelMessage, notifyOnNewAdvert: notifyOnNewAdvert ?? this.notifyOnNewAdvert, + autoSendZeroHopAdvertOnGpsUpdate: + autoSendZeroHopAdvertOnGpsUpdate ?? + this.autoSendZeroHopAdvertOnGpsUpdate, + gpsIntervalSeconds: gpsIntervalSeconds ?? this.gpsIntervalSeconds, autoRouteRotationEnabled: autoRouteRotationEnabled ?? this.autoRouteRotationEnabled, maxRouteWeight: maxRouteWeight ?? this.maxRouteWeight, @@ -442,6 +586,11 @@ class AppSettings { routeWeightFailureDecrement: routeWeightFailureDecrement ?? this.routeWeightFailureDecrement, maxMessageRetries: maxMessageRetries ?? this.maxMessageRetries, + channelMinHopsEnabled: + channelMinHopsEnabled ?? this.channelMinHopsEnabled, + channelMinHops: channelMinHops ?? this.channelMinHops, + channelMinHopsRetries: + channelMinHopsRetries ?? this.channelMinHopsRetries, themeMode: themeMode ?? this.themeMode, languageOverride: languageOverride == _unset ? this.languageOverride @@ -458,6 +607,19 @@ class AppSettings { tcpServerAddress: tcpServerAddress ?? this.tcpServerAddress, tcpServerPort: tcpServerPort ?? this.tcpServerPort, jumpToOldestUnread: jumpToOldestUnread ?? this.jumpToOldestUnread, + imageMessagesEnabled: imageMessagesEnabled ?? this.imageMessagesEnabled, + imageProcessAutomatically: + imageProcessAutomatically ?? this.imageProcessAutomatically, + imageCodecEnabled: imageCodecEnabled ?? this.imageCodecEnabled, + imageCodecSelectedModelId: imageCodecSelectedModelId == _unset + ? this.imageCodecSelectedModelId + : imageCodecSelectedModelId as String?, + imageCodecModelSourceUrl: imageCodecModelSourceUrl == _unset + ? this.imageCodecModelSourceUrl + : imageCodecModelSourceUrl as String?, + imageCodecRatePoint: imageCodecRatePoint ?? this.imageCodecRatePoint, + imageCodecDownloadedModels: + imageCodecDownloadedModels ?? this.imageCodecDownloadedModels, translationEnabled: translationEnabled ?? this.translationEnabled, autoTranslateIncomingMessages: autoTranslateIncomingMessages ?? this.autoTranslateIncomingMessages, diff --git a/lib/models/channel.dart b/lib/models/channel.dart index 324157ef..f05295ae 100644 --- a/lib/models/channel.dart +++ b/lib/models/channel.dart @@ -107,7 +107,7 @@ class Channel { /// Normalize a hashtag name for consistent community PSK derivation. /// Strips leading #, converts to lowercase, trims whitespace. static String _normalizeCommunityHashtag(String hashtag) { - return hashtag.replaceFirst(RegExp(r'^#'), '').toLowerCase().trim(); + return hashtag.trim().replaceFirst(RegExp(r'^#'), '').toLowerCase().trim(); } static String formatPskHex(Uint8List psk) { diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index 80c9705b..3f1421cc 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -41,6 +41,7 @@ class ChannelMessage { final List repeats; final int repeatCount; final int? pathLength; + final int? pathHashWidth; final Uint8List pathBytes; final List pathVariants; final int? channelIndex; @@ -49,7 +50,7 @@ class ChannelMessage { final String? replyToMessageId; final String? replyToSenderName; final String? replyToText; - final Map reactions; + final Map> reactions; ChannelMessage({ this.senderKey, @@ -66,6 +67,7 @@ class ChannelMessage { this.repeats = const [], this.repeatCount = 0, this.pathLength, + this.pathHashWidth, Uint8List? pathBytes, List? pathVariants, this.channelIndex, @@ -74,7 +76,7 @@ class ChannelMessage { this.replyToMessageId, this.replyToSenderName, this.replyToText, - Map? reactions, + Map>? reactions, }) : messageId = messageId ?? '${timestamp.millisecondsSinceEpoch}_${senderName.hashCode}_${text.hashCode}', @@ -93,6 +95,7 @@ class ChannelMessage { List? repeats, int? repeatCount, int? pathLength, + int? pathHashWidth, Uint8List? pathBytes, List? pathVariants, String? packetHash, @@ -104,7 +107,7 @@ class ChannelMessage { Object? translatedLanguageCode = _unset, MessageTranslationStatus? translationStatus, Object? translationModelId = _unset, - Map? reactions, + Map>? reactions, }) { return ChannelMessage( senderKey: senderKey, @@ -129,6 +132,7 @@ class ChannelMessage { repeats: repeats ?? this.repeats, repeatCount: repeatCount ?? this.repeatCount, pathLength: pathLength ?? this.pathLength, + pathHashWidth: pathHashWidth ?? this.pathHashWidth, pathBytes: pathBytes ?? this.pathBytes, pathVariants: pathVariants ?? this.pathVariants, channelIndex: channelIndex, @@ -153,8 +157,9 @@ class ChannelMessage { return null; } - int pathLen; + int? pathLen; int txtType; + int? packetPathHashWidth; Uint8List pathBytes = Uint8List(0); int channelIdx; if (code == respCodeChannelMsgRecvV3) { @@ -163,15 +168,25 @@ class ChannelMessage { final hasPath = (flags & 0x01) != 0; reader.skipBytes(1); // Skip reserved byte channelIdx = reader.readByte(); - pathLen = reader.readInt8(); - txtType = reader.readByte(); - if (hasPath && pathLen > 0) { - reader.rewind(); // Rewind to read path length again for pathBytes - pathBytes = reader.readBytes(pathLen); + final pathByte = reader.readUInt8(); + // 0xFF = direct-routed; hop count is not reported. + if (pathByte != 0xFF) { + // pathByte packs: top 2 bits = hash width mode, low 6 bits = hop count + packetPathHashWidth = ((pathByte & 0xC0) >> 6) + 1; + final hopCount = pathByte & 0x3F; + pathLen = hopCount; + // If a path is present, read hopCount * width bytes + if (hasPath && hopCount > 0) { + final totalPathBytes = hopCount * packetPathHashWidth; + pathBytes = reader.readBytes(totalPathBytes); + } } + // After consuming optional path bytes, read the text type byte. + txtType = reader.readByte(); } else { channelIdx = reader.readByte(); - pathLen = reader.readInt8(); + final pathByte = reader.readUInt8(); + pathLen = pathByte == 0xFF ? null : pathByte & 0x3F; txtType = reader.readByte(); } final timestampRaw = reader.readUInt32LE(); @@ -209,6 +224,7 @@ class ChannelMessage { isOutgoing: false, status: ChannelMessageStatus.sent, pathLength: pathLen, + pathHashWidth: packetPathHashWidth, pathBytes: pathBytes, channelIndex: channelIdx, ); @@ -226,6 +242,7 @@ class ChannelMessage { String? originalText, String? translatedLanguageCode, String? translationModelId, + ChannelMessage? replyTo, }) { return ChannelMessage( senderKey: null, @@ -234,6 +251,9 @@ class ChannelMessage { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + replyToMessageId: replyTo?.messageId, + replyToSenderName: replyTo?.senderName, + replyToText: replyTo?.text, timestamp: DateTime.now(), isOutgoing: true, status: ChannelMessageStatus.pending, @@ -285,8 +305,37 @@ class ChannelMessage { ); } - static ReactionInfo? parseReaction(String text) { - return ReactionHelper.parseReaction(text); + ReactionInfo? parseReaction() { + final reactionInfo = ReactionHelper.parseReaction(text); + reactionInfo?.senderName = senderName; + return reactionInfo; + } + + String computeReactionHash() { + return ReactionHelper.computeReactionHash( + timestamp.millisecondsSinceEpoch ~/ 1000, + senderName, + text, + ); + } + + List reactionList() { + final String hash = computeReactionHash(); + List reactionList = []; + for (final entry in reactions.entries) { + final emoji = entry.key; + for (final senderName in entry.value) { + reactionList.add( + ReactionInfo( + targetHash: hash, // won't be used for anything + emoji: emoji, + senderName: senderName, + hashType: HashType.ours, // also not used for anything + ), + ); + } + } + return reactionList; } } diff --git a/lib/models/community.dart b/lib/models/community.dart index 7261ddf9..9a36f38c 100644 --- a/lib/models/community.dart +++ b/lib/models/community.dart @@ -1,8 +1,8 @@ import 'dart:convert'; -import 'dart:math'; import 'dart:typed_data'; import 'package:crypto/crypto.dart' as crypto; +import 'package:meshcore_open/utils/keys.dart'; import 'channel.dart'; @@ -37,11 +37,7 @@ class Community { /// Generate a new community with a random 32-byte secret factory Community.create({required String id, required String name}) { - final random = Random.secure(); - final secret = Uint8List(32); - for (int i = 0; i < 32; i++) { - secret[i] = random.nextInt(256); - } + final secret = randomBytes(32); return Community( id: id, name: name, @@ -80,12 +76,14 @@ class Community { factory Community.fromJson(Map json) { return Community( id: json['id'] as String, - name: json['name'] as String, + name: json['name'] as String? ?? '', secret: base64Decode(json['secret'] as String), - createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at'] as int), + createdAt: DateTime.fromMillisecondsSinceEpoch( + json['created_at'] as int? ?? 0, + ), hashtagChannels: (json['hashtag_channels'] as List?) - ?.map((e) => e as String) + ?.whereType() .toList() ?? [], ); @@ -161,7 +159,7 @@ class Community { /// Normalize a hashtag name for consistent PSK derivation. /// Strips leading #, converts to lowercase, trims whitespace. static String _normalizeCommunityHashtag(String hashtag) { - return hashtag.replaceFirst(RegExp(r'^#'), '').toLowerCase().trim(); + return hashtag.trim().replaceFirst(RegExp(r'^#'), '').toLowerCase().trim(); } /// Returns true if this is the community's public channel @@ -210,12 +208,7 @@ class Community { /// Create a copy of this community with a regenerated random secret Community withRegeneratedSecret() { - final random = Random.secure(); - final newSecret = Uint8List(32); - for (int i = 0; i < 32; i++) { - newSecret[i] = random.nextInt(256); - } - return withNewSecret(newSecret); + return withNewSecret(randomBytes(32)); } /// Extract secret from QR data (for updating existing community) diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 01d10a9c..dd35993a 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -10,6 +10,7 @@ class Contact { final int flags; final int pathLength; // -1 = flood, 0+ = direct hops (from device) final Uint8List path; // Path bytes from device + final int pathHashWidth; // Bytes per hop in [path], as learned by the device final int? pathOverride; // User's path override: -1 = force flood, null = auto final Uint8List? pathOverrideBytes; // User's path override bytes @@ -29,6 +30,7 @@ class Contact { this.flags = 0, required this.pathLength, required this.path, + this.pathHashWidth = 1, this.pathOverride, this.pathOverrideBytes, this.latitude, @@ -81,6 +83,7 @@ class Contact { int? flags, int? pathLength, Uint8List? path, + int? pathHashWidth, int? pathOverride, Uint8List? pathOverrideBytes, bool clearPathOverride = false, @@ -99,6 +102,7 @@ class Contact { flags: flags ?? this.flags, pathLength: pathLength ?? this.pathLength, path: path ?? this.path, + pathHashWidth: pathHashWidth ?? this.pathHashWidth, pathOverride: clearPathOverride ? null : (pathOverride ?? this.pathOverride), @@ -119,7 +123,7 @@ class Contact { String pathFormattedIdList(int hashByteWidth) { final pathBytes = pathBytesForDisplay; if (pathBytes.isEmpty) return ''; - final w = hashByteWidth.clamp(1, 8); + final w = hashByteWidth.clamp(1, 4); final parts = []; for (int i = 0; i < pathBytes.length; i += w) { final end = (i + w) <= pathBytes.length ? (i + w) : pathBytes.length; @@ -140,6 +144,13 @@ class Contact { return "<${publicKeyHex.substring(0, 8)}...${publicKeyHex.substring(publicKeyHex.length - 8)}>"; } + /// Infers bytes per hop for stored paths that predate [pathHashWidth]. + static int inferPathHashWidth(int hopCount, int byteLen) { + if (hopCount <= 0 || byteLen % hopCount != 0) return 1; + final width = byteLen ~/ hopCount; + return width >= 1 && width <= 3 ? width : 1; + } + Uint8List get pathBytesForDisplay { if (pathOverride != null) { if (pathOverride! < 0) return Uint8List(0); @@ -166,8 +177,18 @@ class Contact { final type = reader.readByte(); final flags = reader.readByte(); final pathLen = reader.readByte(); - final safePathLen = pathLen > 0 - ? (pathLen > maxPathSize ? maxPathSize : pathLen) + int hopCount = 0; + int byteLen = 0; + int width = 1; + if (pathLen == 0xFF) { + hopCount = -1; + } else { + width = ((pathLen & 0xC0) >> 6) + 1; + hopCount = pathLen & 0x3F; + byteLen = hopCount * width; + } + final safePathLen = byteLen > 0 + ? (byteLen > maxPathSize ? maxPathSize : byteLen) : 0; final pathBytes = reader.readBytes(maxPathSize).sublist(0, safePathLen); final name = reader.readCStringGreedy(maxNameSize); @@ -213,8 +234,9 @@ class Contact { name: name.isEmpty ? 'Unknown' : name, type: type, flags: flags, - pathLength: (pathLen == 0xFF || pathLen > maxPathSize) ? -1 : pathLen, + pathLength: hopCount, path: pathBytes, + pathHashWidth: width, latitude: lat, longitude: lon, lastSeen: DateTime.fromMillisecondsSinceEpoch( diff --git a/lib/models/delivery_observation.dart b/lib/models/delivery_observation.dart index a598d2a5..a4bd63bb 100644 --- a/lib/models/delivery_observation.dart +++ b/lib/models/delivery_observation.dart @@ -35,7 +35,7 @@ class DeliveryObservation { pathLength: json['path_length'] as int, messageBytes: json['message_bytes'] as int, secondsSinceLastRx: json['seconds_since_last_rx'] as int? ?? 0, - isFlood: json['is_flood'] as bool, + isFlood: json['is_flood'] as bool? ?? false, deliveryMs: json['delivery_ms'] as int, timestamp: DateTime.parse(json['timestamp'] as String), ); diff --git a/lib/models/display_path.dart b/lib/models/display_path.dart index 71f8ed53..b82574cc 100644 --- a/lib/models/display_path.dart +++ b/lib/models/display_path.dart @@ -1,3 +1,4 @@ +import 'dart:typed_data'; import 'dart:ui'; import 'package:latlong2/latlong.dart'; @@ -13,8 +14,8 @@ class DisplayPath { final Color color; final bool isPrimary; - /// Outbound hop bytes, including hops that could not be placed on the map. - final List hopBytes; + /// Outbound hop prefixes, including hops that could not be placed on the map. + final List hopBytes; /// Resolved map points: self, each locatable hop, then the target when its /// position is known. Hops with no position are skipped here but still diff --git a/lib/models/image_codec_support.dart b/lib/models/image_codec_support.dart new file mode 100644 index 00000000..e11476b3 --- /dev/null +++ b/lib/models/image_codec_support.dart @@ -0,0 +1,835 @@ +import 'dart:typed_data'; + +import '../widgets/image_send_codec_binding.dart'; + +/// Model registry + value types for the neural image codec (AEIC-SE). +/// +/// Mirrors `lib/models/translation_support.dart` field-for-field so the +/// settings screen, the file store and the download machinery can be copied +/// from the translation stack with no structural changes. + +enum ImageCodecStatus { none, pending, completed, failed, skipped } + +extension ImageCodecStatusValue on ImageCodecStatus { + String get value { + switch (this) { + case ImageCodecStatus.pending: + return 'pending'; + case ImageCodecStatus.completed: + return 'completed'; + case ImageCodecStatus.failed: + return 'failed'; + case ImageCodecStatus.skipped: + return 'skipped'; + case ImageCodecStatus.none: + return 'none'; + } + } +} + +ImageCodecStatus parseImageCodecStatus(dynamic value) { + if (value is! String) { + return ImageCodecStatus.none; + } + for (final status in ImageCodecStatus.values) { + if (status.value == value) { + return status; + } + } + return ImageCodecStatus.none; +} + +/// Shape of the decoder's only input tensor: `y_hat`, float32, +/// `[1, 256, 16, 16]`. Static — the export has no dynamic axes and no batching. +const List kImageCodecLatentShape = [1, 256, 16, 16]; + +/// Element count implied by [kImageCodecLatentShape] (65,536). +const int kImageCodecLatentElements = 256 * 16 * 16; + +/// Graph input/output names in the promoted export. Used as a preference when +/// binding tensors; the backend falls back to the graph's sole input/output if +/// a future re-export renames them. +const String kImageCodecDecoderInputName = 'y_hat'; +const String kImageCodecDecoderOutputName = 'image'; + +/// Rate point = which `AEIC_SE_ft*.pkl` the encoder was fine-tuned from. +/// +/// **ft32 IS THE ONLY SHIPPING RATE POINT** ([kShippingAeicRatePoint]). One +/// checkpoint ships, so [aeicRatePointForUi] is constant and the UI has no +/// quality selector to honour. The other members are retained *only* because +/// their ordinals are already persisted in `image_codec_rate_point` and cross +/// the isolate boundary, and because the measured byte counts below are real +/// data worth keeping. Do not reorder, do not add a second shipping entry +/// without a second model in [imageCodecPresetModels]. +/// +/// NOTE ON THE WIRE VALUE. This enum's ordinal is NOT the on-air rate nibble. +/// The on-air chunk-0 metadata byte is defined by `ImageStreamMetadata` in +/// `lib/services/image_chunk_transport.dart` and carries +/// [ImageCodecRatePoint.index], because the transport only ever exposes UI rate +/// points. [AeicRatePointValue]'s `wireValue` is the *model-selection ordinal*: +/// it is what gets persisted in settings and what crosses the isolate boundary +/// to pick a checkpoint. Convert with [aeicRatePointForUi] / +/// [uiRatePointForAeic]; never assume they are the same integer. +/// +/// Measured real rANS bitstream sizes at 512x512 over 26 images +/// (Kodak 24 + 2 custom). `ft2`/`ft4` have not been measured on this corpus. +enum AeicRatePoint { ft2, ft4, ft8, ft16, ft32 } + +/// The one rate point this build encodes and decodes at. +/// +/// ft32: mean 155.8 B, min 110 B, max 209 B over the 26-image corpus, i.e. 1-2 +/// data chunks plus one XOR parity chunk. ft16 was dropped: it needs 2-3 data +/// chunks and leaves only 79 B of headroom under the 3-chunk ceiling. +const AeicRatePoint kShippingAeicRatePoint = AeicRatePoint.ft32; + +extension AeicRatePointValue on AeicRatePoint { + int get wireValue => index; + + /// Mean measured bitstream size in bytes, or `null` where unmeasured. + int? get meanBytes { + switch (this) { + case AeicRatePoint.ft2: + case AeicRatePoint.ft4: + return null; + case AeicRatePoint.ft8: + return 507; + case AeicRatePoint.ft16: + return 288; + case AeicRatePoint.ft32: + return 156; + } + } + + /// Largest bitstream observed on the measurement corpus, or `null`. + int? get maxBytes { + switch (this) { + case AeicRatePoint.ft2: + case AeicRatePoint.ft4: + return null; + case AeicRatePoint.ft8: + return 732; + case AeicRatePoint.ft16: + return 409; + case AeicRatePoint.ft32: + return 209; + } + } + + /// `'ft32 (~156 B)'`. Uses the enum's own `name` for the prefix — do not add + /// a `name` getter here, it would collide with `dart:core`'s `EnumName`. + String get label { + final mean = meanBytes; + return mean == null ? name : '$name (~$mean B)'; + } +} + +AeicRatePoint parseAeicRatePoint(int wireValue) { + if (wireValue < 0 || wireValue >= AeicRatePoint.values.length) { + return kShippingAeicRatePoint; + } + return AeicRatePoint.values[wireValue]; +} + +/// Maps the UI-level rate selector onto the codec's rate points. +/// +/// ft32-only, so this is deliberately constant and ignores [rate]. It is kept +/// as a function (rather than inlining [kShippingAeicRatePoint] at the call +/// sites) so that adding a second checkpoint is a one-function change, and so +/// this file never names an [ImageCodecRatePoint] member — that enum is owned by +/// `image_send_codec_binding.dart` and its membership is the UI's to shrink. +AeicRatePoint aeicRatePointForUi(ImageCodecRatePoint rate) => + kShippingAeicRatePoint; + +/// Inverse of [aeicRatePointForUi]. Constant for the same reason: every rate +/// point this build can produce is the standard one. +ImageCodecRatePoint uiRatePointForAeic(AeicRatePoint rate) => + ImageCodecRatePoint.standard; + +/// Bundle layout revision written into [ImageCodecModelRecord.bundleVersion]. +/// +/// 0 means "installed before the entropy bundle existed", i.e. a decoder-only +/// install that can render a latent but cannot encode or decode a bitstream. +/// Bump this only when the *set of files* a model needs changes; it is what +/// `ImageCodecService.needsModelUpgrade` keys off. +/// +/// 1 -> 2: the bundle gained the **decode-side** entropy graph +/// (`aeic_entropy_decode_fp32_op17.onnx`). A version-1 install has the +/// send-side graph only, so it can encode but cannot decode a bitstream; the +/// remedy is a re-download, which is exactly what `needsModelUpgrade` asks for. +const int kImageCodecBundleVersion = 2; + +/// Same shape and field order as `TranslationModelRecord`, plus the two fields +/// a multi-asset install needs. +class ImageCodecModelRecord { + final String id; + final String name; + final String sourceUrl; + + /// Path of the **decoder graph** — the file ONNX Runtime is handed. The other + /// assets are its siblings in the same directory; see [assetFileNames]. + final String localPath; + + final DateTime downloadedAt; + final int fileSizeBytes; + + /// Every file that was installed for this model, by exact on-disk name. + /// + /// Recorded rather than re-derived so the service can locate the entropy + /// graph and the CDF tables without guessing filenames, and so `deleteModel` + /// can remove all ~1.0 GB instead of just the 3 MB graph. + final List assetFileNames; + + /// What each installed file IS, keyed by its exact on-disk name. + /// + /// Recorded at install time because [assetFileNames] alone stopped being + /// enough at bundle version 2: the bundle now holds THREE `.onnx` files — + /// the synthesis decoder, the send-side entropy graph and the decode-side + /// entropy graph — and no property of a filename distinguishes the last two. + /// Handing the decode-side export to the encoder fails at the first run; + /// handing the send-side one to the decoder would feed rANS the wrong + /// probabilities, which is the silent-corruption failure mode. + /// + /// Empty for records written before this field existed. Consumers fall back + /// to the registry spec, and only then to a filename heuristic. + final Map assetRoles; + + /// [kImageCodecBundleVersion] at install time; 0 for a pre-bundle install. + final int bundleVersion; + + const ImageCodecModelRecord({ + required this.id, + required this.name, + required this.sourceUrl, + required this.localPath, + required this.downloadedAt, + required this.fileSizeBytes, + this.assetFileNames = const [], + this.assetRoles = const {}, + this.bundleVersion = 0, + }); + + /// The installed file recorded as [role], or null when none was. + String? fileNameForRole(ImageCodecAssetRole role) { + for (final entry in assetRoles.entries) { + if (entry.value == role && assetFileNames.contains(entry.key)) { + return entry.key; + } + } + return null; + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'source_url': sourceUrl, + 'local_path': localPath, + 'downloaded_at': downloadedAt.millisecondsSinceEpoch, + 'file_size_bytes': fileSizeBytes, + 'asset_file_names': assetFileNames, + // Role NAMES, not ordinals: appending a member to ImageCodecAssetRole + // must never re-label files already on disk. + 'asset_roles': { + for (final entry in assetRoles.entries) entry.key: entry.value.name, + }, + 'bundle_version': bundleVersion, + }; + } + + factory ImageCodecModelRecord.fromJson(Map json) { + final rawAssets = json['asset_file_names']; + final rawRoles = json['asset_roles']; + return ImageCodecModelRecord( + id: json['id'] as String? ?? '', + name: json['name'] as String? ?? '', + sourceUrl: json['source_url'] as String? ?? '', + localPath: json['local_path'] as String? ?? '', + downloadedAt: DateTime.fromMillisecondsSinceEpoch( + json['downloaded_at'] as int? ?? 0, + ), + fileSizeBytes: json['file_size_bytes'] as int? ?? 0, + assetFileNames: rawAssets is List + ? [ + for (final entry in rawAssets) + if (entry is String && entry.isNotEmpty) entry, + ] + : const [], + assetRoles: rawRoles is Map + ? { + for (final entry in rawRoles.entries) + if (entry.key is String && entry.value is String) + entry.key as String: ?parseImageCodecAssetRole( + entry.value as String, + ), + } + : const {}, + bundleVersion: json['bundle_version'] as int? ?? 0, + ); + } + + ImageCodecModelRecord copyWith({ + String? id, + String? name, + String? sourceUrl, + String? localPath, + DateTime? downloadedAt, + int? fileSizeBytes, + List? assetFileNames, + Map? assetRoles, + int? bundleVersion, + }) { + return ImageCodecModelRecord( + id: id ?? this.id, + name: name ?? this.name, + sourceUrl: sourceUrl ?? this.sourceUrl, + localPath: localPath ?? this.localPath, + downloadedAt: downloadedAt ?? this.downloadedAt, + fileSizeBytes: fileSizeBytes ?? this.fileSizeBytes, + assetFileNames: assetFileNames ?? this.assetFileNames, + assetRoles: assetRoles ?? this.assetRoles, + bundleVersion: bundleVersion ?? this.bundleVersion, + ); + } +} + +String imageCodecModelFriendlyName(ImageCodecModelRecord model) { + for (final spec in imageCodecPresetModels) { + if (spec.id == model.id || spec.fileName == model.name) { + return spec.label; + } + } + final trimmed = model.name.trim(); + if (trimmed.endsWith('.onnx')) { + return trimmed.substring(0, trimmed.length - 5); + } + return trimmed.isEmpty ? model.id : trimmed; +} + +/// What a downloaded file *is*, so nothing has to infer it from position or +/// filename. +/// +/// This exists because the bundle stopped being "graph, then its data sibling". +/// `assets.first` is a decoder graph today and would silently become the +/// entropy graph the moment anyone reordered the list; the ONNX session would +/// then load 67 MB of entropy model and fail on an input named `y_hat`. +enum ImageCodecAssetRole { + /// The synthesis graph handed to ORT: `y_hat -> image`. + decoderGraph, + + /// `.data`. ORT resolves it by the literal filename recorded + /// inside the graph, so it MUST sit beside [decoderGraph] under that name. + decoderWeights, + + /// The fp32 **send-side** entropy graph: one input `image [1,3,512,512]`, + /// outputs `z_q`, `yq0..3`, `sc0..3`. Kept fp32 deliberately — see the + /// bit-exactness note in `image_codec_backend.dart`. + /// + /// This is the ENCODE half only. It emits every stage at once, which is valid + /// because the encoder already knows `y`; a decoder cannot use it at all. + entropyGraph, + + /// Reserved. The 67 MB entropy export is self-contained today and carries no + /// external-data sibling; the role exists so a future re-export that does is + /// a registry change rather than a schema change. + entropyWeights, + + /// The quantised CDF tables the rANS coder indexes. A *wrong* table set + /// desynchronises rANS and yields a sharp, plausible, wrong image with no + /// error, which is why this asset must carry a SHA-256 before ship. + cdfTables, + + /// The fp32 **decode-side** entropy graph, added in bundle version 2. + /// + /// Decoding is inherently sequential — the symbols of stage `i` must be + /// decoded before stage `i+1`'s context exists — so the receiver cannot use + /// the emit-everything-at-once [entropyGraph]. This export is the same + /// sub-networks behind an ONNX `If` on a `stage` selector, so the app can + /// call it five times per image: + /// + /// inputs : `z_q [1,128,4,4]`, `base [1,256,16,16]`, `stage int32 [1]` + /// outputs: `base0`, `means`, `scales`, all `[1,256,16,16]` + /// + /// `stage < 0` runs the hyper-synthesis branch and fills `base0`; + /// `stage 0..3` runs the context branch and fills `means`/`scales`, already + /// multiplied by that stage's mask. The branch not taken emits zeros. + /// + /// Appended after [cdfTables] rather than beside [entropyGraph] so no + /// existing enum ordinal moves. + entropyDecodeGraph, +} + +/// Parses a role written by [ImageCodecModelRecord.toJson], or null when the +/// string names no role this build knows. +/// +/// Null rather than a default: a record from a NEWER build may name a role that +/// does not exist here, and silently filing it under some other role would be +/// worse than admitting the file's purpose is unknown. +ImageCodecAssetRole? parseImageCodecAssetRole(String value) { + for (final role in ImageCodecAssetRole.values) { + if (role.name == value) { + return role; + } + } + return null; +} + +/// One downloadable file belonging to a model. +/// +/// A model is not always one file. The promoted decoder is an ONNX graph plus an +/// external-weights sibling (`.onnx.data`, referenced by relative filename +/// from inside the graph), and ONNX Runtime will not load the graph unless the +/// sibling sits next to it under exactly that name. Downloading only the 2.8 MB +/// graph produces an `ORT_INVALID_PROTOBUF`-class failure at session creation, +/// which is indistinguishable from a corrupt download — hence [sha256]. +class ImageCodecModelAsset { + /// Name the file must have on disk. Not derived from the URL: the external + /// data reference inside the graph is a literal filename. + final String fileName; + + final String sourceUrl; + + /// Expected size in bytes. Advisory — the download re-reads it from the HEAD + /// response — but it is what the UI shows before the first byte arrives. + final int sizeBytes; + + /// Lowercase hex SHA-256 of the file, or `''` when no digest is known. + /// + /// An empty value **skips verification**; see [hasChecksum]. That is the state + /// today, deliberately: nothing has been uploaded, so no digest of a + /// *published* file exists and a hard-failing guess would block the feature. + final String sha256; + + /// What this file is for. See [ImageCodecAssetRole]. + final ImageCodecAssetRole role; + + const ImageCodecModelAsset({ + required this.fileName, + required this.sourceUrl, + required this.sizeBytes, + required this.role, + this.sha256 = '', + }); + + bool get hasChecksum => sha256.length == 64; +} + +/// A declared preset model: its identity plus every file it needs on disk. +/// +/// Mirrors the role of `translationPresetModels` (translation_support.dart:117) +/// but is a *spec*, not an [ImageCodecModelRecord]. Records describe what is +/// actually on this device (path, mtime, real size); specs describe what could +/// be fetched. Conflating them is what made the translation stack unable to +/// express a two-file model. +class ImageCodecModelSpec { + final String id; + final String label; + + /// Every file the model needs, tagged by [ImageCodecAssetRole]. Downloaded in + /// list order into one directory; the order is a download preference only — + /// nothing resolves an asset by position. + final List assets; + + /// True while [assets] carry URLs that have never been fetched by anybody. + /// The UI must not offer a download for a spec with this set unless the user + /// has supplied their own URL. See the note on [imageCodecPresetModels]. + final bool urlsArePlaceholders; + + /// Which checkpoint these graphs and tables belong to. + /// + /// Tables and graphs are per-checkpoint and are not interchangeable: decoding + /// an ft32 bitstream with ft16 tables desynchronises rANS. The bundle's rate + /// point is checked against the bitstream's chunk-0 metadata before a decode. + final AeicRatePoint ratePoint; + + const ImageCodecModelSpec({ + required this.id, + required this.label, + required this.assets, + this.ratePoint = kShippingAeicRatePoint, + this.urlsArePlaceholders = false, + }); + + /// The one asset with [role], or throws when the spec omits it. + ImageCodecModelAsset assetFor(ImageCodecAssetRole role) => + assets.firstWhere((asset) => asset.role == role); + + ImageCodecModelAsset? maybeAssetFor(ImageCodecAssetRole role) { + for (final asset in assets) { + if (asset.role == role) return asset; + } + return null; + } + + /// The decoder graph — the path handed to ONNX Runtime. + /// + /// Defined by role, not by position. Kept under the old name so the settings + /// screen and [imageCodecModelFriendlyName] keep working. + ImageCodecModelAsset get graph => assetFor(ImageCodecAssetRole.decoderGraph); + + String get fileName => graph.fileName; + + int get totalSizeBytes => + assets.fold(0, (sum, asset) => sum + asset.sizeBytes); + + /// True when this spec describes a bundle that can encode AND decode. + /// + /// All five roles, not four: without [ImageCodecAssetRole.entropyDecodeGraph] + /// the install could send a picture and never open one. + bool get isComplete => + maybeAssetFor(ImageCodecAssetRole.decoderGraph) != null && + maybeAssetFor(ImageCodecAssetRole.decoderWeights) != null && + maybeAssetFor(ImageCodecAssetRole.entropyGraph) != null && + maybeAssetFor(ImageCodecAssetRole.entropyDecodeGraph) != null && + maybeAssetFor(ImageCodecAssetRole.cdfTables) != null; +} + +/// The set of on-disk paths a codec session needs, replacing the bare +/// `String modelPath` that used to cross the isolate boundary. +/// +/// [entropyGraphPath], [entropyDecodeGraphPath] and [tablesPath] are nullable +/// because a build that was installed before the entropy bundle existed has +/// none of them, and that install must keep working for latent synthesis rather +/// than becoming unloadable. +class ImageCodecBundle { + /// `*.onnx`; its `*.onnx.data` sibling must be in the same directory under + /// the exact filename the graph records. + final String decoderGraphPath; + + /// fp32 **send-side** entropy graph (`image -> z_q, yq*, sc*`), or null on a + /// pre-bundle install. Encoding needs this one and only this one. + final String? entropyGraphPath; + + /// fp32 **decode-side** entropy graph (`z_q, base, stage -> base0, means, + /// scales`), or null on a bundle-version-1 (or pre-bundle) install. + /// + /// Separate from [entropyGraphPath] because they are two different exports of + /// the same weights: the send side emits all four stages at once, which a + /// decoder cannot use, and a decoder needs the `If`-branched graph it can call + /// five times per image. See [ImageCodecAssetRole.entropyDecodeGraph]. + final String? entropyDecodeGraphPath; + + /// CDF tables binary, or null on a pre-bundle install. + final String? tablesPath; + + /// Checkpoint the graphs and tables belong to. + final AeicRatePoint ratePoint; + + const ImageCodecBundle({ + required this.decoderGraphPath, + this.entropyGraphPath, + this.entropyDecodeGraphPath, + this.tablesPath, + this.ratePoint = kShippingAeicRatePoint, + }); + + /// True when this install can run the **send** half of the entropy path. + /// + /// Deliberately does NOT require [entropyDecodeGraphPath]: a version-1 install + /// can still encode, and reporting it as unable to do anything would be wrong. + /// Use [supportsDecode] to gate a decode. + bool get isComplete => entropyGraphPath != null && tablesPath != null; + + /// True when this install can also turn a bitstream back into a picture. + bool get supportsDecode => isComplete && entropyDecodeGraphPath != null; + + @override + bool operator ==(Object other) => + other is ImageCodecBundle && + other.decoderGraphPath == decoderGraphPath && + other.entropyGraphPath == entropyGraphPath && + other.entropyDecodeGraphPath == entropyDecodeGraphPath && + other.tablesPath == tablesPath && + other.ratePoint == ratePoint; + + @override + int get hashCode => Object.hash( + decoderGraphPath, + entropyGraphPath, + entropyDecodeGraphPath, + tablesPath, + ratePoint, + ); + + @override + String toString() => + 'ImageCodecBundle(decoder: $decoderGraphPath, entropy: $entropyGraphPath, ' + 'entropyDecode: $entropyDecodeGraphPath, tables: $tablesPath, ' + 'rate: ${ratePoint.name})'; +} + +/// Published bundle: https://huggingface.co/zjs81/aeic-se-onnx +/// +/// URL shape matches `translation_support.dart`: +/// `https://huggingface.co//resolve/main/?download=true`. +/// +/// Sizes and digests below are of the published bytes, verified against the +/// local exports under `/Users/Zach/Documents/mycode/aic`. The CDF digest is +/// not optional: a table set that disagrees with the checkpoint desynchronises +/// rANS and produces a sharp, plausible, WRONG image with no error anywhere. +/// +/// EXACTLY ONE ENTRY, and it is ONE bundle rather than a send-only and a +/// receive-capable download: encode needs the entropy graph + tables, decode +/// needs those *and* the decoder, so splitting them only creates an install +/// that can do half the feature. +/// +/// WHY `qdq_conv_pct` AND NOT `qdq_conv_pct_novae`. The `novae` variant leaves +/// the VAE decoder in fp32, and the VAE is the only part that runs at full +/// 512x512, so its activations dominate: 872 MB on disk and 2.99 GiB peak RSS +/// against 835 MB / 2.16 GiB here, for 0.17 dB against the ORIGINAL image. +/// 830 MB of phone RAM is the wrong price for that on the platform where RAM, +/// not quality, is the binding constraint. +final List imageCodecPresetModels = [ + const ImageCodecModelSpec( + id: 'aeic-se-ft32-bundle-v1', + label: 'AEIC-SE 512 image codec (ft32)', + ratePoint: AeicRatePoint.ft32, + urlsArePlaceholders: false, + assets: [ + ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderGraph, + fileName: 'aeic_decoder_qdq_conv_pct.onnx', + sourceUrl: + 'https://huggingface.co/zjs81/aeic-se-onnx/resolve/main/aeic_decoder_qdq_conv_pct.onnx?download=true', + sizeBytes: 3066597, + sha256: + 'fa1ca65c52ecb9e1ec43c05ef792ac8b95ecab21dcb6ab89a825b4dad6a5a571', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderWeights, + fileName: 'aeic_decoder_qdq_conv_pct.onnx.data', + sourceUrl: + 'https://huggingface.co/zjs81/aeic-se-onnx/resolve/main/aeic_decoder_qdq_conv_pct.onnx.data?download=true', + sizeBytes: 872896480, + sha256: + 'f7714df0ec8cc495be1fb4bad3be0458c186c8a61d87b8487f2e8e6b84b8242a', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.entropyGraph, + fileName: 'aeic_entropy_side_fp32_op17.onnx', + sourceUrl: + 'https://huggingface.co/zjs81/aeic-se-onnx/resolve/main/aeic_entropy_side_fp32_op17.onnx?download=true', + sizeBytes: 67262167, + sha256: + 'b7b55b0f6a8a02ec2e8f6e85820c064c741c870c226d276c78df45e83ca1a9d6', + ), + // Local digest, for the uploader to confirm the bytes match: + // efcbbc4829a0029f487f17b7b52373c6af339d7f74a6417463981d0778d6d444 + ImageCodecModelAsset( + role: ImageCodecAssetRole.entropyDecodeGraph, + fileName: 'aeic_entropy_decode_fp32_op17.onnx', + sourceUrl: + 'https://huggingface.co/zjs81/aeic-se-onnx/resolve/main/aeic_entropy_decode_fp32_op17.onnx?download=true', + sizeBytes: 60509540, + sha256: + 'efcbbc4829a0029f487f17b7b52373c6af339d7f74a6417463981d0778d6d444', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.cdfTables, + fileName: 'aeic_cdf_ft32.bin', + sourceUrl: + 'https://huggingface.co/zjs81/aeic-se-onnx/resolve/main/aeic_cdf_ft32.bin?download=true', + sizeBytes: 813648, + sha256: + '4089fde2af16c340642a5c857be42f6d0f21caf71dd5b4f32d62efcd41c77bd5', + ), + ], + ), +]; + +/// Total download for the one shipping bundle: 1,004,548,432 B (958.0 MiB). +/// +/// Named so the pre-flight space check and the tests share one number instead +/// of each re-summing the asset list. Breakdown: 835 MiB decoder (graph + +/// external weights), 64.1 MiB send-side entropy graph, 57.7 MiB decode-side +/// entropy graph, 0.8 MiB CDF tables. +const int kImageCodecBundleTotalBytes = 1004548432; + +/// Result of an encode or a decode. +class ImageCodecResult { + /// Encode result: the compressed payload only, with no chunk headers. + final Uint8List? bitstream; + + /// Decode result: PNG-encoded RGB image. + final Uint8List? pngBytes; + + /// Decode result: packed 8-bit RGB, `resolution * resolution * 3` bytes. + /// + /// This is what the inference backend actually produces; [pngBytes] is an + /// optional re-encoding of it for widgets that want an `Image.memory`. + final Uint8List? rgbBytes; + + final AeicRatePoint ratePoint; + + /// Square edge length. 512 today and a hard floor — the SD-Turbo UNet in the + /// decoder needs a 64x64 latent and collapses below it. + final int resolution; + + final int durationMs; + final ImageCodecStatus status; + + const ImageCodecResult({ + required this.ratePoint, + required this.resolution, + required this.durationMs, + required this.status, + this.bitstream, + this.pngBytes, + this.rgbBytes, + }); +} + +class ImageCodecDownloadCancelled implements Exception { + const ImageCodecDownloadCancelled(); + + @override + String toString() => 'Download canceled.'; +} + +/// Raised by the codec session while the native inference seam is unimplemented. +class ImageCodecUnimplemented implements Exception { + final String detail; + + const ImageCodecUnimplemented(this.detail); + + @override + String toString() => 'Image codec backend not implemented: $detail'; +} + +/// Raised when a bitstream-level [encode]/[decode] is attempted but the entropy +/// path is not present in this build. +/// +/// WHY THIS EXISTS AND WHY IT IS NOT A BUG TO FIX HERE. The shipping ONNX +/// artifact is the **synthesis half only**: `y_hat [1,256,16,16] -> image +/// [1,3,512,512]`. Turning bytes into `y_hat` (and back) needs two more things +/// that do not exist in Dart or in the shipped artifact: +/// +/// 1. the entropy-side graph (`h_s`, `g_c` and the four adapters, kept in +/// fp32 — `aic/onnx/aeic_entropy_side_fp32_op*.onnx`, 67 MB, not exported +/// into the shipped model), and +/// 2. the rANS range coder itself, which today exists only as the AEIC C++ +/// extension (`aic/aeic/src/codec/MLCodec_rans*.so`). +/// +/// Until both land, [ImageCodecBackend.decodeLatentToRgb] is the real, working +/// entry point and the bitstream methods throw this. Faking them is not an +/// option: an rANS desync produces a sharp, plausible, *wrong* image with no +/// error raised, so a stub that returns noise-shaped bytes would be +/// indistinguishable from the genuine failure mode this codec already has. +class ImageCodecEntropyPathMissing extends ImageCodecUnimplemented { + const ImageCodecEntropyPathMissing([ + super.detail = + 'the rANS entropy path (entropy-side graph + range coder) is not part ' + 'of this build; only latent->image synthesis is available', + ]); +} + +/// Raised when a bitstream operation is attempted against an install that +/// predates the entropy bundle. +/// +/// Distinct from [ImageCodecEntropyPathMissing] on purpose. That one means the +/// *build* cannot do this and no user action helps; this one means the *files +/// on this device* are a decoder-only install and the remedy is a download. +/// Reporting the second as the first is what would strand every user who +/// installed the decoder-only build. +class ImageCodecBundleIncomplete extends ImageCodecUnimplemented { + const ImageCodecBundleIncomplete([ + super.detail = + 'the installed model predates the entropy bundle; re-download the ' + 'image codec model', + ]); +} + +/// Raised when a downloaded asset's SHA-256 does not match the expected digest. +class ImageCodecIntegrityFailure implements Exception { + final String fileName; + final String expected; + final String actual; + + const ImageCodecIntegrityFailure({ + required this.fileName, + required this.expected, + required this.actual, + }); + + @override + String toString() => + 'Checksum mismatch for $fileName: expected $expected, got $actual.'; +} + +/// Persisted image-codec preferences. +/// +/// These five fields are destined for `AppSettings` (see the integration notes +/// for task B4, item 1); they live in their own value type until then so this +/// workstream adds no edits to `app_settings.dart`. The JSON keys already match +/// the `image_codec_*` names the AppSettings migration will use, so moving them +/// is a copy, not a rewrite. +class ImageCodecPreferences { + final bool enabled; + final String? selectedModelId; + final String? modelSourceUrl; + + /// [AeicRatePoint.wireValue] of the composer's default rate point. + final int ratePoint; + + final List downloadedModels; + + const ImageCodecPreferences({ + this.enabled = false, + this.selectedModelId, + this.modelSourceUrl, + this.ratePoint = 4, // AeicRatePoint.ft32 + this.downloadedModels = const [], + }); + + AeicRatePoint get aeicRatePoint => parseAeicRatePoint(ratePoint); + + Map toJson() { + return { + 'image_codec_enabled': enabled, + 'image_codec_selected_model_id': selectedModelId, + 'image_codec_model_source_url': modelSourceUrl, + 'image_codec_rate_point': ratePoint, + 'image_codec_downloaded_models': [ + for (final model in downloadedModels) model.toJson(), + ], + }; + } + + factory ImageCodecPreferences.fromJson(Map json) { + final rawModels = json['image_codec_downloaded_models']; + return ImageCodecPreferences( + enabled: json['image_codec_enabled'] as bool? ?? false, + selectedModelId: json['image_codec_selected_model_id'] as String?, + modelSourceUrl: json['image_codec_model_source_url'] as String?, + ratePoint: json['image_codec_rate_point'] as int? ?? 4, + downloadedModels: rawModels is List + ? [ + for (final entry in rawModels) + if (entry is Map) + ImageCodecModelRecord.fromJson(entry), + ] + : const [], + ); + } + + static const Object _unset = Object(); + + ImageCodecPreferences copyWith({ + bool? enabled, + Object? selectedModelId = _unset, + Object? modelSourceUrl = _unset, + int? ratePoint, + List? downloadedModels, + }) { + return ImageCodecPreferences( + enabled: enabled ?? this.enabled, + selectedModelId: identical(selectedModelId, _unset) + ? this.selectedModelId + : selectedModelId as String?, + modelSourceUrl: identical(modelSourceUrl, _unset) + ? this.modelSourceUrl + : modelSourceUrl as String?, + ratePoint: ratePoint ?? this.ratePoint, + downloadedModels: downloadedModels ?? this.downloadedModels, + ); + } +} diff --git a/lib/models/message.dart b/lib/models/message.dart index e1395617..a9b7c0cd 100644 --- a/lib/models/message.dart +++ b/lib/models/message.dart @@ -8,7 +8,7 @@ enum MessageStatus { pending, sent, delivered, failed } class Message { static const Object _unset = Object(); - final Uint8List senderKey; + final Uint8List senderKey; // For outgoing msgs, gets used as recipientKey final String text; final DateTime timestamp; final bool isOutgoing; @@ -30,7 +30,7 @@ class Message { final int? tripTimeMs; final int? pathLength; final Uint8List pathBytes; - final Map reactions; + final Map> reactions; final Map reactionStatuses; final Uint8List fourByteRoomContactKey; @@ -56,7 +56,7 @@ class Message { this.pathLength, Uint8List? pathBytes, Uint8List? fourByteRoomContactKey, - Map? reactions, + Map>? reactions, Map? reactionStatuses, }) : messageId = messageId ?? @@ -84,7 +84,7 @@ class Message { Object? translatedLanguageCode = _unset, MessageTranslationStatus? translationStatus, Object? translationModelId = _unset, - Map? reactions, + Map>? reactions, Map? reactionStatuses, Uint8List? fourByteRoomContactKey, }) { diff --git a/lib/models/radio_settings.dart b/lib/models/radio_settings.dart index e74cf209..f7c4709c 100644 --- a/lib/models/radio_settings.dart +++ b/lib/models/radio_settings.dart @@ -81,6 +81,16 @@ class RadioSettings { txPowerDbm: 20, ), ), + ( + 'Australia (Mid)', + RadioSettings( + frequencyMHz: 915.075, + bandwidth: LoRaBandwidth.bw125, + spreadingFactor: LoRaSpreadingFactor.sf9, + codingRate: LoRaCodingRate.cr4_5, + txPowerDbm: 20, + ), + ), ( 'Australia SA, WA, QLD', RadioSettings( @@ -466,9 +476,19 @@ class RadioSettings { RadioSettings( frequencyMHz: 908.205, bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf10, + spreadingFactor: LoRaSpreadingFactor.sf9, + codingRate: LoRaCodingRate.cr4_8, + txPowerDbm: 22, + ), + ), + ( + 'USA Philly', + RadioSettings( + frequencyMHz: 902.250, + bandwidth: LoRaBandwidth.bw500, + spreadingFactor: LoRaSpreadingFactor.sf11, codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, + txPowerDbm: 22, ), ), ( @@ -478,7 +498,7 @@ class RadioSettings { bandwidth: LoRaBandwidth.bw62_5, spreadingFactor: LoRaSpreadingFactor.sf7, codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, + txPowerDbm: 22, ), ), ( @@ -505,7 +525,7 @@ class RadioSettings { ( 'Off-Grid 869', RadioSettings( - frequencyMHz: 869.0, + frequencyMHz: 869.495, bandwidth: LoRaBandwidth.bw250, spreadingFactor: LoRaSpreadingFactor.sf11, codingRate: LoRaCodingRate.cr4_8, diff --git a/lib/models/remote_node_stats.dart b/lib/models/remote_node_stats.dart new file mode 100644 index 00000000..25d42ae4 --- /dev/null +++ b/lib/models/remote_node_stats.dart @@ -0,0 +1,88 @@ +import 'dart:typed_data'; + +/// Binary status reply pushed as PUSH_CODE_STATUS_RESPONSE. +/// +/// The first 48 bytes are shared by repeater `RepeaterStats` and room +/// `ServerStats`. After that, repeaters send `total_rx_air_time_secs` and +/// `n_recv_errors` (uint32 each), rooms send `n_posted` and `n_post_push` +/// (uint16 each). +class RemoteNodeStats { + static const int payloadOffset = 8; + static const int commonSize = 48; + + final int batteryMv; + final int queueLen; + final int noiseFloor; + final int lastRssi; + final int packetsRecv; + final int packetsSent; + final int txAirSecs; + final int uptimeSecs; + final int floodTx; + final int directTx; + final int floodRx; + final int directRx; + final int errEvents; + final double lastSnr; + final int directDups; + final int floodDups; + final int? rxAirSecs; + final int? recvErrors; + final int? posted; + final int? postPushes; + + const RemoteNodeStats({ + required this.batteryMv, + required this.queueLen, + required this.noiseFloor, + required this.lastRssi, + required this.packetsRecv, + required this.packetsSent, + required this.txAirSecs, + required this.uptimeSecs, + required this.floodTx, + required this.directTx, + required this.floodRx, + required this.directRx, + required this.errEvents, + required this.lastSnr, + required this.directDups, + required this.floodDups, + this.rxAirSecs, + this.recvErrors, + this.posted, + this.postPushes, + }); + + static RemoteNodeStats? tryParse(Uint8List frame, {required bool isRoom}) { + if (frame.length < payloadOffset + commonSize) return null; + final data = ByteData.sublistView(frame, payloadOffset); + int u16(int o) => data.getUint16(o, Endian.little); + int i16(int o) => data.getInt16(o, Endian.little); + int u32(int o) => data.getUint32(o, Endian.little); + bool has(int o, int size) => data.lengthInBytes >= o + size; + + return RemoteNodeStats( + batteryMv: u16(0), + queueLen: u16(2), + noiseFloor: i16(4), + lastRssi: i16(6), + packetsRecv: u32(8), + packetsSent: u32(12), + txAirSecs: u32(16), + uptimeSecs: u32(20), + floodTx: u32(24), + directTx: u32(28), + floodRx: u32(32), + directRx: u32(36), + errEvents: u16(40), + lastSnr: i16(42) / 4.0, + directDups: u16(44), + floodDups: u16(46), + rxAirSecs: !isRoom && has(48, 4) ? u32(48) : null, + recvErrors: !isRoom && has(52, 4) ? u32(52) : null, + posted: isRoom && has(48, 2) ? u16(48) : null, + postPushes: isRoom && has(50, 2) ? u16(50) : null, + ); + } +} diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index e54687c9..a38c4b38 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -6,11 +6,16 @@ import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../models/app_settings.dart'; +import '../models/image_codec_support.dart'; import '../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/mesh_ui.dart'; import '../widgets/sync_progress_overlay.dart'; @@ -18,7 +23,16 @@ import '../helpers/snack_bar_builder.dart'; import 'map_cache_screen.dart'; class AppSettingsScreen extends StatelessWidget { - const AppSettingsScreen({super.key}); + /// Scrolls the image-message settings into view once, on first build. + /// + /// This is how the received-image placeholder's "no model installed" tap + /// lands somewhere useful: the image block sits below appearance, + /// notifications, messaging, battery, map and translation, so pushing the + /// plain settings screen would drop the user at the top with no hint that + /// the thing they tapped for is several screens down. + final bool focusImageMessages; + + const AppSettingsScreen({super.key, this.focusImageMessages = false}); @override Widget build(BuildContext context) { @@ -308,6 +322,22 @@ class AppSettingsScreen extends StatelessWidget { ? (value) => settingsService.setNotifyOnNewMessage(value) : null, ), + if (PlatformInfo.isAndroid) ...[ + const Divider(height: 1, indent: 16), + ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + leading: const Icon(Icons.battery_saver_outlined, size: 20), + title: Text(context.l10n.appSettings_batteryOptimization), + subtitle: Text( + context.l10n.appSettings_batteryOptimizationSubtitle, + ), + trailing: const Icon(Icons.open_in_new, size: 18), + onTap: BackgroundService.openBatteryOptimizationSettings, + ), + ], const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( @@ -597,10 +627,252 @@ class AppSettingsScreen extends StatelessWidget { settingsService.setEnableMessageTracing(value); }, ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.cell_tower, size: 20), + title: Text(context.l10n.appSettings_channelMinHops), + subtitle: Text(context.l10n.appSettings_channelMinHopsSubtitle), + value: settingsService.settings.channelMinHopsEnabled, + onChanged: settingsService.setChannelMinHopsEnabled, + ), + if (settingsService.settings.channelMinHopsEnabled) ...[ + ListTile( + title: Text( + context.l10n.appSettings_channelMinHopsCount( + settingsService.settings.channelMinHops, + ), + ), + subtitle: Slider( + value: settingsService.settings.channelMinHops.toDouble(), + min: 1, + max: 8, + divisions: 7, + label: settingsService.settings.channelMinHops.toString(), + onChanged: (value) => + settingsService.setChannelMinHops(value.toInt()), + ), + ), + ListTile( + title: Text( + context.l10n.appSettings_channelMinHopsRetries( + settingsService.settings.channelMinHopsRetries, + ), + ), + subtitle: Slider( + value: settingsService.settings.channelMinHopsRetries.toDouble(), + min: 1, + max: 5, + divisions: 4, + label: settingsService.settings.channelMinHopsRetries.toString(), + onChanged: (value) => + settingsService.setChannelMinHopsRetries(value.toInt()), + ), + ), + ], + const Divider(height: 1, indent: 16), + _ScrollIntoViewOnce( + enabled: focusImageMessages, + child: SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.image_outlined, size: 20), + title: Text(context.l10n.imageMessages_enableTitle), + subtitle: Text(context.l10n.imageMessages_enableSubtitle), + value: settingsService.settings.imageMessagesEnabled, + onChanged: (value) async { + // ImageCodecService.availability requires BOTH the app-level + // toggle and its own `enabled` preference; one switch drives both + // so the user is never left with a silently half-on feature. + final codec = _imageCodecService(context); + await settingsService.setImageMessagesEnabled(value); + await codec?.setEnabled(value); + }, + ), + ), + if (settingsService.settings.imageMessagesEnabled) ...[ + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.auto_awesome_outlined, size: 20), + title: Text(context.l10n.imageMessages_autoProcessTitle), + subtitle: Text(context.l10n.imageMessages_autoProcessSubtitle), + value: settingsService.settings.imageProcessAutomatically, + onChanged: (value) => + settingsService.setImageProcessAutomatically(value), + ), + _buildImageCodecModels(context), + ], ], ); } + /// The image codec, or null when it is not registered (screen tests). + ImageCodecService? _imageCodecService(BuildContext context) { + try { + return Provider.of(context, listen: false); + } on ProviderNotFoundException { + return null; + } + } + + /// Model registry for image messages: the download entry point, the + /// downloaded weights, and — when the build simply cannot run the codec — + /// [ImageCodecService.unavailableReason] instead of a dead download button. + Widget _buildImageCodecModels(BuildContext context) { + final ImageCodecService codec; + try { + codec = context.watch(); + } on ProviderNotFoundException { + return const SizedBox.shrink(); + } + final scheme = Theme.of(context).colorScheme; + final textTheme = Theme.of(context).textTheme; + final reason = codec.unavailableReason; + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + context.l10n.imageMessages_modelSectionTitle, + style: textTheme.titleSmall, + ), + const SizedBox(height: 6), + if (reason != null) + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(MeshRadii.md), + ), + child: Text( + reason, + style: textTheme.bodySmall?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + for (final spec in imageCodecPresetModels) + _buildImageCodecPreset(context, codec, spec), + for (final model in codec.availableModels) + ListTile( + contentPadding: EdgeInsets.zero, + dense: true, + leading: const Icon(Icons.check_circle_outline, size: 20), + title: Text(model.name.isEmpty ? model.id : model.name), + subtitle: Text(_formatModelBytes(model.fileSizeBytes)), + trailing: IconButton( + icon: const Icon(Icons.delete_outline, size: 20), + tooltip: context.l10n.imageMessages_removeModel, + onPressed: codec.isBusy || codec.isDownloading + ? null + : () => codec.removeModel(model), + ), + ), + if (codec.lastError != null) ...[ + const SizedBox(height: 6), + Text( + codec.lastError!, + style: textTheme.bodySmall?.copyWith(color: scheme.error), + ), + ], + ], + ), + ); + } + + Widget _buildImageCodecPreset( + BuildContext context, + ImageCodecService codec, + ImageCodecModelSpec spec, + ) { + final textTheme = Theme.of(context).textTheme; + final scheme = Theme.of(context).colorScheme; + final alreadyHave = codec.availableModels.any((m) => m.id == spec.id); + // downloadPresetModel throws StateError on a placeholder URL, deliberately, + // so the button must not be offerable until the weights are published. + final blocked = spec.urlsArePlaceholders; + final busy = codec.isDownloading; + + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListTile( + contentPadding: EdgeInsets.zero, + dense: true, + leading: const Icon(Icons.download_outlined, size: 20), + title: Text(spec.label), + subtitle: Text( + blocked + ? context.l10n.imageMessages_modelNotPublished + : _formatModelBytes(spec.totalSizeBytes), + ), + trailing: alreadyHave + ? Text( + context.l10n.imageMessages_modelReady, + style: textTheme.labelMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ) + : busy + ? TextButton( + onPressed: codec.cancelDownload, + child: Text(context.l10n.imageMessages_cancelDownload), + ) + : TextButton( + onPressed: blocked + ? null + : () => _downloadImageCodecModel(context, codec, spec), + child: Text(context.l10n.imageMessages_downloadModel), + ), + ), + if (busy) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: LinearProgressIndicator(value: codec.downloadProgress), + ), + ], + ), + ); + } + + Future _downloadImageCodecModel( + BuildContext context, + ImageCodecService codec, + ImageCodecModelSpec spec, + ) async { + final messenger = ScaffoldMessenger.of(context); + final failed = context.l10n.imageMessages_downloadFailed; + try { + await codec.downloadPresetModel(spec); + } on Exception catch (error) { + messenger.showSnackBar(SnackBar(content: Text('$failed $error'))); + } + } + + String _formatModelBytes(int bytes) { + if (bytes >= 1024 * 1024 * 1024) { + return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB'; + } + if (bytes >= 1024 * 1024) { + return '${(bytes / (1024 * 1024)).toStringAsFixed(0)} MB'; + } + if (bytes >= 1024) return '${(bytes / 1024).toStringAsFixed(0)} kB'; + return '$bytes B'; + } + Widget _buildBatteryContent( BuildContext context, AppSettingsService settingsService, @@ -687,6 +959,10 @@ class AppSettingsScreen extends StatelessWidget { value: 'lipo', child: Text(context.l10n.appSettings_batteryLipo), ), + DropdownMenuItem( + value: 'lipo_hv', + child: Text(context.l10n.appSettings_batteryLipoHv), + ), ], ), ], @@ -699,52 +975,229 @@ class AppSettingsScreen extends StatelessWidget { ) { final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; - return Column( - children: [ - SwitchListTile( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 4, + 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, + ), + ], ), - 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, + ), + 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, + ), + ], ), - 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, + ), + const Divider(height: 1, indent: 16), + InkWell( + 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, + ), + ], ), - 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: () => _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: () => _showTimeFilterSheet(context, settingsService), + onTap: () => _showMapRasterEndpointDialog(context, settingsService), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( children: [ Icon( - Icons.timer_outlined, + Icons.public_outlined, size: 20, color: scheme.onSurfaceVariant, ), @@ -754,19 +1207,14 @@ class AppSettingsScreen extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - context.l10n.appSettings_timeFilter, + context.l10n.appSettings_stadiaEndpoint, 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(), - ), + _mapRasterEndpointSummary(settingsService.settings), style: textTheme.bodySmall?.copyWith( color: scheme.onSurfaceVariant, ), @@ -785,13 +1233,13 @@ class AppSettingsScreen extends StatelessWidget { ), const Divider(height: 1, indent: 16), InkWell( - onTap: () => _showUnitsSheet(context, settingsService), + onTap: () => _showMapApiKeyDialog(context, settingsService), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Row( children: [ Icon( - Icons.straighten, + Icons.key_outlined, size: 20, color: scheme.onSurfaceVariant, ), @@ -801,17 +1249,14 @@ class AppSettingsScreen extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - context.l10n.appSettings_unitsTitle, + context.l10n.appSettings_stadiaApiKey, 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, + _mapApiKeySummary(context, settingsService.settings), style: textTheme.bodySmall?.copyWith( color: scheme.onSurfaceVariant, ), @@ -828,59 +1273,208 @@ class AppSettingsScreen extends StatelessWidget { ), ), ), - const Divider(height: 1, indent: 16), - InkWell( - 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( + ]); + } + + return Column(children: children); + } + + String _mapRasterSourceSummary(AppSettings settings) { + final source = MapRasterSourceCatalog.fromSettings(settings); + return '${source.label} - ${source.description}'; + } + + bool _isStadiaSource(AppSettings settings) { + return MapRasterSourceCatalog.fromSettings(settings).isStadia; + } + + String _mapRasterEndpointSummary(AppSettings settings) { + final endpoint = MapRasterEndpointCatalog.fromSettings(settings); + return '${endpoint.label} - ${endpoint.description}'; + } + + String _mapApiKeySummary(BuildContext context, AppSettings settings) { + return context.l10n.appSettings_stadiaApiKeyConfigured( + _maskApiKey(settings.effectiveMapTileApiKey), + ); + } + + String _maskApiKey(String value) { + if (value.length <= 8) return '********'; + return '${value.substring(0, 4)}...${value.substring(value.length - 4)}'; + } + + void _showMapRasterSourceDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + String selectedId = settingsService.settings.mapRasterSourceId; + showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (dialogContext, setState) => AlertDialog( + title: Text(context.l10n.appSettings_rasterTileSource), + content: SizedBox( + width: 360, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(dialogContext).size.height * 0.6, + ), + child: SingleChildScrollView( + child: RadioGroup( + groupValue: selectedId, + onChanged: (value) { + if (value == null) return; + setState(() { + selectedId = value; + }); + }, child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - Text( - context.l10n.appSettings_offlineMapCache, - style: textTheme.bodyMedium?.copyWith( - fontWeight: FontWeight.w600, + for (final preset in MapRasterSourcePreset.values) + Builder( + builder: (context) { + final option = MapRasterSourceCatalog.fromPreset( + preset, + ); + return RadioListTile( + value: preset.id, + title: Text(option.label), + subtitle: Text(option.description), + ); + }, ), - ), - 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, - ), - ], + ), ), ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(context.l10n.common_cancel), + ), + TextButton( + onPressed: () async { + await settingsService.setMapRasterSourceId(selectedId); + if (!dialogContext.mounted) return; + Navigator.pop(dialogContext); + }, + child: Text(context.l10n.common_save), + ), + ], ), - ], + ), + ); + } + + void _showMapRasterEndpointDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + String selectedId = settingsService.settings.mapTileEndpointId; + showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (dialogContext, setState) => AlertDialog( + title: Text(context.l10n.appSettings_stadiaEndpoint), + content: SizedBox( + width: 360, + child: RadioGroup( + groupValue: selectedId, + onChanged: (value) { + if (value == null) return; + setState(() { + selectedId = value; + }); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in MapRasterEndpointCatalog.presets) + RadioListTile( + value: option.id, + title: Text(option.label), + subtitle: Text(option.description), + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(context.l10n.common_cancel), + ), + TextButton( + onPressed: () async { + await settingsService.setMapTileEndpointId(selectedId); + if (!dialogContext.mounted) return; + Navigator.pop(dialogContext); + }, + child: Text(context.l10n.common_save), + ), + ], + ), + ), + ); + } + + void _showMapApiKeyDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + final currentApiKey = settingsService.settings.mapTileApiKey?.trim() ?? ''; + final maskedApiKey = _maskApiKey( + currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey, + ); + final controller = TextEditingController(text: maskedApiKey); + 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', + ), + ), + ], + ), + ), + 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), + ), + ], + ), ); } @@ -1027,7 +1621,11 @@ class AppSettingsScreen extends StatelessWidget { for (final model in settings.translationDownloadedModels) DropdownMenuItem( value: model.id, - child: Text(translationModelFriendlyName(model)), + child: Text( + translationModelFriendlyName(model), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: settings.translationDownloadedModels.isEmpty @@ -1050,7 +1648,11 @@ class AppSettingsScreen extends StatelessWidget { for (final preset in translationPresetModels) DropdownMenuItem( value: preset.sourceUrl, - child: Text(translationModelFriendlyName(preset)), + child: Text( + translationModelFriendlyName(preset), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: translationService.isBusy @@ -1211,6 +1813,7 @@ class AppSettingsScreen extends StatelessWidget { const SizedBox(height: 8), DropdownButtonFormField( initialValue: settingsService.settings.selectedCyr2latProfileId, + isExpanded: true, decoration: InputDecoration( labelText: context.l10n.channels_cyr2latSettingsSubheading, border: const OutlineInputBorder(), @@ -1218,7 +1821,11 @@ class AppSettingsScreen extends StatelessWidget { items: settingsService.settings.cyr2latProfiles.map((profile) { return DropdownMenuItem( value: profile.id, - child: Text(profile.name), + child: Text( + profile.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ); }).toList(), onChanged: (value) { @@ -2186,3 +2793,45 @@ class _TranslationLanguageDialogContentState ); } } + +/// Scrolls [child] into view exactly once, after the first frame. +/// +/// A `StatefulWidget` rather than a post-frame callback in `build` because the +/// settings screen rebuilds on every `AppSettingsService` notification: a +/// callback in `build` would yank the list back to the image block every time +/// the user touched an unrelated switch. +/// +/// Silently does nothing when there is no enclosing [Scrollable] (screen tests +/// that render a section in isolation) or when the element is gone by the time +/// the frame lands. +class _ScrollIntoViewOnce extends StatefulWidget { + final bool enabled; + final Widget child; + + const _ScrollIntoViewOnce({required this.enabled, required this.child}); + + @override + State<_ScrollIntoViewOnce> createState() => _ScrollIntoViewOnceState(); +} + +class _ScrollIntoViewOnceState extends State<_ScrollIntoViewOnce> { + @override + void initState() { + super.initState(); + if (!widget.enabled) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final scrollable = Scrollable.maybeOf(context); + if (scrollable == null) return; + Scrollable.ensureVisible( + context, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + alignment: 0.1, + ); + }); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/lib/screens/ble_debug_log_screen.dart b/lib/screens/ble_debug_log_screen.dart index fc8fe2d0..7eb4aa5f 100644 --- a/lib/screens/ble_debug_log_screen.dart +++ b/lib/screens/ble_debug_log_screen.dart @@ -10,6 +10,13 @@ import '../helpers/snack_bar_builder.dart'; enum _BleLogView { frames, rawLogRx } +int _decodeRawPathByteLen(int pathLenRaw) { + if (pathLenRaw == 0xFF || pathLenRaw == 0) return 0; + final hashCount = pathLenRaw & 0x3F; + final hashWidth = ((pathLenRaw >> 6) & 0x03) + 1; + return hashCount * hashWidth; +} + class BleDebugLogScreen extends StatefulWidget { const BleDebugLogScreen({super.key}); @@ -314,16 +321,17 @@ class _BleDebugLogScreenState extends State { rawHex: _bytesToHex(raw), ); } - final pathLen = raw[index++]; - if (raw.length < index + pathLen) { + final pathLenRaw = raw[index++]; + final pathByteLen = _decodeRawPathByteLen(pathLenRaw); + if (raw.length < index + pathByteLen) { return _RawPacketInfo( title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', summary: 'Truncated path', rawHex: _bytesToHex(raw), ); } - final pathBytes = raw.sublist(index, index + pathLen); - index += pathLen; + final pathBytes = raw.sublist(index, index + pathByteLen); + index += pathByteLen; if (raw.length <= index) { return _RawPacketInfo( title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}', @@ -336,7 +344,7 @@ class _BleDebugLogScreenState extends State { final title = 'RX ${_payloadTypeLabel(payloadType)} • ${_routeLabel(routeType)} • v$payloadVer'; final summary = _decodePayloadSummary(payloadType, payload); - final pathSummary = pathLen > 0 + final pathSummary = pathByteLen > 0 ? 'Path=${_bytesToHex(pathBytes)}' : 'Path=none'; final detail = '$summary • $pathSummary • len=${raw.length}'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index bbbb270b..2373b30f 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1,11 +1,12 @@ import 'dart:async'; import 'dart:convert'; import 'dart:math' as math; +import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import 'package:intl/intl.dart' hide TextDirection; +import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; @@ -16,22 +17,34 @@ import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; +import '../helpers/message_url_image_helper.dart'; +import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/snack_bar_builder.dart'; 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'; +import '../services/image_codec_service.dart'; +import '../services/received_image_store.dart'; import '../services/translation_service.dart'; +import '../utils/image_save.dart'; +import '../utils/lora_airtime.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_zoom_wrapper.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'; @@ -40,6 +53,7 @@ import '../widgets/translated_message_content.dart'; import '../widgets/unread_divider.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; +import 'app_settings_screen.dart'; import 'channel_message_path_screen.dart'; import 'map_screen.dart'; import 'region_management_screen.dart'; @@ -70,15 +84,21 @@ class _ChannelChatScreenState extends State { bool _isLoadingOlder = false; bool _communitiesLoaded = false; + /// Per-screen image-id allocator. The id is 8 bits and the reassembly key also + /// carries the sender prefix and channel, so a per-screen allocator is enough + /// to keep two images in the same channel apart. + final ImageIdAllocator _imageIds = ImageIdAllocator(); + + /// Chunks acked so far / total, while an image send is in flight. Both 0 when + /// nothing is being sent. + int _imageSendSent = 0; + int _imageSendTotal = 0; + MeshCoreConnector? _connector; DateTime? _lastChannelSendAt; bool _channelSkipNextBottomSnap = false; String? _unreadDividerMessageId; - String? _cachedFormatLocale; - late DateFormat _hmFormat; - late DateFormat _mdFormat; - @override void initState() { super.initState(); @@ -298,21 +318,32 @@ class _ChannelChatScreenState extends State { ), Consumer( builder: (context, connector, _) { - final unreadCount = connector - .getUnreadCountForChannelIndex( - widget.channel.index, - ); - final privacy = widget.channel.isPublicChannel - ? context.l10n.channels_public - : context.l10n.channels_private; - final region = connector.getChannelRegion( + final privacy = switch (Channel.getChannelType( + widget.channel, + _communityIndex, + )) { + ChannelType.public => context.l10n.channels_public, + ChannelType.hashtag => context.l10n.channels_hashtag, + ChannelType.private => context.l10n.channels_private, + ChannelType.communityPublic => + context.l10n.community_publicChannel, + ChannelType.communityHashtag => + context.l10n.community_hashtagChannel, + }; + final ownRegion = connector.getChannelRegion( widget.channel.index, ); + final region = connector.getEffectiveChannelRegion( + widget.channel.index, + ); + final defaultSuffix = ownRegion.isEmpty + ? ' ${context.l10n.channels_regionDefaultSuffix}' + : ''; final regionText = region.isNotEmpty - ? ' • ${context.l10n.channels_regionSetTo(region)}' + ? ' • ${context.l10n.channels_regionSetTo(region)}$defaultSuffix' : ''; return Text( - '$privacy • ${context.l10n.chat_unread(unreadCount)}$regionText', + '$privacy$regionText', overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12), ); @@ -372,8 +403,9 @@ class _ChannelChatScreenState extends State { child: Consumer( builder: (context, connector, child) { final messages = connector.getChannelMessages(widget.channel); + final imageRows = _receivedImageRows(context); - if (messages.isEmpty) { + if (messages.isEmpty && imageRows.isEmpty) { return EmptyState( icon: widget.channel.isPublicChannel ? Icons.public @@ -389,16 +421,27 @@ class _ChannelChatScreenState extends State { ); } - // Reverse messages so newest appear at bottom with reverse: true - final reversedMessages = messages.reversed.toList(); + 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 timestamp 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.timestamp.compareTo(b.timestamp)); + + // Reverse rows so newest appear at bottom with reverse: true + final reversedRows = rows.reversed.toList(); final itemCount = - reversedMessages.length + (_isLoadingOlder ? 1 : 0); + reversedRows.length + (_isLoadingOlder ? 1 : 0); // Prune stale keys (deleted/cleared messages) to avoid // unbounded growth. - final liveIds = reversedMessages - .map((m) => m.messageId) - .toSet(); + final liveIds = reversedRows.map((r) => r.id).toSet(); _messageKeys.removeWhere((id, _) => !liveIds.contains(id)); // Two messages can collide on messageId (same ms + name/text @@ -407,8 +450,8 @@ class _ChannelChatScreenState extends State { // no two widgets share one GlobalKey. final seenIds = {}; final keyedIndices = {}; - for (var i = 0; i < reversedMessages.length; i++) { - if (seenIds.add(reversedMessages[i].messageId)) { + for (var i = 0; i < reversedRows.length; i++) { + if (seenIds.add(reversedRows[i].id)) { keyedIndices.add(i); } } @@ -446,12 +489,11 @@ class _ChannelChatScreenState extends State { ), ); } - final messageIndex = index; - final message = reversedMessages[messageIndex]; + final row = reversedRows[index]; final GlobalKey messageKey; - if (keyedIndices.contains(messageIndex)) { + if (keyedIndices.contains(index)) { messageKey = _messageKeys.putIfAbsent( - message.messageId, + row.id, GlobalKey.new, ); } else { @@ -459,7 +501,7 @@ class _ChannelChatScreenState extends State { } final isUnreadAnchor = _unreadDividerMessageId != null && - message.messageId == _unreadDividerMessageId; + row.id == _unreadDividerMessageId; return Container( key: messageKey, child: Builder( @@ -468,14 +510,33 @@ class _ChannelChatScreenState extends State { .select( (service) => service.scale, ); - final bubble = _buildMessageBubble( - message, - textScale, - ); - if (isUnreadAnchor) { + final message = row.message; + final bubble = message != null + ? _buildMessageBubble( + message, + textScale, + urlImagesEnabled, + ) + : _buildImageBubble( + row.image!, + textScale, + ); + final startsDay = + index == reversedRows.length - 1 || + !isSameChatDay( + reversedRows[index + 1].timestamp, + row.timestamp, + ); + if (isUnreadAnchor || startsDay) { return Column( mainAxisSize: MainAxisSize.min, - children: [const UnreadDivider(), bubble], + children: [ + if (startsDay) + ChatDaySeparator(day: row.timestamp), + if (isUnreadAnchor) + const UnreadDivider(), + bubble, + ], ); } return bubble; @@ -491,7 +552,7 @@ class _ChannelChatScreenState extends State { }, ), ), - _buildMessageComposer(), + _buildInputBar(), ], ), ), @@ -510,7 +571,11 @@ class _ChannelChatScreenState extends State { connector.setChannelUnreadCount(widget.channel.index, count); } - Widget _buildMessageBubble(ChannelMessage message, double textScale) { + Widget _buildMessageBubble( + ChannelMessage message, + double textScale, + bool urlImagesEnabled, + ) { final settingsService = context.watch(); final enableTracing = settingsService.settings.enableMessageTracing; final isOutgoing = message.isOutgoing; @@ -530,6 +595,14 @@ class _ChannelChatScreenState extends State { : (message.pathVariants.isNotEmpty ? message.pathVariants.first : Uint8List(0)); + final displayPathHashWidth = + message.pathHashWidth ?? + context.read().pathHashByteWidth; + final displayHopCount = _displayHopCount( + displayPath, + displayPathHashWidth, + message.pathLength, + ); // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. final bubbleColor = isOutgoing @@ -542,6 +615,33 @@ class _ChannelChatScreenState extends State { final metaColor = textColor.withValues(alpha: 0.65); const bodyFontSize = 14.0; + Widget buildTextContent() { + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + child: TranslatedMessageContent( + displayText: translatedDisplayText, + originalText: originalDisplayText, + style: TextStyle( + color: textColor, + fontSize: bodyFontSize * textScale, + ), + originalStyle: TextStyle( + fontSize: bodyFontSize * textScale, + fontStyle: FontStyle.italic, + color: textColor.withValues(alpha: 0.72), + ), + onSecondaryTap: PlatformInfo.isDesktop + ? () => _showMessageActions(message) + : null, + ), + ), + ], + ); + } + // Asymmetric radius matching chat_screen bubbles. final borderRadius = isOutgoing ? const BorderRadius.only( @@ -569,10 +669,10 @@ class _ChannelChatScreenState extends State { mainAxisAlignment: isOutgoing ? MainAxisAlignment.end : MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, + crossAxisAlignment: CrossAxisAlignment.start, children: [ if (!isOutgoing) ...[ - _buildAvatar(message.senderName), + _buildAvatar(message.senderName, textScale), const SizedBox(width: 6), ], Flexible( @@ -610,10 +710,10 @@ class _ChannelChatScreenState extends State { : EdgeInsets.zero, child: Text( message.senderName, - style: MeshTheme.mono( - fontSize: 11, + style: TextStyle( + fontSize: 13 * textScale, fontWeight: FontWeight.w700, - color: _colorForName(message.senderName), + color: textColor, ), ), ), @@ -647,32 +747,79 @@ class _ChannelChatScreenState extends State { ), ], ) + else if (urlImagesEnabled) + MessageUrlImageFutureBuilder( + messageId: message.messageId, + text: message.text, + builder: (context, snapshot) { + final imageAttachment = snapshot.data; + + if (imageAttachment != null) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 4, + ), + child: Align( + alignment: isOutgoing + ? Alignment.centerRight + : Alignment.centerLeft, + child: MessageUrlImagePreview( + imageUrl: imageAttachment, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 8), + child: TranslatedMessageContent( + displayText: translatedDisplayText, + originalText: originalDisplayText, + style: TextStyle( + color: textColor, + fontSize: bodyFontSize * textScale, + ), + originalStyle: TextStyle( + fontSize: bodyFontSize * textScale, + fontStyle: FontStyle.italic, + color: textColor.withValues( + alpha: 0.72, + ), + ), + onSecondaryTap: PlatformInfo.isDesktop + ? () => _showMessageActions(message) + : null, + ), + ), + ], + ); + } + + return buildTextContent(); + }, + ) else - Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, + Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Flexible( - child: TranslatedMessageContent( - displayText: translatedDisplayText, - originalText: originalDisplayText, - style: TextStyle( - color: textColor, - fontSize: bodyFontSize * textScale, + if (MessageUrlImageHelper.hasPotentialImageUrl( + message.text, + )) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + context.l10n.urlImage_possible, + style: TextStyle( + color: metaColor, + fontSize: 11 * textScale, + ), ), - originalStyle: TextStyle( - fontSize: bodyFontSize * textScale, - fontStyle: FontStyle.italic, - color: textColor.withValues(alpha: 0.72), - ), - onSecondaryTap: PlatformInfo.isDesktop - ? () => _showMessageActions(message) - : null, ), - ), + buildTextContent(), ], ), - if (enableTracing && displayPath.isNotEmpty) ...[ + if (displayPath.isNotEmpty) ...[ const SizedBox(height: 3), Padding( padding: gifId != null @@ -684,22 +831,27 @@ class _ChannelChatScreenState extends State { children: [ RouteChip( isDirect: (message.pathLength ?? -1) >= 0, - hops: (message.pathLength ?? -1) >= 0 - ? message.pathLength - : null, + hops: displayHopCount, ), - const SizedBox(width: 4), - Flexible( - child: Text( - context.l10n.channels_via( - _formatPathPrefixes(displayPath), - ), - style: MeshTheme.mono( - fontSize: 9.5 * textScale, - color: metaColor, + if (enableTracing) ...[ + const SizedBox(width: 4), + Flexible( + child: Text( + context.l10n.channels_via( + _formatPathPrefixes( + displayPath, + displayPathHashWidth, + ), + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: MeshTheme.mono( + fontSize: 9.5 * textScale, + color: metaColor, + ), ), ), - ), + ], ], ), ), @@ -717,13 +869,15 @@ class _ChannelChatScreenState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - _formatTime(context, message.timestamp), + formatChatTime(context, message.timestamp), style: MeshTheme.mono( - fontSize: 10 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), - if (enableTracing && message.repeatCount > 0) ...[ + if (enableTracing && + !isOutgoing && + message.repeatCount > 0) ...[ const SizedBox(width: 6), Icon( Icons.repeat, @@ -734,7 +888,7 @@ class _ChannelChatScreenState extends State { Text( '${message.repeatCount}', style: MeshTheme.mono( - fontSize: 10 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), @@ -742,13 +896,16 @@ class _ChannelChatScreenState extends State { if (isOutgoing) ...[ const SizedBox(width: 4), MessageStatusIcon( - isAcked: - message.status == - ChannelMessageStatus.sent, - isRepeated: - message.status == - ChannelMessageStatus.sent && - displayPath.isNotEmpty, + size: 16 * textScale, + isAcked: false, + isChannel: true, + repeatCount: message.repeatCount, + resendProgress: context + .read() + .channelResendProgress(message.messageId), + hopShortfall: context + .read() + .channelHopShortfall(message.messageId), isPending: message.status == ChannelMessageStatus.pending, @@ -918,7 +1075,7 @@ class _ChannelChatScreenState extends State { runSpacing: 6, children: message.reactions.entries.map((entry) { final emoji = entry.key; - final count = entry.value; + final int count = entry.value.length; return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), @@ -927,35 +1084,97 @@ class _ChannelChatScreenState extends State { borderRadius: BorderRadius.circular(MeshRadii.pill), border: Border.all(color: 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), + child: InkWell( + onTap: () => _showReactionsReport(message), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ Text( - '$count', - style: MeshTheme.mono( - fontSize: 11, - fontWeight: FontWeight.w700, - color: scheme.onSurface, + 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( + context: context, + builder: (context) => AlertDialog( + title: Text(context.l10n.reaction_report), + content: SizedBox( + width: double.maxFinite, + child: Scrollbar( + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 4), + children: message.reactionList().map((reaction) { + return Container( + padding: const EdgeInsetsDirectional.symmetric(vertical: 4), + child: 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: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + reaction.emoji, + style: MeshTheme.emoji(fontSize: 16), + textHeightBehavior: const TextHeightBehavior( + applyHeightToFirstAscent: false, + applyHeightToLastDescent: false, + ), + ), + const SizedBox(width: 12), + Expanded(child: Text(reaction.senderName ?? '???')), + ], + ), + ), + ), + ); + }).toList(), + ), + ), + ), + ), + ); + } + Widget _buildPoiMessage( BuildContext context, MarkerPayload poi, @@ -1025,6 +1244,581 @@ class _ChannelChatScreenState extends State { ); } + /// The image codec, or null when it is not registered (screen tests). + ImageCodecService? get _imageCodec { + try { + return context.read(); + } on ProviderNotFoundException { + return null; + } + } + + void _explainImageCodecNotReady(ImageCodecService codec) { + final l10n = context.l10n; + final availability = codec.availability; + final String message; + switch (availability) { + case ImageCodecAvailability.downloading: + message = l10n.imageSend_codecDownloading; + case ImageCodecAvailability.unavailable: + message = codec.unavailableReason ?? l10n.imageSend_codecUnavailable; + case ImageCodecAvailability.disabled: + message = codec.needsModelDownload + ? l10n.imageSend_modelNotDownloaded + : codec.statusReason ?? l10n.imageSend_codecDisabled; + case ImageCodecAvailability.ready: + return; + } + showDismissibleSnackBar( + context, + content: Text(message), + action: availability == ImageCodecAvailability.disabled + ? SnackBarAction( + label: l10n.receivedImage_openSettings, + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + const AppSettingsScreen(focusImageMessages: true), + ), + ), + ) + : null, + ); + } + + /// Takes no [BuildContext]: it uses the [State]'s own, so the `mounted` + /// checks around each `await` are the ones that actually govern it. + Future _showImageSendPreview() async { + final codec = _imageCodec; + if (codec == null) return; + if (codec.availability != ImageCodecAvailability.ready) { + _explainImageCodecNotReady(codec); + return; + } + final connector = context.read(); + + // The picked bytes are kept past the preview on purpose: the sender's own + // bubble renders from them (see [_registerOutgoingImage]). The bitstream + // cannot serve — turning it back into pixels is a ~2.16 GiB, ~1 s decode + // of an image the sender is already holding. + final XFile? picked; + try { + picked = await ImagePicker().pickImage( + source: ImageSource.gallery, + // The codec centre-crops to 512x512 anyway, so there is nothing to + // gain from decoding a 12 MP original — but stay well above 512 so the + // crop still has detail to work with. + maxWidth: 2048, + maxHeight: 2048, + ); + } on Exception catch (e) { + debugPrint('image pick failed: $e'); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + ); + return; + } + if (picked == null) return; // cancelled at the picker + + final Uint8List sourceBytes; + final int originalFileBytes; + try { + sourceBytes = await picked.readAsBytes(); + // XFile.length() is the on-disk size — what the sheet shows against the + // transmitted size — and unlike dart:io it also works on web. + originalFileBytes = await picked.length(); + } on Exception catch (e) { + debugPrint('image read failed: $e'); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.chat_imagePickFailed)), + ); + return; + } + + if (!mounted) return; + final result = await showImageSendPreviewSheet( + context: context, + imageBytes: sourceBytes, + originalFileBytes: originalFileBytes, + codec: codec, + ); + if (result == null) return; // cancelled at the preview + if (!mounted) return; + await _sendImage(connector, result, sourceBytes: sourceBytes); + } + + /// Chunks [result] and puts it on the channel as GRP_DATA packets. + /// + /// Chunk geometry, CRC and parity all come from [buildImageChunks] \u2014 the + /// single source of truth for the wire format \u2014 and the blobs go out through + /// [MeshCoreConnector.sendImageChunks] as one list, so the connector owns the + /// inter-chunk pacing and the whole image sits inside one scoped send. + /// + /// [sourceBytes] is the original picked file. It is only ever used to draw + /// the sender's own bubble; nothing about the transmission depends on it. + Future _sendImage( + MeshCoreConnector connector, + 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)), + ); + return; + } + final senderPrefix = connector.imageSenderPrefix; + if (senderPrefix == null) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.imageSend_deviceUnsupported)), + ); + return; + } + + final ImageChunkSet chunkSet; + try { + chunkSet = buildImageChunks( + payload: result.payload, + metadata: ImageStreamMetadata( + rate: result.rate, + squareSize: kImageCodecSquareSize, + // The codec stretched the whole frame into a square, which the + // receiver cannot undo from pixels alone. Naming the source shape + // here costs no extra bytes -- it rides in spare bits of the metadata + // byte -- and lets the receiver letterbox back. + aspectCode: await _aspectCodeOf(sourceBytes), + ), + senderPrefix: senderPrefix, + imgId: _imageIds.next(), + parity: result.includeParity, + ); + } on ArgumentError { + messenger.showSnackBar(SnackBar(content: Text(l10n.imageSend_tooLarge))); + 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 + // hammering the channel back-to-back. + final total = result.airtime; + final perPacket = total == null + ? Duration.zero + : Duration( + microseconds: + total.inMicroseconds ~/ + (result.packetCount == 0 ? 1 : result.packetCount), + ); + + setState(() { + _imageSendTotal = chunkSet.blobs.length; + _imageSendSent = 0; + }); + try { + final sent = await connector.sendImageChunks( + chunkSet.blobs, + channelIndex: widget.channel.index, + interChunkDelay: imageSendChunkGap(perPacket), + onProgress: (sentChunks, totalChunks) { + if (!mounted) return; + setState(() => _imageSendSent = sentChunks); + }, + ); + // Register before the snack bar, so the bubble is on screen by the time + // the confirmation appears rather than a frame behind it. + if (sent) { + await _registerOutgoingImage( + result: result, + chunkSet: chunkSet, + senderPrefix: senderPrefix, + sourceBytes: sourceBytes, + ); + } + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + 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'))), + ); + } finally { + if (mounted) { + setState(() { + _imageSendTotal = 0; + _imageSendSent = 0; + }); + } + } + } + + /// Puts the image the user just sent into [ReceivedImageStore] so it appears + /// in their own transcript. + /// + /// GRP_DATA is not echoed back to the sender and an image is not a + /// [ChannelMessage], so without this the sender sees a "sent" snack bar and + /// an otherwise empty conversation. The entry lands in `decoded` directly — + /// an outgoing image is never queued for inference, so showing your own + /// photo costs no model memory. + /// + /// Best effort throughout: a failure here has already been preceded by a + /// successful transmission, so it must not turn into an error the user sees. + Future _registerOutgoingImage({ + required ImageSendPreviewResult result, + required ImageChunkSet chunkSet, + required int senderPrefix, + required Uint8List sourceBytes, + }) async { + final ReceivedImageStore store; + try { + store = context.read(); + } on ProviderNotFoundException { + return; // screen test without the store + } + final previewPng = await _squarePreviewPng(sourceBytes); + if (previewPng == null) return; + try { + await store.registerOutgoing( + channelIndex: widget.channel.index, + // The same 16 bits the chunk header carries, so the entry keys the + // same way an inbound one would. + senderPrefix: senderPrefix, + imgId: chunkSet.imgId, + previewPng: previewPng, + rate: aeicRatePointForUi(result.rate), + chunkCount: chunkSet.dataChunkCount, + ); + } on Exception catch (error) { + debugPrint('outgoing image registration failed: $error'); + } + } + + /// The [kImageAspectCodes] entry matching [imageBytes]'s shape. + /// + /// Decodes only to read the dimensions. Falls back to "unknown" (rendered + /// square) rather than guessing, because asserting the wrong shape would + /// letterbox the receiver's copy incorrectly and look like a codec bug. + static Future _aspectCodeOf(Uint8List imageBytes) async { + ui.Image? image; + try { + final codec = await ui.instantiateImageCodec(imageBytes); + image = (await codec.getNextFrame()).image; + return imageAspectCodeFor(image.width, image.height); + } on Exception catch (error) { + debugPrint('aspect probe failed: $error'); + return kImageAspectUnknown; + } finally { + image?.dispose(); + } + } + + /// [imageBytes] stretched to 512x512, as PNG. + /// + /// This is what the preview sheet showed (`BoxFit.fill` on a 1:1 box is + /// exactly the stretch the codec applies) and what the codec actually + /// encoded, so the sender's bubble matches both. Deliberately not a decode of the + /// bitstream: that would cost ~2.16 GiB and ~1 s to reproduce, less well, an + /// image this device is already holding in memory. + /// + /// Returns null rather than throwing on an undecodable source — the send has + /// already happened by the time this runs. + static Future _squarePreviewPng(Uint8List imageBytes) async { + ui.Image? source; + ui.Image? square; + try { + final codec = await ui.instantiateImageCodec(imageBytes); + source = (await codec.getNextFrame()).image; + final dst = kImageCodecSquareSize.toDouble(); + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder).drawImageRect( + source, + // Whole frame, matching _toSquareRgb in image_codec_service.dart. If + // one of these two is a crop and the other a stretch, the sender's + // bubble silently stops matching what the receiver sees. + ui.Rect.fromLTWH( + 0, + 0, + source.width.toDouble(), + source.height.toDouble(), + ), + ui.Rect.fromLTWH(0, 0, dst, dst), + ui.Paint()..filterQuality = ui.FilterQuality.medium, + ); + square = await recorder.endRecording().toImage( + kImageCodecSquareSize, + kImageCodecSquareSize, + ); + final data = await square.toByteData(format: ui.ImageByteFormat.png); + return data?.buffer.asUint8List(); + } on Exception catch (error) { + debugPrint('outgoing image preview render failed: $error'); + return null; + } finally { + source?.dispose(); + square?.dispose(); + } + } + + /// Received/sent AEIC images for this channel, as transcript rows. + /// + /// 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; + try { + store = context.watch(); + } on ProviderNotFoundException { + return const <_ChannelChatRow>[]; + } + return <_ChannelChatRow>[ + for (final entry in store.entries) + if (entry.channelIndex == widget.channel.index) + _ChannelChatRow(image: entry), + ]; + } + + /// 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. + Widget _buildImageBubble(ReceivedImageEntry entry, double textScale) { + final scheme = Theme.of(context).colorScheme; + final isOutgoing = entry.isOutgoing; + final textColor = isOutgoing ? MeshPalette.meInk : scheme.onSurface; + final metaColor = textColor.withValues(alpha: 0.65); + + final bubble = Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + mainAxisAlignment: isOutgoing + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (!isOutgoing) ...[ + _buildAvatar(_imageSenderLabel(entry), textScale), + const SizedBox(width: 6), + ], + Flexible( + child: Container( + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: isOutgoing ? MeshPalette.me : scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(MeshRadii.lg), + border: Border.all( + color: isOutgoing + ? MeshPalette.meBorder + : scheme.outlineVariant, + width: 1, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isOutgoing) + Padding( + padding: const EdgeInsets.only( + left: 8, + top: 4, + bottom: 4, + ), + child: Text( + _imageSenderLabel(entry), + style: TextStyle( + fontSize: 13 * textScale, + fontWeight: FontWeight.w700, + color: textColor, + ), + ), + ), + ReceivedImageMessage( + streamId: entry.streamId, + isOutgoing: isOutgoing, + fallbackTextColor: textColor, + strings: _receivedImageStrings(context), + // The placeholder's "no model installed" tap lands here. + // `focusImageMessages` scrolls straight to the image block + // — it sits below six other sections, so the plain screen + // would open at the top with no sign of what was tapped for. + onOpenCodecSettings: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + const AppSettingsScreen(focusImageMessages: true), + ), + ), + ), + Padding( + padding: const EdgeInsets.only( + left: 8, + right: 8, + bottom: 4, + ), + child: Text( + formatChatTime(context, entry.firstSeen), + style: MeshTheme.mono( + fontSize: 12 * textScale, + color: metaColor, + ), + ), + ), + ], + ), + ), + ), + ], + ), + ); + return GestureDetector( + onLongPress: () => _showImageActions(entry), + onSecondaryTap: () => _showImageActions(entry), + child: bubble, + ); + } + + void _showImageActions(ReceivedImageEntry entry) { + final l10n = context.l10n; + final canSave = entry.state == ReceivedImageState.decoded; + showMeshSheet( + context, + builder: (sheetContext) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: l10n.receivedImage_awaiting( + entry.bitstreamByteCount, + entry.totalChunks, + ), + subtitle: _imageSenderLabel(entry), + ), + if (canSave) + ListTile( + leading: const Icon(Icons.save_alt), + title: Text(l10n.receivedImage_save), + onTap: () { + Navigator.pop(sheetContext); + _saveImage(entry); + }, + ), + ListTile( + leading: const Icon(Icons.info_outline), + title: Text(l10n.receivedImage_packetInfo), + onTap: () { + Navigator.pop(sheetContext); + _showImagePacketInfo(entry); + }, + ), + const Divider(height: 1), + ListTile( + leading: Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + title: Text( + l10n.common_delete, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + onTap: () async { + Navigator.pop(sheetContext); + await context.read().deleteImage( + entry.streamId, + ); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_messageDeleted), + ); + }, + ), + const SizedBox(height: 8), + ], + ), + ), + ); + } + + Future _saveImage(ReceivedImageEntry entry) async { + final l10n = context.l10n; + final png = await context.read().ensurePng( + entry.streamId, + ); + if (!mounted) return; + final shareText = l10n.receivedImage_shareCaption(entry.bitstreamByteCount); + if (png == null || !await saveImagePng(png, entry, shareText: shareText)) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.receivedImage_saveFailed), + ); + } + } + + void _showImagePacketInfo(ReceivedImageEntry entry) { + final l10n = context.l10n; + final decodeMs = entry.decodeMs; + showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(l10n.receivedImage_packetInfo), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_imageSenderLabel(entry)), + Text(formatChatTime(context, entry.firstSeen)), + Text( + l10n.receivedImage_awaiting( + entry.bitstreamByteCount, + entry.totalChunks, + ), + ), + if (entry.recoveredWithParity) + Text(l10n.receivedImage_parityRecovered), + if (decodeMs != null) Text(l10n.receivedImage_decodeTime(decodeMs)), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(l10n.common_close), + ), + ], + ), + ); + } + + /// GRP_DATA carries no sender name — only the 2-byte public-key prefix the + /// chunk header stamps — so resolve that against the contact list and fall + /// back to the raw prefix only when nobody matches. + /// + /// Two bytes is 65,536 values, so a collision between two known contacts is + /// possible. When it happens the sender is genuinely ambiguous and naming + /// either one would be a guess, so the prefix is shown instead. + String _imageSenderLabel(ReceivedImageEntry entry) { + final hex = entry.senderPrefix.toRadixString(16).padLeft(4, '0'); + final connector = context.read(); + if (entry.isOutgoing) { + return connector.selfName ?? context.l10n.receivedImage_senderPrefix(hex); + } + final matches = connector.contacts + .where((c) => c.publicKeyHex.toLowerCase().startsWith(hex)) + .toList(); + if (matches.length == 1) return matches.single.name; + return context.l10n.receivedImage_senderPrefix(hex); + } + void _showGifPicker(BuildContext context) { showModalBottomSheet( context: context, @@ -1037,8 +1831,11 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildAvatar(String senderName) { - return AvatarCircle(name: senderName, size: 32); + Widget _buildAvatar(String senderName, double textScale) { + return AvatarCircle( + name: senderName, + size: (32 * textScale).clamp(28.0, 56.0), + ); } Widget _buildReplyBanner(double textScale) { @@ -1083,6 +1880,7 @@ class _ChannelChatScreenState extends State { ), IconButton( icon: const Icon(Icons.close, size: 18), + tooltip: context.l10n.chat_cancelReply, onPressed: _cancelReply, color: scheme.onSurfaceVariant, constraints: const BoxConstraints(minWidth: 44, minHeight: 44), @@ -1092,40 +1890,106 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildMessageComposer() { + /// "Sending image — packet 2 of 3", above the composer. + /// + /// A per-chunk figure rather than a spinner because an image occupies the + /// channel for seconds and the user needs to see it advancing. + Widget _buildImageSendProgress(ColorScheme scheme) { + final total = _imageSendTotal; + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHigh, + border: Border( + bottom: BorderSide(color: scheme.outlineVariant, width: 1), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + context.l10n.imageSend_sendingProgress(_imageSendSent, total), + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 6), + LinearProgressIndicator( + value: total == 0 ? null : _imageSendSent / total, + ), + ], + ), + ); + } + + 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 Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_replyingToMessage != null) - Builder( - builder: (context) { - final textScale = context.select( - (service) => service.scale, - ); - return _buildReplyBanner(textScale); - }, - ), - Container( - decoration: BoxDecoration( - color: scheme.surface, - border: Border( - top: BorderSide(color: scheme.outlineVariant, width: 1), - ), - ), - child: SafeArea( - child: Padding( + 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: [ - IconButton( - icon: const Icon(Icons.gif_box), - onPressed: () => _showGifPicker(context), - tooltip: context.l10n.chat_sendGif, + PopupMenuButton( + icon: const Icon(Icons.add_circle_outline), + position: PopupMenuPosition.over, + offset: Offset(0, showImageAction ? -112 : -64), + tooltip: context.l10n.chat_selectSendAction, + onSelected: (action) { + switch (action) { + case 'gif': + _showGifPicker(context); + break; + case 'meshcore-image': + _showImageSendPreview(); + break; + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + if (showImageAction) + PopupMenuItem( + value: 'meshcore-image', + child: Row( + children: [ + const Icon(Icons.image_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageLora), + ], + ), + ), + ], ), if (settings.translationEnabled) MessageTranslationButton( @@ -1171,6 +2035,7 @@ class _ChannelChatScreenState extends State { const SizedBox(width: 8), IconButton( icon: const Icon(Icons.close), + tooltip: context.l10n.chat_removeGif, onPressed: () { _textController.clear(); _textFieldFocusNode.requestFocus(); @@ -1201,25 +2066,19 @@ class _ChannelChatScreenState extends State { decoration: InputDecoration( hintText: context.l10n.chat_typeMessage, border: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.pill, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.outlineVariant, ), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.pill, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.outlineVariant, ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular( - MeshRadii.pill, - ), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.primary, width: 1.5, @@ -1270,9 +2129,9 @@ class _ChannelChatScreenState extends State { ], ), ), - ), + ], ), - ], + ), ); } @@ -1360,6 +2219,7 @@ class _ChannelChatScreenState extends State { } // end transform + final replyTo = _replyingToMessage; _textController.clear(); _cancelReply(); _textFieldFocusNode.requestFocus(); @@ -1369,27 +2229,10 @@ class _ChannelChatScreenState extends State { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + replyTo: replyTo, ); } - String _formatTime(BuildContext context, DateTime time) { - final now = DateTime.now(); - final diff = now.difference(time); - final locale = Localizations.localeOf(context).toString(); - if (locale != _cachedFormatLocale) { - _cachedFormatLocale = locale; - _hmFormat = DateFormat.Hm(locale); - _mdFormat = DateFormat.Md(locale); - } - final hm = _hmFormat.format(time); - - if (diff.inDays > 0) { - return '${_mdFormat.format(time)} $hm'; - } else { - return hm; - } - } - void _showMessagePathInfo(ChannelMessage message) { Navigator.push( context, @@ -1417,8 +2260,8 @@ class _ChannelChatScreenState extends State { mainAxisSize: MainAxisSize.min, children: [ BottomSheetHeader( - title: message.text.length > 40 - ? '${message.text.substring(0, 40)}…' + title: message.text.characters.length > 40 + ? '${message.text.characters.take(40)}…' : message.text, subtitle: message.senderName.isNotEmpty ? message.senderName @@ -1440,6 +2283,23 @@ class _ChannelChatScreenState extends State { _showMessagePathInfo(message); }, ), + if (message.pathBytes.isNotEmpty) + ListTile( + leading: const Icon(Icons.map_outlined), + title: Text(context.l10n.chat_viewPathOnMap), + onTap: () { + Navigator.pop(sheetContext); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ChannelMessagePathMapScreen( + message: message, + channelMessage: true, + ), + ), + ); + }, + ), // Can't react to your own messages if (!message.isOutgoing) ListTile( @@ -1520,12 +2380,7 @@ class _ChannelChatScreenState extends State { final connector = context.read(); final emojiIndex = ReactionHelper.emojiToIndex(emoji); if (emojiIndex == null) return; // Unknown emoji, skip - final timestampSecs = message.timestamp.millisecondsSinceEpoch ~/ 1000; - final hash = ReactionHelper.computeReactionHash( - timestampSecs, - message.senderName, - message.text, - ); + final hash = message.computeReactionHash(); final reactionText = ReactionHelper.encodeReaction(hash, emojiIndex); connector.sendChannelMessage(widget.channel, reactionText); } @@ -1563,6 +2418,13 @@ class _ChannelChatScreenState extends State { context.read().clearMessagesForChannel( widget.channel.index, ); + try { + await context.read().deleteImagesForChannel( + widget.channel.index, + ); + } on ProviderNotFoundException { + return; + } } } @@ -1575,27 +2437,21 @@ class _ChannelChatScreenState extends State { ); } - String _formatPathPrefixes(Uint8List pathBytes) { - return pathBytes - .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) - .join(','); + String _formatPathPrefixes(Uint8List pathBytes, int pathHashByteWidth) { + return PathHelper.splitPathBytes( + pathBytes, + pathHashByteWidth, + ).map(PathHelper.formatHopHex).join(','); } - /// 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]; + int? _displayHopCount( + Uint8List pathBytes, + int pathHashByteWidth, + int? fallbackPathLength, + ) { + if ((fallbackPathLength ?? -1) < 0) return null; + if (pathBytes.isEmpty) return fallbackPathLength; + return PathHelper.splitPathBytes(pathBytes, pathHashByteWidth).length; } Future openRegionSelectDialog(Channel channel) async { @@ -1653,57 +2509,77 @@ class _RegionSelectDialogState extends State<_RegionSelectDialog> { backgroundColor: Colors.transparent, title: Text(context.l10n.channels_regionSelect_Title), centerTitle: true, - actions: [ - IconButton( - tooltip: context.l10n.channels_clearRegion, - icon: const Icon(Icons.backspace_outlined), - onPressed: () { - context.read().setChannelRegion( - widget.channel.index, - '', + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + context.l10n.channels_regionSelectExplanation, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + const SizedBox(height: 8), + if (regions.isEmpty) + Padding( + padding: const EdgeInsets.all(24), + child: Text(context.l10n.channels_regionEmpty), + ) + else + Expanded( + child: ListView.builder( + itemCount: regions.length, + itemBuilder: (context, index) { + final selected = selectedIndex == index; + return ListTile( + leading: Icon( + Icons.landscape, + color: selected ? MeshPalette.blue : null, + ), + title: Text(regions[index]), + trailing: selected + ? const Icon(Icons.check, color: MeshPalette.blue) + : null, + tileColor: selected ? MeshPalette.blueBg : null, + onTap: () { + // Tapping the already-selected region clears it. + context.read().setChannelRegion( + widget.channel.index, + selected ? '' : regions[index], + ); + Navigator.pop(context); + }, ); - Navigator.pop(context); }, ), - IconButton( - tooltip: context.l10n.settings_regionSettingsSubtitle, - icon: const Icon(Icons.settings), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: + context + .read() + .getChannelRegion(widget.channel.index) + .isEmpty + ? null + : () { + context.read().setChannelRegion( + widget.channel.index, + '', + ); + Navigator.pop(context); + }, + child: Text(context.l10n.common_clear), + ), + TextButton( onPressed: () async { await pushRegionManagementScreen(context); if (!mounted) return; loadRegions(); }, + child: Text(context.l10n.channels_manageRegions), ), ], ), - const SizedBox(height: 15), - Expanded( - child: ListView.builder( - itemCount: regions.length, - itemBuilder: (context, index) { - final selected = selectedIndex == index; - return ListTile( - leading: Icon( - Icons.landscape, - color: selected ? MeshPalette.blue : null, - ), - title: Text(regions[index]), - trailing: selected - ? const Icon(Icons.check, color: MeshPalette.blue) - : null, - tileColor: selected ? MeshPalette.blueBg : null, - onTap: () { - // Tapping the already-selected region clears it. - context.read().setChannelRegion( - widget.channel.index, - selected ? '' : regions[index], - ); - Navigator.pop(context); - }, - ); - }, - ), - ), ], ), ), @@ -1872,3 +2748,47 @@ class _SwipeReplyBubbleState extends State<_SwipeReplyBubble> { ); } } + +/// One row of the channel transcript. +/// +/// Exactly one of [message] / [image] is non-null. Images cannot be +/// `ChannelMessage`s: they arrive as GRP_DATA chunks with no text frame behind +/// them, are keyed on (sender prefix, img id, channel) rather than a message id, +/// and are persisted by [ReceivedImageStore] instead of the channel message +/// store. +@immutable +class _ChannelChatRow { + final ChannelMessage? message; + final ReceivedImageEntry? image; + + const _ChannelChatRow({this.message, this.image}); + + DateTime get timestamp => message?.timestamp ?? image!.firstSeen; + + /// Stable identity for the scroll-to-message [GlobalKey] map. The `aeic:` + /// prefix keeps a stream id from ever colliding with a message id. + String get id => message?.messageId ?? 'aeic:${image!.streamId}'; +} + +/// [ReceivedImageStrings] built from the app's localizations. +/// +/// The R6 badge and caption are deliberately absent from this class — they are +/// private consts in `received_image_message.dart` and must stay mandatory. +ReceivedImageStrings _receivedImageStrings(BuildContext context) { + final l10n = context.l10n; + return ReceivedImageStrings( + incoming: l10n.receivedImage_incoming, + queued: l10n.receivedImage_queued, + tapToDecode: l10n.receivedImage_tapToDecode, + awaiting: l10n.receivedImage_awaiting, + tapToProcess: l10n.receivedImage_tapToProcess, + decoding: l10n.receivedImage_decoding, + incomplete: l10n.receivedImage_incomplete, + corrupt: l10n.receivedImage_corrupt, + decoderMissing: l10n.receivedImage_decoderMissing, + evicted: l10n.receivedImage_evicted, + retry: l10n.receivedImage_retry, + decodeAgain: l10n.receivedImage_decodeAgain, + openSettings: l10n.receivedImage_openSettings, + ); +} diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index bc2ca1bd..3132bb46 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:latlong2/latlong.dart'; +import 'package:meshcore_open/helpers/path_helper.dart'; import 'package:meshcore_open/screens/path_trace_map.dart'; import 'package:provider/provider.dart'; @@ -22,7 +23,6 @@ import '../theme/mesh_theme.dart'; import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/path_map_ui.dart'; -import '../widgets/themed_map_tile_layer.dart'; class ChannelMessagePathScreen extends StatelessWidget { final ChannelMessage message; @@ -43,19 +43,40 @@ class ChannelMessagePathScreen extends StatelessWidget { message.pathVariants, ); - final primaryPath = !channelMessage && !message.isOutgoing - ? Uint8List.fromList(primaryPathTmp.reversed.toList()) - : primaryPathTmp; + final hashByteWidth = + (message.pathHashWidth ?? connector.pathHashByteWidth) + .clamp(1, 4) + .toInt(); + final primaryPath = _orientPathBytes( + primaryPathTmp, + hashByteWidth, + reverse: !channelMessage && !message.isOutgoing, + ); final hops = _buildPathHops( primaryPath, connector, l10n, + hashByteWidth, resolveFromEnd: !message.isOutgoing, ); final hasHopDetails = primaryPath.isNotEmpty; - final observedLabel = _formatObservedHops( + + // Convert observed path byte length to hop count using the packet width. + // Legacy messages fall back to the current connector width. + // Reported path length (V3+) is already stored as a hop count; preserve + // the negative flood sentinel when present. + final observedHopCount = _hopCountFromBytes( primaryPath.length, - message.pathLength, + hashByteWidth, + ); + final reportedHopCount = message.pathLength; + final effectiveHopCount = observedHopCount > 0 + ? observedHopCount + : reportedHopCount; + + final observedLabel = _formatObservedHops( + observedHopCount, + effectiveHopCount, l10n, ); final extraPaths = _otherPaths(primaryPath, message.pathVariants); @@ -73,11 +94,8 @@ class ChannelMessagePathScreen extends StatelessWidget { title: context.l10n.contacts_repeaterPathTrace, path: primaryPath, flipPathAround: true, - reversePathAround: - !(!channelMessage && !message.isOutgoing), - pathHashByteWidth: context - .read() - .pathHashByteWidth, + reversePathAround: false, + pathHashByteWidth: hashByteWidth, ), ), ), @@ -98,13 +116,20 @@ class ChannelMessagePathScreen extends StatelessWidget { child: ListView( padding: const EdgeInsets.symmetric(vertical: 8), children: [ - _buildSummaryCard(context, observedLabel: observedLabel), + _buildSummaryCard( + context, + observedLabel: observedLabel, + effectiveHopCount: effectiveHopCount, + ), + const SizedBox(height: 16), if (extraPaths.isNotEmpty) ...[ SectionHeader( l10n.channelPath_otherObservedPaths, padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), ), - _buildPathVariants(context, extraPaths), + const SizedBox(height: 8), + _buildPathVariants(context, extraPaths, hashByteWidth), + const SizedBox(height: 16), ], SectionHeader( l10n.channelPath_repeaterHops, @@ -123,14 +148,18 @@ class ChannelMessagePathScreen extends StatelessWidget { ); } - Widget _buildSummaryCard(BuildContext context, {String? observedLabel}) { + Widget _buildSummaryCard( + BuildContext context, { + String? observedLabel, + required int? effectiveHopCount, + }) { final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; - final routeChip = message.pathLength == null + final routeChip = effectiveHopCount == null ? null - : message.pathLength! < 0 + : effectiveHopCount < 0 ? const RouteChip(isDirect: false) - : RouteChip(isDirect: true, hops: message.pathLength); + : RouteChip(isDirect: true, hops: effectiveHopCount); return MeshCard( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), @@ -172,7 +201,7 @@ class ChannelMessagePathScreen extends StatelessWidget { _buildDetailRow( context, l10n.channelPath_pathLabelTitle, - _formatPathLabel(message.pathLength, l10n), + _formatPathLabel(effectiveHopCount, l10n), scheme: scheme, ), if (observedLabel != null) @@ -187,7 +216,11 @@ class ChannelMessagePathScreen extends StatelessWidget { ); } - Widget _buildPathVariants(BuildContext context, List variants) { + Widget _buildPathVariants( + BuildContext context, + List variants, + int hashByteWidth, + ) { final l10n = context.l10n; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -210,7 +243,11 @@ class ChannelMessagePathScreen extends StatelessWidget { Text( l10n.channelPath_observedPathTitle( i + 1, - _formatHopCount(variants[i].length, l10n), + _formatHopCount( + variants[i].length, + hashByteWidth, + l10n, + ), ), style: Theme.of(context).textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w600, @@ -218,7 +255,7 @@ class ChannelMessagePathScreen extends StatelessWidget { ), const SizedBox(height: 2), Text( - _formatPathPrefixes(variants[i]), + _formatPathPrefixes(variants[i], hashByteWidth), style: MeshTheme.mono( fontSize: 11, color: Theme.of(context).colorScheme.onSurfaceVariant, @@ -402,31 +439,31 @@ class ChannelMessagePathScreen extends StatelessWidget { ); } - String _formatPathLabel(int? pathLength, AppLocalizations l10n) { - if (pathLength == null) return l10n.channelPath_unknownPath; - if (pathLength < 0) return l10n.channelPath_floodPath; - if (pathLength == 0) return l10n.channelPath_directPath; - return l10n.chat_hopsCount(pathLength); + String _formatPathLabel(int? hopCount, AppLocalizations l10n) { + if (hopCount == null) return l10n.channelPath_unknownPath; + if (hopCount < 0) return l10n.channelPath_floodPath; + if (hopCount == 0) return l10n.channelPath_directPath; + return l10n.chat_hopsCount(hopCount); } String? _formatObservedHops( int observedCount, - int? pathLength, + int? targetHopCount, AppLocalizations l10n, ) { - if (observedCount <= 0 && (pathLength == null || pathLength <= 0)) { + if (observedCount <= 0 && (targetHopCount == null || targetHopCount <= 0)) { return null; } - if (pathLength == null || pathLength < 0) { + if (targetHopCount == null || targetHopCount < 0) { return observedCount > 0 ? l10n.chat_hopsCount(observedCount) : null; } if (observedCount == 0) { - return l10n.channelPath_observedZeroOf(pathLength); + return l10n.channelPath_observedZeroOf(targetHopCount); } - if (observedCount == pathLength) { + if (observedCount == targetHopCount) { return l10n.chat_hopsCount(observedCount); } - return l10n.channelPath_observedSomeOf(observedCount, pathLength); + return l10n.channelPath_observedSomeOf(observedCount, targetHopCount); } Widget _buildDetailRow( @@ -623,7 +660,10 @@ class _ChannelMessagePathMapScreenState ? kPrimaryPathColor : kAlternatePathColors[(index - 1) % kAlternatePathColors.length], isPrimary: isPrimary, - hopBytes: List.from(orientedBytes), + hopBytes: [ + for (final hop in hops) + if (hop.hopBytes != null) Uint8List.fromList(hop.hopBytes!), + ], points: points, pointLabels: labels, pointConfirmed: confirmed, @@ -808,7 +848,11 @@ class _ChannelMessagePathMapScreenState primaryPath, ); - final selectedPath = _orientPath(selectedPathTmp); + 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. @@ -817,19 +861,21 @@ class _ChannelMessagePathMapScreenState 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); + 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( @@ -908,7 +954,7 @@ class _ChannelMessagePathMapScreenState ? LatLngBounds.fromPoints(points) : null; final mapKey = ValueKey( - '${_formatPathPrefixes(selectedPath)},${context.l10n.pathTrace_you}', + '${_formatPathPrefixes(selectedPath, width)},${context.l10n.pathTrace_you}', ); _pathDistance = _getPathDistance(points); @@ -967,7 +1013,7 @@ class _ChannelMessagePathMapScreenState }, ), children: [ - ThemedMapTileLayer(tileCache: tileCache), + tileCache.buildTileLayer(context), AnimatedBuilder( animation: _playback, builder: (context, _) { @@ -1045,6 +1091,7 @@ class _ChannelMessagePathMapScreenState context, observedPaths, selectedIndex, + width, (index) { setState(() { _selectedPath = observedPaths[index].pathBytes; @@ -1086,10 +1133,12 @@ class _ChannelMessagePathMapScreenState BuildContext context, List<_ObservedPath> paths, int selectedIndex, + int hashByteWidth, ValueChanged onSelected, { double topOffset = 16, }) { final l10n = context.l10n; + final width = hashByteWidth.clamp(1, 4).toInt(); final selectedPath = paths[selectedIndex]; final label = selectedPath.isPrimary ? l10n.channelPath_primaryPath(selectedIndex + 1) @@ -1120,7 +1169,7 @@ class _ChannelMessagePathMapScreenState value: i, child: Text( '${paths[i].isPrimary ? l10n.channelPath_primaryPath(i + 1) : l10n.channelPath_pathLabel(i + 1)}' - ' • ${_formatHopCount(paths[i].pathBytes.length, l10n)}', + ' • ${_formatHopCount(paths[i].pathBytes.length, width, l10n)}', ), ), ], @@ -1134,7 +1183,7 @@ class _ChannelMessagePathMapScreenState Text( l10n.channelPath_selectedPathLabel( label, - _formatPathPrefixes(selectedPath.pathBytes), + _formatPathPrefixes(selectedPath.pathBytes, width), ), style: TextStyle( color: Theme.of(context).colorScheme.onSurfaceVariant, @@ -1378,11 +1427,11 @@ class _ChannelMessagePathMapScreenState } /// Orients recorded path bytes in the direction the packet traveled. - Uint8List _orientPath(Uint8List bytes) { + Uint8List _orientPath(Uint8List bytes, int hashByteWidth) { final reverse = (!widget.message.isOutgoing && !widget.channelMessage) || (widget.message.isOutgoing && widget.channelMessage); - return reverse ? Uint8List.fromList(bytes.reversed.toList()) : bytes; + return _orientPathBytes(bytes, hashByteWidth, reverse: reverse); } Marker _buildNodeLabelMarker({required LatLng point, required String label}) { @@ -1738,6 +1787,7 @@ class _PathHop { final Contact? contact; final LatLng? position; final AppLocalizations l10n; + final Uint8List? hopBytes; const _PathHop({ required this.index, @@ -1745,12 +1795,18 @@ class _PathHop { required this.contact, required this.position, required this.l10n, + this.hopBytes, }); bool get hasLocation => position != null; String get displayLabel { - final prefixLabel = _formatPrefix(prefix); + final prefixLabel = hopBytes != null && hopBytes!.isNotEmpty + ? hopBytes! + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join('') + .toUpperCase() + : _formatPrefix(prefix); return '($prefixLabel) ${_resolveName(contact, l10n)}'; } } @@ -1765,10 +1821,12 @@ class _ObservedPath { List<_PathHop> _buildPathHops( Uint8List pathBytes, MeshCoreConnector connector, - AppLocalizations l10n, { + 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!) @@ -1778,19 +1836,23 @@ List<_PathHop> _buildPathHops( contacts: connector.allContacts, endpoint: endpoint, resolveFromEnd: resolveFromEnd, + pathHashByteWidth: width, ); + final hopChunks = PathHelper.splitPathBytes(pathBytes, width); final hops = <_PathHop>[]; - for (var i = 0; i < pathBytes.length; i++) { - final contact = resolvedContacts[i]; + for (var i = 0; i < hopChunks.length; i++) { + final hopBytes = hopChunks[i]; + final contact = i < resolvedContacts.length ? resolvedContacts[i] : null; final resolvedPosition = _resolvePosition(contact); hops.add( _PathHop( index: i + 1, - prefix: pathBytes[i], + prefix: hopBytes.isNotEmpty ? hopBytes[0] : 0, contact: contact, position: resolvedPosition, l10n: l10n, + hopBytes: hopBytes, ), ); } @@ -1810,14 +1872,35 @@ String _formatPrefix(int prefix) { return prefix.toRadixString(16).padLeft(2, '0').toUpperCase(); } -String _formatPathPrefixes(Uint8List pathBytes) { - return pathBytes - .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) - .join(','); +String _formatPathPrefixes(Uint8List pathBytes, int hashByteWidth) { + return PathHelper.splitPathBytes( + pathBytes, + hashByteWidth, + ).map(PathHelper.formatHopHex).join(','); } -String _formatHopCount(int count, AppLocalizations l10n) { - return l10n.chat_hopsCount(count); +Uint8List _orientPathBytes( + Uint8List pathBytes, + int hashByteWidth, { + required bool reverse, +}) { + if (!reverse || pathBytes.isEmpty) return pathBytes; + final hops = PathHelper.splitPathBytes(pathBytes, hashByteWidth); + return Uint8List.fromList([for (final hop in hops.reversed) ...hop]); +} + +int _hopCountFromBytes(int byteCount, int hashByteWidth) { + if (byteCount <= 0) return 0; + final width = hashByteWidth.clamp(1, 4).toInt(); + return (byteCount + width - 1) ~/ width; +} + +String _formatHopCount( + int byteCount, + int hashByteWidth, + AppLocalizations l10n, +) { + return l10n.chat_hopsCount(_hopCountFromBytes(byteCount, hashByteWidth)); } String _resolveName(Contact? contact, AppLocalizations l10n) { diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 2de232c6..1abba59c 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1,9 +1,9 @@ import 'dart:async'; -import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/utils/keys.dart'; import 'package:meshcore_open/utils/platform_info.dart'; import 'package:meshcore_open/widgets/app_bar.dart'; import 'package:provider/provider.dart'; @@ -12,6 +12,7 @@ import 'package:uuid/uuid.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../services/app_settings_service.dart'; +import '../services/received_image_store.dart'; import '../services/ui_view_state_service.dart'; import '../models/channel.dart'; import '../models/community.dart'; @@ -27,6 +28,7 @@ import '../widgets/qr_code_display.dart'; import '../widgets/quick_switch_bar.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/unread_badge.dart'; +import '../helpers/gif_helper.dart'; import '../helpers/snack_bar_builder.dart'; import 'channel_chat_screen.dart'; import 'community_qr_scanner_screen.dart'; @@ -220,6 +222,7 @@ class _ChannelsScreenState extends State if (viewState.channelsSearchText.isNotEmpty) IconButton( icon: const Icon(Icons.clear), + tooltip: context.l10n.common_clearSearch, onPressed: () { _searchDebounce?.cancel(); _searchDebounce = null; @@ -282,8 +285,6 @@ class _ChannelsScreenState extends State buildDefaultDragHandles: false, itemCount: filteredChannels.length, onReorderItem: (oldIndex, newIndex) { - // onReorderItem already adjusts newIndex after the - // removed item, unlike the deprecated onReorder. final reordered = List.from( filteredChannels, ); @@ -403,7 +404,7 @@ class _ChannelsScreenState extends State iconColor = MeshPalette.signal; case ChannelType.hashtag: icon = Icons.tag; - iconColor = MeshPalette.blue; + iconColor = MeshPalette.warn; case ChannelType.private: icon = Icons.lock; iconColor = MeshPalette.blue; @@ -412,7 +413,12 @@ class _ChannelsScreenState extends State // Last message preview final messages = connector.getChannelMessages(channel); final lastMessage = messages.isNotEmpty ? messages.last : null; - final lastPreview = lastMessage?.text ?? ''; + final lastMessageText = lastMessage?.text ?? ''; + final lastPreview = + lastMessageText.isNotEmpty && + GifHelper.parseGif(lastMessageText) != null + ? context.l10n.chat_receivedGif + : lastMessageText; final lastTime = lastMessage?.timestamp; final channelLabel = channel.name.isEmpty @@ -455,7 +461,7 @@ class _ChannelsScreenState extends State ) : null, child: Row( - crossAxisAlignment: CrossAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, children: [ // Leading avatar with optional community badge Stack( @@ -512,12 +518,18 @@ class _ChannelsScreenState extends State overflow: TextOverflow.ellipsis, ), ), - const SizedBox(width: 6), - StatusChip( - label: 'CH ${channel.index}', - color: MeshPalette.blue, - fontSize: 10, - ), + if (showDragHandle) ...[ + const SizedBox(width: 6), + Text( + 'CH ${channel.index}', + style: MeshTheme.mono( + fontSize: 11, + color: scheme.onSurfaceVariant.withValues( + alpha: 0.7, + ), + ), + ), + ], ], ), if (subtitle.isNotEmpty) ...[ @@ -578,14 +590,21 @@ class _ChannelsScreenState extends State ], ), if (showDragHandle && dragIndex != null) ...[ - const SizedBox(width: 4), ReorderableDragStartListener( index: dragIndex, - child: Padding( - padding: const EdgeInsets.all(8), - child: Icon( - Icons.drag_handle, - color: scheme.onSurfaceVariant, + child: MouseRegion( + cursor: SystemMouseCursors.grab, + child: Tooltip( + message: context.l10n.channels_dragToReorder, + child: SizedBox( + width: 48, + height: 48, + child: Icon( + Icons.drag_indicator, + size: 28, + color: scheme.onSurface, + ), + ), ), ), ), @@ -805,6 +824,13 @@ class _ChannelsScreenState extends State connector.channels, connector.maxChannels, ); + if (nextIndex == null) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.channels_noFreeSlots), + ); + return; + } final hasPublicChannel = connector.channels.any((c) => c.isPublicChannel); int? selectedOption; final nameController = TextEditingController(); @@ -938,11 +964,7 @@ class _ChannelsScreenState extends State ); return; } - final random = Random.secure(); - final psk = Uint8List(16); - for (int i = 0; i < 16; i++) { - psk[i] = random.nextInt(256); - } + final psk = randomBytes(16); Navigator.pop(sheetContext); await connector.setChannel( nextIndex, @@ -1450,24 +1472,7 @@ class _ChannelsScreenState extends State controller: scrollController, padding: const EdgeInsets.only(bottom: 24), children: [ - buildOptionCard( - optionIndex: 0, - icon: Icons.add, - title: sheetContext.l10n.channels_createPrivateChannel, - subtitle: - sheetContext.l10n.channels_createPrivateChannelDesc, - ), - if (selectedOption == 0) - buildExpandedContent(_channelMessageStore)!, - buildOptionCard( - optionIndex: 1, - icon: Icons.lock, - title: sheetContext.l10n.channels_joinPrivateChannel, - subtitle: - sheetContext.l10n.channels_joinPrivateChannelDesc, - ), - if (selectedOption == 1) - buildExpandedContent(_channelMessageStore)!, + SectionHeader(sheetContext.l10n.channels_addSectionJoin), if (!hasPublicChannel) ...[ buildOptionCard( optionIndex: 2, @@ -1488,6 +1493,15 @@ class _ChannelsScreenState extends State ), 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, @@ -1496,6 +1510,18 @@ class _ChannelsScreenState extends State ), 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, @@ -1528,6 +1554,7 @@ class _ChannelsScreenState extends State final pskController = TextEditingController(text: channel.pskHex); bool smazEnabled = connector.isChannelSmazEnabled(channel.index); bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index); + bool urlImagesEnabled = connector.isChannelUrlImagesEnabled(channel.index); String? selectedCyr2LatProfileId = connector.getChannelCyr2LatProfileId( channel.index, ); @@ -1571,11 +1598,7 @@ class _ChannelsScreenState extends State icon: const Icon(Icons.casino), tooltip: sheetContext.l10n.channels_generateRandomPsk, onPressed: () { - final random = Random.secure(); - final bytes = Uint8List(16); - for (int i = 0; i < 16; i++) { - bytes[i] = random.nextInt(256); - } + final bytes = randomBytes(16); pskController.text = Channel.formatPskHex(bytes); }, ), @@ -1634,6 +1657,13 @@ class _ChannelsScreenState extends State ), ), ], + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(sheetContext.l10n.urlImage_enable), + value: urlImagesEnabled, + onChanged: (value) => + setSheetState(() => urlImagesEnabled = value), + ), const SizedBox(height: 24), ], ), @@ -1683,6 +1713,10 @@ class _ChannelsScreenState extends State channel.index, cyr2latEnabled, ); + await connector.setChannelUrlImagesEnabled( + channel.index, + urlImagesEnabled, + ); await connector.setChannelCyr2LatProfileId( channel.index, selectedCyr2LatProfileId, @@ -1724,6 +1758,12 @@ class _ChannelsScreenState extends State ChannelMessageStore channelMessageStore, Channel channel, ) { + ReceivedImageStore? imageStore; + try { + imageStore = context.read(); + } on ProviderNotFoundException { + imageStore = null; + } showDialog( context: context, builder: (dialogContext) => AlertDialog( @@ -1743,6 +1783,7 @@ class _ChannelsScreenState extends State await connector.deleteChannel(channel.index); await channelMessageStore.clearChannelMessages(channel.index); + await imageStore?.deleteImagesForChannel(channel.index); if (!context.mounted) return; @@ -1787,12 +1828,12 @@ class _ChannelsScreenState extends State ); } - int _findNextAvailableIndex(List channels, int maxChannels) { + int? _findNextAvailableIndex(List channels, int maxChannels) { final usedIndices = channels.map((c) => c.index).toSet(); for (int i = 0; i < maxChannels; i++) { if (!usedIndices.contains(i)) return i; } - return 0; + return null; } void _showManageCommunitiesDialog(BuildContext context) { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 7eca042b..30aac388 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -7,11 +7,14 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; +import '../utils/app_logger.dart'; import '../utils/platform_info.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; +import '../helpers/message_url_image_helper.dart'; +import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; @@ -28,6 +31,7 @@ import '../services/path_history_service.dart'; import '../services/translation_service.dart'; import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/byte_count_input.dart'; +import '../widgets/chat_day_separator.dart'; import 'channel_message_path_screen.dart'; import 'map_screen.dart'; import '../widgets/emoji_picker.dart'; @@ -46,6 +50,14 @@ import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import 'telemetry_screen.dart'; +// Image messages are deliberately absent from this screen, and there is no +// flag to flip: the AEIC wire format is `CMD_SEND_CHANNEL_DATA` (62) / +// GRP_DATA 0x06, which addresses a channel index rather than a contact key, +// and the companion protocol has no direct-message equivalent (there is no +// CMD_SEND_DATA — see `meshcore_protocol.dart`). Sending a private photo on +// channel 0 to reach one contact would broadcast it to everyone on that +// channel. Channel chats keep the feature; see `channel_chat_screen.dart`. + class ChatScreen extends StatefulWidget { final Contact contact; final int initialUnreadCount; @@ -178,10 +190,6 @@ class _ChatScreenState extends State { title: Consumer2( builder: (context, pathService, connector, _) { final contact = _resolveContact(connector); - final unreadCount = connector.getUnreadCountForContactKey( - widget.contact.publicKeyHex, - ); - final unreadLabel = context.l10n.chat_unread(unreadCount); final pathLabel = _currentPathLabel(contact); return Column( @@ -200,7 +208,7 @@ class _ChatScreenState extends State { child: Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: Text( - '$pathLabel • $unreadLabel', + pathLabel, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 11, @@ -424,10 +432,20 @@ class _ChatScreenState extends State { final isUnreadAnchor = _unreadDividerMessageId != null && message.messageId == _unreadDividerMessageId; - final child = isUnreadAnchor + final startsDay = + messageIndex == reversedMessages.length - 1 || + !isSameChatDay( + reversedMessages[messageIndex + 1].timestamp, + message.timestamp, + ); + final child = isUnreadAnchor || startsDay ? Column( mainAxisSize: MainAxisSize.min, - children: [const UnreadDivider(), bubble], + children: [ + if (startsDay) ChatDaySeparator(day: message.timestamp), + if (isUnreadAnchor) const UnreadDivider(), + bubble, + ], ) : bubble; if (identical(message, _pendingUnreadScrollTarget)) { @@ -469,9 +487,9 @@ class _ChatScreenState extends State { crossAxisAlignment: CrossAxisAlignment.center, children: [ IconButton( - icon: const Icon(Icons.gif_box), - onPressed: () => _showGifPicker(context), + icon: const Icon(Icons.gif_box_outlined), tooltip: context.l10n.chat_sendGif, + onPressed: () => _showGifPicker(context), ), if (settings.translationEnabled) MessageTranslationButton( @@ -479,6 +497,9 @@ class _ChatScreenState extends State { 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, @@ -516,6 +537,7 @@ class _ChatScreenState extends State { const SizedBox(width: 8), IconButton( icon: const Icon(Icons.close), + tooltip: context.l10n.chat_removeGif, onPressed: () { _textController.clear(); _textFieldFocusNode.requestFocus(); @@ -527,6 +549,11 @@ class _ChatScreenState extends State { } return ByteCountedTextField( maxBytes: maxBytes, + softLimitBytes: + maxTextPayloadBytesAfterFullLengthAttempts, + softLimitNote: context.l10n.chat_longMessageRetryNote( + maxFullLengthTextAttempt + 1, + ), controller: _textController, focusNode: _textFieldFocusNode, hintText: context.l10n.chat_typeMessage, @@ -546,15 +573,15 @@ class _ChatScreenState extends State { decoration: InputDecoration( hintText: context.l10n.chat_typeMessage, border: OutlineInputBorder( - borderRadius: BorderRadius.circular(MeshRadii.pill), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide(color: scheme.outlineVariant), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(MeshRadii.pill), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide(color: scheme.outlineVariant), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(MeshRadii.pill), + borderRadius: BorderRadius.circular(MeshRadii.md), borderSide: BorderSide( color: scheme.primary, width: 1.5, @@ -776,17 +803,35 @@ class _ChatScreenState extends State { } String _currentPathLabel(Contact contact) { + final connector = context.read(); + // Check if user has set a path override if (contact.pathOverride != null) { if (contact.pathOverride! < 0) return context.l10n.chat_floodForced; if (contact.pathOverride == 0) return context.l10n.chat_directForced; - return context.l10n.chat_hopsForced(contact.pathOverride!); + final bytes = contact.pathOverrideBytes ?? Uint8List(0); + final hopCount = _displayHopCount( + bytes, + contact.pathOverride!, + connector.pathHashByteWidth, + ); + return context.l10n.chat_hopsForced(hopCount); } // Use device's path if (contact.pathLength < 0) return context.l10n.chat_floodAuto; if (contact.pathLength == 0) return context.l10n.chat_direct; - return context.l10n.chat_hopsCount(contact.pathLength); + final hopCount = _displayHopCount( + contact.path, + contact.pathLength, + contact.pathHashWidth, + ); + return context.l10n.chat_hopsCount(hopCount); + } + + int _displayHopCount(List pathBytes, int storedHopCount, int hashWidth) { + if (pathBytes.isEmpty) return storedHopCount; + return PathHelper.splitPathBytes(pathBytes, hashWidth).length; } void _showContactInfo(BuildContext context) { @@ -807,7 +852,10 @@ class _ChatScreenState extends State { ), _buildInfoRow( context.l10n.chat_path, - contact.pathLabel(context.l10n), + contact.pathLabel( + context.l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), ), _buildInfoRow( context.l10n.contact_lastSeen, @@ -845,6 +893,9 @@ class _ChatScreenState extends State { bool cyr2latEnabled = connector.isContactCyr2LatEnabled( contact.publicKeyHex, ); + bool urlImagesEnabled = connector.isContactUrlImagesEnabled( + contact.publicKeyHex, + ); String? selectedCyr2LatProfileId = connector.getContactCyr2LatProfileId( contact.publicKeyHex, ); @@ -944,6 +995,19 @@ class _ChatScreenState extends State { ), ], const Divider(height: 8), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(context.l10n.urlImage_enable), + value: urlImagesEnabled, + onChanged: (value) { + connector.setContactUrlImagesEnabled( + contact.publicKeyHex, + value, + ); + setDialogState(() => urlImagesEnabled = value); + }, + ), + const Divider(height: 8), SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(context.l10n.contact_teleBase), @@ -1049,7 +1113,11 @@ class _ChatScreenState extends State { ); } - void _openMessagePath(Message message, Contact contact) { + void _openMessagePath( + Message message, + Contact contact, { + bool openMap = false, + }) { final connector = context.read(); final fourByteHex = message.fourByteRoomContactKey .map((b) => b.toRadixString(16).padLeft(2, '0')) @@ -1081,7 +1149,9 @@ class _ChatScreenState extends State { Navigator.push( context, MaterialPageRoute( - builder: (context) => ChannelMessagePathScreen(message: pathMessage), + builder: (context) => openMap + ? ChannelMessagePathMapScreen(message: pathMessage) + : ChannelMessagePathScreen(message: pathMessage), ), ); } @@ -1103,8 +1173,8 @@ class _ChatScreenState extends State { mainAxisSize: MainAxisSize.min, children: [ BottomSheetHeader( - title: message.text.length > 40 - ? '${message.text.substring(0, 40)}…' + title: message.text.characters.length > 40 + ? '${message.text.characters.take(40)}…' : message.text, ), // Can't react to your own messages @@ -1125,6 +1195,15 @@ class _ChatScreenState extends State { _openMessagePath(message, contact); }, ), + if (message.pathBytes.isNotEmpty) + ListTile( + leading: const Icon(Icons.map_outlined), + title: Text(context.l10n.chat_viewPathOnMap), + onTap: () { + Navigator.pop(sheetContext); + _openMessagePath(message, contact, openMap: true); + }, + ), ListTile( leading: const Icon(Icons.copy), title: Text(context.l10n.common_copy), @@ -1248,6 +1327,7 @@ class _ChatScreenState extends State { final senderName = liveContact.type == advTypeRoom ? senderContact.name : null; + appLogger.info('Sending reaction using senderName: $senderName'); final hash = ReactionHelper.computeReactionHash( timestampSecs, senderName, @@ -1284,6 +1364,9 @@ class _MessageBubble extends StatelessWidget { final gifId = GifHelper.parseGif(message.text); final poi = parseMarkerText(message.text); final isFailed = message.status == MessageStatus.failed; + final urlImagesEnabled = context.select( + (connector) => connector.isContactUrlImagesEnabled(sourceId), + ); // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. final bubbleColor = isFailed @@ -1331,6 +1414,30 @@ class _MessageBubble extends StatelessWidget { ? message.originalText : (translatedDisplayText != messageText ? messageText : null); + Widget buildTextContent() { + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + child: TranslatedMessageContent( + displayText: translatedDisplayText, + originalText: originalDisplayText, + style: TextStyle( + color: textColor, + fontSize: bodyFontSize * textScale, + ), + originalStyle: TextStyle( + color: textColor.withValues(alpha: 0.72), + fontSize: bodyFontSize * textScale, + ), + onSecondaryTap: PlatformInfo.isDesktop ? onLongPress : null, + ), + ), + ], + ); + } + return Padding( padding: const EdgeInsets.symmetric(vertical: 3), child: Column( @@ -1418,28 +1525,76 @@ class _MessageBubble extends StatelessWidget { ), ], ) + else if (urlImagesEnabled) + MessageUrlImageFutureBuilder( + messageId: message.messageId, + text: message.text, + builder: (context, snapshot) { + final imageAttachment = snapshot.data; + + if (imageAttachment != null) { + return Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 4, + ), + child: Align( + alignment: isOutgoing + ? Alignment.centerRight + : Alignment.centerLeft, + child: MessageUrlImagePreview( + imageUrl: imageAttachment, + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 8), + child: TranslatedMessageContent( + displayText: translatedDisplayText, + originalText: originalDisplayText, + style: TextStyle( + color: textColor, + fontSize: bodyFontSize * textScale, + ), + originalStyle: TextStyle( + color: textColor.withValues( + alpha: 0.72, + ), + fontSize: bodyFontSize * textScale, + ), + onSecondaryTap: PlatformInfo.isDesktop + ? onLongPress + : null, + ), + ), + ], + ); + } + + return buildTextContent(); + }, + ) else - Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, + Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Flexible( - child: TranslatedMessageContent( - displayText: translatedDisplayText, - originalText: originalDisplayText, - style: TextStyle( - color: textColor, - fontSize: bodyFontSize * textScale, + if (MessageUrlImageHelper.hasPotentialImageUrl( + message.text, + )) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + context.l10n.urlImage_possible, + style: TextStyle( + color: metaColor, + fontSize: 11 * textScale, + ), ), - originalStyle: TextStyle( - color: textColor.withValues(alpha: 0.72), - fontSize: bodyFontSize * textScale, - ), - onSecondaryTap: PlatformInfo.isDesktop - ? onLongPress - : null, ), - ), + buildTextContent(), ], ), if (enableTracing && @@ -1480,16 +1635,16 @@ class _MessageBubble extends StatelessWidget { crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( - _formatTime(message.timestamp), + formatChatTime(context, message.timestamp), style: MeshTheme.mono( - fontSize: 10 * textScale, + fontSize: 12 * textScale, color: metaColor, ), ), if (isOutgoing) ...[ const SizedBox(width: 2), MessageStatusIcon( - size: 12 * textScale, + size: 16 * textScale, onColor: metaColor, isAcked: message.status == @@ -1515,7 +1670,7 @@ class _MessageBubble extends StatelessWidget { Text( '${(message.tripTimeMs! / 1000).toStringAsFixed(1)}s', style: MeshTheme.mono( - fontSize: 9 * textScale, + fontSize: 11 * textScale, color: isOutgoing ? metaColor : scheme.tertiary, @@ -1621,7 +1776,7 @@ class _MessageBubble extends StatelessWidget { runSpacing: 6, children: message.reactions.entries.map((entry) { final emoji = entry.key; - final count = entry.value; + final count = entry.value.length; final status = message.reactionStatuses[emoji]; final isPending = status == MessageStatus.pending || status == MessageStatus.sent; @@ -1694,12 +1849,6 @@ class _MessageBubble extends StatelessWidget { Widget _buildAvatar(String senderName) { return AvatarCircle(name: senderName, size: 32); } - - String _formatTime(DateTime time) { - final hour = time.hour.toString().padLeft(2, '0'); - final minute = time.minute.toString().padLeft(2, '0'); - return '$hour:$minute'; - } } /// Deterministic name-to-hue mapping consistent with [AvatarCircle]. diff --git a/lib/screens/companion_radio_stats_screen.dart b/lib/screens/companion_radio_stats_screen.dart index f7d8f46e..748f4a20 100644 --- a/lib/screens/companion_radio_stats_screen.dart +++ b/lib/screens/companion_radio_stats_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/models/companion_radio_stats.dart'; +import 'package:meshcore_open/screens/telemetry_screen.dart'; import 'package:meshcore_open/l10n/l10n.dart'; import 'package:meshcore_open/theme/mesh_theme.dart'; import 'package:meshcore_open/widgets/mesh_ui.dart'; @@ -46,8 +47,8 @@ class _CompanionRadioStatsScreenState extends State { @override void dispose() { _connector?.radioStatsNotifier.removeListener(_onStatsUpdate); - _connector?.releaseRadioStatsPolling(); _connector?.setPollingInterval(30); + _connector?.releaseRadioStatsPolling(); super.dispose(); } @@ -77,6 +78,18 @@ class _CompanionRadioStatsScreenState extends State { appBar: AppBar( title: Text(l10n.radioStats_screenTitle), centerTitle: true, + actions: [ + Selector( + selector: (_, c) => c.isConnected, + builder: (context, connected, _) => IconButton( + icon: const Icon(Icons.thermostat), + tooltip: l10n.contact_telemetry, + onPressed: connected + ? () => pushSelfTelemetryScreen(context) + : null, + ), + ), + ], ), body: Selector( selector: (_, c) => ( @@ -109,8 +122,8 @@ class _CompanionRadioStatsScreenState extends State { padding: const EdgeInsets.symmetric(vertical: 8), children: [ if (stats != null) ...[ - const SectionHeader( - 'Signal', + SectionHeader( + l10n.radioStats_sectionSignal, padding: EdgeInsets.fromLTRB(16, 16, 16, 8), ), MeshCard( @@ -144,8 +157,8 @@ class _CompanionRadioStatsScreenState extends State { ], ), ), - const SectionHeader( - 'Airtime', + SectionHeader( + l10n.radioStats_sectionAirtime, padding: EdgeInsets.fromLTRB(16, 16, 16, 8), ), MeshCard( diff --git a/lib/screens/contact_qr_scanner_screen.dart b/lib/screens/contact_qr_scanner_screen.dart new file mode 100644 index 00000000..87348c0f --- /dev/null +++ b/lib/screens/contact_qr_scanner_screen.dart @@ -0,0 +1,310 @@ +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:mobile_scanner/mobile_scanner.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 '../theme/mesh_theme.dart'; +import '../utils/contact_qr.dart'; +import '../utils/contact_qr_frame.dart'; +import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/qr_scanner_widget.dart'; + +/// Screen for scanning MeshCore contact QR codes, either with the camera +/// or by picking a photo containing a QR code from the gallery. +class ContactQrScannerScreen extends StatefulWidget { + const ContactQrScannerScreen({super.key}); + + @override + State createState() => _ContactQrScannerScreenState(); +} + +class _ContactQrScannerScreenState extends State { + bool _isProcessing = false; + + /// Set after a failed import so the camera does not immediately rescan the + /// same QR and resend the frame in a loop. + bool _importFailed = false; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: AdaptiveAppBarTitle(context.l10n.contacts_scanQrCode), + centerTitle: true, + actions: [ + IconButton( + tooltip: context.l10n.contacts_qrFromGallery, + icon: const Icon(Icons.photo_library), + onPressed: _isProcessing ? null : _pickFromGallery, + ), + ], + ), + body: _isProcessing + ? Container( + color: Theme.of(context).colorScheme.surface, + child: const Center(child: CircularProgressIndicator()), + ) + : _importFailed + ? _buildImportFailed(context) + : QrScannerWidget( + onScanned: (data) => _handleScannedData(data), + validator: (data) => parseContactQr(data) != null, + onValidationFailed: (_) => _showInvalidQrError(), + instructions: context.l10n.contacts_scanQrInstructions, + overlay: _buildThemedOverlay(context), + ), + ); + } + + Widget _buildImportFailed(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.error_outline, + size: 64, + color: Theme.of(context).colorScheme.error, + ), + const SizedBox(height: 16), + Text( + context.l10n.contacts_contactImportFailed, + style: Theme.of(context).textTheme.titleMedium, + textAlign: TextAlign.center, + ), + const SizedBox(height: 24), + FilledButton.icon( + onPressed: () => setState(() => _importFailed = false), + icon: const Icon(Icons.refresh), + label: Text(context.l10n.common_retry), + ), + ], + ), + ), + ); + } + + 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; + + // Claim the flag before awaiting the picker, otherwise a camera detection + // can start a second import while the gallery sheet is open. + setState(() { + _isProcessing = true; + }); + + final XFile? image; + try { + image = await ImagePicker().pickImage(source: ImageSource.gallery); + } catch (e) { + if (mounted) { + setState(() { + _isProcessing = false; + }); + _showGalleryError(); + } + return; + } + if (!mounted) return; + if (image == null) { + setState(() { + _isProcessing = false; + }); + return; + } + + String? rawValue; + bool decodedAnyBarcode = false; + final controller = MobileScannerController(); + try { + final capture = await controller.analyzeImage(image.path); + for (final barcode in capture?.barcodes ?? const []) { + final value = barcode.rawValue; + if (value == null || value.isEmpty) continue; + decodedAnyBarcode = true; + if (parseContactQr(value) != null) { + rawValue = value; + break; + } + } + } on UnsupportedError { + rawValue = null; + } catch (e) { + rawValue = null; + } finally { + controller.dispose(); + } + + if (!mounted) return; + + if (rawValue == null) { + setState(() { + _isProcessing = false; + }); + if (decodedAnyBarcode) { + _showInvalidQrError(); + } else { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_noQrCodeFound), + backgroundColor: MeshPalette.warn, + duration: const Duration(seconds: 2), + ); + } + return; + } + + setState(() { + _isProcessing = false; + }); + await _handleScannedData(rawValue); + } + + Future _handleScannedData(String data) async { + if (_isProcessing) return; + + setState(() { + _isProcessing = true; + _importFailed = false; + }); + + final scanned = parseContactQr(data); + if (scanned == null) { + if (mounted) { + setState(() { + _isProcessing = false; + }); + _showInvalidQrError(); + } + return; + } + + final connector = Provider.of(context, listen: false); + final publicKey = scanned.publicKey; + // Saved contacts first (their flags matter), then discovery-only records, + // which still carry a known name worth preserving. + final existing = publicKey == null + ? null + : connector.allContactsUnfiltered + .where( + (contact) => contact.publicKeyHex == pubKeyToHex(publicKey), + ) + .firstOrNull; + final frame = buildContactQrFrame( + scanned, + existing: existing, + pathHashByteWidth: connector.pathHashByteWidth, + ); + + try { + await connector.sendFrame(frame, waitForGenericAck: true); + await connector.refreshContacts(); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactImported), + ); + // Keep _isProcessing set: resetting it would restart the camera on a + // closing route and let a second detection import and pop again. + Navigator.pop(context); + } catch (e) { + if (mounted) { + setState(() { + _isProcessing = false; + _importFailed = true; + }); + } + } + } + + void _showInvalidQrError() { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_invalidAdvertFormat), + backgroundColor: MeshPalette.warn, + duration: const Duration(seconds: 2), + ); + } + + void _showGalleryError() { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_qrGalleryFailed), + backgroundColor: MeshPalette.warn, + duration: const Duration(seconds: 2), + ); + } +} diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 44ec78d2..ccddcdf9 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -34,6 +34,7 @@ import '../widgets/unread_badge.dart'; import '../helpers/snack_bar_builder.dart'; import 'channels_screen.dart'; import 'chat_screen.dart'; +import 'contact_qr_scanner_screen.dart'; import 'discovery_screen.dart'; import 'map_screen.dart'; import 'repeater_hub_screen.dart'; @@ -185,6 +186,14 @@ class _ContactsScreenState extends State } final hexString = pubKeyToHex(advertPacket); Clipboard.setData(ClipboardData(text: "meshcore://$hexString")); + _pendingOperations.remove(ContactOperationType.export); + if (mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactAdvertCopied), + ); + } + return; } // Generic OK/ERR acks carry no command correlation, so consume only @@ -376,6 +385,21 @@ class _ContactsScreenState extends State ), onTap: () => _contactImport(), ), + PopupMenuItem( + child: Row( + children: [ + const Icon(Icons.qr_code_scanner), + const SizedBox(width: 8), + Text(context.l10n.contacts_scanQrCode), + ], + ), + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const ContactQrScannerScreen(), + ), + ), + ), const PopupMenuDivider(), PopupMenuItem( child: Row( @@ -488,6 +512,19 @@ class _ContactsScreenState extends State _contactImport(); }, ), + ListTile( + leading: const Icon(Icons.qr_code_scanner), + title: Text(context.l10n.contacts_scanQrCode), + onTap: () { + Navigator.pop(sheetContext); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const ContactQrScannerScreen(), + ), + ); + }, + ), ListTile( leading: const Icon(Icons.person_add_rounded), title: Text(context.l10n.discoveredContacts_Title), @@ -704,7 +741,7 @@ class _ContactsScreenState extends State return EmptyState( icon: Icons.people_outline, title: context.l10n.contacts_noContacts, - subtitle: context.l10n.contacts_contactsWillAppear, + subtitle: context.l10n.contacts_noContactsDiscoveredHint, action: FilledButton.icon( onPressed: () => Navigator.push( context, @@ -882,6 +919,20 @@ class _ContactsScreenState extends State ], ), ), + ListTile( + dense: true, + leading: const Icon(Icons.person_add_rounded), + title: Text( + context.l10n.contacts_discoveredNearby( + connector.discoveredContacts.where((c) => !c.isActive).length, + ), + ), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) => const DiscoveryScreen()), + ), + ), Expanded( child: RefreshIndicator( onRefresh: () => connector.getContacts(), @@ -915,12 +966,14 @@ class _ContactsScreenState extends State return _ContactTileEntrance( index: index, contact: contact, + pathHashByteWidth: connector.pathHashByteWidth, lastSeen: _resolveLastSeen(contact), unreadCount: unreadCount, isFavorite: contact.isFavorite, onTap: () => _openChat(context, contact), onLongPress: () => _showContactOptions(context, connector, contact), + onManage: _manageAction(context, contact), ); }, ), @@ -1046,6 +1099,17 @@ class _ContactsScreenState extends State } } + VoidCallback? _manageAction(BuildContext context, Contact contact) { + if (contact.type == advTypeRepeater) { + return () => _showRepeaterLogin(context, contact); + } + if (contact.type == advTypeRoom) { + return () => + _showRoomLogin(context, contact, RoomLoginDestination.management); + } + return null; + } + void _handleQuickSwitch(int index, BuildContext context) { if (index == 0) return; switch (index) { @@ -1371,7 +1435,10 @@ class _ContactsScreenState extends State MaterialPageRoute( builder: (context) => PathTraceMapScreen( title: context.l10n.contacts_repeaterPing, - path: Uint8List.fromList([contact.publicKey.first]), + path: contact.pathBytesForDisplay.isNotEmpty + ? contact.pathBytesForDisplay + : _contactPathPrefix(contact, hw), + flipPathAround: true, targetContact: contact, pathHashByteWidth: hw, ), @@ -1405,8 +1472,8 @@ class _ContactsScreenState extends State : context.l10n.contacts_roomPing, path: contact.pathBytesForDisplay.isNotEmpty ? contact.pathBytesForDisplay - : Uint8List.fromList([contact.publicKey.first]), - flipPathAround: contact.pathBytesForDisplay.isNotEmpty, + : _contactPathPrefix(contact, hw), + flipPathAround: true, targetContact: contact, pathHashByteWidth: hw, ), @@ -1501,7 +1568,7 @@ class _ContactsScreenState extends State color: Theme.of(context).colorScheme.error, ), title: Text( - context.l10n.contacts_deleteContact, + context.l10n.contacts_removeFromContacts, style: TextStyle(color: Theme.of(context).colorScheme.error), ), onTap: () { @@ -1516,32 +1583,61 @@ class _ContactsScreenState extends State ); } + Uint8List _contactPathPrefix(Contact contact, int hashByteWidth) { + if (contact.publicKey.isEmpty) return Uint8List(0); + final width = hashByteWidth + .clamp(1, pubKeySize) + .toInt() + .clamp(1, contact.publicKey.length) + .toInt(); + return Uint8List.fromList(contact.publicKey.sublist(0, width)); + } + void _confirmDelete( BuildContext context, MeshCoreConnector connector, Contact contact, ) { + var keepHistory = false; showDialog( context: context, - builder: (dialogContext) => AlertDialog( - title: Text(context.l10n.contacts_deleteContact), - content: Text(context.l10n.contacts_removeConfirm(contact.name)), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext), - child: Text(context.l10n.common_cancel), + builder: (dialogContext) => StatefulBuilder( + builder: (dialogContext, setDialogState) => AlertDialog( + title: Text(context.l10n.contacts_removeFromContacts), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + context.l10n.contacts_removeFromContactsConfirm(contact.name), + ), + CheckboxListTile( + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + value: keepHistory, + title: Text(context.l10n.contacts_keepChatHistory), + onChanged: (value) => + setDialogState(() => keepHistory = value ?? false), + ), + ], ), - TextButton( - onPressed: () { - Navigator.pop(dialogContext); - connector.removeContact(contact); - }, - child: Text( - context.l10n.common_delete, - style: TextStyle(color: Theme.of(context).colorScheme.error), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(context.l10n.common_cancel), ), - ), - ], + TextButton( + onPressed: () { + Navigator.pop(dialogContext); + connector.removeContact(contact, keepMessages: keepHistory); + }, + child: Text( + context.l10n.contacts_remove, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + ], + ), ), ); } @@ -1549,19 +1645,23 @@ class _ContactsScreenState extends State class _ContactTile extends StatelessWidget { final Contact contact; + final int pathHashByteWidth; final DateTime lastSeen; final int unreadCount; final bool isFavorite; final VoidCallback onTap; final VoidCallback onLongPress; + final VoidCallback? onManage; const _ContactTile({ required this.contact, + required this.pathHashByteWidth, required this.lastSeen, required this.unreadCount, required this.isFavorite, required this.onTap, required this.onLongPress, + this.onManage, }); /// Node-type avatar color per design language. @@ -1598,9 +1698,6 @@ class _ContactTile extends StatelessWidget { final scheme = Theme.of(context).colorScheme; final emoji = firstEmoji(contact.name); final isChat = contact.type == advTypeChat; - final pathLen = contact.pathBytesForDisplay.length; - final isDirect = contact.pathLength >= 0; - final hasPath = pathLen > 0 || contact.pathLength == 0; return GestureDetector( onSecondaryTapUp: PlatformInfo.isDesktop ? (_) => onLongPress() : null, @@ -1676,7 +1773,10 @@ class _ContactTile extends StatelessWidget { children: [ Expanded( child: Text( - contact.pathLabel(context.l10n), + contact.pathLabel( + context.l10n, + pathHashByteWidth: pathHashByteWidth, + ), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -1685,13 +1785,6 @@ class _ContactTile extends StatelessWidget { ), ), ), - if (hasPath) ...[ - const SizedBox(width: 6), - RouteChip( - isDirect: isDirect, - hops: isDirect ? contact.pathLength : null, - ), - ], ], ), ], @@ -1730,6 +1823,15 @@ class _ContactTile extends StatelessWidget { ], ), ), + if (onManage != null) + IconButton( + icon: const Icon(Icons.admin_panel_settings_outlined), + tooltip: contact.type == advTypeRoom + ? context.l10n.room_management + : context.l10n.contacts_manageRepeater, + visualDensity: VisualDensity.compact, + onPressed: onManage, + ), ], ), ), @@ -1763,20 +1865,24 @@ class _ContactTile extends StatelessWidget { class _ContactTileEntrance extends StatelessWidget { final int index; final Contact contact; + final int pathHashByteWidth; final DateTime lastSeen; final int unreadCount; final bool isFavorite; final VoidCallback onTap; final VoidCallback onLongPress; + final VoidCallback? onManage; const _ContactTileEntrance({ required this.index, required this.contact, + required this.pathHashByteWidth, required this.lastSeen, required this.unreadCount, required this.isFavorite, required this.onTap, required this.onLongPress, + this.onManage, }); @override @@ -1785,11 +1891,13 @@ class _ContactTileEntrance extends StatelessWidget { index: index, child: _ContactTile( contact: contact, + pathHashByteWidth: pathHashByteWidth, lastSeen: lastSeen, unreadCount: unreadCount, isFavorite: isFavorite, onTap: onTap, onLongPress: onLongPress, + onManage: onManage, ), ); } diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index 4a782d6f..b749041c 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -34,9 +34,17 @@ class _DiscoveryScreenState extends State { ContactTypeFilter typeFilter = ContactTypeFilter.all; DiscoverySortOption discoverySortOption = DiscoverySortOption.lastSeen; Timer? _searchDebounce; + ScaffoldMessengerState? _messenger; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _messenger = ScaffoldMessenger.maybeOf(context); + } @override void dispose() { + _messenger?.hideCurrentSnackBar(); _searchController.dispose(); _searchDebounce?.cancel(); super.dispose(); @@ -169,33 +177,7 @@ class _DiscoveryScreenState extends State { return ListEntrance( index: index, child: MeshCard( - onTap: () async { - try { - final imported = await connector.importDiscoveredContact(contact); - if (!context.mounted) return; - if (!imported) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactImportFailed), - ); - return; - } - showDismissibleSnackBar( - context, - content: Text(context.l10n.discoveredContacts_contactAdded), - action: SnackBarAction( - label: context.l10n.common_undo, - onPressed: () => connector.removeContact(contact), - ), - ); - } catch (_) { - if (!context.mounted) return; - showDismissibleSnackBar( - context, - content: Text(context.l10n.contacts_contactImportFailed), - ); - } - }, + onTap: () => _addContact(context, contact, connector), onLongPress: () => _showContactContextMenu(contact, connector), onSecondaryTap: PlatformInfo.isDesktop ? () => _showContactContextMenu(contact, connector) @@ -296,12 +278,49 @@ class _DiscoveryScreenState extends State { ), ), ), + IconButton( + tooltip: context.l10n.discoveredContacts_addContact, + icon: const Icon(Icons.person_add_alt_1), + onPressed: () => _addContact(context, contact, connector), + ), ], ), ), ); } + Future _addContact( + BuildContext context, + Contact contact, + MeshCoreConnector connector, + ) async { + try { + final imported = await connector.importDiscoveredContact(contact); + if (!context.mounted) return; + if (!imported) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactImportFailed), + ); + return; + } + showDismissibleSnackBar( + context, + content: Text(context.l10n.discoveredContacts_contactAdded), + action: SnackBarAction( + label: context.l10n.common_undo, + onPressed: () => connector.removeContact(contact), + ), + ); + } catch (_) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_contactImportFailed), + ); + } + } + Future _showContactContextMenu( Contact contact, MeshCoreConnector connector, @@ -431,6 +450,7 @@ class _DiscoveryScreenState extends State { if (searchQuery.isNotEmpty) IconButton( icon: const Icon(Icons.clear), + tooltip: context.l10n.common_clearSearch, onPressed: () { _searchController.clear(); setState(() { diff --git a/lib/screens/line_of_sight_map_screen.dart b/lib/screens/line_of_sight_map_screen.dart index fe935e43..7117affa 100644 --- a/lib/screens/line_of_sight_map_screen.dart +++ b/lib/screens/line_of_sight_map_screen.dart @@ -20,7 +20,6 @@ import '../widgets/app_bar.dart'; import '../widgets/quick_switch_bar.dart'; import '../icons/los_icon.dart'; import '../theme/mesh_theme.dart'; -import '../widgets/themed_map_tile_layer.dart'; class LineOfSightEndpoint { final String label; @@ -357,7 +356,7 @@ class _LineOfSightMapScreenState extends State { Widget build(BuildContext context) { final settings = context.watch().settings; final isImperial = settings.unitSystem == UnitSystem.imperial; - final tileCache = context.read(); + final tileCache = context.watch(); final endpoints = _visibleEndpoints(); final mapPoints = [ if (_start != null) _start!.point, @@ -443,8 +442,8 @@ class _LineOfSightMapScreenState extends State { }, ), children: [ - ThemedMapTileLayer( - tileCache: tileCache, + tileCache.buildTileLayer( + context, opacity: _showTerrainLayer ? 1 : 0.72, ), if (_result != null && _result!.segments.isNotEmpty) diff --git a/lib/screens/map_cache_screen.dart b/lib/screens/map_cache_screen.dart index 6455c15c..9cb45d36 100644 --- a/lib/screens/map_cache_screen.dart +++ b/lib/screens/map_cache_screen.dart @@ -12,7 +12,6 @@ import '../widgets/adaptive_app_bar_title.dart'; import '../helpers/snack_bar_builder.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; -import '../widgets/themed_map_tile_layer.dart'; class MapCacheScreen extends StatefulWidget { const MapCacheScreen({super.key}); @@ -34,6 +33,11 @@ class _MapCacheScreenState extends State { bool _isDownloading = false; int _completedTiles = 0; int _failedTiles = 0; + List _cachedTiles = const []; + int _cachedTileBytes = 0; + bool _isLoadingCachedTiles = false; + double _overlayZoom = 2.0; + LatLngBounds? _visibleBounds; @override void initState() { @@ -123,8 +127,10 @@ class _MapCacheScreenState extends State { _minZoom = safeMin; _maxZoom = safeMax; _selectedBounds = bounds; + _visibleBounds = bounds; }); _updateEstimate(); + _refreshCachedTiles(); if (bounds != null) { _mapController.fitCamera( CameraFit.bounds(bounds: bounds, padding: const EdgeInsets.all(48)), @@ -181,6 +187,7 @@ class _MapCacheScreenState extends State { Future _startDownload() async { final bounds = _selectedBounds; + final cacheService = context.read(); if (bounds == null) { showDismissibleSnackBar( context, @@ -197,6 +204,18 @@ class _MapCacheScreenState extends State { return; } + if (!cacheService.source.allowsBulkDownload) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.mapCache_bulkDownloadDisabledInConfig( + cacheService.source.label, + ), + ), + ); + return; + } + final confirmed = await showDialog( context: context, builder: (dialogContext) => AlertDialog( @@ -219,8 +238,6 @@ class _MapCacheScreenState extends State { if (confirmed != true || !mounted) return; - final cacheService = context.read(); - setState(() { _isDownloading = true; _completedTiles = 0; @@ -254,6 +271,8 @@ class _MapCacheScreenState extends State { result.failed, ) : context.l10n.mapCache_cachedTiles(result.downloaded); + await _refreshCachedTiles(); + if (!mounted) return; showDismissibleSnackBar(context, content: Text(message)); } @@ -280,16 +299,61 @@ class _MapCacheScreenState extends State { final cacheService = context.read(); await cacheService.clearCache(); if (!mounted) return; + await _refreshCachedTiles(); + if (!mounted) return; showDismissibleSnackBar( context, content: Text(context.l10n.mapCache_offlineCacheCleared), ); } + Future _refreshCachedTiles() async { + if (!mounted) return; + setState(() { + _isLoadingCachedTiles = true; + }); + final cacheService = context.read(); + final inventory = await cacheService.getCachedTileInventory(); + if (!mounted) return; + setState(() { + _cachedTiles = inventory.tiles; + _cachedTileBytes = inventory.totalBytes; + _isLoadingCachedTiles = false; + }); + } + + String _formatBytes(int bytes) { + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) { + return '${(bytes / 1024).toStringAsFixed(1)} KB'; + } + return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + } + @override Widget build(BuildContext context) { - final tileCache = context.read(); + final tileCache = context.watch(); + final source = tileCache.source; final selectedBounds = _selectedBounds; + final activeCachedTiles = tileCache.filterTilesForActiveSource( + _cachedTiles, + ); + final cachedInSelection = tileCache.countTilesForBounds( + activeCachedTiles, + bounds: selectedBounds, + minZoom: _minZoom, + maxZoom: _maxZoom, + ); + final overlayPolygons = tileCache.buildCachedTilePolygons( + activeCachedTiles, + zoom: _overlayZoom.round().clamp(0, 19).toInt(), + visibleBounds: _visibleBounds, + ); + final cacheSummary = + '${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))}'; final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final isDesktop = _isDesktopPlatform(defaultTargetPlatform); @@ -327,9 +391,23 @@ 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; + }); + } + }, ), children: [ - ThemedMapTileLayer(tileCache: tileCache), + tileCache.buildTileLayer(context), if (selectedBounds != null) PolygonLayer( polygons: [ @@ -341,9 +419,24 @@ class _MapCacheScreenState extends State { ), ], ), + if (overlayPolygons.isNotEmpty) + PolygonLayer(polygons: overlayPolygons), ], ), if (isDesktop) _buildDesktopMapControls(), + Positioned( + top: 12, + left: isDesktop ? 84 : 12, + child: Card( + child: Padding( + padding: const EdgeInsets.all(8), + child: Text( + 'Z: ${_overlayZoom.round()}:', + style: const TextStyle(fontSize: 12), + ), + ), + ), + ), Positioned( top: 12, right: 12, @@ -445,6 +538,34 @@ class _MapCacheScreenState extends State { 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( @@ -471,7 +592,10 @@ class _MapCacheScreenState extends State { child: ElevatedButton.icon( icon: const Icon(Icons.download), label: Text(l10n.mapCache_downloadTilesButton), - onPressed: _isDownloading || selectedBounds == null + onPressed: + _isDownloading || + selectedBounds == null || + !source.allowsBulkDownload ? null : _startDownload, ), diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 18e3ba9d..aec3ba9e 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:math'; import 'package:flutter/foundation.dart'; @@ -5,27 +6,30 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:latlong2/latlong.dart'; +import 'package:meshcore_open/helpers/path_helper.dart'; import 'package:meshcore_open/screens/path_trace_map.dart'; import 'package:meshcore_open/widgets/app_bar.dart'; import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; -import '../l10n/l10n.dart'; import '../connector/meshcore_protocol.dart'; +import '../l10n/l10n.dart'; import '../models/app_settings.dart'; import '../models/channel.dart'; import '../models/contact.dart'; +import '../models/path_history.dart'; import '../l10n/contact_localization.dart'; import '../services/app_settings_service.dart'; import '../services/path_history_service.dart'; import '../services/map_marker_service.dart'; import '../services/map_tile_cache_service.dart'; +import '../storage/prefs_manager.dart'; import '../utils/contact_search.dart'; +import '../utils/disconnect_navigation_mixin.dart'; import '../utils/battery_utils.dart'; import '../utils/route_transitions.dart'; import '../widgets/quick_switch_bar.dart'; import '../widgets/sync_progress_overlay.dart'; -import '../widgets/themed_map_tile_layer.dart'; import '../icons/los_icon.dart'; import 'channels_screen.dart'; import 'chat_screen.dart'; @@ -34,6 +38,7 @@ import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/repeater_login_dialog.dart'; import '../widgets/room_login_dialog.dart'; +import '../helpers/guessed_location_estimator.dart'; import '../helpers/snack_bar_builder.dart'; import 'repeater_hub_screen.dart'; import 'settings_screen.dart'; @@ -59,7 +64,7 @@ class MapScreen extends StatefulWidget { State createState() => _MapScreenState(); } -class _MapScreenState extends State { +class _MapScreenState extends State with DisconnectNavigationMixin { // Zoom level at which node labels start to appear static const double _labelZoomThreshold = 14.0; // Below this zoom, nearby nodes collapse into clusters. @@ -79,6 +84,7 @@ class _MapScreenState extends State { bool _hasInitializedMap = false; bool _removedMarkersLoaded = false; final List _pathTrace = []; + final List _pathTraceHopWidths = []; final List _pathTraceContacts = []; final List _points = []; final List _polylines = []; @@ -92,21 +98,82 @@ class _MapScreenState extends State { final FocusNode _searchFocus = FocusNode(); String _searchQuery = ''; List<_GuessedLocation> _cachedGuessedLocations = []; - String _guessedLocationsCacheKey = ''; + int? _guessedLocationsCacheKey; + static const Duration _guessMaxAge = Duration(days: 7); + ({LatLng center, double zoom})? _cachedFallbackCamera; + bool _guessInFlight = false; + VoidCallback? _guessRerun; + // Saved paths for contacts outside the path-history cache, read once. + final Map> _storedPaths = {}; int? _sharedMarkersCacheSignature; Locale? _sharedMarkersCacheLocale; List<_SharedMarker> _cachedSharedMarkers = const []; _NodeMarkersCacheKey? _nodeMarkersCacheKey; List _cachedNodeMarkers = const []; + static const String _lastCameraKey = 'map_last_camera'; + + ({LatLng center, double zoom}) _fallbackCamera(MeshCoreConnector connector) { + final lat = connector.selfLatitude; + final lon = connector.selfLongitude; + if (lat != null && lon != null && isPlausibleLocation(lat, lon)) { + return (center: LatLng(lat, lon), zoom: 12.0); + } + final saved = PrefsManager.instance.getStringList(_lastCameraKey); + if (saved != null && saved.length == 3) { + final values = saved.map(double.tryParse).toList(); + if (!values.contains(null)) { + return (center: LatLng(values[0]!, values[1]!), zoom: values[2]!); + } + } + return (center: const LatLng(20, 0), zoom: _mapMinZoom); + } + + void _saveLastCamera() { + try { + final camera = _mapController.camera; + PrefsManager.instance.setStringList(_lastCameraKey, [ + camera.center.latitude.toString(), + camera.center.longitude.toString(), + camera.zoom.toString(), + ]); + } catch (_) {} + } + @override void dispose() { + _saveLastCamera(); _searchController.dispose(); _searchFocus.dispose(); _mapController.dispose(); super.dispose(); } + ColorScheme get _overlayScheme => Theme.of(context).colorScheme; + + bool get _useDarkOverlay => Theme.of(context).brightness == Brightness.dark; + + Color get _overlayPanelColor => _useDarkOverlay + ? MapPalette.panelDark + : _overlayScheme.surfaceContainerLow.withValues(alpha: 0.96); + + Color get _overlayPrimaryTextColor => + _useDarkOverlay ? MapPalette.textPrimary : _overlayScheme.onSurface; + + Color get _overlaySecondaryTextColor => _useDarkOverlay + ? MapPalette.textSecondary + : _overlayScheme.onSurfaceVariant; + + Color get _overlayMutedTextColor => + _useDarkOverlay ? MapPalette.textMuted : _overlayScheme.onSurfaceVariant; + + Color get _overlayBorderColor => + _useDarkOverlay ? MapPalette.border : _overlayScheme.outlineVariant; + + Color get _overlayShadowColor => _useDarkOverlay + ? MapPalette.markerShadow + : Colors.black.withValues(alpha: 0.18); + _NodeAge _ageOf(Contact contact) { final d = DateTime.now().difference(contact.lastSeen); if (d.inMinutes <= 60) return _NodeAge.online; @@ -168,15 +235,6 @@ class _MapScreenState extends State { } } - bool _checkLocationPlausibility(double lat, double lon) { - const double epsilon = 1e-6; - return (lat.abs() > epsilon || lon.abs() > epsilon) && - lat >= -90.0 && - lat <= 90.0 && - lon >= -180.0 && - lon <= 180.0; - } - double _standardDeviation(List values) { if (values.length <= 1) { return 0.0; @@ -233,12 +291,12 @@ class _MapScreenState extends State { bottom: 96, child: DecoratedBox( decoration: BoxDecoration( - color: MapPalette.panelDark, + color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MapPalette.border), - boxShadow: const [ + border: Border.all(color: _overlayBorderColor), + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 8, offset: Offset(0, 3), ), @@ -250,20 +308,20 @@ class _MapScreenState extends State { mainAxisSize: MainAxisSize.min, children: [ IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.add), visualDensity: VisualDensity.standard, tooltip: context.l10n.map_zoomIn, onPressed: () => _zoomMapBy(1), ), IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.remove), tooltip: context.l10n.map_zoomOut, onPressed: () => _zoomMapBy(-1), ), IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.crop_free), tooltip: context.l10n.map_centerMap, onPressed: () => _mapController.move(center, zoom), @@ -272,7 +330,7 @@ class _MapScreenState extends State { IconButton( color: MapPalette.selected, icon: const Icon(Icons.my_location), - tooltip: context.l10n.map_setAsMyLocation, + tooltip: context.l10n.map_centerOnMe, onPressed: () => _mapController.move( LatLng(connector.selfLatitude!, connector.selfLongitude!), max(_zoom, 14), @@ -319,6 +377,9 @@ class _MapScreenState extends State { _MapConnectorSnapshot.fromConnector, ); final connector = connectorSnapshot.connector; + if (!checkConnectionAndNavigate(connector)) { + return const SizedBox.shrink(); + } final settings = context.select( (service) => service.settings, ); @@ -328,6 +389,7 @@ class _MapScreenState extends State { final settingsService = context.read(); final pathHistory = context.read(); final tileCache = context.read(); + final scheme = Theme.of(context).colorScheme; final isDesktop = _isDesktopPlatform(defaultTargetPlatform); final allContacts = connector.allContacts; @@ -399,29 +461,42 @@ class _MapScreenState extends State { noLocations: true, ); - // Compute guessed locations with caching + // Guessed locations are computed in a background isolate; the last + // result stays on screen until the new one arrives. final maxRangeKm = _estimateLoRaRangeKm(connector); - final filteredKeys = guessCandidates - .map((c) => '${c.publicKeyHex}:${c.path.join("-")}') - .join(','); - final anchorKeys = allContactsWithLocation - .map( + final cacheKey = Object.hash( + Object.hashAll( + guessCandidates.map( + (c) => Object.hash(c.publicKeyHex, _bytesSignature(c.path)), + ), + ), + Object.hashAll( + allContactsWithLocation.map( (c) => - '${c.publicKeyHex}:${c.latitude}:${c.longitude}:${c.path.isNotEmpty ? c.path.last : ""}', - ) - .join(','); - final cacheKey = - '$filteredKeys|$anchorKeys|$pathHistoryVersion:${connector.currentFreqHz}:${connector.currentSf}:${connector.currentBwHz}:${connector.currentTxPower}:${settings.mapShowGuessedLocations}'; + Object.hash(c.publicKeyHex, c.latitude, c.longitude, c.type), + ), + ), + pathHistoryVersion, + maxRangeKm, + connector.selfLatitude, + connector.selfLongitude, + settings.mapShowGuessedLocations, + ); if (cacheKey != _guessedLocationsCacheKey) { _guessedLocationsCacheKey = cacheKey; - _cachedGuessedLocations = settings.mapShowGuessedLocations - ? _computeGuessedLocations( - guessCandidates, - allContactsWithLocation, - pathHistory, - maxRangeKm, - ) - : []; + if (settings.mapShowGuessedLocations) { + unawaited( + _startGuessedLocations( + cacheKey, + guessCandidates, + allContactsWithLocation, + pathHistory, + maxRangeKm, + ), + ); + } else { + _cachedGuessedLocations = []; + } } final guessedLocations = settings.mapShowGuessedLocations ? _cachedGuessedLocations @@ -460,14 +535,13 @@ class _MapScreenState extends State { } } - // Calculate center and zoom of all nodes, or default to (0, 0) - LatLng center = const LatLng(0, 0); - double initialZoom = 10.0; - final hasMapContent = - contactsWithLocation.isNotEmpty || - sharedMarkers.isNotEmpty || - _isSelectingPoi || - highlightPosition != null; + // 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( @@ -542,13 +616,11 @@ class _MapScreenState extends State { _hasInitializedMap = true; _showNodeLabels = initialZoom >= _labelZoomThreshold; _zoom = initialZoom; - if (hasMapContent) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { - _mapController.move(center, initialZoom); - } - }); - } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _mapController.move(center, initialZoom); + } + }); } final allowBack = !connector.isConnected; @@ -579,8 +651,8 @@ class _MapScreenState extends State { canPop: allowBack, child: Scaffold( appBar: AppBar( - backgroundColor: MapPalette.panelDark, - foregroundColor: MapPalette.textPrimary, + backgroundColor: scheme.surface, + foregroundColor: scheme.onSurface, title: AppBarTitle(context.l10n.map_title), centerTitle: true, automaticallyImplyLeading: false, @@ -738,6 +810,12 @@ class _MapScreenState extends State { onSecondaryTap: (_, latLng) { _handleMapContextPress(context, connector, latLng); }, + onMapEvent: (event) { + if (event is MapEventMoveEnd || + event is MapEventFlingAnimationEnd) { + _saveLastCamera(); + } + }, onPositionChanged: (camera, hasGesture) { // Track zoom in half-step buckets so cluster/marker // detail levels update without rebuilding every frame. @@ -753,7 +831,7 @@ class _MapScreenState extends State { }, ), children: [ - ThemedMapTileLayer(tileCache: tileCache), + tileCache.buildTileLayer(context), if (_polylines.isNotEmpty && _isBuildingPathTrace) PolylineLayer(polylines: _polylines), if (sharedMarkerPolylines.isNotEmpty) @@ -894,6 +972,20 @@ class _MapScreenState extends State { pinCount: sharedMarkers.length, ), if (_isBuildingPathTrace) _buildPathTraceOverlay(), + if (contactsWithLocation.isEmpty && + selectedContact == null && + !_isBuildingPathTrace) + Positioned( + left: 16, + right: 88, + bottom: 16, + child: Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(context.l10n.map_noNodesLocationHint), + ), + ), + ), if (selectedContact != null && !_isBuildingPathTrace) _buildSelectedNodeCard(context, selectedContact, connector), ], @@ -906,7 +998,7 @@ class _MapScreenState extends State { _handleQuickSwitch(index, context), contactsUnreadCount: connector.getTotalContactsUnreadCount(), channelsUnreadCount: connector.getTotalChannelsUnreadCount(), - highContrast: true, + highContrast: _useDarkOverlay, ), ), floatingActionButton: @@ -961,6 +1053,7 @@ class _MapScreenState extends State { showChatNodes: settings.mapShowChatNodes, showOtherNodes: settings.mapShowOtherNodes, isBuildingPathTrace: _isBuildingPathTrace, + clusterNodes: settings.mapClusterNodes, ); if (key != _nodeMarkersCacheKey) { _nodeMarkersCacheKey = key; @@ -976,143 +1069,100 @@ class _MapScreenState extends State { return _cachedNodeMarkers; } - List<_GuessedLocation> _computeGuessedLocations( - List allContacts, + Future _startGuessedLocations( + int cacheKey, + List candidates, List withLocation, PathHistoryService pathHistory, double? maxRangeKm, - ) { - // Index known-location repeaters by their 1-byte hash. - // null value = two repeaters share the same hash byte (ambiguous collision). - final repeaterByHash = {}; - - for (final c in withLocation) { - if (c.type == advTypeRepeater) { - if (repeaterByHash.containsKey(c.publicKey[0])) { - repeaterByHash[c.publicKey[0]] = - null; // collision: can't disambiguate - } else { - repeaterByHash[c.publicKey[0]] = c; - } - } - } - - final result = <_GuessedLocation>[]; - - for (final contact in allContacts) { - if (contact.hasLocation) continue; - if (contact.lastSeen.isBefore( - DateTime.now().subtract(const Duration(hours: 24)), - )) { - continue; // skip stale contacts - } - - final anchorSet = {}; - - // Collect the contact-side (last-hop) repeater from every known path. - // path = [device-side hop, ..., contact-side hop] - // Only path.last is actually within radio range of the contact — using - // earlier bytes would anchor against our own side of the network. - final pathSets = >[ - contact.path.toList(), - ...pathHistory - .getRecentPaths(contact.publicKeyHex) - .map((r) => r.pathBytes), - ]; - final lastHopBytes = {}; - for (final pathBytes in pathSets) { - if (pathBytes.isEmpty) continue; - final lastHop = pathBytes.last; - lastHopBytes.add(lastHop); - final r = repeaterByHash[lastHop]; - if (r != null) anchorSet.add(LatLng(r.latitude!, r.longitude!)); - } - - // Filter anchors that are geometrically inconsistent with radio range. - // Two anchors more than 2 * maxRange apart cannot both be in direct radio - // range of the same node, so isolated outliers are removed. - final anchors = maxRangeKm != null && anchorSet.length > 1 - ? _filterConsistentAnchors(anchorSet.toList(), maxRangeKm) - : anchorSet.toList(); - - if (anchors.isEmpty) continue; - - final LatLng position; - if (anchors.length == 1) { - // Spread single-anchor guesses around the anchor so they remain visible. - position = _offsetGuessedPosition( - anchors[0], - contact, - radiusMeters: 330, - ); - if (!_checkLocationPlausibility( - position.latitude, - position.longitude, - )) { - continue; // discard implausible guesses near (0, 0) - } - } else { - double lat = 0, lon = 0, weight = 1.0; - int counted = 0; - for (final a in anchors) { - if (counted == 0) { - lat = a.latitude; - lon = a.longitude; - } else { - lat += a.latitude * weight; - lon += a.longitude * weight; - } - // weight subsequent anchors less to create a bias towards the first (if more than 2) - weight = weight / 2; - counted++; - } - position = _offsetGuessedPosition( - LatLng(lat / anchors.length, lon / anchors.length), - contact, - radiusMeters: anchors.length >= 3 ? 80 : 120, - ); - if (!_checkLocationPlausibility( - position.latitude, - position.longitude, - )) { - continue; // discard implausible guesses near (0, 0 - } - } - result.add( - _GuessedLocation( - contact: contact, - position: position, - highConfidence: anchors.length >= 2, - ), + ) async { + if (_guessInFlight) { + _guessRerun = () => _startGuessedLocations( + cacheKey, + candidates, + withLocation, + pathHistory, + maxRangeKm, ); + return; } - - return result; - } - - LatLng _offsetGuessedPosition( - LatLng anchor, - Contact contact, { - required double radiusMeters, - }) { - final seed = _guessSeed(contact.publicKey); - final angle = ((seed & 0xFFFF) / 0x10000) * 2 * pi; - final latOffsetDeg = (radiusMeters / 111320.0) * cos(angle); - final lonScale = max(cos(anchor.latitude * pi / 180.0).abs(), 0.2); - final lonOffsetDeg = (radiusMeters / (111320.0 * lonScale)) * sin(angle); - return LatLng( - anchor.latitude + latOffsetDeg, - anchor.longitude + lonOffsetDeg, + _guessInFlight = true; + final connector = context.read(); + final selfLat = connector.selfLatitude; + final selfLon = connector.selfLongitude; + // Old paths say little about where a node is now. + final cutoff = DateTime.now().subtract(_guessMaxAge); + 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); + } + if (!mounted) { + _guessInFlight = false; + return; + } + List pathsFor(String key) => pathHistory.isCached(key) + ? pathHistory.peekRecentPaths(key) + : _storedPaths[key] ?? const []; + final input = ( + candidates: [ + for (final c in eligible) + ( + publicKey: c.publicKey, + paths: [ + (c.path.toList(), c.pathHashWidth), + for (final r in pathsFor(c.publicKeyHex)) + ( + r.pathBytes, + Contact.inferPathHashWidth(r.hopCount, r.pathBytes.length), + ), + ], + ), + ], + anchors: [ + for (final r in withLocation) + if (r.type == advTypeRepeater || r.type == advTypeRoom) + (r.publicKey, r.latitude!, r.longitude!), + ], + selfPosition: + selfLat != null && + selfLon != null && + isPlausibleLocation(selfLat, selfLon) + ? (selfLat, selfLon) + : null, + maxRangeKm: maxRangeKm, ); - } - - int _guessSeed(Uint8List publicKey) { - var seed = 0x811C9DC5; - for (final byte in publicKey) { - seed ^= byte; - seed = (seed * 0x01000193) & 0x7FFFFFFF; + List<(int, double, double, bool)> placed; + try { + placed = await compute(estimateGuessedLocations, input); + } catch (e) { + debugPrint('Guessed location estimate failed: $e'); + placed = const []; + } finally { + _guessInFlight = false; } - return seed; + final rerun = _guessRerun; + _guessRerun = null; + if (!mounted) return; + if (!context.read().settings.mapShowGuessedLocations) { + return; + } + // Show this result even if inputs moved on; it is newer than what is on + // screen, and the queued rerun replaces it shortly. + rerun?.call(); + setState(() { + _cachedGuessedLocations = [ + for (final (index, lat, lon, highConfidence) in placed) + _GuessedLocation( + contact: eligible[index], + position: LatLng(lat, lon), + highConfidence: highConfidence, + ), + ]; + }); } /// Estimates the free-space maximum LoRa range in km from the connected @@ -1161,20 +1211,6 @@ class _MapScreenState extends State { } } - /// Removes anchors that have no neighbour within 2 * maxRangeKm. - /// A node cannot be simultaneously in radio range of two points farther apart - /// than twice the expected maximum range. - List _filterConsistentAnchors( - List anchors, - double maxRangeKm, - ) { - const distance = Distance(); - final maxDistM = maxRangeKm * 2000; - return anchors - .where((a) => anchors.any((b) => b != a && distance(a, b) <= maxDistM)) - .toList(); - } - List _buildGuessedMarker( List<_GuessedLocation> guessed, { required bool showLabels, @@ -1207,14 +1243,14 @@ class _MapScreenState extends State { height: 36, decoration: BoxDecoration( shape: BoxShape.circle, - color: MapPalette.panelDark, + color: _overlayPanelColor, border: Border.all( - color: guess.highConfidence ? color : MapPalette.textMuted, + color: guess.highConfidence ? color : _overlayMutedTextColor, width: guess.highConfidence ? 2.5 : 2, ), - boxShadow: const [ + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 7, offset: Offset(0, 2), ), @@ -1223,7 +1259,7 @@ class _MapScreenState extends State { alignment: Alignment.center, child: Icon( Icons.not_listed_location, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, size: 19, ), ), @@ -1300,12 +1336,20 @@ class _MapScreenState extends State { // Key-prefix overlaps are a visual highlight only: flag the repeaters/rooms // whose first key byte collides with another repeater/room on the map. - final overlapPrefixes = {}; + final overlapPrefixes = {}; if (overlapsMode) { - final counts = {}; + final hopWidth = context + .read() + .pathHashByteWidth + .clamp(1, pubKeySize) + .toInt(); + final counts = {}; for (final contact in contacts) { - if (contact.type == advTypeRepeater || contact.type == advTypeRoom) { - final prefix = contact.publicKey.first; + if ((contact.type == advTypeRepeater || contact.type == advTypeRoom) && + contact.publicKey.length >= hopWidth) { + final prefix = PathHelper.formatHopHex( + contact.publicKey.sublist(0, hopWidth), + ); counts[prefix] = (counts[prefix] ?? 0) + 1; } } @@ -1313,10 +1357,20 @@ class _MapScreenState extends State { if (count > 1) overlapPrefixes.add(prefix); }); } + final overlapHopWidth = context + .read() + .pathHashByteWidth + .clamp(1, pubKeySize) + .toInt(); bool isOverlap(Contact contact) => overlapsMode && (contact.type == advTypeRepeater || contact.type == advTypeRoom) && - overlapPrefixes.contains(contact.publicKey.first); + contact.publicKey.length >= overlapHopWidth && + overlapPrefixes.contains( + PathHelper.formatHopHex( + contact.publicKey.sublist(0, overlapHopWidth), + ), + ); void addNode(Contact contact, {bool dot = false}) { final overlap = isOverlap(contact); @@ -1333,7 +1387,10 @@ class _MapScreenState extends State { } } - if (_zoom >= _clusterOffZoom || overlapsMode || _isBuildingPathTrace) { + if (!settings.mapClusterNodes || + _zoom >= _clusterOffZoom || + overlapsMode || + _isBuildingPathTrace) { for (final contact in items) { addNode(contact); } @@ -1541,12 +1598,12 @@ class _MapScreenState extends State { child: Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( - color: MapPalette.panelDark, + color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.xs), - border: Border.all(color: MapPalette.border), - boxShadow: const [ + border: Border.all(color: _overlayBorderColor), + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 4, offset: Offset(0, 1), ), @@ -1560,7 +1617,7 @@ class _MapScreenState extends State { style: MeshTheme.mono( fontSize: 10, fontWeight: FontWeight.w700, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), ), ), @@ -1681,7 +1738,7 @@ class _MapScreenState extends State { decoration: BoxDecoration( shape: BoxShape.circle, color: statusColor, - border: Border.all(color: MapPalette.panelDark, width: 2), + border: Border.all(color: _overlayPanelColor, width: 2), ), alignment: Alignment.center, child: batteryLow @@ -1704,10 +1761,10 @@ class _MapScreenState extends State { Expanded( child: Text( label, - style: const TextStyle( + style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, - color: MapPalette.textSecondary, + color: _overlaySecondaryTextColor, ), overflow: TextOverflow.ellipsis, ), @@ -1765,9 +1822,9 @@ class _MapScreenState extends State { children: [ Expanded( child: Material( - color: MapPalette.panelDark, + color: _overlayPanelColor, shape: StadiumBorder( - side: const BorderSide(color: MapPalette.border), + side: BorderSide(color: _overlayBorderColor), ), clipBehavior: Clip.antiAlias, child: TextField( @@ -1775,18 +1832,17 @@ class _MapScreenState extends State { focusNode: _searchFocus, decoration: InputDecoration( hintText: context.l10n.map_searchHint, - hintStyle: const TextStyle( - color: MapPalette.textSecondary, - ), - prefixIcon: const Icon( + hintStyle: TextStyle(color: _overlaySecondaryTextColor), + prefixIcon: Icon( Icons.search, size: 20, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), suffixIcon: hasQuery ? IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.close, size: 18), + tooltip: context.l10n.common_clearSearch, onPressed: () { setState(() { _searchQuery = ''; @@ -1805,9 +1861,9 @@ class _MapScreenState extends State { vertical: 12, ), ), - style: const TextStyle( + style: TextStyle( fontSize: 14, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, fontWeight: FontWeight.w600, ), cursorColor: MapPalette.selected, @@ -1819,9 +1875,9 @@ class _MapScreenState extends State { ), const SizedBox(width: 8), Material( - color: MapPalette.panelDark, + color: _overlayPanelColor, shape: StadiumBorder( - side: const BorderSide(color: MapPalette.border), + side: BorderSide(color: _overlayBorderColor), ), clipBehavior: Clip.antiAlias, child: InkWell( @@ -1845,17 +1901,17 @@ class _MapScreenState extends State { style: MeshTheme.mono( fontSize: 13, fontWeight: FontWeight.w700, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), ), const SizedBox(width: 2), AnimatedRotation( turns: _statsExpanded ? 0.5 : 0, duration: const Duration(milliseconds: 200), - child: const Icon( + child: Icon( Icons.expand_more, size: 16, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), ), ], @@ -1908,6 +1964,14 @@ class _MapScreenState extends State { !settings.mapShowChatNodes, ), ), + _mapChip( + label: context.l10n.map_groupChip, + selected: settings.mapClusterNodes, + color: MapPalette.cluster, + onTap: () => settingsService.setMapClusterNodes( + !settings.mapClusterNodes, + ), + ), ]; if (constraints.maxWidth < 600) { @@ -1950,49 +2014,53 @@ class _MapScreenState extends State { final accent = color ?? MapPalette.selected; return Padding( padding: const EdgeInsets.only(right: 6), - child: Material( - color: selected - ? Color.alphaBlend( - accent.withValues(alpha: 0.34), - MapPalette.panelDark, - ) - : MapPalette.panelDark, - shape: StadiumBorder( - side: BorderSide( - color: selected ? accent : MapPalette.border, - width: selected ? 1.5 : 1, + child: Semantics( + button: true, + selected: selected, + child: Material( + color: selected + ? Color.alphaBlend( + accent.withValues(alpha: 0.34), + _overlayPanelColor, + ) + : _overlayPanelColor, + shape: StadiumBorder( + side: BorderSide( + color: selected ? accent : _overlayBorderColor, + width: selected ? 1.5 : 1, + ), ), - ), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () { - HapticFeedback.selectionClick(); - onTap(); - }, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (selected) ...[ - const Icon( - Icons.check, - size: 13, - color: MapPalette.textPrimary, + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () { + HapticFeedback.selectionClick(); + onTap(); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (selected) ...[ + Icon( + Icons.check, + size: 13, + color: _overlayPrimaryTextColor, + ), + const SizedBox(width: 4), + ], + Text( + label, + style: TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: selected + ? _overlayPrimaryTextColor + : _overlaySecondaryTextColor, + ), ), - const SizedBox(width: 4), ], - Text( - label, - style: TextStyle( - fontSize: 12.5, - fontWeight: FontWeight.w600, - color: selected - ? MapPalette.textPrimary - : MapPalette.textSecondary, - ), - ), - ], + ), ), ), ), @@ -2019,14 +2087,14 @@ class _MapScreenState extends State { margin: const EdgeInsets.only(top: 6), constraints: const BoxConstraints(maxHeight: 300), decoration: BoxDecoration( - color: MapPalette.panelDark, + color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MapPalette.border), - boxShadow: const [ + border: Border.all(color: _overlayBorderColor), + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 10, - offset: Offset(0, 4), + offset: const Offset(0, 4), ), ], ), @@ -2035,8 +2103,8 @@ class _MapScreenState extends State { padding: const EdgeInsets.all(16), child: Text( context.l10n.map_noResults, - style: const TextStyle( - color: MapPalette.textSecondary, + style: TextStyle( + color: _overlaySecondaryTextColor, fontSize: 13, ), ), @@ -2046,7 +2114,7 @@ class _MapScreenState extends State { padding: const EdgeInsets.symmetric(vertical: 4), itemCount: results.length, separatorBuilder: (_, _) => - const Divider(height: 1, color: MapPalette.border), + Divider(height: 1, color: _overlayBorderColor), itemBuilder: (context, index) { final c = results[index]; final color = _getNodeColor(c.type); @@ -2067,10 +2135,10 @@ class _MapScreenState extends State { children: [ Text( c.name, - style: const TextStyle( + style: TextStyle( fontSize: 13.5, fontWeight: FontWeight.w600, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), overflow: TextOverflow.ellipsis, ), @@ -2078,7 +2146,7 @@ class _MapScreenState extends State { c.publicKeyHex.substring(0, 12), style: MeshTheme.mono( fontSize: 10.5, - color: MapPalette.textSecondary, + color: _overlaySecondaryTextColor, ), ), ], @@ -2088,13 +2156,13 @@ class _MapScreenState extends State { Icon( Icons.chevron_right, size: 18, - color: MapPalette.textSecondary, + color: _overlaySecondaryTextColor, ) else Text( context.l10n.map_noGps.toUpperCase(), style: MeshTheme.accentLabel( - color: MapPalette.textMuted, + color: _overlayMutedTextColor, fontSize: 8.5, ), ), @@ -2154,14 +2222,14 @@ class _MapScreenState extends State { width: 230, padding: const EdgeInsets.fromLTRB(14, 12, 14, 12), decoration: BoxDecoration( - color: MapPalette.panelDark, + color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MapPalette.border), - boxShadow: const [ + border: Border.all(color: _overlayBorderColor), + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 10, - offset: Offset(0, 4), + offset: const Offset(0, 4), ), ], ), @@ -2178,7 +2246,7 @@ class _MapScreenState extends State { ), _statRow(context.l10n.map_hidden, hiddenCount, MapPalette.offline), _statRow(context.l10n.map_markers, pinCount, MapPalette.shared), - const Divider(height: 16, color: MapPalette.border), + Divider(height: 16, color: _overlayBorderColor), _buildLegendItem( Icons.person, context.l10n.map_chat, @@ -2208,7 +2276,7 @@ class _MapScreenState extends State { _buildLegendItem( Icons.not_listed_location, context.l10n.map_guessedLocation, - MapPalette.textMuted, + _overlayMutedTextColor, ), ], ), @@ -2229,7 +2297,10 @@ class _MapScreenState extends State { Expanded( child: Text( label, - style: TextStyle(fontSize: 12.5, color: MapPalette.textSecondary), + style: TextStyle( + fontSize: 12.5, + color: _overlaySecondaryTextColor, + ), overflow: TextOverflow.ellipsis, ), ), @@ -2238,7 +2309,7 @@ class _MapScreenState extends State { style: MeshTheme.mono( fontSize: 13, fontWeight: FontWeight.w700, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), ), ], @@ -2271,8 +2342,8 @@ class _MapScreenState extends State { child: MeshCard( margin: EdgeInsets.zero, padding: const EdgeInsets.fromLTRB(14, 12, 8, 12), - color: MapPalette.panelDark, - borderColor: MapPalette.border, + color: _overlayPanelColor, + borderColor: _overlayBorderColor, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -2295,10 +2366,10 @@ class _MapScreenState extends State { Flexible( child: Text( contact.name, - style: const TextStyle( + style: TextStyle( fontSize: 15, fontWeight: FontWeight.w700, - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, ), overflow: TextOverflow.ellipsis, ), @@ -2326,9 +2397,9 @@ class _MapScreenState extends State { Flexible( child: Text( contact.typeLabel(context.l10n), - style: const TextStyle( + style: TextStyle( fontSize: 11.5, - color: MapPalette.textSecondary, + color: _overlaySecondaryTextColor, ), overflow: TextOverflow.ellipsis, ), @@ -2340,14 +2411,15 @@ class _MapScreenState extends State { ), if (pos != null) IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.center_focus_strong, size: 20), tooltip: context.l10n.map_centerOnNode, onPressed: () => _mapController.move(pos, max(_zoom, 15)), ), IconButton( - color: MapPalette.textPrimary, + color: _overlayPrimaryTextColor, icon: const Icon(Icons.close, size: 20), + tooltip: context.l10n.common_close, onPressed: _clearSelection, ), ], @@ -2363,7 +2435,10 @@ class _MapScreenState extends State { ), _miniMeta( context.l10n.map_path, - contact.pathLabel(context.l10n), + contact.pathLabel( + context.l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), ), _miniMeta('ID', contact.publicKeyHex.substring(0, 12)), if (pos != null) @@ -2407,14 +2482,17 @@ class _MapScreenState extends State { Text( label.toUpperCase(), style: MeshTheme.accentLabel( - color: MapPalette.textMuted, + color: _overlayMutedTextColor, fontSize: 8, ), ), const SizedBox(height: 1), Text( value, - style: MeshTheme.mono(fontSize: 11.5, color: MapPalette.textPrimary), + style: MeshTheme.mono( + fontSize: 11.5, + color: _overlayPrimaryTextColor, + ), ), ], ); @@ -2476,6 +2554,12 @@ class _MapScreenState extends State { } _showRoomLogin(context, contact); }), + action(context.l10n.map_manageServer, Icons.room_preferences, () { + if (!contact.isActive) { + connector.importDiscoveredContact(contact); + } + _showRoomLogin(context, contact, manage: true); + }), ]; default: return const []; @@ -2655,13 +2739,16 @@ class _MapScreenState extends State { ); } - void _showRoomLogin(BuildContext context, Contact room) { + void _showRoomLogin( + BuildContext context, + Contact room, { + bool manage = false, + }) { showDialog( context: context, builder: (context) => RoomLoginDialog( room: room, - // onLogin(password, isAdmin) isAdmin not used for room caht screen - onLogin: (password, _) { + onLogin: (password, isAdmin) { final connector = context.read(); final unread = connector.getUnreadCountForContactKey( room.publicKeyHex, @@ -2670,8 +2757,13 @@ class _MapScreenState extends State { Navigator.push( context, MaterialPageRoute( - builder: (context) => - ChatScreen(contact: room, initialUnreadCount: unread), + builder: (context) => manage + ? RepeaterHubScreen( + repeater: room, + password: password, + isAdmin: isAdmin, + ) + : ChatScreen(contact: room, initialUnreadCount: unread), ), ); }, @@ -2741,6 +2833,18 @@ class _MapScreenState extends State { child: Text(context.l10n.map_joinRoom), ), ); + actions.add( + FilledButton( + onPressed: () { + if (!contact.isActive) { + connector.importDiscoveredContact(contact); + } + Navigator.pop(sheetContext); + _showRoomLogin(context, contact, manage: true); + }, + child: Text(context.l10n.map_manageServer), + ), + ); } return SafeArea( child: SingleChildScrollView( @@ -2764,7 +2868,10 @@ class _MapScreenState extends State { children: [ _buildInfoRow( context.l10n.map_path, - contact.pathLabel(context.l10n), + contact.pathLabel( + context.l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), ), if (contact.hasLocation) _buildInfoRow( @@ -3384,6 +3491,16 @@ class _MapScreenState extends State { onChanged: (value) => service.setMapShowMarkers(value), ), + SwitchListTile( + title: Text(sheetContext.l10n.map_clusterNodes), + subtitle: Text( + sheetContext.l10n.map_clusterNodesSubtitle, + ), + value: settings.mapClusterNodes, + dense: true, + onChanged: (value) => + service.setMapClusterNodes(value), + ), SwitchListTile( title: Text( sheetContext.l10n.map_showGuessedLocations, @@ -3510,10 +3627,23 @@ class _MapScreenState extends State { } void _addToPath(BuildContext context, Contact contact, {LatLng? position}) { + final connector = context.read(); + final hopWidth = min( + connector.pathHashByteWidth.clamp(1, pubKeySize), + contact.publicKey.length, + ).toInt(); + final hopPrefix = contact.publicKey.sublist(0, hopWidth); + for (final existingHop in PathHelper.splitPathBytes( + _pathTrace, + connector.pathHashByteWidth, + )) { + if (listEquals(existingHop, hopPrefix)) { + return; + } + } setState(() { - _pathTrace.add( - contact.publicKey[0], - ); // Add first 16 bytes of public key to path trace + _pathTrace.addAll(hopPrefix); // Add the hop-width pubkey prefix. + _pathTraceHopWidths.add(hopWidth); _pathTraceContacts.add( contact.copyWith( latitude: position?.latitude ?? contact.latitude, @@ -3528,6 +3658,7 @@ class _MapScreenState extends State { setState(() { _isBuildingPathTrace = true; _pathTrace.clear(); + _pathTraceHopWidths.clear(); _pathTraceContacts.clear(); _points.clear(); _polylines.clear(); @@ -3537,8 +3668,19 @@ class _MapScreenState extends State { void _removePath() { setState(() { + final recordedHopWidth = _pathTraceHopWidths.isNotEmpty + ? _pathTraceHopWidths.removeLast() + : context.read().pathHashByteWidth.clamp( + 1, + pubKeySize, + ); + final hopByteCount = min(recordedHopWidth, _pathTrace.length).toInt(); _pathTraceContacts.removeLast(); - _pathTrace.removeLast(); // Remove last node from path trace + // A path trace hop can be wider than one byte; remove the full hash prefix. + _pathTrace.removeRange( + _pathTrace.length - hopByteCount, + _pathTrace.length, + ); _points.removeLast(); // Remove last point from points list _polylines.clear(); // Clear polylines }); @@ -3555,14 +3697,14 @@ class _MapScreenState extends State { right: 16, child: DecoratedBox( decoration: BoxDecoration( - color: MapPalette.panelDark, + color: _overlayPanelColor, borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: MapPalette.border), - boxShadow: const [ + border: Border.all(color: _overlayBorderColor), + boxShadow: [ BoxShadow( - color: MapPalette.markerShadow, + color: _overlayShadowColor, blurRadius: 10, - offset: Offset(0, 4), + offset: const Offset(0, 4), ), ], ), @@ -3575,24 +3717,34 @@ class _MapScreenState extends State { children: [ Text( l10n.contacts_pathTrace, - style: TextStyle(fontWeight: FontWeight.bold), + style: TextStyle( + fontWeight: FontWeight.bold, + color: _overlayPrimaryTextColor, + ), ), if (_pathTrace.isEmpty) const SizedBox(height: 8), if (_pathTrace.isEmpty) - Text(l10n.map_tapToAdd, style: TextStyle(fontSize: 12)), + Text( + l10n.map_tapToAdd, + style: TextStyle( + fontSize: 12, + color: _overlaySecondaryTextColor, + ), + ), const SizedBox(height: 6), if (_pathTrace.isNotEmpty) Text( "${l10n.path_currentPathLabel} ${formatDistance(getPathDistanceMeters(_points), isImperial: isImperial)}", style: MeshTheme.mono( fontSize: 12, - color: MapPalette.textSecondary, + color: _overlaySecondaryTextColor, ), ), SelectableText( - _pathTrace - .map((b) => b.toRadixString(16).padLeft(2, '0')) - .join(','), + PathHelper.splitPathBytes( + _pathTrace, + context.read().pathHashByteWidth, + ).map(PathHelper.formatHopHex).join(','), style: MeshTheme.mono( fontSize: 18, fontWeight: FontWeight.w700, @@ -3617,6 +3769,7 @@ class _MapScreenState extends State { builder: (context) => PathTraceMapScreen( title: l10n.contacts_pathTrace, path: Uint8List.fromList(_pathTrace), + flipPathAround: false, pathHashByteWidth: hashW, pathContacts: _pathTraceContacts, ), @@ -3639,6 +3792,10 @@ class _MapScreenState extends State { title: l10n.contacts_pathTrace, path: Uint8List.fromList(_pathTrace), flipPathAround: true, + pathHashByteWidth: context + .read() + .pathHashByteWidth, + pathContacts: _pathTraceContacts, ), ), ); @@ -3661,6 +3818,7 @@ class _MapScreenState extends State { setState(() { _isBuildingPathTrace = false; _pathTrace.clear(); + _pathTraceHopWidths.clear(); _points.clear(); _polylines.clear(); }); @@ -3700,6 +3858,7 @@ int _mapContactSignature(Contact contact) { contact.flags, contact.pathLength, _bytesSignature(contact.path), + contact.pathHashWidth, contact.pathOverride, _bytesSignature(contact.pathOverrideBytes), contact.latitude, @@ -3742,42 +3901,32 @@ class _MapConnectorSnapshot { ), ); + // Only detect that a conversation changed; _collectSharedMarkers does the + // per-message scan when this signature moves. final markerParts = [connector.selfName]; for (final contact in connector.contacts) { - markerParts.add(contact.publicKeyHex); - markerParts.add(contact.name); - for (final message in connector.getMessages(contact)) { - if (!message.text.trimLeft().startsWith('m:')) continue; - markerParts.add( - Object.hash( - message.messageId, - message.text, - message.timestamp.millisecondsSinceEpoch, - message.isOutgoing, - ), - ); - } + final messages = connector.getMessages(contact); + markerParts.add( + Object.hash( + contact.publicKeyHex, + contact.name, + messages.length, + messages.isEmpty ? null : messages.last.messageId, + ), + ); } for (final channel in connector.channels) { + final messages = connector.getChannelMessages(channel); markerParts.add( Object.hash( channel.index, channel.name, channel.isPublicChannel, channel.isEmpty, + messages.length, + messages.isEmpty ? null : messages.last.messageId, ), ); - for (final message in connector.getChannelMessages(channel)) { - if (!message.text.trimLeft().startsWith('m:')) continue; - markerParts.add( - Object.hash( - message.messageId, - message.text, - message.senderName, - message.timestamp.millisecondsSinceEpoch, - ), - ); - } } return _MapConnectorSnapshot( @@ -3835,6 +3984,7 @@ class _NodeMarkersCacheKey { final bool showChatNodes; final bool showOtherNodes; final bool isBuildingPathTrace; + final bool clusterNodes; const _NodeMarkersCacheKey({ required this.contactsSignature, @@ -3854,6 +4004,7 @@ class _NodeMarkersCacheKey { required this.showChatNodes, required this.showOtherNodes, required this.isBuildingPathTrace, + required this.clusterNodes, }); @override @@ -3875,7 +4026,8 @@ class _NodeMarkersCacheKey { showRepeaters == other.showRepeaters && showChatNodes == other.showChatNodes && showOtherNodes == other.showOtherNodes && - isBuildingPathTrace == other.isBuildingPathTrace; + isBuildingPathTrace == other.isBuildingPathTrace && + clusterNodes == other.clusterNodes; } @override @@ -3897,6 +4049,7 @@ class _NodeMarkersCacheKey { showChatNodes, showOtherNodes, isBuildingPathTrace, + clusterNodes, ); } @@ -3935,6 +4088,7 @@ MarkerPayload? parseMarkerText(String text) { final lat = double.tryParse(match.group(1) ?? ''); final lon = double.tryParse(match.group(2) ?? ''); if (lat == null || lon == null) return null; + if (lat.abs() > 90 || lon.abs() > 180) return null; final label = (match.group(3) ?? '').trim(); final flags = (match.group(4) ?? '').trim(); return MarkerPayload(position: LatLng(lat, lon), label: label, flags: flags); diff --git a/lib/screens/neighbors_screen.dart b/lib/screens/neighbors_screen.dart index 529a00dd..c3537948 100644 --- a/lib/screens/neighbors_screen.dart +++ b/lib/screens/neighbors_screen.dart @@ -31,12 +31,16 @@ class NeighborsScreen extends StatefulWidget { class _NeighborsScreenState extends State { static const int _reqNeighborsKeyLen = 4; + // Firmware packs results into a 130-byte buffer (simple_repeater/MyMesh.cpp). + static const int _reqNeighborsPageSize = 130 ~/ (_reqNeighborsKeyLen + 5); static const int _statusPayloadOffset = 8; static const int _statusStatsSize = 52; static const int _statusResponseBytes = _statusPayloadOffset + _statusStatsSize; Uint8List _tagData = Uint8List(4); + bool _awaitingSent = false; int _neighborCount = 0; + int _pageOffset = 0; bool _isLoading = false; bool _isLoaded = false; @@ -82,12 +86,14 @@ class _NeighborsScreenState extends State { _frameSubscription = connector.receivedFrames.listen((frame) { if (frame.isEmpty) return; - if (frame[0] == respCodeSent) { + if (frame[0] == respCodeSent && _awaitingSent && frame.length >= 6) { + _awaitingSent = false; _tagData = frame.sublist(2, 6); } // Check if it's a binary response if (frame[0] == pushCodeBinaryResponse && + frame.length >= 6 && listEquals(frame.sublist(2, 6), _tagData)) { _handleNeighborsResponse(connector, frame.sublist(6)); } @@ -148,7 +154,11 @@ class _NeighborsScreenState extends State { final contacts = connector.allContactsUnfiltered; try { final neighborCount = buffer.readUInt16LE(); - final parsedNeighbors = parseNeighborsData(buffer, buffer.readUInt16LE()); + final page = parseNeighborsData(buffer, buffer.readUInt16LE()); + final parsedNeighbors = [ + if (_pageOffset > 0) ...?_parsedNeighbors, + ...page, + ]; contacts.where((c) => c.type == advTypeRepeater).forEach((repeater) { for (var neighborData in parsedNeighbors) { final publicKey = neighborData['publicKey']; @@ -166,13 +176,19 @@ class _NeighborsScreenState extends State { _neighborCount = neighborCount; }); + _tagData = Uint8List(4); + _statusTimeout?.cancel(); + _recordStatusResult(true); + if (!mounted) return; + if (page.isNotEmpty && parsedNeighbors.length < neighborCount) { + _loadNeighbors(offset: parsedNeighbors.length); + return; + } showDismissibleSnackBar( context, content: Text(context.l10n.neighbors_receivedData), backgroundColor: Theme.of(context).colorScheme.tertiary, ); - _statusTimeout?.cancel(); - if (!mounted) return; setState(() { _isLoading = false; _isLoaded = true; @@ -183,9 +199,10 @@ class _NeighborsScreenState extends State { } } - Future _loadNeighbors() async { + Future _loadNeighbors({int offset = 0}) async { if (_commandService == null) return; + _pageOffset = offset; setState(() { _isLoading = true; _isLoaded = false; @@ -202,13 +219,14 @@ class _NeighborsScreenState extends State { payload: Uint8List.fromList([ reqTypeGetNeighbors, 0x00, - 0x0F, - 0x00, - 0x00, + _reqNeighborsPageSize, + offset & 0xFF, + (offset >> 8) & 0xFF, 0x00, _reqNeighborsKeyLen, ]), ); + _awaitingSent = true; await connector.sendFrame(frame); final pathLengthValue = selection.useFlood ? -1 : selection.hopCount; @@ -234,6 +252,7 @@ class _NeighborsScreenState extends State { _recordStatusResult(false); }); } catch (e) { + _awaitingSent = false; if (mounted) { setState(() { _isLoading = false; @@ -276,7 +295,7 @@ class _NeighborsScreenState extends State { return Scaffold( appBar: AppBar( title: Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( @@ -296,7 +315,7 @@ class _NeighborsScreenState extends State { ), ], ), - centerTitle: false, + centerTitle: true, actions: [ IconButton( icon: Icon(isFloodMode ? Icons.waves : Icons.route), diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 2eebdc71..5d1d8278 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -7,6 +7,7 @@ import 'package:flutter_map/flutter_map.dart'; import 'package:latlong2/latlong.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/path_helper.dart'; import 'package:meshcore_open/l10n/l10n.dart'; import 'package:meshcore_open/models/app_settings.dart'; import 'package:meshcore_open/models/contact.dart'; @@ -19,7 +20,6 @@ import 'package:meshcore_open/services/path_history_service.dart'; import 'package:meshcore_open/utils/app_logger.dart'; import 'package:meshcore_open/widgets/path_map_ui.dart'; import 'package:meshcore_open/widgets/snr_indicator.dart'; -import 'package:meshcore_open/widgets/themed_map_tile_layer.dart'; import 'package:provider/provider.dart'; import '../theme/mesh_theme.dart'; @@ -27,9 +27,9 @@ export 'package:meshcore_open/widgets/path_map_ui.dart' show formatDistance, getPathDistanceMeters; class PathTraceData { - final Uint8List pathData; + final List pathData; final List snrData; - final Map pathContacts; + final Map pathContacts; PathTraceData({ required this.pathData, @@ -38,6 +38,20 @@ class PathTraceData { }); } +String _hopKey(Uint8List hopBytes) => PathHelper.formatHopHex(hopBytes); + +Uint8List _lastHopChunk(Uint8List path, int hopWidth) { + if (path.isEmpty) return Uint8List(0); + final width = hopWidth.clamp(1, path.length).toInt(); + return Uint8List.fromList(path.sublist(path.length - width)); +} + +bool _matchesHopPrefix(Uint8List a, Uint8List b) { + if (a.isEmpty || b.isEmpty) return false; + final width = min(a.length, b.length); + return listEquals(a.sublist(0, width), b.sublist(0, width)); +} + class PathTraceMapScreen extends StatefulWidget { final String title; final Uint8List path; @@ -77,11 +91,12 @@ class _PathTraceMapScreenState extends State Timer? _timeoutTimer; bool _isLoading = false; + bool _awaitingTraceSent = false; bool _failed2Loaded = false; bool _hasData = false; PathTraceData? _traceData; - // Inferred positions for hops that have no GPS location, keyed by hop byte. - Map _inferredHopPositions = {}; + // Inferred positions for hops that have no GPS location, keyed by hop prefix. + Map _inferredHopPositions = {}; // Endpoint position for the target contact (GPS or guessed). LatLng? _targetContactPosition; bool _targetContactIsGuessed = false; @@ -94,26 +109,97 @@ class _PathTraceMapScreenState extends State double _pathDistanceMeters = 0.0; bool _showNodeLabels = true; Contact? _targetContact; + Uint8List? _sentTagBytes; // Live path resolved at trace time; used by the response handler for // endpoint inference so it matches the path that was actually traced. Uint8List _tracedPath = Uint8List(0); + int _tracedPathHashWidth = 1; // Packet-flow animation + multi-path view state. late final PathPlaybackController _playback; PathHistoryService? _pathHistory; PathViewMode _viewMode = PathViewMode.single; List _displayPaths = []; - List _primaryOutboundHops = []; + List _primaryOutboundHops = []; String _selectedPathId = 'primary'; final Set _hiddenPathIds = {}; bool _panelCollapsed = false; bool _animationEnabled = true; bool _followPacket = false; - String _formatPathPrefixes(Uint8List pathBytes) { - return pathBytes - .map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()) - .join(','); + String _formatPathPrefixes(Uint8List pathBytes, [int? hashByteWidth]) { + return PathHelper.splitPathBytes( + pathBytes, + hashByteWidth ?? widget.pathHashByteWidth, + ).map(PathHelper.formatHopHex).join(','); + } + + int _traceHashByteWidth(int pathHashByteWidth) { + final width = pathHashByteWidth.clamp(1, pubKeySize).toInt(); + if (width <= 1) return 1; + if (width == 2) return 2; + // Trace packets encode hash width as 1 << flags, so 3-byte path hashes + // must be traced with a 4-byte public-key prefix. + return 4; + } + + int _traceFlagsForHashWidth(int traceHashByteWidth) { + if (traceHashByteWidth <= 1) return 0; + if (traceHashByteWidth == 2) return 1; + return 2; + } + + Uint8List _reversePathByHop(Uint8List pathBytes, int hopWidth) { + final reversedHops = PathHelper.splitPathBytes( + pathBytes, + hopWidth, + ).reversed; + final bytes = []; + for (final hop in reversedHops) { + bytes.addAll(hop); + } + return Uint8List.fromList(bytes); + } + + Uint8List? _expandHopForTrace( + Uint8List hop, + int traceHashByteWidth, + MeshCoreConnector connector, + ) { + if (hop.length == traceHashByteWidth) return hop; + + final candidates = [ + ...?widget.pathContacts, + if (widget.targetContact != null) widget.targetContact!, + ...connector.allContactsUnfiltered, + ]; + for (final contact in candidates) { + if (contact.publicKey.length < traceHashByteWidth) continue; + if (!listEquals(contact.publicKey.sublist(0, hop.length), hop)) continue; + return Uint8List.fromList( + contact.publicKey.sublist(0, traceHashByteWidth), + ); + } + return null; + } + + Uint8List? _tracePathFromBytes( + Uint8List pathBytes, + int traceHashByteWidth, + MeshCoreConnector connector, { + int? pathHashByteWidth, + }) { + final hops = PathHelper.splitPathBytes( + pathBytes, + pathHashByteWidth ?? widget.pathHashByteWidth, + ); + final traceBytes = []; + for (final hop in hops) { + final traceHop = _expandHopForTrace(hop, traceHashByteWidth, connector); + if (traceHop == null) return null; + traceBytes.addAll(traceHop); + } + return Uint8List.fromList(traceBytes); } @override @@ -233,62 +319,84 @@ class _PathTraceMapScreenState extends State ); } - Uint8List buildPath(Uint8List pathBytes) { - Uint8List traceBytes; + Uint8List? buildPath( + Uint8List pathBytes, + int traceHashByteWidth, + MeshCoreConnector connector, { + int? pathHashByteWidth, + }) { + final pathHops = PathHelper.splitPathBytes( + pathBytes, + pathHashByteWidth ?? widget.pathHashByteWidth, + ); + final hopWidth = traceHashByteWidth.clamp(1, pubKeySize).toInt(); - if (pathBytes.isEmpty) { - final pk = widget.targetContact?.publicKey; - final n = widget.pathHashByteWidth.clamp(1, pubKeySize); - if (pk != null && pk.length >= n) { - return Uint8List.fromList(pk.sublist(0, n)); + // Compute targetPrefix if targetContact is provided + Uint8List? targetPrefix; + if (widget.targetContact != null) { + final pk = widget.targetContact!.publicKey; + if (pk.isNotEmpty) { + final len = pk.length >= hopWidth ? hopWidth : pk.length; + targetPrefix = Uint8List.fromList(pk.sublist(0, len)); } - traceBytes = Uint8List(1); - traceBytes[0] = pk?[0] ?? 0; - return traceBytes; } - if (widget.targetContact?.type == advTypeRepeater || - widget.targetContact?.type == advTypeRoom) { - final len = (pathBytes.length + pathBytes.length + 1); - traceBytes = Uint8List(len); - traceBytes[pathBytes.length] = widget.targetContact?.publicKey[0] ?? 0; - for (int i = 0; i < pathBytes.length; i++) { - traceBytes[i] = pathBytes[i]; - if (i < pathBytes.length) { - traceBytes[len - 1 - i] = pathBytes[i]; + final outboundHops = []; + for (final hop in pathHops) { + final traceHop = _expandHopForTrace(hop, traceHashByteWidth, connector); + if (traceHop == null) return null; + outboundHops.add(traceHop); + } + if (targetPrefix != null) { + // Check if targetPrefix is already the last hop in pathHops to avoid duplication + bool alreadyEndedWithTarget = false; + if (outboundHops.isNotEmpty) { + if (listEquals(outboundHops.last, targetPrefix)) { + alreadyEndedWithTarget = true; } } - } else { - if (pathBytes.length < 2) { - return pathBytes[0] == 0 ? Uint8List(0) : pathBytes; - } - final len = (pathBytes.length + pathBytes.length - 1); - traceBytes = Uint8List(len); - for (int i = 0; i < pathBytes.length; i++) { - traceBytes[i] = pathBytes[i]; - if (i < pathBytes.length - 1) { - traceBytes[len - 1 - i] = pathBytes[i]; - } + if (!alreadyEndedWithTarget) { + outboundHops.add(targetPrefix); } } - return traceBytes; + + if (outboundHops.isEmpty) { + return Uint8List(0); + } + + final mirroredHops = [...outboundHops]; + if (outboundHops.length > 1) { + mirroredHops.addAll( + outboundHops.sublist(0, outboundHops.length - 1).reversed, + ); + } + + final traceBytes = []; + for (final hop in mirroredHops) { + traceBytes.addAll(hop); + } + return Uint8List.fromList(traceBytes); } /// Resolves the path bytes to trace. When tracing a specific contact's /// route (flipPathAround), re-read that contact's live forced/auto path from /// the connector so a path the user just changed (force flood / set path / /// reset to auto) is honored immediately, instead of the value captured when - /// this screen was first pushed. - Uint8List _resolveLivePath(MeshCoreConnector connector) { + /// this screen was first pushed. Also returns the path's bytes per hop: the + /// contact's learned width for its device path, the local mode otherwise. + (Uint8List, int) _resolveLivePath(MeshCoreConnector connector) { final target = widget.targetContact; if (!widget.flipPathAround || target == null) { - return widget.path; + return (widget.path, widget.pathHashByteWidth); } final live = connector.allContactsUnfiltered.firstWhere( (c) => c.publicKeyHex == target.publicKeyHex, orElse: () => target, ); - return live.pathBytesForDisplay; + final width = live.pathOverride == null && live.path.isNotEmpty + ? live.pathHashWidth + : widget.pathHashByteWidth; + return (live.pathBytesForDisplay, width); } Future _doPathTrace() async { @@ -301,27 +409,62 @@ class _PathTraceMapScreenState extends State } final connector = Provider.of(context, listen: false); - final livePath = _resolveLivePath(connector); + final (livePath, hopWidth) = _resolveLivePath(connector); + final traceHashByteWidth = _traceHashByteWidth(hopWidth); _tracedPath = livePath; + _tracedPathHashWidth = hopWidth; final pathTmp = widget.reversePathAround - ? Uint8List.fromList(livePath.reversed.toList()) + ? _reversePathByHop(livePath, hopWidth) : livePath; - final path = widget.flipPathAround ? buildPath(pathTmp) : pathTmp; + final path = widget.flipPathAround + ? buildPath( + pathTmp, + traceHashByteWidth, + connector, + pathHashByteWidth: hopWidth, + ) + : _tracePathFromBytes( + pathTmp, + traceHashByteWidth, + connector, + pathHashByteWidth: hopWidth, + ); + + if (path == null) { + if (!mounted) return; + setState(() { + _isLoading = false; + _failed2Loaded = true; + }); + return; + } appLogger.info( - 'Initiating path trace with path: ${_formatPathPrefixes(path)}', + 'Initiating path trace with path: ' + '${_formatPathPrefixes(path, traceHashByteWidth)}', tag: 'PathTraceMapScreen', noNotify: !mounted, ); + final sentTag = DateTime.now().millisecondsSinceEpoch ~/ 1000; + _sentTagBytes = Uint8List(4) + ..[0] = sentTag & 0xFF + ..[1] = (sentTag >> 8) & 0xFF + ..[2] = (sentTag >> 16) & 0xFF + ..[3] = (sentTag >> 24) & 0xFF; + + final flags = _traceFlagsForHashWidth(traceHashByteWidth); + final tracePayload = path.isEmpty ? Uint8List.fromList([0x00]) : path; + final frame = buildTraceReq( - DateTime.now().millisecondsSinceEpoch ~/ 1000, - 0, //auth - 0, //flag - payload: path, + sentTag, + 0, // auth + flags, // flag + payload: tracePayload, ); + _awaitingTraceSent = true; connector.sendFrame(frame); } @@ -335,7 +478,8 @@ class _PathTraceMapScreenState extends State try { final code = frameBuffer.readUInt8(); - if (code == respCodeSent) { + if (code == respCodeSent && _awaitingTraceSent) { + _awaitingTraceSent = false; frameBuffer.skipBytes(1); //reserved tagData = frameBuffer.readBytes(4); final timeoutMilliseconds = frameBuffer.readUInt32LE(); @@ -354,7 +498,8 @@ class _PathTraceMapScreenState extends State ); } - if (code == respCodeErr) { + if (code == respCodeErr && _awaitingTraceSent) { + _awaitingTraceSent = false; _timeoutTimer?.cancel(); if (!mounted) return; setState(() { @@ -364,15 +509,13 @@ class _PathTraceMapScreenState extends State } // Check if it's a binary response - if (frame.length > 8 && + if (frame.length >= 12 && code == pushCodeTraceData && - listEquals(frame.sublist(4, 8), tagData)) { + (listEquals(frame.sublist(4, 8), _sentTagBytes) || + listEquals(frame.sublist(4, 8), tagData))) { _timeoutTimer?.cancel(); if (!mounted) return; - frameBuffer.skipBytes(3); //reserved + path length + flag - if (listEquals(frameBuffer.readBytes(4), tagData)) { - _handleTraceResponse(frame); - } + _handleTraceResponse(frame); } } catch (e) { _timeoutTimer?.cancel(); @@ -393,21 +536,30 @@ class _PathTraceMapScreenState extends State final buffer = BufferReader(frame); try { buffer.skipBytes(2); // Skip push code and reserved byte - int pathLength = buffer.readUInt8(); - final int flags = buffer - .readUInt8(); // path_sz = flags & 0x03 (path-hash mode, fw v1.11+) + final pathLenByte = buffer.readUInt8(); + final flags = buffer.readUInt8(); buffer.skipBytes(4); // Skip tag data buffer.skipBytes(4); // Skip auth code - final int pathSz = flags & 0x03; - Uint8List pathData = buffer.readBytes(pathLength); + var width = _traceHashByteWidth(1 << (flags & 0x03)); + var pathLength = pathLenByte == 0xFF ? 0 : pathLenByte; + if (pathLength > buffer.remaining && (pathLenByte & 0xC0) != 0) { + final packedWidth = ((pathLenByte & 0xC0) >> 6) + 1; + final packedLength = (pathLenByte & 0x3F) * packedWidth; + if (packedLength <= buffer.remaining) { + width = packedWidth; + pathLength = packedLength; + } + } + final pathBytes = buffer.readBytes(pathLength); + final pathData = PathHelper.splitPathBytes(pathBytes, width); // Firmware emits (path_len >> path_sz) hop SNRs plus 1 final SNR (to this node). - final int snrCount = (pathLength >> pathSz) + 1; + final snrCount = (pathLength ~/ width) + 1; List snrData = buffer .readBytes(snrCount) .map((snr) => snr.toSigned(8).toDouble() / 4) .toList(); - Map pathContacts = {}; + Map pathContacts = {}; Contact lastContact = Contact( path: Uint8List(0), pathLength: 0, @@ -419,7 +571,12 @@ class _PathTraceMapScreenState extends State lastSeen: DateTime.now(), ); if (widget.pathContacts != null) { - pathContacts = {for (var c in widget.pathContacts!) c.publicKey[0]: c}; + final hopWidth = width.clamp(1, pubKeySize).toInt(); + pathContacts = { + for (var c in widget.pathContacts!) + if (c.publicKey.length >= hopWidth) + _hopKey(Uint8List.fromList(c.publicKey.sublist(0, hopWidth))): c, + }; } else { final contacts = connector.allContactsUnfiltered; contacts.where((c) => c.type != advTypeChat).forEach((repeater) { @@ -434,12 +591,14 @@ class _PathTraceMapScreenState extends State _maxRepeaterMatchDistanceMeters) { return; //skip reapeaters that are far away from the last one with known GPS, to avoid false matches } - for (var repeaterData in pathData) { + for (final repeaterData in pathData) { + final hopWidth = repeaterData.length; + if (repeater.publicKey.length < hopWidth) continue; if (listEquals( - repeater.publicKey.sublist(0, 1), - Uint8List.fromList([repeaterData]), + repeater.publicKey.sublist(0, hopWidth), + repeaterData, )) { - pathContacts[repeaterData] = repeater; + pathContacts[_hopKey(repeaterData)] = repeater; lastContact = repeater; } } @@ -448,13 +607,20 @@ class _PathTraceMapScreenState extends State // For hops with no GPS contact, infer position from other contacts // with known GPS that share the same last-hop byte. - final Map inferredPositions = {}; + final Map inferredPositions = {}; for (final hop in pathData) { - final contact = pathContacts[hop]; + final hopKey = _hopKey(hop); + final contact = pathContacts[hopKey]; if (contact != null && contact.hasLocation) continue; final peers = connector.contacts .where( - (c) => c.hasLocation && c.path.isNotEmpty && c.path.last == hop, + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix( + _lastHopChunk(c.path, c.pathHashWidth), + hop, + ), ) .toList(); if (peers.isNotEmpty) { @@ -464,7 +630,7 @@ class _PathTraceMapScreenState extends State final lon = peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; - inferredPositions[hop] = LatLng(lat, lon); + inferredPositions[hopKey] = LatLng(lat, lon); } } @@ -486,20 +652,31 @@ class _PathTraceMapScreenState extends State final tc = _targetContact!; if (tc.hasLocation) { targetPos = LatLng(tc.latitude!, tc.longitude!); - } else if (_tracedPath.length > 1) { + } else if (pathData.length > 1 || _tracedPath.isNotEmpty) { // Infer from the last hop: average GPS contacts sharing that hop. // For a round-trip path (flipPathAround/reversePathAround), the target-side hop // sits in the middle of the symmetric sequence; .last is the local side. + final tracedHops = PathHelper.splitPathBytes( + _tracedPath, + _tracedPathHashWidth, + ); + final hopsForEndpoint = tracedHops.isNotEmpty + ? tracedHops + : pathData; final lastHop = widget.reversePathAround - ? _tracedPath.first - : _tracedPath.last; + ? hopsForEndpoint.first + : hopsForEndpoint.last; + final lastHopKey = _hopKey(lastHop); final peers = connector.allContacts .where( (c) => c.hasLocation && c.path.isNotEmpty && - c.path.last == lastHop, + _matchesHopPrefix( + _lastHopChunk(c.path, c.pathHashWidth), + lastHop, + ), ) .toList(); if (peers.isNotEmpty) { @@ -516,9 +693,9 @@ class _PathTraceMapScreenState extends State lon + offsetDeg * sin(angle), ); targetGuessed = true; - } else if (inferredPositions.containsKey(lastHop)) { - final lat = inferredPositions[lastHop]!.latitude; - final lon = inferredPositions[lastHop]!.longitude; + } else if (inferredPositions.containsKey(lastHopKey)) { + final lat = inferredPositions[lastHopKey]!.latitude; + final lon = inferredPositions[lastHopKey]!.longitude; const offsetDeg = 0.003; final angle = (tc.publicKey[1] / 255.0) * 2 * pi; targetPos = LatLng( @@ -528,7 +705,7 @@ class _PathTraceMapScreenState extends State targetGuessed = true; } else { // As a last resort, just place it at the same position as the last hop. - final contact = pathContacts[lastHop]; + final contact = pathContacts[lastHopKey]; if (contact != null && contact.hasLocation) { const offsetDeg = 0.003; final angle = (tc.publicKey[1] / 255.0) * 2 * pi; @@ -546,21 +723,22 @@ class _PathTraceMapScreenState extends State _points = []; _points.add(LatLng(connector.selfLatitude!, connector.selfLongitude!)); - int hopLast = 0; - int hopLastLast = 0; + String hopLast = ''; + String hopLastLast = ''; for (final hop in _traceData!.pathData) { - if (hop == hopLastLast && widget.flipPathAround) { + final hopKey = _hopKey(hop); + if (hopKey == hopLastLast && widget.flipPathAround) { break; //skip duplicate hops in round-trip paths } - final contact = _traceData!.pathContacts[hop]; + final contact = _traceData!.pathContacts[hopKey]; if (contact != null && contact.hasLocation) { _points.add(LatLng(contact.latitude!, contact.longitude!)); } else { - final inferred = inferredPositions[hop]; + final inferred = inferredPositions[hopKey]; if (inferred != null) _points.add(inferred); } hopLastLast = hopLast; - hopLast = hop; + hopLast = hopKey; } if (targetPos != null) { if (_targetContact != null && _targetContact!.type == advTypeChat) { @@ -583,7 +761,7 @@ class _PathTraceMapScreenState extends State _initialZoom = _points.isNotEmpty ? 13.0 : 2.0; _bounds = _points.length > 1 ? LatLngBounds.fromPoints(_points) : null; _mapKey = ValueKey( - '${context.l10n.pathTrace_you},${_formatPathPrefixes(_traceData!.pathData)}', + '${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}', ); _pathDistanceMeters = getPathDistanceMeters(_points); _primaryOutboundHops = _outboundHops(pathData); @@ -605,37 +783,47 @@ class _PathTraceMapScreenState extends State /// Outbound hop bytes of the traced path, mirroring the round-trip /// dedup logic used when building [_points]. - List _outboundHops(Uint8List pathData) { - final hops = []; - int hopLast = 0; - int hopLastLast = 0; + List _outboundHops(List pathData) { + final hops = []; + var hopLast = ''; + var hopLastLast = ''; for (final hop in pathData) { - if (hop == hopLastLast && widget.flipPathAround) break; + final hopKey = _hopKey(hop); + if (hopKey == hopLastLast && widget.flipPathAround) break; hops.add(hop); hopLastLast = hopLast; - hopLast = hop; + hopLast = hopKey; } return hops; } - Contact? _contactForHop(int hop, MeshCoreConnector connector) { - final traced = _traceData?.pathContacts[hop]; + Contact? _contactForHop(Uint8List hop, MeshCoreConnector connector) { + final traced = _traceData?.pathContacts[_hopKey(hop)]; if (traced != null) return traced; for (final c in connector.allContactsUnfiltered) { if (c.type != advTypeChat && - c.publicKey.isNotEmpty && - c.publicKey[0] == hop) { + c.publicKey.length >= hop.length && + listEquals(c.publicKey.sublist(0, hop.length), hop)) { return c; } } return null; } - LatLng? _inferredPositionForHop(int hop, MeshCoreConnector connector) { - final cached = _inferredHopPositions[hop]; + LatLng? _inferredPositionForHop(Uint8List hop, MeshCoreConnector connector) { + final hopKey = _hopKey(hop); + final cached = _inferredHopPositions[hopKey]; if (cached != null) return cached; final peers = connector.contacts - .where((c) => c.hasLocation && c.path.isNotEmpty && c.path.last == hop) + .where( + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix( + _lastHopChunk(c.path, c.pathHashWidth), + hop, + ), + ) .toList(); if (peers.isEmpty) return null; final lat = @@ -643,10 +831,14 @@ class _PathTraceMapScreenState extends State final lon = peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; final pos = LatLng(lat, lon); - _inferredHopPositions[hop] = pos; + _inferredHopPositions[hopKey] = pos; return pos; } + String _pathKeyForHops(List hops) { + return hops.map(PathHelper.formatHopHex).join(','); + } + /// 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) { @@ -664,18 +856,25 @@ class _PathTraceMapScreenState extends State final target = widget.targetContact; final history = _pathHistory; if (target != null && history != null) { - final seen = {_primaryOutboundHops.join(',')}; + final seen = {_pathKeyForHops(_primaryOutboundHops)}; var altIndex = 0; for (final record in history.getRecentPaths(target.publicKeyHex)) { if (record.pathBytes.isEmpty) continue; - if (!seen.add(record.pathBytes.join(','))) continue; + final recordHops = PathHelper.splitPathBytes( + record.pathBytes, + Contact.inferPathHashWidth( + record.hopCount, + record.pathBytes.length, + ), + ); + if (!seen.add(_pathKeyForHops(recordHops))) continue; if (altIndex >= kAlternatePathColors.length) break; final alt = _buildDisplayPath( - id: 'alt-${record.pathBytes.join('-')}', + id: 'alt-${_pathKeyForHops(recordHops)}', label: context.l10n.pathMap_alternate(altIndex + 1), color: kAlternatePathColors[altIndex], isPrimary: false, - hops: record.pathBytes, + hops: recordHops, record: record, connector: connector, ); @@ -700,7 +899,7 @@ class _PathTraceMapScreenState extends State required String label, required Color color, required bool isPrimary, - required List hops, + required List hops, required MeshCoreConnector connector, PathRecord? record, }) { @@ -719,7 +918,7 @@ class _PathTraceMapScreenState extends State for (var i = 0; i < hops.length; i++) { final hop = hops[i]; - final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase(); + final hex = PathHelper.formatHopHex(hop); final contact = _contactForHop(hop, connector); LatLng? pos; var isGps = false; @@ -773,7 +972,7 @@ class _PathTraceMapScreenState extends State label: label, color: color, isPrimary: isPrimary, - hopBytes: List.from(hops), + hopBytes: List.from(hops), points: points, pointLabels: labels, pointConfirmed: confirmed, @@ -934,29 +1133,34 @@ class _PathTraceMapScreenState extends State } List _buildHopMarkers( - List pathData, { + List pathData, { required bool showLabels, required Contact? target, }) { final markers = []; - int hopLast = 0; - int hopLastLast = 0; + String hopLast = ''; + String hopLastLast = ''; for (final hop in pathData) { - final contact = _traceData!.pathContacts[hop]; - final inferred = _inferredHopPositions[hop]; + final hopKey = _hopKey(hop); + final contact = _traceData!.pathContacts[hopKey]; + final inferred = _inferredHopPositions[hopKey]; final hasGps = contact != null && contact.hasLocation; - if (hop == hopLastLast && widget.flipPathAround) { + if (hopKey == hopLastLast && widget.flipPathAround) { continue; //skip duplicate hops in round-trip paths } if (!hasGps && inferred == null) { hopLastLast = hopLast; - hopLast = hop; + hopLast = hopKey; continue; //skip hops with no GPS and no inferred position } final point = hasGps ? LatLng(contact.latitude!, contact.longitude!) : inferred!; - final label = hop.toRadixString(16).padLeft(2, '0').toUpperCase(); + final label = PathHelper.formatHopHex(hop); + final shortLabel = label.length > 2 ? label.substring(0, 2) : label; + final fullLabel = label.length > 2 + ? (contact?.name != null ? '$label: ${contact!.name}' : label) + : (contact?.name ?? label); markers.add( Marker( @@ -989,9 +1193,9 @@ class _PathTraceMapScreenState extends State ), alignment: Alignment.center, child: Text( - hasGps ? label : '~$label', + shortLabel, style: MeshTheme.mono( - fontSize: 10, + fontSize: 12, fontWeight: FontWeight.w700, color: hasGps ? MeshPalette.signal : MeshPalette.warn, ), @@ -1001,15 +1205,10 @@ class _PathTraceMapScreenState extends State ), ); if (showLabels) { - markers.add( - _buildNodeLabelMarker( - point: point, - label: contact?.name ?? '~$label', - ), - ); + markers.add(_buildNodeLabelMarker(point: point, label: fullLabel)); } hopLastLast = hopLast; - hopLast = hop; + hopLast = hopKey; } _addEndpointMarkers(markers, showLabels: showLabels, target: target); @@ -1137,17 +1336,22 @@ class _PathTraceMapScreenState extends State final connector = context.read(); final markers = []; - // Hop byte -> paths that use it, in display order. - final hopPaths = >{}; + // Hop prefix -> paths that use it, in display order. + final hopPaths = >{}; + final hopsByKey = {}; for (final path in _visiblePaths) { for (final hop in path.hopBytes) { - final list = hopPaths.putIfAbsent(hop, () => []); + final hopKey = _hopKey(hop); + hopsByKey[hopKey] = hop; + final list = hopPaths.putIfAbsent(hopKey, () => []); if (!list.contains(path)) list.add(path); } } for (final entry in hopPaths.entries) { - final hop = entry.key; + final hopKey = entry.key; + final hop = hopsByKey[hopKey]; + if (hop == null) continue; final paths = entry.value; final contact = _contactForHop(hop, connector); final hasGps = contact != null && contact.hasLocation; @@ -1155,7 +1359,7 @@ class _PathTraceMapScreenState extends State ? LatLng(contact.latitude!, contact.longitude!) : _inferredPositionForHop(hop, connector); if (point == null) continue; - final label = hop.toRadixString(16).padLeft(2, '0').toUpperCase(); + final label = PathHelper.formatHopHex(hop); final baseColor = hasGps ? MeshPalette.signal : MeshPalette.warn; final shared = paths.length > 1; @@ -1240,11 +1444,11 @@ class _PathTraceMapScreenState extends State } void _showSharedNodeSheet( - int hop, + Uint8List hop, Contact? contact, List paths, ) { - final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase(); + final hex = PathHelper.formatHopHex(hop); showSharedNodeSheet( context, title: @@ -1291,29 +1495,28 @@ class _PathTraceMapScreenState extends State } String formatDirectionText(PathTraceData pathTraceData, int index) { - if (index == 0 || index == pathTraceData.snrData.length - 1) { + if (pathTraceData.pathData.isEmpty) { + return context.l10n.pathTrace_you; + } + if (index < 0 || index > pathTraceData.pathData.length) { + return context.l10n.pathTrace_you; + } + + if (index == 0 || index == pathTraceData.pathData.length) { if (index == 0) { return context.l10n.pathTrace_you; } else { - final contactName = pathTraceData - .pathContacts[pathTraceData.pathData[pathTraceData.pathData.length - - 1]] - ?.name; - final hex = pathTraceData.pathData[pathTraceData.pathData.length - 1] - .toRadixString(16) - .padLeft(2, '0') - .toUpperCase(); + final hop = pathTraceData.pathData.last; + final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name; + final hex = PathHelper.formatHopHex(hop); return contactName != null ? "$hex: $contactName" : "$hex: ${context.l10n.channelPath_unknownRepeater}"; } } else { - final contactName = - pathTraceData.pathContacts[pathTraceData.pathData[index - 1]]?.name; - final hex = pathTraceData.pathData[index - 1] - .toRadixString(16) - .padLeft(2, '0') - .toUpperCase(); + final hop = pathTraceData.pathData[index - 1]; + final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name; + final hex = PathHelper.formatHopHex(hop); return contactName != null ? "$hex: $contactName" : "$hex: ${context.l10n.channelPath_unknownRepeater}"; @@ -1321,14 +1524,18 @@ class _PathTraceMapScreenState extends State } String formatDirectionSubText(PathTraceData pathTraceData, int index) { - if (index == 0 || index == pathTraceData.snrData.length - 1) { + if (pathTraceData.pathData.isEmpty) { + return context.l10n.pathTrace_you; + } + if (index < 0 || index > pathTraceData.pathData.length) { + return context.l10n.pathTrace_you; + } + + if (index == 0 || index == pathTraceData.pathData.length) { if (index == 0) { - final contactName = - pathTraceData.pathContacts[pathTraceData.pathData[0]]?.name; - final hex = pathTraceData.pathData[0] - .toRadixString(16) - .padLeft(2, '0') - .toUpperCase(); + final hop = pathTraceData.pathData.first; + final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name; + final hex = PathHelper.formatHopHex(hop); return contactName != null ? "$hex: $contactName" : "$hex: ${context.l10n.channelPath_unknownRepeater}"; @@ -1336,12 +1543,9 @@ class _PathTraceMapScreenState extends State return context.l10n.pathTrace_you; } } else { - final contactName = - pathTraceData.pathContacts[pathTraceData.pathData[index]]?.name; - final hex = pathTraceData.pathData[index] - .toRadixString(16) - .padLeft(2, '0') - .toUpperCase(); + final hop = pathTraceData.pathData[index]; + final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name; + final hex = PathHelper.formatHopHex(hop); return contactName != null ? "$hex: $contactName" : "$hex: ${context.l10n.channelPath_unknownRepeater}"; @@ -1399,7 +1603,7 @@ class _PathTraceMapScreenState extends State }, ), children: [ - ThemedMapTileLayer(tileCache: tileCache), + tileCache.buildTileLayer(context), AnimatedBuilder( animation: _playback, builder: (context, _) { @@ -1670,11 +1874,11 @@ class _PathTraceMapScreenState extends State final connector = context.read(); final l10n = context.l10n; - final hopUseCount = {}; + final hopUseCount = {}; if (_viewMode == PathViewMode.combined) { for (final p in _visiblePaths) { - for (final hop in p.hopBytes.toSet()) { - hopUseCount.update(hop, (v) => v + 1, ifAbsent: () => 1); + for (final hopKey in p.hopBytes.map(PathHelper.formatHopHex).toSet()) { + hopUseCount.update(hopKey, (v) => v + 1, ifAbsent: () => 1); } } } @@ -1690,7 +1894,7 @@ class _PathTraceMapScreenState extends State Widget? trailing; if (index < path.hopBytes.length) { final hop = path.hopBytes[index]; - final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase(); + final hex = PathHelper.formatHopHex(hop); final contact = _contactForHop(hop, connector); title = contact != null ? '$hex: ${contact.name}' @@ -1703,7 +1907,7 @@ class _PathTraceMapScreenState extends State : inferred ? l10n.pathTrace_legendInferred : l10n.pathMap_noLocation; - final sharedCount = hopUseCount[hop] ?? 0; + final sharedCount = hopUseCount[_hopKey(hop)] ?? 0; subtitle = sharedCount > 1 ? '$status · ${l10n.pathMap_sharedNodeCount(sharedCount)}' : status; diff --git a/lib/screens/region_management_screen.dart b/lib/screens/region_management_screen.dart index df6c477c..3997f8b9 100644 --- a/lib/screens/region_management_screen.dart +++ b/lib/screens/region_management_screen.dart @@ -78,13 +78,82 @@ class _RegionManagementScreenState extends State { ), ], ), - body: ListView.builder( - padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 88), - itemCount: _regions.length, - itemBuilder: (context, index) { - final region = _regions[index]; - return _buildRegionTile(context, region); - }, + body: _regions.isEmpty + ? _buildEmptyState(context) + : ListView.builder( + padding: const EdgeInsets.only( + left: 16, + right: 16, + top: 8, + bottom: 88, + ), + itemCount: _regions.length + 1, + itemBuilder: (context, index) { + if (index == 0) return _buildDefaultRegionTile(context); + return _buildRegionTile(context, _regions[index - 1]); + }, + ), + ); + } + + Widget _buildEmptyState(BuildContext context) { + final l10n = context.l10n; + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.landscape, size: 48, color: MeshPalette.blue), + const SizedBox(height: 16), + Text( + l10n.settings_regionEmptyExplanation, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 24), + FilledButton.icon( + icon: const Icon(Icons.travel_explore), + label: Text(l10n.settings_regionFetchFromRepeaters), + onPressed: _isFetchingRegions ? null : _showFetchRegionsDialog, + ), + const SizedBox(height: 8), + OutlinedButton.icon( + icon: const Icon(Icons.add), + label: Text(l10n.settings_regionAddRegion), + onPressed: () => _showAddRegionDialog(context), + ), + ], + ), + ), + ); + } + + Widget _buildDefaultRegionTile(BuildContext context) { + final l10n = context.l10n; + final connector = context.watch(); + final current = _regions.contains(connector.defaultRegion) + ? connector.defaultRegion + : ''; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: DropdownButtonFormField( + key: ValueKey(current), + initialValue: current, + decoration: InputDecoration( + labelText: l10n.settings_regionDefault, + helperText: l10n.settings_regionDefaultSubtitle, + border: const OutlineInputBorder(), + ), + items: [ + DropdownMenuItem( + value: '', + child: Text(l10n.settings_regionDefaultNone), + ), + for (final region in _regions) + DropdownMenuItem(value: region, child: Text(region)), + ], + onChanged: (value) => connector.setDefaultRegion(value ?? ''), ), ); } @@ -440,7 +509,12 @@ class _RegionManagementScreenState extends State { await connector.clearContactPath(repeater); return; } - await connector.setContactPath(repeater, originalPath, originalPathLength); + await connector.setContactPath( + repeater, + originalPath, + originalPathLength, + pathHashWidth: repeater.pathHashWidth, + ); } Set _parseRegionsResponse(Uint8List frame) { diff --git a/lib/screens/repeater_cli_screen.dart b/lib/screens/repeater_cli_screen.dart index 5024f334..b6cab578 100644 --- a/lib/screens/repeater_cli_screen.dart +++ b/lib/screens/repeater_cli_screen.dart @@ -34,6 +34,8 @@ class _RepeaterCliScreenState extends State { int _historyIndex = -1; StreamSubscription? _frameSubscription; RepeaterCommandService? _commandService; + bool _regionLoadActive = false; + static final RegExp _regionLoadPattern = RegExp(r'^region +load( |$)'); late final List> _quickCommands = [ {'labelKey': 'advertise', 'command': 'advert'}, @@ -111,8 +113,13 @@ class _RepeaterCliScreenState extends State { } void _sendCommand({bool showDebug = false}) async { + if (_regionLoadActive) { + _sendRegionLoadLine(); + return; + } final command = _commandController.text.trim(); if (command.isEmpty) return; + final startsRegionLoad = _regionLoadPattern.hasMatch(command.toLowerCase()); setState(() { _commandHistory.add({ @@ -121,6 +128,9 @@ class _RepeaterCliScreenState extends State { 'timestamp': DateTime.now().toString(), }); }); + _commandController.clear(); + _historyIndex = -1; + _commandFocusNode.requestFocus(); if (showDebug && mounted) { final frame = buildSendCliCommandFrame( @@ -168,12 +178,79 @@ class _RepeaterCliScreenState extends State { } } + // The reply to `region load` may be lost even though the repeater entered + // load mode, so enter it regardless; a blank line always ends it safely. + if (startsRegionLoad && mounted) { + setState(() { + _regionLoadActive = true; + _commandHistory.add({ + 'type': 'response', + 'text': context.l10n.repeater_cliRegionLoadActive, + 'timestamp': DateTime.now().toString(), + }); + }); + } + + _scrollToBottom(); + } + + /// In `region load` mode lines go out verbatim: no `XX|` prefix and no + /// trimming, since indentation encodes the parent. Region lines get no + /// reply; a blank line commits the load and is answered with + /// "OK - loaded N regions". + Future _sendRegionLoadLine() async { + final line = _commandController.text; + final isTerminator = line.trim().isEmpty; + final connector = Provider.of(context, listen: false); + final repeater = _resolveRepeater(connector); + setState(() { + _commandHistory.add({ + 'type': 'command', + 'text': isTerminator ? context.l10n.repeater_cliRegionLoadEnd : line, + 'timestamp': DateTime.now().toString(), + }); + }); _commandController.clear(); _historyIndex = -1; _commandFocusNode.requestFocus(); + String? response; + var ended = false; + try { + if (isTerminator) { + response = await _commandService!.sendCommand( + repeater, + '', + retries: 1, + raw: true, + ); + ended = true; + } else { + await _commandService!.sendUnansweredLine(repeater, line); + } + } catch (e) { + if (mounted) { + response = context.l10n.repeater_cliCommandError(e.toString()); + } + } + if (!mounted) return; + setState(() { + if (ended) _regionLoadActive = false; + if (response != null) { + _commandHistory.add({ + 'type': 'response', + 'text': response, + 'timestamp': DateTime.now().toString(), + }); + } + }); + _scrollToBottom(); + } + + void _scrollToBottom() { + if (!mounted) return; Future.delayed(const Duration(milliseconds: 100), () { - if (_scrollController.hasClients) { + if (mounted && _scrollController.hasClients) { _scrollController.animateTo( _scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 200), @@ -337,7 +414,9 @@ class _RepeaterCliScreenState extends State { backgroundColor: MeshPalette.blueBg, side: const BorderSide(color: MeshPalette.blueLine), visualDensity: VisualDensity.compact, - onPressed: () => _useQuickCommand(cmd['command']!), + onPressed: _regionLoadActive + ? null + : () => _useQuickCommand(cmd['command']!), ), ); }).toList(), @@ -392,12 +471,14 @@ class _RepeaterCliScreenState extends State { color: MeshPalette.ink, ), decoration: InputDecoration( - hintText: context.l10n.repeater_enterCommandHint, + hintText: _regionLoadActive + ? context.l10n.repeater_cliRegionLoadHint + : context.l10n.repeater_enterCommandHint, hintStyle: MeshTheme.mono( fontSize: 13, color: MeshPalette.ink4, ), - prefixText: '> ', + prefixText: _regionLoadActive ? '' : '> ', prefixStyle: MeshTheme.mono( fontSize: 13, color: MeshPalette.blue, @@ -609,22 +690,6 @@ class _RepeaterCliScreenState extends State { command: 'powersaving {on|off}', description: l10n.repeater_cliHelpPowersavingOnOff, ), - _CommandHelpEntry( - command: 'erase', - description: l10n.repeater_cliHelpErase, - ), - _CommandHelpEntry( - command: 'stats-packets', - description: l10n.repeater_cliHelpStatsPackets, - ), - _CommandHelpEntry( - command: 'stats-radio', - description: l10n.repeater_cliHelpStatsRadio, - ), - _CommandHelpEntry( - command: 'stats-core', - description: l10n.repeater_cliHelpStatsCore, - ), ]; final settingsCommands = [ @@ -648,6 +713,14 @@ class _RepeaterCliScreenState extends State { command: 'set flood.max {max-hops}', description: l10n.repeater_cliHelpSetFloodMax, ), + _CommandHelpEntry( + command: 'set flood.max.unscoped {0-64}', + description: l10n.repeater_cliHelpSetFloodMaxUnscoped, + ), + _CommandHelpEntry( + command: 'set flood.max.advert {0-64}', + description: l10n.repeater_cliHelpSetFloodMaxAdvert, + ), _CommandHelpEntry( command: 'set int.thresh {db}', description: l10n.repeater_cliHelpSetIntThresh, @@ -700,26 +773,6 @@ class _RepeaterCliScreenState extends State { command: 'set direct.txdelay {factor}', description: l10n.repeater_cliHelpSetDirectTxDelay, ), - _CommandHelpEntry( - command: 'set bridge.enabled {on|off}', - description: l10n.repeater_cliHelpSetBridgeEnabled, - ), - _CommandHelpEntry( - command: 'set bridge.delay {0-10000}', - description: l10n.repeater_cliHelpSetBridgeDelay, - ), - _CommandHelpEntry( - command: 'set bridge.source {rx|tx}', - description: l10n.repeater_cliHelpSetBridgeSource, - ), - _CommandHelpEntry( - command: 'set bridge.baud {speed}', - description: l10n.repeater_cliHelpSetBridgeBaud, - ), - _CommandHelpEntry( - command: 'set bridge.secret {shared-secret}', - description: l10n.repeater_cliHelpSetBridgeSecret, - ), _CommandHelpEntry( command: 'set adc.multiplier {factor}', description: l10n.repeater_cliHelpSetAdcMultiplier, @@ -744,6 +797,14 @@ class _RepeaterCliScreenState extends State { command: 'set radio.rxgain {on|off}', description: l10n.repeater_cliHelpSetRadioRxGain, ), + _CommandHelpEntry( + command: 'set radio.fem.rxgain {on|off}', + description: l10n.repeater_cliHelpSetRadioFemRxGain, + ), + _CommandHelpEntry( + command: 'set radio.fem.txgain {on|off}', + description: l10n.repeater_cliHelpSetRadioFemTxGain, + ), _CommandHelpEntry( command: 'set owner.info {text}', description: l10n.repeater_cliHelpSetOwnerInfo, @@ -756,17 +817,57 @@ class _RepeaterCliScreenState extends State { command: 'set loop.detect {off|minimal|moderate|strict}', description: l10n.repeater_cliHelpSetLoopDetect, ), + ]; + + final bridgeCommands = [ _CommandHelpEntry( - command: 'set freq {mhz}', - description: l10n.repeater_cliHelpSetFreq, + command: 'set bridge.enabled {on|off}', + description: l10n.repeater_cliHelpSetBridgeEnabled, + ), + _CommandHelpEntry( + command: 'set bridge.delay {0-10000}', + description: l10n.repeater_cliHelpSetBridgeDelay, + ), + _CommandHelpEntry( + command: 'set bridge.source {rx|tx}', + description: l10n.repeater_cliHelpSetBridgeSource, + ), + _CommandHelpEntry( + command: 'set bridge.baud {speed}', + description: l10n.repeater_cliHelpSetBridgeBaud, + ), + _CommandHelpEntry( + command: 'set bridge.secret {shared-secret}', + description: l10n.repeater_cliHelpSetBridgeSecret, ), _CommandHelpEntry( command: 'set bridge.channel {1-14}', description: l10n.repeater_cliHelpSetBridgeChannel, ), - ]; - - final bridgeCommands = [ + _CommandHelpEntry( + command: 'get bridge.enabled', + description: l10n.repeater_cliHelpGetBridgeEnabled, + ), + _CommandHelpEntry( + command: 'get bridge.delay', + description: l10n.repeater_cliHelpGetBridgeDelay, + ), + _CommandHelpEntry( + command: 'get bridge.source', + description: l10n.repeater_cliHelpGetBridgeSource, + ), + _CommandHelpEntry( + command: 'get bridge.baud', + description: l10n.repeater_cliHelpGetBridgeBaud, + ), + _CommandHelpEntry( + command: 'get bridge.channel', + description: l10n.repeater_cliHelpGetBridgeChannel, + ), + _CommandHelpEntry( + command: 'get bridge.secret', + description: l10n.repeater_cliHelpGetBridgeSecret, + ), _CommandHelpEntry( command: 'get bridge.type', description: l10n.repeater_cliHelpGetBridgeType, @@ -808,6 +909,10 @@ class _RepeaterCliScreenState extends State { command: 'region load', description: l10n.repeater_cliHelpRegionLoad, ), + _CommandHelpEntry( + command: 'region def {name}[,{jump-prefix}] ...', + description: l10n.repeater_cliHelpRegionDef, + ), _CommandHelpEntry( command: 'region get {* | name-prefix}', description: l10n.repeater_cliHelpRegionGet, @@ -871,10 +976,6 @@ class _RepeaterCliScreenState extends State { command: 'get public.key', description: l10n.repeater_cliHelpGetPublicKey, ), - _CommandHelpEntry( - command: 'get prv.key', - description: l10n.repeater_cliHelpGetPrvKey, - ), _CommandHelpEntry( command: 'get repeat', description: l10n.repeater_cliHelpGetRepeat, @@ -895,6 +996,14 @@ class _RepeaterCliScreenState extends State { command: 'get radio.rxgain', description: l10n.repeater_cliHelpGetRadioRxGain, ), + _CommandHelpEntry( + command: 'get radio.fem.rxgain', + description: l10n.repeater_cliHelpGetRadioFemRxGain, + ), + _CommandHelpEntry( + command: 'get radio.fem.txgain', + description: l10n.repeater_cliHelpGetRadioFemTxGain, + ), _CommandHelpEntry( command: 'get af', description: l10n.repeater_cliHelpGetAf, @@ -955,6 +1064,14 @@ class _RepeaterCliScreenState extends State { command: 'get flood.max', description: l10n.repeater_cliHelpGetFloodMax, ), + _CommandHelpEntry( + command: 'get flood.max.unscoped', + description: l10n.repeater_cliHelpGetFloodMaxUnscoped, + ), + _CommandHelpEntry( + command: 'get flood.max.advert', + description: l10n.repeater_cliHelpGetFloodMaxAdvert, + ), _CommandHelpEntry( command: 'get owner.info', description: l10n.repeater_cliHelpGetOwnerInfo, @@ -967,34 +1084,6 @@ class _RepeaterCliScreenState extends State { command: 'get loop.detect', description: l10n.repeater_cliHelpGetLoopDetect, ), - _CommandHelpEntry( - command: 'get acl', - description: l10n.repeater_cliHelpGetAcl, - ), - _CommandHelpEntry( - command: 'get bridge.enabled', - description: l10n.repeater_cliHelpGetBridgeEnabled, - ), - _CommandHelpEntry( - command: 'get bridge.delay', - description: l10n.repeater_cliHelpGetBridgeDelay, - ), - _CommandHelpEntry( - command: 'get bridge.source', - description: l10n.repeater_cliHelpGetBridgeSource, - ), - _CommandHelpEntry( - command: 'get bridge.baud', - description: l10n.repeater_cliHelpGetBridgeBaud, - ), - _CommandHelpEntry( - command: 'get bridge.channel', - description: l10n.repeater_cliHelpGetBridgeChannel, - ), - _CommandHelpEntry( - command: 'get bridge.secret', - description: l10n.repeater_cliHelpGetBridgeSecret, - ), _CommandHelpEntry( command: 'get bootloader.ver', description: l10n.repeater_cliHelpGetBootloaderVer, @@ -1103,7 +1192,12 @@ class _RepeaterCliScreenState extends State { const SizedBox(height: 16), _buildHelpSection(context, l10n.repeater_sensors, sensorCommands), const SizedBox(height: 16), - _buildHelpSection(context, l10n.repeater_bridge, bridgeCommands), + _buildHelpSection( + context, + l10n.repeater_bridge, + bridgeCommands, + note: l10n.repeater_bridgeNote, + ), const SizedBox(height: 16), _buildHelpSection( context, diff --git a/lib/screens/repeater_hub_screen.dart b/lib/screens/repeater_hub_screen.dart index ab15e01e..324cd231 100644 --- a/lib/screens/repeater_hub_screen.dart +++ b/lib/screens/repeater_hub_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; @@ -31,6 +32,7 @@ class RepeaterHubScreen extends StatelessWidget { final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final settingsService = context.watch(); + final connector = context.watch(); final chemistry = settingsService.batteryChemistryForRepeater( repeater.publicKeyHex, ); @@ -85,7 +87,10 @@ class RepeaterHubScreen extends StatelessWidget { ), const SizedBox(height: 4), Text( - repeater.pathLabel(l10n), + repeater.pathLabel( + l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), style: Theme.of(context).textTheme.bodySmall ?.copyWith(color: scheme.onSurfaceVariant), ), @@ -117,7 +122,9 @@ class RepeaterHubScreen extends StatelessWidget { ), ), StatusChip( - label: isAdmin ? 'ADMIN' : 'GUEST', + label: isAdmin + ? l10n.repeater_roleAdmin + : l10n.repeater_roleGuest, color: isAdmin ? MeshPalette.blue : scheme.onSurfaceVariant, @@ -160,6 +167,10 @@ class RepeaterHubScreen extends StatelessWidget { value: 'lipo', child: Text(l10n.appSettings_batteryLipo), ), + DropdownMenuItem( + value: 'lipo_hv', + child: Text(l10n.appSettings_batteryLipoHv), + ), ], ), ), @@ -209,23 +220,26 @@ class RepeaterHubScreen extends StatelessWidget { }, ), - _HubActionTile( - index: 2, - icon: Icons.group, - title: l10n.repeater_neighbors, - subtitle: l10n.repeater_neighborsSubtitle, - accentColor: MeshPalette.signal, - onTap: () { - HapticFeedback.selectionClick(); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - NeighborsScreen(repeater: repeater, password: password), - ), - ); - }, - ), + if (repeater.type != advTypeRoom) + _HubActionTile( + index: 2, + icon: Icons.group, + title: l10n.repeater_neighbors, + subtitle: l10n.repeater_neighborsSubtitle, + accentColor: MeshPalette.signal, + onTap: () { + HapticFeedback.selectionClick(); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => NeighborsScreen( + repeater: repeater, + password: password, + ), + ), + ); + }, + ), if (isAdmin) ...[ _HubActionTile( @@ -296,46 +310,53 @@ class _HubActionTile extends StatelessWidget { final scheme = Theme.of(context).colorScheme; return ListEntrance( index: index, - child: MeshCard( - onTap: onTap, - child: Row( - children: [ - Container( - width: 44, - height: 44, - decoration: BoxDecoration( - color: accentColor.withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(MeshRadii.md), - border: Border.all(color: accentColor.withValues(alpha: 0.3)), + child: Semantics( + button: true, + child: MeshCard( + onTap: onTap, + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: accentColor.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(MeshRadii.md), + border: Border.all(color: accentColor.withValues(alpha: 0.3)), + ), + alignment: Alignment.center, + child: Icon(icon, size: 22, color: accentColor), ), - alignment: Alignment.center, - child: Icon(icon, size: 22, color: accentColor), - ), - const SizedBox(width: 14), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - style: const TextStyle( - fontWeight: FontWeight.w600, - fontSize: 15, + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 15, + ), ), - ), - const SizedBox(height: 2), - Text( - subtitle, - style: TextStyle( - fontSize: 12.5, - color: scheme.onSurfaceVariant, + const SizedBox(height: 2), + Text( + subtitle, + style: TextStyle( + fontSize: 12.5, + color: scheme.onSurfaceVariant, + ), ), - ), - ], + ], + ), ), - ), - Icon(Icons.chevron_right, color: scheme.onSurfaceVariant, size: 20), - ], + Icon( + Icons.chevron_right, + color: scheme.onSurfaceVariant, + size: 20, + ), + ], + ), ), ), ); diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index dca0d7f4..47127041 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -1,16 +1,19 @@ import 'dart:async'; -import 'dart:typed_data'; +import 'dart:math'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +import '../helpers/utf8_length_limiter.dart'; import '../services/repeater_command_service.dart'; import '../services/storage_service.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/routing_sheet.dart'; +import '../utils/keys.dart'; import '../helpers/snack_bar_builder.dart'; class RepeaterSettingsScreen extends StatefulWidget { @@ -44,6 +47,7 @@ enum _SettingField { advertInterval, floodAdvertInterval, pathHashMode, + prvKey, txDelay, directTxDelay, intThresh, @@ -109,6 +113,12 @@ class _RepeaterSettingsScreenState extends State { bool _refreshingIntThresh = false; bool _refreshingAgcResetInterval = false; bool _runningAction = false; + bool _loadingAll = false; + int _unansweredSections = 0; + double _loadAllProgress = 0; + final Set _loadedKeys = {}; + bool _searchingForKeyPair = false; + bool _stopSearchingForKeyPair = false; StreamSubscription? _frameSubscription; RepeaterCommandService? _commandService; @@ -154,6 +164,11 @@ class _RepeaterSettingsScreenState extends State { // Advanced int _pathHashMode = 0; // 0-2 + final TextEditingController _prvKeyController = TextEditingController(); + final TextEditingController _pubKeyController = TextEditingController(); + final TextEditingController _prvKeyPrefixController = TextEditingController(); + final KeyPairSearcher _keyPairSearcher = KeyPairSearcher(); + final int _searchChunkTime = 30; // time in ms to search before yielding final TextEditingController _txDelayController = TextEditingController(); final TextEditingController _directTxDelayController = TextEditingController(); @@ -181,6 +196,13 @@ class _RepeaterSettingsScreenState extends State { ]; final List _spreadingFactorOptions = [5, 6, 7, 8, 9, 10, 11, 12]; final List _codingRateOptions = [5, 6, 7, 8]; + static const int _minRepeaterTxPower = -9; + static const int _maxRepeaterTxPower = 30; + // CommonCLI.h: password[16], node_name[32], owner_info[120]. + static const int _maxPasswordBytes = 15; + static const int _maxNameBytes = 31; + static const int _maxOwnerInfoBytes = 119; + static const int _maxAgcResetInterval = 255 * 4; @override void initState() { @@ -206,6 +228,10 @@ class _RepeaterSettingsScreenState extends State { _txDelayController.dispose(); _directTxDelayController.dispose(); _intThreshController.dispose(); + _prvKeyController.dispose(); + _pubKeyController.dispose(); + _prvKeyPrefixController.dispose(); + _stopSearchingForKeyPair = true; super.dispose(); } @@ -273,7 +299,7 @@ class _RepeaterSettingsScreenState extends State { break; case 'tx': final dbm = int.tryParse(value.replaceAll(RegExp(r'[^0-9-]'), '')); - if (dbm != null && dbm >= 1 && dbm <= 30) { + if (dbm != null && dbm >= -128 && dbm <= 127) { _txPowerController.text = dbm.toString(); } break; @@ -350,7 +376,9 @@ class _RepeaterSettingsScreenState extends State { break; case 'agc.reset.interval': final v = int.tryParse(value.trim()); - if (v != null && v >= 0) _agcResetInterval = v; + if (v != null && v >= 0) { + _agcResetInterval = v.clamp(0, _maxAgcResetInterval); + } break; } } @@ -374,10 +402,18 @@ class _RepeaterSettingsScreenState extends State { } } if (parts.length > 2) { - _spreadingFactor = int.tryParse(parts[2].trim()) ?? _spreadingFactor; + final sf = int.tryParse(parts[2].trim()); + if (sf != null && _spreadingFactorOptions.contains(sf)) { + _spreadingFactor = sf; + } } if (parts.length > 3) { - _codingRate = int.tryParse(parts[3].trim()) ?? _codingRate; + final cr = int.tryParse(parts[3].trim()); + // Some firmware reports CR as 1-4 instead of 5-8. + final uiCr = cr != null && cr <= 4 ? cr + 4 : cr; + if (uiCr != null && _codingRateOptions.contains(uiCr)) { + _codingRate = uiCr; + } } } @@ -409,10 +445,15 @@ class _RepeaterSettingsScreenState extends State { final key = normalized.substring(4).trim(); final value = _extractGetValue(response); if (value == null) return false; - setState(() => _applyGetValue(key, value)); + setState(() { + _applyGetValue(key, value); + _loadedKeys.add(key); + }); return true; } + bool _loaded(String key) => _loadedKeys.contains(key); + /// Firmware GET replies are always `> ` (CommonCLI.cpp `sprintf(reply, "> %s", ...)`). /// Returns the first such value, trimmed; null if none found. String? _extractGetValue(String response) { @@ -437,6 +478,7 @@ class _RepeaterSettingsScreenState extends State { setState(() => setRefreshing(true)); var successCount = 0; + var answered = false; final connector = Provider.of(context, listen: false); final repeater = _resolveRepeater(connector); for (final command in commands) { @@ -446,14 +488,22 @@ class _RepeaterSettingsScreenState extends State { command, retries: 1, ); + if (!mounted) return; + answered = true; if (_handleGetResponse(command, response)) successCount += 1; await Future.delayed(const Duration(milliseconds: 200)); } catch (e) { debugPrint('Error fetching $command: $e'); } + if (!mounted) return; } - if (mounted) { + if (_loadingAll) { + // A reply we can't use usually means older firmware without that + // setting; only a section that never answered counts as a failure. + if (!answered) _unansweredSections += 1; + setState(() => setRefreshing(false)); + } else { showDismissibleSnackBar( context, content: Text( @@ -688,9 +738,52 @@ class _RepeaterSettingsScreenState extends State { } } + Future _refreshAll() async { + if (_loadingAll) return; + final sections = Function()>[ + _refreshBasicSettings, + _refreshRadioSettings, + _refreshTxPower, + _refreshRxGain, + _refreshLat, + _refreshLon, + _refreshRepeat, + _refreshAllowReadOnly, + _refreshMultiAcks, + _refreshLoopDetect, + _refreshDutyCycle, + _refreshAdvertInterval, + _refreshFloodAdvertInterval, + _refreshFloodMax, + _refreshOwnerInfo, + _refreshPathHashMode, + _refreshTxDelay, + _refreshDirectTxDelay, + _refreshIntThresh, + _refreshAgcResetInterval, + ]; + _unansweredSections = 0; + setState(() { + _loadingAll = true; + _loadAllProgress = 0; + }); + for (var i = 0; i < sections.length; i++) { + if (!mounted) return; + await sections[i](); + if (!mounted) return; + setState(() => _loadAllProgress = (i + 1) / sections.length); + } + setState(() => _loadingAll = false); + if (_unansweredSections > 0) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.repeater_settingsLoadIncomplete), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + } + Future _loadSettings() async { - // Just populate with current repeater data on initial load - // User must click sync button to fetch from device setState(() { _nameController.text = widget.repeater.name; @@ -720,11 +813,18 @@ class _RepeaterSettingsScreenState extends State { }); try { + final l10n = context.l10n; // Each pending command remembers the dirty-field it came from (null for // password commands, which always re-send when text is present). On // failure we keep that field in `_dirtyFields` so the Save button stays // available and the user can retry. final pending = <({_SettingField? field, String command})>[]; + final failures = []; + final retainDirty = <_SettingField>{}; + void reject(_SettingField field, String message) { + failures.add(message); + retainDirty.add(field); + } if (_dirtyFields.contains(_SettingField.name) && _nameController.text.isNotEmpty) { @@ -754,9 +854,24 @@ class _RepeaterSettingsScreenState extends State { _bandwidth != null && _spreadingFactor != null && _codingRate != null) { - final freqText = _freqController.text.trim(); - if (double.tryParse(freqText) != null) { - final bwKHz = _bandwidth! / 1000; + final freqText = _normalizeDecimal(_freqController.text); + final freq = double.tryParse(freqText); + final bwKHz = _bandwidth! / 1000; + 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'); + } else if (_spreadingFactor! < 5 || _spreadingFactor! > 12) { + reject( + _SettingField.radio, + '${l10n.repeater_spreadingFactor}: $_spreadingFactor', + ); + } else if (_codingRate! < 5 || _codingRate! > 8) { + reject( + _SettingField.radio, + '${l10n.repeater_codingRate}: $_codingRate', + ); + } else { pending.add(( field: _SettingField.radio, command: @@ -768,26 +883,46 @@ class _RepeaterSettingsScreenState extends State { if (_dirtyFields.contains(_SettingField.txPower) && _txPowerController.text.isNotEmpty) { final dbm = int.tryParse(_txPowerController.text.trim()); - if (dbm != null) { + if (dbm == null || + dbm < _minRepeaterTxPower || + dbm > _maxRepeaterTxPower) { + reject( + _SettingField.txPower, + '${l10n.repeater_txPower}: ${_txPowerController.text.trim()} ' + '($_minRepeaterTxPower-$_maxRepeaterTxPower dBm)', + ); + } else { pending.add((field: _SettingField.txPower, command: 'set tx $dbm')); } } if (_dirtyFields.contains(_SettingField.lat) && - _latController.text.isNotEmpty && - _isValidCoordinate(_latController.text, 90)) { - pending.add(( - field: _SettingField.lat, - command: 'set lat ${_latController.text}', - )); + _latController.text.isNotEmpty) { + if (_isValidCoordinate(_latController.text, 90)) { + pending.add(( + field: _SettingField.lat, + command: 'set lat ${_normalizeDecimal(_latController.text)}', + )); + } else { + reject( + _SettingField.lat, + '${l10n.repeater_latitude}: ${_latController.text.trim()}', + ); + } } if (_dirtyFields.contains(_SettingField.lon) && - _lonController.text.isNotEmpty && - _isValidCoordinate(_lonController.text, 180)) { - pending.add(( - field: _SettingField.lon, - command: 'set lon ${_lonController.text}', - )); + _lonController.text.isNotEmpty) { + if (_isValidCoordinate(_lonController.text, 180)) { + pending.add(( + field: _SettingField.lon, + command: 'set lon ${_normalizeDecimal(_lonController.text)}', + )); + } else { + reject( + _SettingField.lon, + '${l10n.repeater_longitude}: ${_lonController.text.trim()}', + ); + } } if (_dirtyFields.contains(_SettingField.repeat)) { @@ -860,34 +995,58 @@ class _RepeaterSettingsScreenState extends State { command: 'set path.hash.mode $_pathHashMode', )); } + if (_dirtyFields.contains(_SettingField.prvKey)) { + final v = _prvKeyController.text.trim(); + if (v != "") { + pending.add((field: _SettingField.prvKey, command: 'set prv.key $v')); + } + } if (_dirtyFields.contains(_SettingField.txDelay) && _txDelayController.text.isNotEmpty) { - final v = double.tryParse(_txDelayController.text.trim()); + final v = double.tryParse(_normalizeDecimal(_txDelayController.text)); if (v != null) { pending.add(( field: _SettingField.txDelay, command: 'set txdelay $v', )); + } else { + reject( + _SettingField.txDelay, + '${l10n.repeater_txDelay}: ${_txDelayController.text.trim()}', + ); } } if (_dirtyFields.contains(_SettingField.directTxDelay) && _directTxDelayController.text.isNotEmpty) { - final v = double.tryParse(_directTxDelayController.text.trim()); + final v = double.tryParse( + _normalizeDecimal(_directTxDelayController.text), + ); if (v != null) { pending.add(( field: _SettingField.directTxDelay, command: 'set direct.txdelay $v', )); + } else { + reject( + _SettingField.directTxDelay, + '${l10n.repeater_directTxDelay}: ' + '${_directTxDelayController.text.trim()}', + ); } } if (_dirtyFields.contains(_SettingField.intThresh) && _intThreshController.text.isNotEmpty) { final v = int.tryParse(_intThreshController.text.trim()); - if (v != null) { + if (v != null && v >= 0 && v <= 255) { pending.add(( field: _SettingField.intThresh, command: 'set int.thresh $v', )); + } else { + reject( + _SettingField.intThresh, + '${l10n.repeater_intThresh}: ${_intThreshController.text.trim()}', + ); } } if (_dirtyFields.contains(_SettingField.agcResetInterval)) { @@ -897,8 +1056,6 @@ class _RepeaterSettingsScreenState extends State { )); } - final failures = []; - final retainDirty = <_SettingField>{}; var passwordsFailed = false; var rebootNeeded = false; for (final entry in pending) { @@ -931,6 +1088,7 @@ class _RepeaterSettingsScreenState extends State { } await Future.delayed(const Duration(milliseconds: 200)); } + if (!mounted) return; // Only clear password fields if every password command succeeded — // otherwise the user keeps their typed value to retry. @@ -947,7 +1105,6 @@ class _RepeaterSettingsScreenState extends State { }); if (mounted) { - final l10n = context.l10n; if (failures.isEmpty && rebootNeeded) { showDismissibleSnackBar( context, @@ -970,11 +1127,10 @@ class _RepeaterSettingsScreenState extends State { } } } catch (e) { - setState(() { - _isLoading = false; - }); - if (mounted) { + setState(() { + _isLoading = false; + }); showDismissibleSnackBar( context, content: Text( @@ -991,9 +1147,12 @@ class _RepeaterSettingsScreenState extends State { _flagHasChanges(); } + static String _normalizeDecimal(String text) => + text.trim().replaceAll(',', '.'); + static bool _isValidCoordinate(String text, double max) { if (text.trim().isEmpty) return true; - final value = double.tryParse(text.trim()); + final value = double.tryParse(_normalizeDecimal(text)); return value != null && value >= -max && value <= max; } @@ -1005,6 +1164,36 @@ class _RepeaterSettingsScreenState extends State { } } + void _startSearchingForKeyPair() async { + if (_searchingForKeyPair) return; + setState(() { + _searchingForKeyPair = true; + _stopSearchingForKeyPair = false; + }); + _searchForKeyPair(); + } + + void _searchForKeyPair() async { + if (_stopSearchingForKeyPair) { + if (mounted) setState(() => _searchingForKeyPair = false); + return; + } + final String prefix = _prvKeyPrefixController.text.trim(); + MCKeyPair? keys = await _keyPairSearcher.findMatchingKeyPair( + prefix, + _searchChunkTime, + ); + if (keys == null) { + // Ran out of time; schedule another attempt. + Timer.run(_searchForKeyPair); + } else { + setState(() => _searchingForKeyPair = false); + _prvKeyController.text = pubKeyToHex(keys.private); + _pubKeyController.text = pubKeyToHex(keys.public); + _markChanged(_SettingField.prvKey); + } + } + Widget _buildInlineRefreshButton({ required bool isRefreshing, required VoidCallback onRefresh, @@ -1045,13 +1234,24 @@ class _RepeaterSettingsScreenState extends State { 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 ? null : _saveSettings, + onPressed: _isLoading || _loadingAll ? 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, @@ -1060,6 +1260,27 @@ class _RepeaterSettingsScreenState extends State { : 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, + ), + ), + TextButton( + onPressed: _isLoading ? null : _refreshAll, + child: Text(context.l10n.repeater_refreshAll), + ), + ], + ), + ), + ), _buildBasicSettingsCard(), _buildRadioSettingsCard(), _buildLocationSettingsCard(), @@ -1069,6 +1290,7 @@ class _RepeaterSettingsScreenState extends State { _buildOwnerInfoCard(), _buildActionsCard(), _buildAdvancedCard(), + _buildKeysCard(), const SizedBox(height: 16), _buildDangerZoneCard(), ], @@ -1102,10 +1324,14 @@ class _RepeaterSettingsScreenState extends State { children: [ TextField( controller: _nameController, + enabled: _loaded('name'), decoration: InputDecoration( labelText: l10n.repeater_repeaterName, helperText: l10n.repeater_repeaterNameHelper, ), + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(_maxNameBytes), + ], onChanged: (_) => _markChanged(_SettingField.name), ), const SizedBox(height: 12), @@ -1116,6 +1342,9 @@ class _RepeaterSettingsScreenState extends State { helperText: l10n.repeater_adminPasswordHelper, ), obscureText: true, + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(_maxPasswordBytes), + ], onChanged: (_) => _flagHasChanges(), ), const SizedBox(height: 12), @@ -1126,6 +1355,9 @@ class _RepeaterSettingsScreenState extends State { helperText: l10n.repeater_guestPasswordHelper, ), obscureText: true, + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(_maxPasswordBytes), + ], onChanged: (_) => _flagHasChanges(), ), ], @@ -1160,9 +1392,10 @@ class _RepeaterSettingsScreenState extends State { children: [ TextField( controller: _freqController, + enabled: _loaded('radio'), decoration: InputDecoration( labelText: l10n.repeater_frequencyMhz, - helperText: l10n.repeater_frequencyHelper, + helperText: l10n.repeater_frequencyRangeHelper, suffixText: 'MHz', ), keyboardType: const TextInputType.numberWithOptions( @@ -1177,12 +1410,15 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _txPowerController, + enabled: _loaded('tx'), decoration: InputDecoration( labelText: l10n.repeater_txPower, - helperText: l10n.repeater_txPowerHelper, + helperText: l10n.repeater_txPowerRangeHelper, suffixText: 'dBm', ), - keyboardType: TextInputType.number, + keyboardType: const TextInputType.numberWithOptions( + signed: true, + ), onChanged: (_) => _markChanged(_SettingField.txPower), ), ), @@ -1203,14 +1439,16 @@ class _RepeaterSettingsScreenState extends State { child: Text(_formatBandwidthLabel(bw)), ); }).toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _bandwidth = value; - }); - _markChanged(_SettingField.radio); - } - }, + onChanged: !_loaded('radio') + ? null + : (value) { + if (value != null) { + setState(() { + _bandwidth = value; + }); + _markChanged(_SettingField.radio); + } + }, ), const SizedBox(height: 12), DropdownButtonFormField( @@ -1221,14 +1459,16 @@ class _RepeaterSettingsScreenState extends State { items: _spreadingFactorOptions.map((sf) { return DropdownMenuItem(value: sf, child: Text('SF$sf')); }).toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _spreadingFactor = value; - }); - _markChanged(_SettingField.radio); - } - }, + onChanged: !_loaded('radio') + ? null + : (value) { + if (value != null) { + setState(() { + _spreadingFactor = value; + }); + _markChanged(_SettingField.radio); + } + }, ), const SizedBox(height: 12), DropdownButtonFormField( @@ -1239,20 +1479,23 @@ class _RepeaterSettingsScreenState extends State { items: _codingRateOptions.map((cr) { return DropdownMenuItem(value: cr, child: Text('4/$cr')); }).toList(), - onChanged: (value) { - if (value != null) { - setState(() { - _codingRate = value; - }); - _markChanged(_SettingField.radio); - } - }, + onChanged: !_loaded('radio') + ? null + : (value) { + if (value != null) { + setState(() { + _codingRate = value; + }); + _markChanged(_SettingField.radio); + } + }, ), const SizedBox(height: 4), _buildFeatureToggleRow( title: l10n.repeater_rxGain, subtitle: l10n.repeater_rxGainHelper, value: _rxGainBoosted, + loaded: _loaded('radio.rxgain'), isRefreshing: _refreshingRxGain, onChanged: (v) { setState(() => _rxGainBoosted = v); @@ -1284,6 +1527,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _latController, + enabled: _loaded('lat'), decoration: InputDecoration( labelText: l10n.repeater_latitude, helperText: l10n.repeater_latitudeHelper, @@ -1318,6 +1562,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _lonController, + enabled: _loaded('lon'), decoration: InputDecoration( labelText: l10n.repeater_longitude, helperText: l10n.repeater_longitudeHelper, @@ -1366,6 +1611,7 @@ class _RepeaterSettingsScreenState extends State { title: l10n.repeater_packetForwarding, subtitle: l10n.repeater_packetForwardingSubtitle, value: _repeatEnabled, + loaded: _loaded('repeat'), isRefreshing: _refreshingRepeat, onChanged: (value) { setState(() { @@ -1380,6 +1626,7 @@ class _RepeaterSettingsScreenState extends State { title: l10n.repeater_guestAccess, subtitle: l10n.repeater_guestAccessSubtitle, value: _allowReadOnly, + loaded: _loaded('allow.read.only'), isRefreshing: _refreshingAllowReadOnly, onChanged: (value) { setState(() { @@ -1394,6 +1641,7 @@ class _RepeaterSettingsScreenState extends State { title: l10n.repeater_multiAcks, subtitle: l10n.repeater_multiAcksSubtitle, value: _multiAcks, + loaded: _loaded('multi.acks'), isRefreshing: _refreshingMultiAcks, onChanged: (v) { setState(() => _multiAcks = v); @@ -1428,6 +1676,7 @@ class _RepeaterSettingsScreenState extends State { required String title, required String subtitle, required bool value, + required bool loaded, required bool isRefreshing, required ValueChanged onChanged, required VoidCallback onRefresh, @@ -1439,8 +1688,8 @@ class _RepeaterSettingsScreenState extends State { child: SwitchListTile( title: Text(title), subtitle: Text(subtitle), - value: value, - onChanged: onChanged, + value: loaded && value, + onChanged: loaded ? onChanged : null, contentPadding: EdgeInsets.zero, ), ), @@ -1476,19 +1725,23 @@ class _RepeaterSettingsScreenState extends State { child: ListTile( title: Text(l10n.repeater_localAdvertInterval), subtitle: Text( - l10n.repeater_localAdvertIntervalMinutes( - _advertInterval, - ), + _loaded('advert.interval') + ? l10n.repeater_localAdvertIntervalMinutes( + _advertInterval, + ) + : '—', ), trailing: Switch( - value: _advertEnable, - onChanged: (value) { - setState(() { - _advertInterval = value ? 60 : 0; - _advertEnable = value; - }); - _markChanged(_SettingField.advertInterval); - }, + value: _loaded('advert.interval') && _advertEnable, + onChanged: !_loaded('advert.interval') + ? null + : (value) { + setState(() { + _advertInterval = value ? 60 : 0; + _advertEnable = value; + }); + _markChanged(_SettingField.advertInterval); + }, ), contentPadding: EdgeInsets.zero, ), @@ -1510,16 +1763,14 @@ class _RepeaterSettingsScreenState extends State { ], ), Slider( - value: _advertInterval == 0 - ? 60.toDouble() - : _advertInterval.toDouble(), + value: _advertInterval.clamp(60, 240).toDouble(), min: 60, max: 240, divisions: 18, label: l10n.repeater_localAdvertIntervalMinutes( _advertInterval, ), - onChanged: _advertEnable + onChanged: _advertEnable && _loaded('advert.interval') ? (value) { setState(() { _advertInterval = value.toInt(); @@ -1535,19 +1786,25 @@ class _RepeaterSettingsScreenState extends State { child: ListTile( title: Text(l10n.repeater_floodAdvertInterval), subtitle: Text( - l10n.repeater_floodAdvertIntervalHours( - _floodAdvertInterval, - ), + _loaded('flood.advert.interval') + ? l10n.repeater_floodAdvertIntervalHours( + _floodAdvertInterval, + ) + : '—', ), trailing: Switch( - value: _floodAdvertEnable, - onChanged: (value) { - setState(() { - _floodAdvertInterval = value ? 3 : 0; - _floodAdvertEnable = value; - }); - _markChanged(_SettingField.floodAdvertInterval); - }, + value: + _loaded('flood.advert.interval') && + _floodAdvertEnable, + onChanged: !_loaded('flood.advert.interval') + ? null + : (value) { + setState(() { + _floodAdvertInterval = value ? 3 : 0; + _floodAdvertEnable = value; + }); + _markChanged(_SettingField.floodAdvertInterval); + }, ), contentPadding: EdgeInsets.zero, ), @@ -1569,16 +1826,15 @@ class _RepeaterSettingsScreenState extends State { ], ), Slider( - value: _floodAdvertInterval == 0 - ? 3.toDouble() - : _floodAdvertInterval.toDouble(), + value: _floodAdvertInterval.clamp(3, 168).toDouble(), min: 3, max: 168, divisions: 165, label: l10n.repeater_floodAdvertIntervalHours( _floodAdvertInterval, ), - onChanged: _floodAdvertEnable + onChanged: + _floodAdvertEnable && _loaded('flood.advert.interval') ? (value) { setState(() { _floodAdvertInterval = value.toInt(); @@ -1595,7 +1851,7 @@ class _RepeaterSettingsScreenState extends State { title: Text(l10n.repeater_floodMax), subtitle: Text(l10n.repeater_floodMaxHelper), trailing: Text( - '$_floodMax', + _loaded('flood.max') ? '$_floodMax' : '—', style: const TextStyle(fontWeight: FontWeight.bold), ), contentPadding: EdgeInsets.zero, @@ -1621,10 +1877,12 @@ class _RepeaterSettingsScreenState extends State { max: 64, divisions: 64, label: '$_floodMax', - onChanged: (v) { - setState(() => _floodMax = v.toInt()); - _markChanged(_SettingField.floodMax); - }, + onChanged: !_loaded('flood.max') + ? null + : (v) { + setState(() => _floodMax = v.toInt()); + _markChanged(_SettingField.floodMax); + }, ), ], ), @@ -1648,7 +1906,7 @@ class _RepeaterSettingsScreenState extends State { children: [ Expanded( child: DropdownButtonFormField( - initialValue: _loopDetect, + initialValue: _loaded('loop.detect') ? _loopDetect : null, decoration: InputDecoration( labelText: l10n.repeater_loopDetect, helperText: l10n.repeater_loopDetectHelper, @@ -1672,12 +1930,14 @@ class _RepeaterSettingsScreenState extends State { child: Text(l10n.repeater_loopDetectStrict), ), ], - onChanged: (v) { - if (v != null) { - setState(() => _loopDetect = v); - _markChanged(_SettingField.loopDetect); - } - }, + onChanged: !_loaded('loop.detect') + ? null + : (v) { + if (v != null) { + setState(() => _loopDetect = v); + _markChanged(_SettingField.loopDetect); + } + }, ), ), _buildInlineRefreshButton( @@ -1695,7 +1955,9 @@ class _RepeaterSettingsScreenState extends State { title: Text(l10n.repeater_dutyCycle), subtitle: Text(l10n.repeater_dutyCycleHelper), trailing: Text( - l10n.repeater_dutyCyclePercent(_dutyCycle), + _loaded('dutycycle') + ? l10n.repeater_dutyCyclePercent(_dutyCycle) + : '—', style: const TextStyle(fontWeight: FontWeight.bold), ), contentPadding: EdgeInsets.zero, @@ -1721,10 +1983,12 @@ class _RepeaterSettingsScreenState extends State { max: 100, divisions: 99, label: l10n.repeater_dutyCyclePercent(_dutyCycle), - onChanged: (v) { - setState(() => _dutyCycle = v.toInt()); - _markChanged(_SettingField.dutyCycle); - }, + onChanged: !_loaded('dutycycle') + ? null + : (v) { + setState(() => _dutyCycle = v.toInt()); + _markChanged(_SettingField.dutyCycle); + }, ), ], ), @@ -1755,6 +2019,7 @@ class _RepeaterSettingsScreenState extends State { MeshCard( child: TextField( controller: _ownerInfoController, + enabled: _loaded('owner.info'), decoration: InputDecoration( labelText: l10n.repeater_ownerInfo, helperText: l10n.repeater_ownerInfoHelper, @@ -1762,6 +2027,9 @@ class _RepeaterSettingsScreenState extends State { ), maxLines: 4, minLines: 2, + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(_maxOwnerInfoBytes), + ], onChanged: (_) => _markChanged(_SettingField.ownerInfo), ), ), @@ -1836,23 +2104,36 @@ class _RepeaterSettingsScreenState extends State { children: [ Expanded( child: DropdownButtonFormField( - initialValue: _pathHashMode, + initialValue: _loaded('path.hash.mode') + ? _pathHashMode + : null, decoration: InputDecoration( labelText: l10n.repeater_pathHashMode, helperText: l10n.repeater_pathHashModeHelper, helperMaxLines: 5, ), - items: const [ - DropdownMenuItem(value: 0, child: Text('0')), - DropdownMenuItem(value: 1, child: Text('1')), - DropdownMenuItem(value: 2, child: Text('2')), + items: [ + DropdownMenuItem( + value: 0, + child: Text(l10n.repeater_pathHashModeOption0), + ), + DropdownMenuItem( + value: 1, + child: Text(l10n.repeater_pathHashModeOption1), + ), + DropdownMenuItem( + value: 2, + child: Text(l10n.repeater_pathHashModeOption2), + ), ], - onChanged: (v) { - if (v != null) { - setState(() => _pathHashMode = v); - _markChanged(_SettingField.pathHashMode); - } - }, + onChanged: !_loaded('path.hash.mode') + ? null + : (v) { + if (v != null) { + setState(() => _pathHashMode = v); + _markChanged(_SettingField.pathHashMode); + } + }, ), ), _buildInlineRefreshButton( @@ -1869,6 +2150,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _txDelayController, + enabled: _loaded('txdelay'), decoration: InputDecoration( labelText: l10n.repeater_txDelay, helperText: l10n.repeater_txDelayHelper, @@ -1894,6 +2176,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _directTxDelayController, + enabled: _loaded('direct.txdelay'), decoration: InputDecoration( labelText: l10n.repeater_directTxDelay, helperText: l10n.repeater_directTxDelayHelper, @@ -1919,6 +2202,7 @@ class _RepeaterSettingsScreenState extends State { Expanded( child: TextField( controller: _intThreshController, + enabled: _loaded('int.thresh'), decoration: InputDecoration( labelText: l10n.repeater_intThresh, helperText: l10n.repeater_intThreshHelper, @@ -1943,7 +2227,9 @@ class _RepeaterSettingsScreenState extends State { title: Text(l10n.repeater_agcResetInterval), subtitle: Text(l10n.repeater_agcResetIntervalHelper), trailing: Text( - '${_agcResetInterval}s', + _loaded('agc.reset.interval') + ? '${_agcResetInterval}s' + : '—', style: const TextStyle(fontWeight: FontWeight.bold), ), contentPadding: EdgeInsets.zero, @@ -1966,18 +2252,141 @@ class _RepeaterSettingsScreenState extends State { ], ), Slider( - value: _agcResetInterval.toDouble(), + value: _agcResetInterval.clamp(0, _maxAgcResetInterval).toDouble(), min: 0, - max: 240, - divisions: 60, + max: _maxAgcResetInterval.toDouble(), + divisions: _maxAgcResetInterval ~/ 4, label: '${_agcResetInterval}s', - onChanged: (v) { - setState(() { - // Clamp to multiple of 4 to match firmware semantics. - _agcResetInterval = (v.toInt() ~/ 4) * 4; - }); - _markChanged(_SettingField.agcResetInterval); - }, + onChanged: !_loaded('agc.reset.interval') + ? null + : (v) { + setState(() { + // Clamp to multiple of 4 to match firmware semantics. + _agcResetInterval = (v.toInt() ~/ 4) * 4; + }); + _markChanged(_SettingField.agcResetInterval); + }, + ), + ], + ), + ); + } + + Widget _buildKeysCard() { + final l10n = context.l10n; + return MeshCard( + child: ExpansionTile( + leading: const Icon(Icons.vpn_key), + title: Text( + l10n.repeater_keySettings, + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600), + ), + subtitle: Text(l10n.repeater_keySettingsSubtitle), + childrenPadding: const EdgeInsets.fromLTRB(0, 8, 0, 4), + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + controller: _prvKeyController, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp("[0-9a-fA-F]")), + ], + decoration: InputDecoration( + labelText: l10n.repeater_prvKey, + helperText: l10n.repeater_prvKeyHelper, + helperMaxLines: 3, + border: const OutlineInputBorder(), + ), + onChanged: (_) { + _pubKeyController.text = ""; + if (_prvKeyController.text.isNotEmpty) { + _markChanged(_SettingField.prvKey); + } + }, + ), + ), + const SizedBox(width: 8), + Padding( + padding: const EdgeInsets.only(top: 8), + child: _searchingForKeyPair + ? IconButton( + icon: const Icon(Icons.cancel, size: 24), + onPressed: (() => _stopSearchingForKeyPair = true), + tooltip: l10n.repeater_stopGeneratingPrvKey, + visualDensity: VisualDensity.compact, + ) + : IconButton( + icon: const Icon(Icons.casino_rounded, size: 24), + onPressed: () { + _startSearchingForKeyPair(); + }, + tooltip: l10n.repeater_generatePrvKey, + visualDensity: VisualDensity.compact, + ), + ), + ], + ), + const SizedBox(height: 16), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + readOnly: true, + controller: _pubKeyController, + style: TextStyle( + color: Theme.of( + context, + ).textTheme.headlineSmall?.color?.withValues(alpha: 0.6), + ), + decoration: InputDecoration( + labelText: l10n.repeater_pubKey, + helperText: l10n.repeater_pubKeyHelper, + helperMaxLines: 3, + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 16), + Padding( + padding: const EdgeInsets.only(top: 12), + child: SizedBox( + width: 24, + height: 24, + child: _searchingForKeyPair + ? CircularProgressIndicator(strokeWidth: 2) + : null, + ), + ), + const SizedBox(width: 8), + ], + ), + const SizedBox(height: 16), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + controller: _prvKeyPrefixController, + maxLength: 4, + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp("[0-9a-fA-F]")), + ], + onChanged: (_) => setState(() => {}), // updates helper text + decoration: InputDecoration( + labelText: l10n.repeater_pubKeyPrefix, + helperText: l10n.repeater_pubKeyPrefixHelper( + pow(16, _prvKeyPrefixController.text.length).toInt(), + ), + helperMaxLines: 3, + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 48), + ], ), ], ), diff --git a/lib/screens/repeater_status_screen.dart b/lib/screens/repeater_status_screen.dart index e7d1fbe6..a3661a18 100644 --- a/lib/screens/repeater_status_screen.dart +++ b/lib/screens/repeater_status_screen.dart @@ -1,12 +1,12 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../models/path_selection.dart'; +import '../models/remote_node_stats.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../services/app_settings_service.dart'; @@ -32,10 +32,7 @@ class RepeaterStatusScreen extends StatefulWidget { } class _RepeaterStatusScreenState extends State { - static const int _statusPayloadOffset = 8; - static const int _statusStatsSize = 52; - static const int _statusResponseBytes = - _statusPayloadOffset + _statusStatsSize; + static const int _statusResponseBytes = RemoteNodeStats.payloadOffset + 56; bool _isLoading = false; StreamSubscription? _frameSubscription; @@ -50,6 +47,9 @@ class _RepeaterStatusScreenState extends State { int? _noiseFloor; int? _txAirSecs; int? _rxAirSecs; + int? _recvErrors; + int? _posted; + int? _postPushes; int? _packetsSent; int? _packetsRecv; int? _floodTx; @@ -124,72 +124,39 @@ class _RepeaterStatusScreenState extends State { if (frame.length < 8) return; final prefix = frame.sublist(2, 8); if (!_matchesRepeaterPrefix(prefix)) return; - if (frame.length < _statusResponseBytes) return; - - final data = ByteData.sublistView( - frame, - _statusPayloadOffset, - _statusResponseBytes, - ); - int offset = 0; - - final batteryMv = data.getUint16(offset, Endian.little); - offset += 2; - final queueLen = data.getUint16(offset, Endian.little); - offset += 2; - final noiseFloor = data.getInt16(offset, Endian.little); - offset += 2; - final lastRssi = data.getInt16(offset, Endian.little); - offset += 2; - final packetsRecv = data.getUint32(offset, Endian.little); - offset += 4; - final packetsSent = data.getUint32(offset, Endian.little); - offset += 4; - final txAirSecs = data.getUint32(offset, Endian.little); - offset += 4; - final uptimeSecs = data.getUint32(offset, Endian.little); - offset += 4; - final floodTx = data.getUint32(offset, Endian.little); - offset += 4; - final directTx = data.getUint32(offset, Endian.little); - offset += 4; - final floodRx = data.getUint32(offset, Endian.little); - offset += 4; - final directRx = data.getUint32(offset, Endian.little); - offset += 4; - final errEvents = data.getUint16(offset, Endian.little); - offset += 2; - final lastSnrRaw = data.getInt16(offset, Endian.little); - offset += 2; - final directDups = data.getUint16(offset, Endian.little); - offset += 2; - final floodDups = data.getUint16(offset, Endian.little); - offset += 2; - final rxAirSecs = data.getUint32(offset, Endian.little); + final stats = RemoteNodeStats.tryParse(frame, isRoom: _isRoom); + if (stats == null) return; _statusTimeout?.cancel(); if (!mounted) return; + final rxAirSecs = stats.rxAirSecs; setState(() { _isLoading = false; - _batteryMv = batteryMv; - _queueLen = queueLen; - _noiseFloor = noiseFloor; - _lastRssi = lastRssi; - _packetsRecv = packetsRecv; - _packetsSent = packetsSent; - _txAirSecs = txAirSecs; + _batteryMv = stats.batteryMv; + _queueLen = stats.queueLen; + _noiseFloor = stats.noiseFloor; + _lastRssi = stats.lastRssi; + _packetsRecv = stats.packetsRecv; + _packetsSent = stats.packetsSent; + _txAirSecs = stats.txAirSecs; _rxAirSecs = rxAirSecs; - _uptimeSecs = uptimeSecs; - _floodTx = floodTx; - _directTx = directTx; - _floodRx = floodRx; - _directRx = directRx; - _debugFlags = errEvents; - _lastSnr = lastSnrRaw / 4.0; - _dupDirect = directDups; - _dupFlood = floodDups; - _chanUtil = ((txAirSecs + rxAirSecs) / uptimeSecs) * 100; + _recvErrors = stats.recvErrors; + _posted = stats.posted; + _postPushes = stats.postPushes; + _uptimeSecs = stats.uptimeSecs; + _floodTx = stats.floodTx; + _directTx = stats.directTx; + _floodRx = stats.floodRx; + _directRx = stats.directRx; + _debugFlags = stats.errEvents; + _lastSnr = stats.lastSnr; + _dupDirect = stats.directDups; + _dupFlood = stats.floodDups; + _chanUtil = rxAirSecs != null && stats.uptimeSecs > 0 + ? ((stats.txAirSecs + rxAirSecs) / stats.uptimeSecs) * 100 + : null; }); + final batteryMv = stats.batteryMv; final connector = Provider.of(context, listen: false); connector.updateRepeaterBatterySnapshot( widget.repeater.publicKeyHex, @@ -199,6 +166,8 @@ class _RepeaterStatusScreenState extends State { _recordStatusResult(true); } + bool get _isRoom => widget.repeater.type == advTypeRoom; + bool _matchesRepeaterPrefix(Uint8List prefix) { final target = widget.repeater.publicKey; if (target.length < 6 || prefix.length < 6) return false; @@ -266,6 +235,9 @@ class _RepeaterStatusScreenState extends State { _noiseFloor = null; _txAirSecs = null; _rxAirSecs = null; + _recvErrors = null; + _posted = null; + _postPushes = null; _packetsSent = null; _packetsRecv = null; _floodTx = null; @@ -551,12 +523,13 @@ class _RepeaterStatusScreenState extends State { value: _formatDuration(_txAirSecs), color: MeshPalette.warn, ), - _StatItem( - icon: Icons.download, - label: l10n.repeater_rxAirtime, - value: _formatDuration(_rxAirSecs), - color: MeshPalette.signal, - ), + if (!_isRoom) + _StatItem( + icon: Icons.download, + label: l10n.repeater_rxAirtime, + value: _formatDuration(_rxAirSecs), + color: MeshPalette.signal, + ), ]), ), @@ -583,16 +556,39 @@ class _RepeaterStatusScreenState extends State { value: _duplicateText(), color: scheme.onSurfaceVariant, ), - _StatItem( - icon: Icons.percent, - label: l10n.repeater_chanUtil, - value: _chanUtilText(), - color: _chanUtil != null && _chanUtil! > 80 - ? MeshPalette.alert - : _chanUtil != null && _chanUtil! > 50 - ? MeshPalette.warn - : MeshPalette.signal, - ), + if (_isRoom) ...[ + _StatItem( + icon: Icons.forum_outlined, + label: l10n.room_postsStored, + value: _formatValue(_posted), + color: MeshPalette.blue, + ), + _StatItem( + icon: Icons.outbox, + label: l10n.room_postsPushed, + value: _formatValue(_postPushes), + color: MeshPalette.signal, + ), + ] else + _StatItem( + icon: Icons.error_outline, + label: l10n.repeater_recvErrors, + value: _formatValue(_recvErrors), + color: _recvErrors != null && _recvErrors! > 0 + ? MeshPalette.warn + : scheme.onSurfaceVariant, + ), + if (!_isRoom) + _StatItem( + icon: Icons.percent, + label: l10n.repeater_chanUtil, + value: _chanUtilText(), + color: _chanUtil != null && _chanUtil! > 80 + ? MeshPalette.alert + : _chanUtil != null && _chanUtil! > 50 + ? MeshPalette.warn + : MeshPalette.signal, + ), ]), ), const SizedBox(height: 8), @@ -618,23 +614,33 @@ class _RepeaterStatusScreenState extends State { } Widget _buildStatGrid(List<_StatItem> items) { - return GridView.count( - crossAxisCount: 2, - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - mainAxisSpacing: 8, - crossAxisSpacing: 8, - childAspectRatio: 2.2, - children: items - .map( - (item) => StatTile( + final textScaler = MediaQuery.textScalerOf(context); + return LayoutBuilder( + builder: (context, constraints) { + final columns = constraints.maxWidth / textScaler.scale(1) < 320 + ? 1 + : 2; + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: items.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: columns, + mainAxisSpacing: 8, + crossAxisSpacing: 8, + mainAxisExtent: textScaler.scale(52) + 28, + ), + itemBuilder: (context, index) { + final item = items[index]; + return StatTile( icon: item.icon, label: item.label, value: item.value, color: item.color, - ), - ) - .toList(), + ); + }, + ); + }, ); } } diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index f8ff3692..502e0f18 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,5 +1,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:meshcore_open/utils/gpx_export.dart'; import 'package:meshcore_open/widgets/elements_ui.dart'; import 'package:provider/provider.dart'; @@ -9,6 +10,7 @@ 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'; @@ -18,6 +20,7 @@ import 'app_settings_screen.dart'; import 'app_debug_log_screen.dart'; import 'ble_debug_log_screen.dart'; import '../widgets/radio_stats_entry.dart'; +import 'telemetry_screen.dart'; import '../widgets/sync_progress_overlay.dart'; import 'region_management_screen.dart'; @@ -27,15 +30,24 @@ int _toUiCodingRate(int deviceCr) { return deviceCr <= 4 ? deviceCr + 4 : deviceCr; } -/// Convert UI coding-rate value (5-8) back to firmware encoding. -/// Uses the current device CR to detect which encoding the firmware expects. -int _toDeviceCodingRate(int uiCr, int? deviceCr) { - if (deviceCr != null && deviceCr <= 4) { - return uiCr - 4; +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 uiCr; + 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}); @@ -279,6 +291,18 @@ class _SettingsScreenState extends State { value: connector.deviceIdLabel, ), _buildBatteryInfoRow(context, connector), + if (connector.manufacturerName != null) + _infoRow( + context, + label: l10n.settings_infoHardware, + value: connector.manufacturerName!, + ), + if (connector.firmwareVersionString != null) + _infoRow( + context, + label: l10n.settings_infoFirmware, + value: connector.firmwareVersionString!, + ), if (connector.selfName != null) _infoRow( context, @@ -286,12 +310,10 @@ class _SettingsScreenState extends State { value: connector.selfName!, ), if (connector.selfPublicKey != null) - _infoRow( + _publicKeyRow( context, label: l10n.settings_infoPublicKey, - value: - '${pubKeyToHex(connector.selfPublicKey!).substring(0, 16)}...', - mono: true, + publicKeyHex: pubKeyToHex(connector.selfPublicKey!), ), _infoRow( context, @@ -312,6 +334,31 @@ class _SettingsScreenState extends State { ); } + /// Copies the key rendered in the row, not whatever the connector holds when + /// the tap lands: a disconnect in between clears `selfPublicKey`. + Widget _publicKeyRow( + BuildContext context, { + required String label, + required String publicKeyHex, + }) { + return _infoRow( + context, + label: label, + value: publicKeyHex, + mono: true, + onTap: () => _copyPublicKey(context, publicKeyHex), + ); + } + + Future _copyPublicKey(BuildContext context, String publicKeyHex) async { + await Clipboard.setData(ClipboardData(text: publicKeyHex)); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.settings_publicKeyCopied), + ); + } + Widget _infoRow( BuildContext context, { required String label, @@ -462,15 +509,56 @@ class _SettingsScreenState extends State { context, icon: Icons.sensors_outlined, title: l10n.radioStats_settingsTile, - subtitle: l10n.radioStats_settingsSubtitle, + subtitle: + connector.isConnected && !connector.supportsCompanionRadioStats + ? l10n.settings_requiresFirmware('v1.10') + : l10n.radioStats_settingsSubtitle, onTap: connector.isConnected && connector.supportsCompanionRadioStats ? () => pushCompanionRadioStatsScreen(context) : null, ), + const Divider(height: 1, indent: 16), + _tappableTile( + context, + icon: Icons.thermostat_outlined, + title: l10n.contact_telemetry, + subtitle: l10n.repeater_telemetrySubtitle, + onTap: connector.isConnected + ? () => pushSelfTelemetryScreen(context) + : null, + ), + const Divider(height: 1, indent: 16), + _tappableTile( + context, + icon: Icons.route_outlined, + title: l10n.repeater_pathHashMode, + subtitle: + connector.isConnected && + (connector.firmwareVerCode ?? 0) < + _minFirmwareVerCodeForPathHashMode + ? l10n.settings_requiresFirmware('v1.14') + : _pathHashModeSubtitle(context, connector.pathHashByteWidth), + onTap: + connector.isConnected && + (connector.firmwareVerCode ?? 0) >= + _minFirmwareVerCodeForPathHashMode + ? () => _editPathHashMode(context, connector) + : null, + ), ], ); } + String _pathHashModeSubtitle(BuildContext context, int pathHashByteWidth) { + final l10n = context.l10n; + return switch (pathHashByteWidth.clamp(1, 4).toInt()) { + 1 => l10n.repeater_pathHashModeOption0, + 2 => l10n.repeater_pathHashModeOption1, + 3 => l10n.repeater_pathHashModeOption2, + _ => l10n.repeater_pathHashModeOption3, + }; + } + Widget _buildLocationCardContent( BuildContext context, MeshCoreConnector connector, @@ -759,8 +847,86 @@ class _SettingsScreenState extends State { ); } + void _editPathHashMode(BuildContext context, MeshCoreConnector connector) { + final l10n = context.l10n; + var selectedMode = (connector.pathHashByteWidth - 1).clamp(0, 2).toInt(); + + showDialog( + context: context, + builder: (dialogContext) => StatefulBuilder( + builder: (builderContext, setDialogState) => AlertDialog( + title: Text(l10n.repeater_pathHashMode), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DropdownButtonFormField( + initialValue: selectedMode, + decoration: InputDecoration( + labelText: l10n.repeater_pathHashMode, + border: const OutlineInputBorder(), + ), + items: [ + DropdownMenuItem( + value: 0, + child: Text(l10n.repeater_pathHashModeOption0), + ), + DropdownMenuItem( + value: 1, + child: Text(l10n.repeater_pathHashModeOption1), + ), + DropdownMenuItem( + value: 2, + child: Text(l10n.repeater_pathHashModeOption2), + ), + ], + onChanged: (value) { + if (value == null) return; + setDialogState(() => selectedMode = value); + }, + ), + const SizedBox(height: 12), + Text( + l10n.settings_pathHashModeHelper, + style: Theme.of(builderContext).textTheme.bodySmall, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: () async { + Navigator.pop(dialogContext); + try { + await connector.setPathHashMode(selectedMode); + await connector.refreshDeviceInfo(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.repeater_settingsSaved), + ); + } catch (e) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_error(e.toString())), + ); + } + }, + child: Text(l10n.common_save), + ), + ], + ), + ), + ); + } + void _editLocation(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; + final settingsService = context.read(); final latController = TextEditingController(); final lonController = TextEditingController(); final intervalController = TextEditingController(); @@ -772,9 +938,9 @@ class _SettingsScreenState extends State { final bool hasGPS = customVars.containsKey("gps"); bool isGPSEnabled = customVars["gps"] == "1"; - // Read current interval or default to 900 (15 minutes) - final currentInterval = - int.tryParse(customVars["gps_interval"] ?? "") ?? 900; + final currentInterval = settingsService.resolvedGpsIntervalSeconds( + customVars, + ); intervalController.text = currentInterval.toString(); String? intervalError; @@ -782,7 +948,7 @@ class _SettingsScreenState extends State { showDialog( context: context, builder: (dialogContext) => StatefulBuilder( - builder: (context, setDialogState) => AlertDialog( + builder: (builderContext, setDialogState) => AlertDialog( title: Text(l10n.settings_location), content: Column( mainAxisSize: MainAxisSize.min, @@ -848,7 +1014,7 @@ class _SettingsScreenState extends State { ), actions: [ TextButton( - onPressed: () => Navigator.pop(context), + onPressed: () => Navigator.pop(dialogContext), child: Text(l10n.common_cancel), ), TextButton( @@ -869,10 +1035,14 @@ class _SettingsScreenState extends State { } } - Navigator.pop(context); + Navigator.pop(dialogContext); if (interval != null) { - await connector.setCustomVar("gps_interval:$interval"); + await settingsService.setGpsIntervalSeconds( + interval, + writeToDevice: (value) => + connector.setCustomVar("gps_interval:$value"), + ); await connector.refreshDeviceInfo(); if (!context.mounted) return; showDismissibleSnackBar( @@ -1172,29 +1342,48 @@ class _SettingsScreenState extends State { void _privacySettings(BuildContext context, MeshCoreConnector connector) { final l10n = context.l10n; + final settingsService = context.read(); int telemetryMode = connector.telemetryModeBase; int telemetryLocMode = connector.telemetryModeLoc; int telemetryEnvMode = connector.telemetryModeEnv; bool advertLocPolicy = connector.advertLocationPolicy == 0 ? false : true; int multiAcks = connector.multiAcks; + bool autoZeroHopAdvertOnGpsUpdate = + settingsService.settings.autoSendZeroHopAdvertOnGpsUpdate; final telemModeBase = [ - DropdownMenuItem(value: teleModeDeny, child: Text(l10n.settings_denyAll)), + DropdownMenuItem( + value: teleModeDeny, + child: Text( + l10n.settings_denyAll, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), DropdownMenuItem( value: teleModeAllowFlags, - child: Text(l10n.settings_allowByContact), + child: Text( + l10n.settings_allowByContact, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: teleModeAllowAll, - child: Text(l10n.settings_allowAll), + child: Text( + l10n.settings_allowAll, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), ]; showDialog( context: context, builder: (dialogContext) => StatefulBuilder( - builder: (context, setDialogState) => AlertDialog( + builder: (builderContext, setDialogState) => AlertDialog( + insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24), title: Text(l10n.settings_privacy), content: SingleChildScrollView( child: Column( @@ -1212,8 +1401,23 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { }, ), const SizedBox(height: 8), + FeatureToggleRow( + title: l10n.settings_autoZeroHopAdvertOnGpsUpdate, + subtitle: l10n.settings_autoZeroHopAdvertOnGpsUpdateSubtitle, + value: autoZeroHopAdvertOnGpsUpdate, + enabled: advertLocPolicy, + onChanged: advertLocPolicy + ? (value) { + setDialogState( + () => autoZeroHopAdvertOnGpsUpdate = value, + ); + } + : null, + ), + const SizedBox(height: 8), SwitchListTile( title: Text(l10n.settings_multiAck), + subtitle: Text(l10n.settings_multiAckSubtitle), value: multiAcks == 1, onChanged: (value) { setDialogState(() => multiAcks = value ? 1 : 0); @@ -1223,6 +1427,7 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { const SizedBox(height: 16), DropdownButtonFormField( initialValue: telemetryMode, + isExpanded: true, decoration: InputDecoration( labelText: l10n.settings_telemetryBaseMode, border: const OutlineInputBorder(), @@ -1237,6 +1442,7 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { const SizedBox(height: 16), DropdownButtonFormField( initialValue: telemetryLocMode, + isExpanded: true, decoration: InputDecoration( labelText: l10n.settings_telemetryLocationMode, border: const OutlineInputBorder(), @@ -1251,6 +1457,7 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { const SizedBox(height: 16), DropdownButtonFormField( initialValue: telemetryEnvMode, + isExpanded: true, decoration: InputDecoration( labelText: l10n.settings_telemetryEnvironmentMode, border: const OutlineInputBorder(), @@ -1262,17 +1469,22 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { } }, ), + const SizedBox(height: 8), + Text( + l10n.settings_telemetryPerContactHint, + style: Theme.of(context).textTheme.bodySmall, + ), ], ), ), actions: [ TextButton( - onPressed: () => Navigator.pop(context), + onPressed: () => Navigator.pop(dialogContext), child: Text(l10n.common_cancel), ), TextButton( onPressed: () async { - Navigator.pop(context); + Navigator.pop(dialogContext); await connector.setTelemetryModeBase( telemetryMode, telemetryLocMode, @@ -1280,6 +1492,9 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) { advertLocPolicy ? 1 : 0, multiAcks, ); + await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate( + autoZeroHopAdvertOnGpsUpdate, + ); await connector.refreshDeviceInfo(); if (!context.mounted) return; showDismissibleSnackBar( @@ -1412,8 +1627,7 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { if (preset.frequencyHz == snapshot.frequencyHz && preset.bandwidth == snapshot.bandwidth && preset.spreadingFactor == snapshot.spreadingFactor && - preset.codingRate == snapshot.codingRate && - preset.txPowerDbm == snapshot.txPowerDbm) { + preset.codingRate == snapshot.codingRate) { return i; } } @@ -1447,9 +1661,15 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { } double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) { - if (baseFrequencyMHz < 500) return 433.0; - if (baseFrequencyMHz < 900) return 869.0; - return 918.0; + 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) { @@ -1494,14 +1714,13 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { if (offGridFreqHz == current.frequencyHz && preset.bandwidth == current.bandwidth && preset.spreadingFactor == current.spreadingFactor && - preset.codingRate == current.codingRate && - preset.txPowerDbm == current.txPowerDbm) { + preset.codingRate == current.codingRate) { return _RadioSettingsSnapshot( frequencyMHz: preset.frequencyMHz, bandwidth: preset.bandwidth, spreadingFactor: preset.spreadingFactor, codingRate: preset.codingRate, - txPowerDbm: preset.txPowerDbm, + txPowerDbm: current.txPowerDbm, ); } } @@ -1590,14 +1809,15 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { void _validateFields() { final l10n = context.l10n; final freqMHz = double.tryParse(_frequencyController.text); - _frequencyError = (freqMHz == null || freqMHz < 300 || freqMHz > 2500) + _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 < 0 || txPower > maxTxPower) - ? '${l10n.settings_txPowerInvalid} (0-$maxTxPower dBm)' + _txPowerError = + (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) + ? '${l10n.settings_txPowerInvalid} ($_minTxPowerDbm-$maxTxPower dBm)' : null; } @@ -1634,7 +1854,7 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { final freqMHz = double.tryParse(_frequencyController.text); final txPower = int.tryParse(_txPowerController.text); - if (freqMHz == null || freqMHz < 300 || freqMHz > 2500) { + if (freqMHz == null || freqMHz < 150 || freqMHz > 2500) { showDismissibleSnackBar( context, content: Text(l10n.settings_frequencyInvalid), @@ -1643,10 +1863,12 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { } final maxTxPower = widget.connector.maxTxPower ?? 22; - if (txPower == null || txPower < 0 || txPower > maxTxPower) { + if (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) { showDismissibleSnackBar( context, - content: Text('${l10n.settings_txPowerInvalid} (0-$maxTxPower dBm)'), + content: Text( + '${l10n.settings_txPowerInvalid} ($_minTxPowerDbm-$maxTxPower dBm)', + ), ); return; } @@ -1654,18 +1876,14 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { final freqHz = (freqMHz * 1000).round(); final bwHz = _bandwidth.hz; final sf = _spreadingFactor.value; - final cr = _toDeviceCodingRate( - _codingRate.value, - widget.connector.currentCr, - ); + 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) { - const validRepeatFreqsKHz = {433000, 869000, 918000}; - if (_clientRepeat && !validRepeatFreqsKHz.contains(freqHz)) { + if (_clientRepeat && !_isAllowedRepeatFreqKHz(widget.connector, freqHz)) { showDismissibleSnackBar( context, content: Text(l10n.settings_clientRepeatFreqWarning), @@ -1676,23 +1894,53 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { try { _logRadioSettingsState('Saving radio settings'); - await widget.connector.sendFrame( - buildSetRadioParamsFrame( - freqHz, - bwHz, - sf, - cr, + 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, ); - await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); - await widget.connector.refreshDeviceInfo(); + 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(widget.connector.currentCr), + rememberedSnapshot.toMeshCoreSnapshot(), ); } @@ -1714,6 +1962,27 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { 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'; @@ -1760,20 +2029,30 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { children: [ DropdownButtonFormField( key: ValueKey(_selectedPresetIndex), - initialValue: _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), + child: Text( + RadioSettings.presets[i].$1, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: (index) { - if (index != null) { + if (index != null && index >= 0) { _applyPreset(index); } }, @@ -1785,7 +2064,11 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { decoration: InputDecoration( labelText: l10n.settings_frequency, border: const OutlineInputBorder(), - helperText: l10n.settings_frequencyHelper, + helperText: _clientRepeat + ? l10n.settings_clientRepeatFrequencyNote( + _frequencyController.text, + ) + : l10n.settings_frequencyHelper, errorText: _frequencyError, ), keyboardType: const TextInputType.numberWithOptions( @@ -1867,9 +2150,10 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { decoration: InputDecoration( labelText: l10n.settings_txPower, border: const OutlineInputBorder(), - helperText: widget.connector.maxTxPower != null - ? '${l10n.settings_txPowerHelper} (max: ${widget.connector.maxTxPower} dBm)' - : l10n.settings_txPowerHelper, + helperText: l10n.settings_txPowerRangeHelper( + _minTxPowerDbm, + widget.connector.maxTxPower ?? 22, + ), errorText: _txPowerError, ), keyboardType: TextInputType.number, @@ -1884,6 +2168,11 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { contentPadding: EdgeInsets.zero, ), ], + const SizedBox(height: 16), + Text( + l10n.settings_radioMatchWarning, + style: Theme.of(context).textTheme.bodySmall, + ), ], ), ), @@ -1945,12 +2234,12 @@ class _RadioSettingsSnapshot { } /// Convert back to the connector's raw-int snapshot. - MeshCoreRadioStateSnapshot toMeshCoreSnapshot(int? deviceCr) { + MeshCoreRadioStateSnapshot toMeshCoreSnapshot() { return MeshCoreRadioStateSnapshot( freqHz: frequencyHz, bwHz: bandwidth.hz, sf: spreadingFactor.value, - cr: _toDeviceCodingRate(codingRate.value, deviceCr), + cr: codingRate.value, txPowerDbm: txPowerDbm, ); } diff --git a/lib/screens/telemetry_screen.dart b/lib/screens/telemetry_screen.dart index fafa68f2..76cff5be 100644 --- a/lib/screens/telemetry_screen.dart +++ b/lib/screens/telemetry_screen.dart @@ -22,10 +22,36 @@ import '../widgets/telemetry_location_map.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; +/// Opens the telemetry screen for the locally connected node. +void pushSelfTelemetryScreen(BuildContext context) { + final connector = Provider.of(context, listen: false); + final selfKey = connector.selfPublicKey; + if (selfKey == null || selfKey.isEmpty) return; + final selfContact = Contact( + publicKey: selfKey, + name: connector.selfName ?? '', + type: advTypeChat, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.now(), + ); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => TelemetryScreen(contact: selfContact, isSelf: true), + ), + ); +} + class TelemetryScreen extends StatefulWidget { final Contact contact; + final bool isSelf; - const TelemetryScreen({super.key, required this.contact}); + const TelemetryScreen({ + super.key, + required this.contact, + this.isSelf = false, + }); @override State createState() => _TelemetryScreenState(); @@ -40,6 +66,7 @@ class _TelemetryScreenState extends State { static const int _autoRefreshMaxQuantity = 10; int _tagData = 0; + bool _awaitingSent = false; bool _isLoading = false; bool _isLoaded = false; @@ -101,7 +128,8 @@ class _TelemetryScreenState extends State { final reader = BufferReader(frame); try { final cmd = reader.readByte(); - if (cmd == respCodeSent) { + if (cmd == respCodeSent && _awaitingSent) { + _awaitingSent = false; reader.skipBytes(1); // Skip the reserved byte _tagData = reader.readUInt32LE(); _tripTime = reader.readUInt32LE(); @@ -158,7 +186,7 @@ class _TelemetryScreenState extends State { void _handleTelemetryResponse(Uint8List frame) { final parsedTelemetry = CayenneLpp.parseByChannel(frame); final batteryMv = _extractTelemetryBatteryMillivolts(parsedTelemetry); - if (batteryMv != null) { + if (batteryMv != null && !widget.isSelf) { final connector = Provider.of(context, listen: false); connector.updateRepeaterBatterySnapshot( widget.contact.publicKeyHex, @@ -183,6 +211,7 @@ class _TelemetryScreenState extends State { ); } _statusTimeout?.cancel(); + _recordTelemetryResult(true); if (!mounted) return; setState(() { _isLoading = false; @@ -204,21 +233,55 @@ class _TelemetryScreenState extends State { }); try { final connector = Provider.of(context, listen: false); - final selection = await connector.preparePathForContactSend( - _resolveContact(connector), - ); - _pendingStatusSelection = selection; Uint8List frame; - if (widget.contact.type != advTypeChat) { - frame = buildSendBinaryReq( - widget.contact.publicKey, - payload: buildTelemetryBinaryPayload(), - ); + if (widget.isSelf) { + // ask the connected node for its own telemetry, no mesh path involved + 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); + }); } else { - frame = buildSendTelemetryReq(widget.contact.publicKey); + final selection = await connector.preparePathForContactSend( + _resolveContact(connector), + ); + _pendingStatusSelection = selection; + if (widget.contact.type != advTypeChat) { + frame = buildSendBinaryReq( + widget.contact.publicKey, + payload: buildTelemetryBinaryPayload(), + ); + } else { + frame = buildSendTelemetryReq(widget.contact.publicKey); + } } + // A local self request gets no respCodeSent, so any that arrives belongs + // to another send and must not replace the 5s self timeout. + _awaitingSent = !widget.isSelf; await connector.sendFrame(frame); } catch (e) { + _awaitingSent = false; + _statusTimeout?.cancel(); if (mounted) { setState(() { _isLoading = false; @@ -334,7 +397,7 @@ class _TelemetryScreenState extends State { return Scaffold( appBar: AppBar( title: Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( @@ -350,15 +413,16 @@ class _TelemetryScreenState extends State { ), ], ), - centerTitle: false, + centerTitle: true, bottom: const SyncProgressAppBarBottom(), actions: [ - IconButton( - icon: Icon(isFloodMode ? Icons.waves : Icons.route), - tooltip: l10n.repeater_routingMode, - onPressed: () => - ContactRoutingSheet.show(context, contact: widget.contact), - ), + if (!widget.isSelf) + IconButton( + icon: Icon(isFloodMode ? Icons.waves : Icons.route), + tooltip: l10n.repeater_routingMode, + onPressed: () => + ContactRoutingSheet.show(context, contact: widget.contact), + ), IconButton( icon: _isLoading ? const SizedBox( @@ -495,7 +559,7 @@ class _TelemetryScreenState extends State { _temperatureText(value, isImperialUnits), ); case 'humidity': - return _TelemetryFieldDisplay(l10n.telemetry_humidityLabel, text); + return _TelemetryFieldDisplay(l10n.telemetry_humidityLabel, '$text%'); case 'accelerometer': return _TelemetryFieldDisplay( l10n.telemetry_accelerometerLabel, @@ -912,10 +976,12 @@ class _TelemetryScreenState extends State { ), ), const SizedBox(width: 8), - Text( - value, - style: MeshTheme.mono(fontSize: 13, color: scheme.onSurface), - textAlign: TextAlign.end, + Flexible( + child: Text( + value, + style: MeshTheme.mono(fontSize: 13, color: scheme.onSurface), + textAlign: TextAlign.end, + ), ), ], ), diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 88ff0f47..80b0e9a9 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; import '../models/app_settings.dart'; +import '../models/image_codec_support.dart'; import '../models/translation_support.dart'; import '../storage/prefs_manager.dart'; import '../utils/app_logger.dart'; @@ -13,6 +14,14 @@ class AppSettingsService extends ChangeNotifier { AppSettings get settings => _settings; + int resolvedGpsIntervalSeconds(Map? deviceCustomVars) { + final deviceValue = int.tryParse(deviceCustomVars?['gps_interval'] ?? ''); + if (deviceValue != null && deviceValue >= 0) { + return deviceValue; + } + return _settings.gpsIntervalSeconds; + } + String batteryChemistryForDevice(String deviceId) { final stored = _settings.batteryChemistryByDeviceId[deviceId]; if (stored == 'liion') return 'nmc'; @@ -96,6 +105,10 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(mapShowGuessedLocations: value)); } + Future setMapClusterNodes(bool value) async { + await updateSettings(_settings.copyWith(mapClusterNodes: value)); + } + Future setEnableMessageTracing(bool value) async { await updateSettings(_settings.copyWith(enableMessageTracing: value)); } @@ -112,6 +125,25 @@ class AppSettingsService extends ChangeNotifier { ); } + Future setMapRasterSourceId(String value) async { + await updateSettings(_settings.copyWith(mapRasterSourceId: value)); + } + + Future setMapTileEndpointId(String value) async { + await updateSettings(_settings.copyWith(mapTileEndpointId: value)); + } + + Future setMapTileApiKey(String? value) async { + final normalized = value?.trim(); + await updateSettings( + _settings.copyWith( + mapTileApiKey: (normalized == null || normalized.isEmpty) + ? null + : normalized, + ), + ); + } + Future setNotificationsEnabled(bool value) async { await updateSettings(_settings.copyWith(notificationsEnabled: value)); } @@ -128,6 +160,28 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(notifyOnNewAdvert: value)); } + Future setAutoSendZeroHopAdvertOnGpsUpdate(bool value) async { + await updateSettings( + _settings.copyWith(autoSendZeroHopAdvertOnGpsUpdate: value), + ); + } + + Future setGpsIntervalSeconds( + int value, { + Future Function(int value)? writeToDevice, + }) async { + await updateSettings(_settings.copyWith(gpsIntervalSeconds: value)); + if (writeToDevice == null) return; + try { + await writeToDevice(value); + } catch (e) { + appLogger.warn( + 'Failed to write GPS interval to device: $e', + tag: 'AppSettings', + ); + } + } + Future setAutoRouteRotationEnabled(bool value) async { await updateSettings(_settings.copyWith(autoRouteRotationEnabled: value)); } @@ -156,6 +210,18 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(maxMessageRetries: value)); } + Future setChannelMinHopsEnabled(bool value) async { + await updateSettings(_settings.copyWith(channelMinHopsEnabled: value)); + } + + Future setChannelMinHops(int value) async { + await updateSettings(_settings.copyWith(channelMinHops: value)); + } + + Future setChannelMinHopsRetries(int value) async { + await updateSettings(_settings.copyWith(channelMinHopsRetries: value)); + } + Future setThemeMode(String value) async { await updateSettings(_settings.copyWith(themeMode: value)); } @@ -231,6 +297,57 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(jumpToOldestUnread: value)); } + Future setImageMessagesEnabled(bool value) async { + await updateSettings(_settings.copyWith(imageMessagesEnabled: value)); + } + + /// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into + /// `ReceivedImageStore.processAutomatically` on every settings change; the + /// store applies it to future arrivals only, so flipping it does not + /// retroactively decode a backlog. + Future setImageProcessAutomatically(bool value) async { + await updateSettings(_settings.copyWith(imageProcessAutomatically: value)); + } + + // ---- neural image codec (AEIC-SE) --------------------------------------- + + Future setImageCodecEnabled(bool value) async { + await updateSettings(_settings.copyWith(imageCodecEnabled: value)); + } + + Future setImageCodecSelectedModelId(String? value) async { + await updateSettings(_settings.copyWith(imageCodecSelectedModelId: value)); + } + + Future setImageCodecModelSourceUrl(String? value) async { + await updateSettings(_settings.copyWith(imageCodecModelSourceUrl: value)); + } + + /// [value] is an [AeicRatePoint.wireValue], not an enum index. + Future setImageCodecRatePoint(int value) async { + await updateSettings(_settings.copyWith(imageCodecRatePoint: value)); + } + + Future setImageCodecDownloadedModels( + List value, + ) async { + await updateSettings(_settings.copyWith(imageCodecDownloadedModels: value)); + } + + /// Writes the whole block in one persist, which is what + /// `ImageCodecService` does on every preference change. + Future setImageCodecPreferences(ImageCodecPreferences value) async { + await updateSettings( + _settings.copyWith( + imageCodecEnabled: value.enabled, + imageCodecSelectedModelId: value.selectedModelId, + imageCodecModelSourceUrl: value.modelSourceUrl, + imageCodecRatePoint: value.ratePoint, + imageCodecDownloadedModels: value.downloadedModels, + ), + ); + } + Future setTranslationEnabled(bool value) async { await updateSettings(_settings.copyWith(translationEnabled: value)); } diff --git a/lib/services/background_service.dart b/lib/services/background_service.dart index 23d5fafe..75684079 100644 --- a/lib/services/background_service.dart +++ b/lib/services/background_service.dart @@ -70,6 +70,11 @@ class BackgroundService { return AppLocalizations.delegate.load(match); } + static Future openBatteryOptimizationSettings() async { + if (!PlatformInfo.isAndroid) return; + await FlutterForegroundTask.openIgnoreBatteryOptimizationSettings(); + } + Future stop() async { if (!PlatformInfo.isAndroid) return; final running = await FlutterForegroundTask.isRunningService; diff --git a/lib/services/entropy_tables.dart b/lib/services/entropy_tables.dart new file mode 100644 index 00000000..b02f0793 --- /dev/null +++ b/lib/services/entropy_tables.dart @@ -0,0 +1,287 @@ +// Parser for the AEIC CDF table file (`aeic_cdf_ft32.bin`) that ships inside the +// image-codec model bundle. +// +// The file is produced by `exp/export_golden.py::write_table_file` in the AEIC +// research repo. Layout, all little-endian, tightly packed, no padding: +// +// off type field +// 0 char[8] magic = "AEICCDF\x01" +// 8 u32 version = 1 +// 12 u32 precision = 16 +// 16 u32 bypassPrecision = 2 +// 20 u32 streamParts = 2 +// 24 u32 numGroups = 2 +// 28 ... group blocks (group 0 = z, group 1 = y) +// ... index-quantizer block +// char[4] "END\0" +// +// group block: +// u32 numCdfs R +// u32 cdfWidth W +// i32[R] cdfLength row r is valid only on [0, cdfLength[r]) +// i32[R] offset symbol offset for row r +// i32[R*W] quantizedCdf row-major +// +// index-quantizer block: +// char[4] "IDXP" +// f64 logScaleMin +// f64 logScaleStep +// u32 scalesLevels +// f32 scaleThreshold (scale below this => index -1) +// f32 scaleFloor +// f32[N] scaleTable +library; + +import 'dart:typed_data'; + +/// Thrown when the CDF table file is malformed or of an unsupported version. +class EntropyTableFormatException implements Exception { + EntropyTableFormatException(this.message); + + final String message; + + @override + String toString() => 'EntropyTableFormatException: $message'; +} + +/// One CDF group (z = entropy bottleneck, y = Gaussian conditional). +class CdfGroup { + CdfGroup({ + required this.numCdfs, + required this.cdfWidth, + required this.cdfLength, + required this.offset, + required this.quantizedCdf, + }); + + /// Number of CDF rows (`R`). + final int numCdfs; + + /// Stride of a row in [quantizedCdf] (`W`). Entries beyond + /// `cdfLength[row]` are padding and must never be read. + final int cdfWidth; + + /// Valid length of each row; `cdfLength[r] - 2` is the escape symbol. + final Int32List cdfLength; + + /// Symbol offset per row. + final Int32List offset; + + /// Row-major CDF table, `R * W` entries. + final Int32List quantizedCdf; + + /// Value at `[row][col]`. + int cdfAt(int row, int col) => quantizedCdf[row * cdfWidth + col]; +} + +/// Constants needed to reproduce `my_build_indexes` (the scale -> CDF-row +/// quantizer). Carried for completeness; the shipping encoder gets its index +/// arrays straight out of the ONNX graph instead of recomputing them here, +/// because Dart's `log` is not bit-identical to ORT's float32 `Log`. +class IndexQuantizerParams { + IndexQuantizerParams({ + required this.logScaleMin, + required this.logScaleStep, + required this.scalesLevels, + required this.scaleThreshold, + required this.scaleFloor, + required this.scaleTable, + }); + + final double logScaleMin; + final double logScaleStep; + final int scalesLevels; + final double scaleThreshold; + final double scaleFloor; + final Float32List scaleTable; +} + +/// The parsed contents of `aeic_cdf_ft32.bin`. +class EntropyTables { + EntropyTables({ + required this.version, + required this.precision, + required this.bypassPrecision, + required this.streamParts, + required this.groups, + required this.indexQuantizer, + }); + + static const List magic = [ + 0x41, 0x45, 0x49, 0x43, 0x43, 0x44, 0x46, 0x01, // "AEICCDF\x01" + ]; + + /// Format version. Only version 1 is understood. + final int version; + + /// rANS probability precision in bits (16). + final int precision; + + /// Bits per bypass symbol (2). + final int bypassPrecision; + + /// Number of interleaved rANS sub-streams the bitstream is split into (2). + final int streamParts; + + /// CDF groups in file order: index 0 = z, index 1 = y. + final List groups; + + final IndexQuantizerParams indexQuantizer; + + /// The `z` (entropy bottleneck) group. + CdfGroup get zGroup => groups[0]; + + /// The `y` (Gaussian conditional) group. + CdfGroup get yGroup => groups[1]; + + /// Parses the table file. Throws [EntropyTableFormatException] on any + /// structural problem. + static EntropyTables parse(Uint8List bytes) { + if (bytes.length < 32) { + throw EntropyTableFormatException('file too short (${bytes.length} B)'); + } + for (var i = 0; i < magic.length; i++) { + if (bytes[i] != magic[i]) { + throw EntropyTableFormatException('bad magic at byte $i'); + } + } + final ByteData bd = ByteData.view( + bytes.buffer, + bytes.offsetInBytes, + bytes.lengthInBytes, + ); + var off = 8; + + int u32() { + _need(bytes, off, 4); + final int v = bd.getUint32(off, Endian.little); + off += 4; + return v; + } + + final int version = u32(); + if (version != 1) { + throw EntropyTableFormatException('unsupported version $version'); + } + final int precision = u32(); + final int bypassPrecision = u32(); + final int streamParts = u32(); + final int numGroups = u32(); + if (precision <= 0 || precision > 16) { + throw EntropyTableFormatException('bad precision $precision'); + } + if (bypassPrecision <= 0 || bypassPrecision >= precision) { + throw EntropyTableFormatException('bad bypassPrecision $bypassPrecision'); + } + if (streamParts < 1 || streamParts > 16) { + throw EntropyTableFormatException('bad streamParts $streamParts'); + } + if (numGroups < 1 || numGroups > 64) { + throw EntropyTableFormatException('bad numGroups $numGroups'); + } + + Int32List i32(int count) { + _need(bytes, off, count * 4); + final Int32List out = Int32List(count); + var p = off; + for (var i = 0; i < count; i++) { + out[i] = bd.getInt32(p, Endian.little); + p += 4; + } + off = p; + return out; + } + + final List groups = []; + for (var g = 0; g < numGroups; g++) { + final int r = u32(); + final int w = u32(); + if (r <= 0 || w <= 0 || r > 1 << 20 || w > 1 << 24) { + throw EntropyTableFormatException('group $g has bad shape ${r}x$w'); + } + final Int32List cdfLength = i32(r); + final Int32List offset = i32(r); + final Int32List cdf = i32(r * w); + for (var row = 0; row < r; row++) { + final int n = cdfLength[row]; + if (n < 2 || n > w) { + throw EntropyTableFormatException( + 'group $g row $row has cdfLength $n (width $w)', + ); + } + } + groups.add( + CdfGroup( + numCdfs: r, + cdfWidth: w, + cdfLength: cdfLength, + offset: offset, + quantizedCdf: cdf, + ), + ); + } + + _need(bytes, off, 4); + if (bytes[off] != 0x49 || + bytes[off + 1] != 0x44 || + bytes[off + 2] != 0x58 || + bytes[off + 3] != 0x50) { + throw EntropyTableFormatException('missing IDXP block at byte $off'); + } + off += 4; + _need(bytes, off, 8 + 8 + 4 + 4 + 4); + final double logScaleMin = bd.getFloat64(off, Endian.little); + final double logScaleStep = bd.getFloat64(off + 8, Endian.little); + final int levels = bd.getUint32(off + 16, Endian.little); + final double scaleThreshold = bd.getFloat32(off + 20, Endian.little); + final double scaleFloor = bd.getFloat32(off + 24, Endian.little); + off += 28; + if (levels <= 0 || levels > 1 << 20) { + throw EntropyTableFormatException('bad scalesLevels $levels'); + } + _need(bytes, off, levels * 4); + final Float32List scaleTable = Float32List(levels); + for (var i = 0; i < levels; i++) { + scaleTable[i] = bd.getFloat32(off + i * 4, Endian.little); + } + off += levels * 4; + + _need(bytes, off, 4); + if (bytes[off] != 0x45 || + bytes[off + 1] != 0x4E || + bytes[off + 2] != 0x44 || + bytes[off + 3] != 0x00) { + throw EntropyTableFormatException('missing END trailer at byte $off'); + } + off += 4; + if (off != bytes.length) { + throw EntropyTableFormatException( + 'trailing data: parsed $off of ${bytes.length} bytes', + ); + } + + return EntropyTables( + version: version, + precision: precision, + bypassPrecision: bypassPrecision, + streamParts: streamParts, + groups: groups, + indexQuantizer: IndexQuantizerParams( + logScaleMin: logScaleMin, + logScaleStep: logScaleStep, + scalesLevels: levels, + scaleThreshold: scaleThreshold, + scaleFloor: scaleFloor, + scaleTable: scaleTable, + ), + ); + } + + static void _need(Uint8List bytes, int off, int count) { + if (off < 0 || off + count > bytes.length) { + throw EntropyTableFormatException( + 'truncated file: needed $count bytes at $off of ${bytes.length}', + ); + } + } +} diff --git a/lib/services/image_chunk_transport.dart b/lib/services/image_chunk_transport.dart new file mode 100644 index 00000000..2731d2b8 --- /dev/null +++ b/lib/services/image_chunk_transport.dart @@ -0,0 +1,1353 @@ +/// Chunked image transport over MeshCore `PAYLOAD_TYPE_GRP_DATA` (0x06), +/// carried by the companion command `CMD_SEND_CHANNEL_DATA` (62) and received +/// as `RESP_CODE_CHANNEL_DATA_RECV` (27). +/// +/// This file is the SINGLE SOURCE OF TRUTH for the on-air chunk framing: the +/// blob size, header layout, per-chunk capacities and the XOR parity scheme. +/// `lib/utils/lora_airtime.dart` re-exports the constants below rather than +/// declaring rivals, so the airtime estimator cannot drift from the chunker; +/// anything else that needs chunk geometry must do the same. +/// +/// Everything above the "protocol glue" section is pure Dart: no Flutter, no +/// BLE, no connector. It is directly unit-testable. +/// +/// ## Wire format +/// +/// One MeshCore GRP_DATA blob per chunk, at most [kImageChunkBlobBytes] bytes: +/// +/// ``` +/// off size field +/// 0 2 sender_prefix selfPublicKey[0..1] — the firmware supplies no +/// sender identity on RESP_CODE_CHANNEL_DATA_RECV, +/// so it must be in-band in EVERY chunk (chunk 0 +/// may be the one that is lost). +/// 2 1 img_id uint8, random-ish per image +/// 3 1 idx<<4 | total idx 0..15, total 1..15. +/// idx == total => XOR parity chunk. +/// 4 .. body see below +/// ``` +/// +/// Data chunk body: +/// * chunk 0: `[meta]` + image bytes. `meta` is [ImageStreamMetadata] packed +/// as `aspect(4) | resolution(2) | rate(2)`. The aspect nibble names the +/// source photo's shape so the receiver can undo the stretch into the +/// square — see [kImageAspectCodes]. It costs no extra bytes. +/// * others : image bytes +/// * at most [kImageChunkBodyBytes] bytes. +/// +/// Parity chunk body: +/// * `[len_xor]` + XOR of every data chunk body, each zero-padded to +/// [kImageChunkBodyBytes]. +/// * `len_xor` is the XOR of every data chunk's body LENGTH. It is what makes +/// recovery self-describing: a lost chunk's length is recovered as +/// `len_xor ^ XOR(lengths of the bodies that did arrive)`, so the last +/// (short) chunk can be rebuilt without transmitting a total length. +/// +/// Body capacity is [kImageChunkBodyBytes] = blob(163) - header(4) - the +/// parity chunk's 1 length byte, so that the parity chunk itself still fits in +/// a single blob. The cost is exactly one wasted byte in each data chunk; that +/// is the price of self-describing single-loss recovery. +/// +/// ## Integrity +/// +/// There is deliberately NO app-level checksum. Two layers below already cover +/// corruption of a delivered chunk: the LoRa PHY CRCs every packet (`setCRC(1)` +/// in each radio driver, and a failing packet is dropped by the modem), and +/// MeshCore verifies a 2-byte HMAC-SHA256 per packet and rejects on mismatch +/// (`Utils::MACThenDecrypt` returns 0 for a bad tag). What no lower layer can +/// see is a cross-image MERGE — two senders colliding on senderPrefix + imgId + +/// channel inside one TTL, ~1/65536 per concurrent pair — which produces a +/// corrupt image rather than a clean failure. That residual risk is accepted: +/// paying 2 bytes to detect it cost far more than it was worth, because it +/// pushed the measured ft32 mean past the single-chunk capacity. +/// +/// ## Capacity check against measured codec output +/// chunk 0: 157 data bytes (158 body - 1 meta), other chunks: 158. +/// ft32 mean 155.8 B -> 1 chunk (2 packets with parity). +/// ft32 max 209 B -> 2 chunks (157+158 = 315). +/// ft16 max 409 B -> 3 chunks (157+158+158 = 473). +/// Design goals (ft32 1-2 chunks, ft16 2-3 chunks) hold. +library; + +import 'dart:math' as math; +import 'dart:typed_data'; + +import '../widgets/image_send_codec_binding.dart' show ImageCodecRatePoint; + +// --------------------------------------------------------------------------- +// Protocol constants (firmware-derived; see the transport investigation) +// --------------------------------------------------------------------------- + +/// `CMD_SEND_CHANNEL_DATA` — companion command that emits a GRP_DATA packet. +const int cmdSendChannelData = 62; + +/// `RESP_CODE_CHANNEL_DATA_RECV` — inbound frame carrying a GRP_DATA blob. +const int respCodeChannelDataRecv = 27; + +/// `OUT_PATH_UNKNOWN` — request flood routing. +const int outPathUnknown = 0xFF; + +/// Our application data type. `0x0000` is rejected by the firmware. +const int dataTypeAeicImage = 0xAE1C; + +/// Maximum blob we will ever put in one GRP_DATA packet. +/// +/// Binding limits, smallest first: +/// * app `maxFrameSize` 172 - 9 byte RESP header = **163** <- used +/// * BLE ATT_MTU 176 - 3 notify - 9 resp header = 164 +/// * radio `MAX_GROUP_DATA_LENGTH` 184 - 16 - 3 = 165 +/// * serial `MAX_CHANNEL_DATA_LENGTH` 176 - 9 = 167 +const int kImageChunkBlobBytes = 163; + +/// Per-chunk header: sender_prefix(2) + img_id(1) + idx/total(1). +const int kImageChunkHeaderBytes = 4; + +/// The parity chunk spends one body byte on the XOR of the data body lengths. +const int kImageParityLengthBytes = 1; + +/// Maximum body bytes in any chunk (data or parity payload region). +const int kImageChunkBodyBytes = + kImageChunkBlobBytes - kImageChunkHeaderBytes - kImageParityLengthBytes; + +/// The single [ImageStreamMetadata] byte carried by chunk 0. +const int kImageChunkMetadataBytes = 1; + +/// Body bytes of chunk 0 that are NOT image data: just the metadata byte. +/// +/// A CRC-16 briefly lived here. It was removed: the LoRa PHY already CRCs every +/// packet (`setCRC(1)` in every radio driver) and MeshCore verifies a 2-byte +/// HMAC per packet (`Utils::MACThenDecrypt`, which returns 0 on mismatch), so a +/// corrupted chunk never reaches this layer. The only thing an app-level CRC +/// added was detection of a cross-image merge (two senders colliding on +/// senderPrefix + imgId + channel inside one TTL, ~1/65536), and it cost 2 of +/// chunk 0's bytes -- which pushed the measured ft32 mean of 155.8 B past the +/// single-chunk capacity and turned half of all images from 1 packet into 3. +const int kImageChunkZeroMetadataBytes = kImageChunkMetadataBytes; + +/// Image bytes carried by chunk 0. +const int kImageChunkFirstCapacity = + kImageChunkBodyBytes - kImageChunkZeroMetadataBytes; + +/// Image bytes carried by every chunk after chunk 0. +const int kImageChunkCapacity = kImageChunkBodyBytes; + +/// `total` is 4 bits and must be >= 1, so at most 15 data chunks. +const int kImageMaxDataChunks = 15; + +/// Largest image bitstream this framing can carry. +const int kImageMaxPayloadBytes = + kImageChunkFirstCapacity + (kImageMaxDataChunks - 1) * kImageChunkCapacity; + +/// Bytes of the sender public key repeated in every chunk. +const int kImageSenderPrefixBytes = 2; + +/// How long a partially received image is kept before it is abandoned. +const Duration kImageReassemblyTtl = Duration(seconds: 60); + +// --------------------------------------------------------------------------- +// Rate point <-> wire code +// --------------------------------------------------------------------------- + +/// Wire code for `ft32` in the low nibble of the chunk-0 metadata byte. +const int kImageRateWireStandard = 0; + +/// Wire code for `ft16`. Reserved: ft16 is NOT a shipping rate point, but the +/// code stays allocated so an ft32-only build and a future ft16-capable build +/// agree on the nibble. +const int kImageRateWireHigh = 1; + +/// Number of rate codes this build knows how to name. +const int kImageRateWireCodeCount = 2; + +/// Maps a UI rate point to the wire code written into the metadata byte. +/// +/// THIS IS NOT `AeicRatePoint.wireValue`. There are two rate enumerations in +/// this codebase and they do not share an ordinal space: +/// +/// * `AeicRatePoint` (`lib/models/image_codec_support.dart`) is +/// `{ft2, ft4, ft8, ft16, ft32}` and its `wireValue` is that ordinal, 0..4. +/// It selects a MODEL from the registry. `ft32` is 4 there. +/// * [ImageCodecRatePoint] is `{standard, high}`, 0..1, and is what the +/// chunk-0 nibble names. `ft32` is [kImageRateWireStandard] == 0 here. +/// +/// Writing an `AeicRatePoint.wireValue` into the nibble would put 4 on the wire +/// for the only shipping rate, which [imageRatePointFromWireCode] rejects +/// outright rather than silently landing on a rate point that decodes to the +/// wrong model. The switch is exhaustive on purpose: adding a rate point is a +/// compile error here, not a silent ordinal shift. +int imageRateWireCode(ImageCodecRatePoint rate) { + switch (rate) { + case ImageCodecRatePoint.standard: + return kImageRateWireStandard; + case ImageCodecRatePoint.high: + return kImageRateWireHigh; + } +} + +/// Inverse of [imageRateWireCode]; null for a code this build cannot decode. +ImageCodecRatePoint? imageRatePointFromWireCode(int code) { + switch (code) { + case kImageRateWireStandard: + return ImageCodecRatePoint.standard; + case kImageRateWireHigh: + return ImageCodecRatePoint.high; + default: + return null; + } +} + +// --------------------------------------------------------------------------- +// Stream metadata (the single byte carried by chunk 0) +// --------------------------------------------------------------------------- + +/// Square sizes addressable by the 2-bit resolution code in the metadata byte. +/// +/// Index == wire code. 512 is code 0 because it is the only size the current +/// decoder supports; the rest exist so a future model can be signalled without +/// a format change. +const List kImageResolutionCodes = [512, 256, 768, 1024]; + +/// Source aspect ratios addressable by the 4-bit aspect code, as `w:h`. +/// +/// The codec encodes a 512x512 SQUARE — the whole frame stretched to fit, not a +/// crop, so nothing outside the frame is discarded. That stretch is not +/// invertible from the pixels alone, so the sender names the original shape +/// here and the receiver letterboxes back to it. +/// +/// This costs ZERO extra bytes: the metadata byte previously spent 4 bits on a +/// resolution with 4 legal values and 4 bits on a rate with 2, so the byte was +/// repacked (2 + 2 + 4) rather than widened. Adding a byte would have cost far +/// more than it looks — the measured ft32 mean of 155.8 B sits just under +/// chunk 0's 157-byte capacity, so one more byte pushes a chunk of the +/// distribution from 1 data chunk to 2, i.e. from 2 packets on air to 3. That +/// is exactly what the CRC did before it was removed. +/// +/// Index == wire code. Code 0 is 1:1 (no letterboxing). Code 15 means "not one +/// of these" and is rendered square, unstretched — a graceful degradation, not +/// an error. The rest are the shapes phone cameras actually produce, so the +/// common cases restore EXACTLY rather than approximately. +const List> kImageAspectCodes = >[ + [1, 1], // 0 square + [5, 4], // 1 landscape + [4, 3], // 2 + [3, 2], // 3 + [16, 10], // 4 + [16, 9], // 5 + [2, 1], // 6 + [21, 9], // 7 + [4, 5], // 8 portrait + [3, 4], // 9 + [2, 3], // 10 + [10, 16], // 11 + [9, 16], // 12 + [1, 2], // 13 + [9, 21], // 14 + [1, 1], // 15 unknown -> render square +]; + +/// Wire code for "shape unknown"; the receiver renders it square. +const int kImageAspectUnknown = 15; + +/// The [kImageAspectCodes] entry closest to `width / height`, in log space so +/// that 4:3 and 3:4 are equally far from square. +/// +/// Returns [kImageAspectUnknown] for a ratio outside roughly 21:9..9:21, rather +/// than snapping a panorama onto 21:9 and letterboxing it wrongly. +int imageAspectCodeFor(int width, int height) { + if (width <= 0 || height <= 0) return kImageAspectUnknown; + final target = math.log(width / height); + var best = kImageAspectUnknown; + var bestErr = double.infinity; + for (var i = 0; i < kImageAspectCodes.length; i++) { + if (i == kImageAspectUnknown) continue; // duplicate of 1:1 + final e = kImageAspectCodes[i]; + final err = (math.log(e[0] / e[1]) - target).abs(); + if (err < bestErr) { + bestErr = err; + best = i; + } + } + // Half a step between 21:9 and the next ratio out; beyond that we would be + // asserting a shape the sender never had. + return bestErr <= 0.18 ? best : kImageAspectUnknown; +} + +/// Contents of the chunk-0 metadata byte: `resolution_code << 4 | rate_index`. +class ImageStreamMetadata { + /// Codec rate point. Reuses the UI enum — there is deliberately no second + /// rate-point enum in this codebase. + final ImageCodecRatePoint rate; + + /// Square edge length in pixels the sender encoded at. + final int squareSize; + + /// Index into [kImageAspectCodes]: the shape the source photo was BEFORE it + /// was stretched into the square. The receiver letterboxes back to it. + final int aspectCode; + + /// Original `width / height`, or 1.0 when the sender said "unknown". + double get aspectRatio { + final e = kImageAspectCodes[aspectCode & 0x0F]; + return e[0] / e[1]; + } + + /// True when the image should be rendered square, unstretched. + bool get isSquare => aspectCode == 0 || aspectCode == kImageAspectUnknown; + + const ImageStreamMetadata({ + required this.rate, + this.squareSize = 512, + this.aspectCode = 0, + }); + + /// Encodes to the single wire byte. + /// + /// Throws [ArgumentError] if [squareSize] is not one of + /// [kImageResolutionCodes]. + int encode() { + final code = kImageResolutionCodes.indexOf(squareSize); + if (code < 0) { + throw ArgumentError.value( + squareSize, + 'squareSize', + 'not representable; must be one of $kImageResolutionCodes', + ); + } + // Repacked: aspect(4) | resolution(2) | rate(2). Lossless for every value + // the old 4+4 layout could express, because resolution has 4 legal codes + // and rate has 2. + return ((aspectCode & 0x0F) << 4) | + ((code & 0x03) << 2) | + (imageRateWireCode(rate) & 0x03); + } + + /// Decodes the wire byte, or returns null if it names a rate point or + /// resolution this build does not know. + /// + /// Deliberately never falls back to a default rate: an unknown code means the + /// sender is running a format we cannot decode, and guessing `standard` would + /// hand the wrong model a bitstream it will happily turn into garbage. The + /// caller surfaces null as [ImageChunkStatus.unsupportedFormat]. + static ImageStreamMetadata? decode(int byte) { + final rate = imageRatePointFromWireCode(byte & 0x03); + final code = (byte >> 2) & 0x03; + final aspect = (byte >> 4) & 0x0F; + if (rate == null) return null; + if (code >= kImageResolutionCodes.length) return null; + return ImageStreamMetadata( + rate: rate, + squareSize: kImageResolutionCodes[code], + aspectCode: aspect, + ); + } + + @override + String toString() => + 'ImageStreamMetadata(${rate.name}, ${squareSize}px, ' + 'aspect ${kImageAspectCodes[aspectCode & 0x0F].join(":")})'; + + @override + bool operator ==(Object other) => + other is ImageStreamMetadata && + other.rate == rate && + other.squareSize == squareSize && + other.aspectCode == aspectCode; + + @override + int get hashCode => Object.hash(rate, squareSize, aspectCode); +} + +// --------------------------------------------------------------------------- +// Chunk header +// --------------------------------------------------------------------------- + +/// Parsed 4-byte chunk header. +class ImageChunkHeader { + /// First [kImageSenderPrefixBytes] bytes of the sender's public key. + final int senderPrefix; + + final int imgId; + + /// 0-based chunk index. Equals [total] for the parity chunk. + final int index; + + /// Number of DATA chunks in this image (parity not counted). 1..15. + final int total; + + const ImageChunkHeader({ + required this.senderPrefix, + required this.imgId, + required this.index, + required this.total, + }); + + bool get isParity => index == total; + + @override + String toString() => + 'ImageChunkHeader(sender: 0x' + '${senderPrefix.toRadixString(16).padLeft(4, '0')}, img: $imgId, ' + 'idx: $index/$total${isParity ? ' parity' : ''})'; +} + +/// Packs [senderPrefix] (2 bytes, big-endian as an int) into a header. +Uint8List _writeHeader(int senderPrefix, int imgId, int index, int total) { + return Uint8List.fromList([ + (senderPrefix >> 8) & 0xFF, + senderPrefix & 0xFF, + imgId & 0xFF, + ((index & 0x0F) << 4) | (total & 0x0F), + ]); +} + +/// Reads the first two bytes of a public key as the sender prefix integer. +/// +/// Returns null when [publicKey] is too short to identify a sender. +int? senderPrefixFromKey(List? publicKey) { + if (publicKey == null || publicKey.length < kImageSenderPrefixBytes) { + return null; + } + return ((publicKey[0] & 0xFF) << 8) | (publicKey[1] & 0xFF); +} + +/// Parses the header of a received blob, or null if it cannot be a chunk. +ImageChunkHeader? parseImageChunkHeader(Uint8List blob) { + if (blob.length < kImageChunkHeaderBytes) return null; + if (blob.length > kImageChunkBlobBytes) return null; + final total = blob[3] & 0x0F; + if (total == 0) return null; + final index = (blob[3] >> 4) & 0x0F; + if (index > total) return null; // index == total is the parity chunk + return ImageChunkHeader( + senderPrefix: ((blob[0] & 0xFF) << 8) | (blob[1] & 0xFF), + imgId: blob[2] & 0xFF, + index: index, + total: total, + ); +} + +// --------------------------------------------------------------------------- +// Chunking (send side) +// --------------------------------------------------------------------------- + +/// Number of DATA chunks needed for a [payloadBytes]-long bitstream. +/// +/// A zero-length payload still needs one chunk: chunk 0 carries the metadata +/// byte, and a receiver must be able to observe an empty image rather than +/// nothing at all. +int imageDataChunkCount(int payloadBytes) { + final n = math.max(payloadBytes, 0); + if (n <= kImageChunkFirstCapacity) return 1; + final remaining = n - kImageChunkFirstCapacity; + return 1 + (remaining / kImageChunkCapacity).ceil(); +} + +/// The blobs of one image, ready to hand to `CMD_SEND_CHANNEL_DATA`. +class ImageChunkSet { + /// Every blob in send order; the parity blob, if any, is last. + final List blobs; + + /// Number of data chunks (excludes parity). + final int dataChunkCount; + + final bool hasParity; + + final int imgId; + + final int senderPrefix; + + const ImageChunkSet({ + required this.blobs, + required this.dataChunkCount, + required this.hasParity, + required this.imgId, + required this.senderPrefix, + }); + + int get totalBytes => blobs.fold(0, (a, b) => a + b.length); +} + +/// Splits an encoded image bitstream into chunk blobs. +/// +/// Chunk 0's body opens with the metadata byte; the rest is image bytes. +/// +/// [senderPrefix] must come from the local node's public key (see +/// [senderPrefixFromKey]); receivers key reassembly on it and drop chunks whose +/// prefix equals their own. +/// +/// [parity] appends one XOR parity chunk (GRP_DATA is unacknowledged, so this +/// buys recovery of exactly one lost chunk). +/// +/// Throws [ArgumentError] when [payload] exceeds [kImageMaxPayloadBytes]. +ImageChunkSet buildImageChunks({ + required Uint8List payload, + required ImageStreamMetadata metadata, + required int senderPrefix, + required int imgId, + bool parity = true, +}) { + if (payload.length > kImageMaxPayloadBytes) { + throw ArgumentError.value( + payload.length, + 'payload', + 'exceeds kImageMaxPayloadBytes ($kImageMaxPayloadBytes)', + ); + } + final total = imageDataChunkCount(payload.length); + + // Build the bodies first; parity is a pure function of them. + final bodies = []; + var offset = 0; + for (var i = 0; i < total; i++) { + final capacity = i == 0 ? kImageChunkFirstCapacity : kImageChunkCapacity; + final take = math.min(capacity, payload.length - offset); + final body = BytesBuilder(); + if (i == 0) body.addByte(metadata.encode()); + if (take > 0) body.add(payload.sublist(offset, offset + take)); + offset += take; + bodies.add(body.toBytes()); + } + + final blobs = []; + for (var i = 0; i < total; i++) { + final blob = BytesBuilder() + ..add(_writeHeader(senderPrefix, imgId, i, total)) + ..add(bodies[i]); + blobs.add(blob.toBytes()); + } + + if (parity) { + final xor = Uint8List(kImageChunkBodyBytes); + var lenXor = 0; + for (final body in bodies) { + lenXor ^= body.length; + for (var j = 0; j < body.length; j++) { + xor[j] ^= body[j]; + } + } + final blob = BytesBuilder() + ..add(_writeHeader(senderPrefix, imgId, total, total)) + ..addByte(lenXor & 0xFF) + ..add(xor); + blobs.add(blob.toBytes()); + } + + return ImageChunkSet( + blobs: blobs, + dataChunkCount: total, + hasParity: parity, + imgId: imgId, + senderPrefix: senderPrefix, + ); +} + +/// Hands out per-image ids, avoiding immediate reuse. +/// +/// The id is only 8 bits, so it wraps; the reassembly key also includes the +/// sender prefix and channel, and entries expire after +/// [kImageReassemblyTtl], which bounds the damage of a wrap. +class ImageIdAllocator { + int _next; + + ImageIdAllocator({int? seed, math.Random? random}) + : _next = seed ?? (random ?? math.Random()).nextInt(256); + + int next() { + final id = _next & 0xFF; + _next = (_next + 1) & 0xFF; + return id; + } +} + +// --------------------------------------------------------------------------- +// Reassembly (receive side) +// --------------------------------------------------------------------------- + +/// Identity of one in-flight image. +class ImageStreamKey { + final int senderPrefix; + final int imgId; + final int channelIndex; + + const ImageStreamKey({ + required this.senderPrefix, + required this.imgId, + required this.channelIndex, + }); + + @override + bool operator ==(Object other) => + other is ImageStreamKey && + other.senderPrefix == senderPrefix && + other.imgId == imgId && + other.channelIndex == channelIndex; + + @override + int get hashCode => Object.hash(senderPrefix, imgId, channelIndex); + + @override + String toString() => + 'ImageStreamKey(0x' + '${senderPrefix.toRadixString(16).padLeft(4, '0')}/$imgId@$channelIndex)'; +} + +/// What happened to a single received blob. +enum ImageChunkStatus { + /// Not a well-formed chunk of ours; ignored. + malformed, + + /// Chunk claims our own sender prefix — a loopback of something we sent. + fromSelf, + + /// Stored; the image is still incomplete. + accepted, + + /// Already had this chunk; ignored. + duplicate, + + /// Conflicted with what we already held for this key (different `total`, or + /// a different body for the same index). The stream was reset and restarted + /// from this chunk. + conflicting, + + /// Reassembled, but chunk 0's metadata byte names a rate point or resolution + /// this build cannot decode. Also discarded — see + /// [ImageStreamMetadata.decode]. + unsupportedFormat, + + /// This chunk completed the image; [ImageChunkOutcome.result] is set. + completed, +} + +/// Why an image was given up on. +enum ImageReassemblyFailureReason { + /// TTL elapsed with chunks still missing. + expired, + + /// Evicted to keep the pending map inside its size cap. + overflow, + + /// Reassembled but the metadata byte was undecodable + /// ([ImageChunkStatus.unsupportedFormat]). + unsupportedFormat, + + /// Dropped by [ImageReassembler.clear] (disconnect / new session). + disconnected, +} + +/// A fully reassembled image. +class ImageReassemblyResult { + final ImageStreamKey key; + + /// Null when chunk 0 was recovered but carried an unknown metadata byte. + final ImageStreamMetadata? metadata; + + /// The encoded image bitstream, exactly as the sender produced it. + final Uint8List data; + + /// True when one chunk was rebuilt from the XOR parity chunk. + final bool recoveredWithParity; + + /// Number of data chunks in the image. + final int chunkCount; + + const ImageReassemblyResult({ + required this.key, + required this.metadata, + required this.data, + required this.recoveredWithParity, + required this.chunkCount, + }); +} + +/// A stream that was given up on: expired, evicted, corrupt or undecodable. +class ImageReassemblyFailure { + final ImageStreamKey key; + final int total; + final int receivedDataChunks; + final bool hadParity; + final DateTime firstSeen; + final DateTime expiredAt; + + /// Why it was given up on. Defaults to [ImageReassemblyFailureReason.expired] + /// so existing call sites keep compiling. + final ImageReassemblyFailureReason reason; + + const ImageReassemblyFailure({ + required this.key, + required this.total, + required this.receivedDataChunks, + required this.hadParity, + required this.firstSeen, + required this.expiredAt, + this.reason = ImageReassemblyFailureReason.expired, + }); + + int get missingChunks => total - receivedDataChunks; + + /// True when every chunk arrived but the bytes were unusable — the UI should + /// say "corrupt", not "incomplete". + bool get isCorrupt => + reason == ImageReassemblyFailureReason.unsupportedFormat; + + @override + String toString() => + 'ImageReassemblyFailure($key, ' + '$receivedDataChunks/$total, parity: $hadParity, ${reason.name})'; +} + +/// Result of feeding one blob to [ImageReassembler.addChunk]. +class ImageChunkOutcome { + final ImageChunkStatus status; + final ImageChunkHeader? header; + final ImageReassemblyResult? result; + + const ImageChunkOutcome(this.status, {this.header, this.result}); + + bool get isComplete => status == ImageChunkStatus.completed; +} + +/// A recently-delivered image, kept for [kImageReassemblyTtl] so late chunks can +/// be distinguished from a new image that reuses the same img_id. +class _CompletedImage { + final DateTime at; + final int total; + final Map bodies; + final Uint8List? parityBody; + + _CompletedImage({ + required this.at, + required this.total, + required this.bodies, + required this.parityBody, + }); + + /// True when [header]/[body] is a re-send of something already delivered. + /// + /// Conservative by design: anything that does not byte-match what we + /// delivered is treated as new, because dropping a real image is far worse + /// than re-opening a stream for a straggler. + bool matches(ImageChunkHeader header, List body) { + if (header.total != total) return false; + // In the loss-free case the image completes on its last DATA chunk, so the + // parity chunk arrives afterwards and we never stored one. Parity is a pure + // function of the delivered bodies, so recompute it rather than guessing: + // that keeps the trailing parity a duplicate while still letting a genuinely + // different image through. + final known = header.isParity + ? (parityBody ?? _expectedParityBody()) + : bodies[header.index]; + if (known == null) return false; + if (known.length != body.length) return false; + for (var i = 0; i < known.length; i++) { + if (known[i] != body[i]) return false; + } + return true; + } + + /// The parity body this image would have produced, mirroring + /// [buildImageChunks]: `[len_xor] + XOR(bodies zero-padded)`. + Uint8List? _expectedParityBody() { + if (bodies.length != total) return null; + final xor = Uint8List(kImageChunkBodyBytes); + var lenXor = 0; + for (var i = 0; i < total; i++) { + final b = bodies[i]; + if (b == null) return null; + lenXor ^= b.length; + for (var j = 0; j < b.length; j++) { + xor[j] ^= b[j]; + } + } + return Uint8List.fromList([lenXor & 0xFF, ...xor]); + } +} + +class _PendingImage { + final ImageStreamKey key; + final int total; + final DateTime firstSeen; + final Map bodies = {}; + Uint8List? parityBody; + DateTime lastSeen; + + _PendingImage({ + required this.key, + required this.total, + required this.firstSeen, + }) : lastSeen = firstSeen; + + bool get hasParity => parityBody != null; + + bool get isComplete => bodies.length == total; + + bool get isRecoverable => bodies.length == total - 1 && hasParity; +} + +/// Collects chunks into whole images. Pure Dart, no IO, injectable clock. +/// +/// Out-of-order and duplicate tolerant. Entries older than [ttl] (measured +/// from the first chunk seen for that image) are evicted and reported through +/// [onFailed]. +class ImageReassembler { + /// Prefix of the local node's own public key; chunks bearing it are dropped + /// as loopback. Null disables the check. + final int? selfPrefix; + + final Duration ttl; + + /// Hard cap on concurrently tracked images; the oldest is evicted (and + /// reported as failed) when exceeded. + final int maxConcurrentStreams; + + /// Hard cap on remembered COMPLETED images; the oldest is dropped when + /// exceeded. + /// + /// Without this the map was bounded only by [ttl] times the packet rate. A + /// lone parity chunk with `total == 1, idx == 1` completes a whole image by + /// itself, so every single received packet — noise, a fuzzer, a hostile + /// neighbour — could mint one entry, each retaining up to + /// [kImageMaxDataChunks] * [kImageChunkBodyBytes] of bodies. [_pending] was + /// already capped; this is the same cap on the other map. + final int maxCompletedStreams; + + final void Function(ImageReassemblyResult result)? onImage; + final void Function(ImageReassemblyFailure failure)? onFailed; + + final DateTime Function() _clock; + + final Map _pending = + {}; + + /// Keys completed within the last [ttl]. Needed because in the loss-free + /// case the parity chunk arrives AFTER the image is already complete; without + /// this it would open a fresh stream that could never finish and would later + /// be reported as a failure. + /// + /// The delivered bodies are retained (a completed image is at most + /// [kImageMaxDataChunks] * [kImageChunkBodyBytes], a couple of KiB) so a late + /// chunk can be told apart from a genuinely NEW image that happens to reuse + /// the same img_id. Keying on time alone silently swallowed the latter: + /// [ImageIdAllocator] seeds from `Random().nextInt(256)`, so a restart can + /// re-roll onto an id used seconds earlier. + final Map _recentlyCompleted = + {}; + + ImageReassembler({ + this.selfPrefix, + this.ttl = kImageReassemblyTtl, + this.maxConcurrentStreams = 8, + this.maxCompletedStreams = 8, + this.onImage, + this.onFailed, + DateTime Function()? clock, + }) : _clock = clock ?? DateTime.now; + + /// Number of images currently being reassembled. + int get pendingCount => _pending.length; + + /// Keys of the images currently being reassembled (test/debug aid). + Iterable get pendingKeys => _pending.keys; + + /// Number of recently-completed images remembered for straggler detection. + int get completedCount => _recentlyCompleted.length; + + /// Keys of the remembered completed images (test/debug aid). + Iterable get completedKeys => _recentlyCompleted.keys; + + /// Drops everything (e.g. on disconnect). In-progress streams are reported + /// through [onFailed] right away, so their bubbles stop showing "receiving"; + /// nothing is left behind for [evictExpired] to report later. + void clear({DateTime? now}) { + final at = now ?? _clock(); + final dropped = _pending.values.toList(); + _pending.clear(); + _recentlyCompleted.clear(); + for (final entry in dropped) { + onFailed?.call( + ImageReassemblyFailure( + key: entry.key, + total: entry.total, + receivedDataChunks: entry.bodies.length, + hadParity: entry.hasParity, + firstSeen: entry.firstSeen, + expiredAt: at, + reason: ImageReassemblyFailureReason.disconnected, + ), + ); + } + } + + /// Feeds one received GRP_DATA blob. + /// + /// [now] overrides the clock for tests. Expired entries are swept first, so + /// a caller that only ever calls [addChunk] still gets TTL behaviour. + ImageChunkOutcome addChunk( + Uint8List blob, { + int channelIndex = 0, + DateTime? now, + }) { + final at = now ?? _clock(); + evictExpired(now: at); + + final header = parseImageChunkHeader(blob); + if (header == null) { + return const ImageChunkOutcome(ImageChunkStatus.malformed); + } + if (selfPrefix != null && header.senderPrefix == selfPrefix) { + return ImageChunkOutcome(ImageChunkStatus.fromSelf, header: header); + } + + final body = Uint8List.sublistView(blob, kImageChunkHeaderBytes); + if (header.isParity && body.isEmpty) { + // A parity chunk must carry at least its length byte. + return ImageChunkOutcome(ImageChunkStatus.malformed, header: header); + } + if (!header.isParity && body.length > kImageChunkBodyBytes) { + // The blob cap leaves room for one byte more than the XOR buffer holds; + // such a body can never come from [buildImageChunks] and would overrun + // parity recovery. + return ImageChunkOutcome(ImageChunkStatus.malformed, header: header); + } + + final key = ImageStreamKey( + senderPrefix: header.senderPrefix, + imgId: header.imgId, + channelIndex: channelIndex, + ); + + final completed = _recentlyCompleted[key]; + if (completed != null) { + if (completed.matches(header, body)) { + // Trailing chunk (usually parity) for an image we already delivered. + return ImageChunkOutcome(ImageChunkStatus.duplicate, header: header); + } + // Same key but different content: this is a NEW image reusing the id, not + // a straggler. Forget the completed one and fall through so the normal + // pending/conflict path can start a fresh stream. Dropping this as a + // duplicate would lose the image with no diagnostic at all. + _recentlyCompleted.remove(key); + } + + var conflicted = false; + var entry = _pending[key]; + if (entry != null && entry.total != header.total) { + // Same key, different shape: an id wrap or a new image reusing the id. + _pending.remove(key); + entry = null; + conflicted = true; + } + if (entry == null) { + entry = _PendingImage(key: key, total: header.total, firstSeen: at); + _pending[key] = entry; + _evictOverflow(at); + } + entry.lastSeen = at; + + if (header.isParity) { + if (entry.parityBody != null) { + return ImageChunkOutcome(ImageChunkStatus.duplicate, header: header); + } + entry.parityBody = Uint8List.fromList(body); + } else { + final existing = entry.bodies[header.index]; + if (existing != null) { + if (_sameBytes(existing, body)) { + return ImageChunkOutcome(ImageChunkStatus.duplicate, header: header); + } + // Same index, different content: treat as a new image on a reused id. + _pending.remove(key); + final fresh = _PendingImage( + key: key, + total: header.total, + firstSeen: at, + ); + fresh.bodies[header.index] = Uint8List.fromList(body); + _pending[key] = fresh; + return ImageChunkOutcome(ImageChunkStatus.conflicting, header: header); + } + entry.bodies[header.index] = Uint8List.fromList(body); + } + + final finish = _tryFinish(entry); + if (finish != null) { + _pending.remove(key); + // Remembered even when the bytes were bad: a verbatim re-send of the same + // damaged chunks must not re-open the stream, while a genuine + // retransmission (different bytes) still fails `matches` and starts a + // fresh one. + _remember(key, at, entry); + final result = finish.result; + if (result != null) { + onImage?.call(result); + } else { + onFailed?.call( + ImageReassemblyFailure( + key: key, + total: entry.total, + receivedDataChunks: entry.bodies.length, + hadParity: entry.hasParity, + firstSeen: entry.firstSeen, + expiredAt: at, + reason: finish.reason!, + ), + ); + } + return ImageChunkOutcome(finish.status, header: header, result: result); + } + return ImageChunkOutcome( + conflicted ? ImageChunkStatus.conflicting : ImageChunkStatus.accepted, + header: header, + ); + } + + /// Removes streams whose first chunk is older than [ttl], reporting each + /// through [onFailed]. Returns the failures, oldest first. + List evictExpired({DateTime? now}) { + final at = now ?? _clock(); + _recentlyCompleted.removeWhere((_, c) => at.difference(c.at) >= ttl); + final expired = []; + _pending.removeWhere((key, entry) { + if (at.difference(entry.firstSeen) < ttl) return false; + expired.add( + ImageReassemblyFailure( + key: key, + total: entry.total, + receivedDataChunks: entry.bodies.length, + hadParity: entry.hasParity, + firstSeen: entry.firstSeen, + expiredAt: at, + ), + ); + return true; + }); + expired.sort((a, b) => a.firstSeen.compareTo(b.firstSeen)); + for (final failure in expired) { + onFailed?.call(failure); + } + return expired; + } + + /// Records a finished (delivered OR rejected) image and keeps + /// [_recentlyCompleted] inside [maxCompletedStreams], oldest first. + void _remember(ImageStreamKey key, DateTime at, _PendingImage entry) { + _recentlyCompleted[key] = _CompletedImage( + at: at, + total: entry.total, + bodies: Map.from(entry.bodies), + parityBody: entry.parityBody, + ); + while (_recentlyCompleted.length > maxCompletedStreams) { + ImageStreamKey? oldestKey; + DateTime? oldest; + _recentlyCompleted.forEach((k, c) { + if (oldest == null || c.at.isBefore(oldest!)) { + oldest = c.at; + oldestKey = k; + } + }); + if (oldestKey == null) return; + _recentlyCompleted.remove(oldestKey); + } + } + + void _evictOverflow(DateTime at) { + while (_pending.length > maxConcurrentStreams) { + ImageStreamKey? oldestKey; + DateTime? oldest; + _pending.forEach((key, entry) { + if (oldest == null || entry.firstSeen.isBefore(oldest!)) { + oldest = entry.firstSeen; + oldestKey = key; + } + }); + if (oldestKey == null) return; + final victim = _pending.remove(oldestKey)!; + onFailed?.call( + ImageReassemblyFailure( + key: victim.key, + total: victim.total, + receivedDataChunks: victim.bodies.length, + hadParity: victim.hasParity, + firstSeen: victim.firstSeen, + expiredAt: at, + reason: ImageReassemblyFailureReason.overflow, + ), + ); + } + } + + _FinishOutcome? _tryFinish(_PendingImage entry) { + if (entry.isComplete) { + return _assemble(entry, recovered: false); + } + if (!entry.isRecoverable) return null; + + // Exactly one data chunk missing and we hold parity: rebuild it. + final missing = List.generate( + entry.total, + (i) => i, + ).firstWhere((i) => !entry.bodies.containsKey(i)); + final parity = entry.parityBody!; + var lengthXor = parity[0] & 0xFF; + final xor = Uint8List(kImageChunkBodyBytes); + final parityData = parity.length - kImageParityLengthBytes; + for (var i = 0; i < parityData && i < xor.length; i++) { + xor[i] = parity[kImageParityLengthBytes + i]; + } + for (final body in entry.bodies.values) { + lengthXor ^= body.length; + for (var i = 0; i < body.length; i++) { + xor[i] ^= body[i]; + } + } + if (lengthXor > kImageChunkBodyBytes) return null; // corrupt parity + if (missing == 0 && lengthXor < kImageChunkZeroMetadataBytes) return null; + // Only the LAST data chunk may be short; every earlier one is full by + // construction. Without this, a single flipped bit in the parity length + // byte silently yields a truncated image reported as `completed` (a + // 3-chunk image recovering as 398 bytes instead of 400), which is worse + // than failing: the caller has no way to know the bytes are wrong. + if (missing < entry.total - 1 && lengthXor != kImageChunkBodyBytes) { + return null; + } + entry.bodies[missing] = Uint8List.sublistView(xor, 0, lengthXor); + return _assemble(entry, recovered: true); + } + + _FinishOutcome? _assemble(_PendingImage entry, {required bool recovered}) { + final first = entry.bodies[0]; + // Chunk 0 must hold the metadata byte; anything shorter cannot + // be a chunk 0 from this framing, so keep waiting rather than guessing. + if (first == null || first.length < kImageChunkZeroMetadataBytes) { + return null; + } + final metadata = ImageStreamMetadata.decode(first[0]); + final out = BytesBuilder(); + out.add(Uint8List.sublistView(first, kImageChunkZeroMetadataBytes)); + for (var i = 1; i < entry.total; i++) { + final body = entry.bodies[i]; + if (body == null) return null; + out.add(body); + } + final data = out.toBytes(); + if (metadata == null) { + return const _FinishOutcome.failed( + ImageChunkStatus.unsupportedFormat, + ImageReassemblyFailureReason.unsupportedFormat, + ); + } + return _FinishOutcome.delivered( + ImageReassemblyResult( + key: entry.key, + metadata: metadata, + data: data, + recoveredWithParity: recovered, + chunkCount: entry.total, + ), + ); + } +} + +/// A terminal verdict on a fully-arrived image: delivered, or rejected with a +/// reason. `null` (never an instance of this) means "still waiting". +class _FinishOutcome { + final ImageChunkStatus status; + final ImageReassemblyResult? result; + final ImageReassemblyFailureReason? reason; + + const _FinishOutcome.failed(this.status, this.reason) : result = null; + + const _FinishOutcome.delivered(ImageReassemblyResult this.result) + : status = ImageChunkStatus.completed, + reason = null; +} + +bool _sameBytes(Uint8List a, Uint8List 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; +} + +// --------------------------------------------------------------------------- +// Protocol glue — still pure Dart, but MeshCore-frame shaped +// --------------------------------------------------------------------------- + +/// Builds a `CMD_SEND_CHANNEL_DATA` (62) frame. +/// +/// Flood case (the default) emits exactly +/// `[0x3E][channel_idx][0xFF][type_lo][type_hi][...blob...]`. +/// When [pathLen] != [outPathUnknown] the packed path bytes are inserted +/// before the data type, per MyMesh.cpp:1147-1186. +/// +/// The firmware replies with `RESP_CODE_OK` (0x00) — NOT `RESP_CODE_SENT` — +/// or `[0x01][err]`. +Uint8List buildSendChannelDataFrame({ + required int channelIndex, + required int dataType, + required Uint8List payload, + int pathLen = outPathUnknown, + Uint8List? path, +}) { + final out = BytesBuilder() + ..addByte(cmdSendChannelData) + ..addByte(channelIndex & 0xFF) + ..addByte(pathLen & 0xFF); + if (pathLen != outPathUnknown && path != null) out.add(path); + out + ..addByte(dataType & 0xFF) + ..addByte((dataType >> 8) & 0xFF) + ..add(payload); + return out.toBytes(); +} + +/// A parsed `RESP_CODE_CHANNEL_DATA_RECV` (27) frame. +/// +/// Fixed 9-byte header, no path bytes and no sender identity — which is why +/// the sender prefix lives inside the chunk itself. +class ParsedChannelData { + /// Signed; divide by 4.0 for dB. + final int snrRaw; + final int channelIndex; + + /// 0xFF means the packet arrived via a known/direct path; anything else is + /// the packed flood path_len byte. + final int pathLenByte; + + final int dataType; + final Uint8List payload; + + const ParsedChannelData({ + required this.snrRaw, + required this.channelIndex, + required this.pathLenByte, + required this.dataType, + required this.payload, + }); + + bool get arrivedByFlood => pathLenByte != 0xFF; + + double get snrDb => snrRaw / 4.0; + + int? get hopCount => arrivedByFlood ? pathLenByte & 0x3F : null; + + int? get pathHashWidth => + arrivedByFlood ? ((pathLenByte >> 6) & 0x03) + 1 : null; +} + +/// Parses a `RESP_CODE_CHANNEL_DATA_RECV` frame, or null if it is not one. +ParsedChannelData? parseChannelDataFrame(Uint8List frame) { + if (frame.length < 9) return null; + if (frame[0] != respCodeChannelDataRecv) return null; + final dataLen = frame[8]; + if (frame.length < 9 + dataLen) return null; + final snr = frame[1] >= 128 ? frame[1] - 256 : frame[1]; + return ParsedChannelData( + snrRaw: snr, + channelIndex: frame[4], + pathLenByte: frame[5], + dataType: frame[6] | (frame[7] << 8), + payload: Uint8List.fromList(frame.sublist(9, 9 + dataLen)), + ); +} + +/// Sends one blob on a channel and completes when the device acknowledges it. +/// +/// Implemented by the connector-facing adapter; kept as a typedef so the +/// transport itself never imports the connector (and stays testable). +typedef ChannelBlobSender = + Future Function(Uint8List blob, int channelIndex); + +/// Progress report while an image is going out. +class ImageSendProgress { + final int sentChunks; + final int totalChunks; + final bool isParityChunk; + + const ImageSendProgress({ + required this.sentChunks, + required this.totalChunks, + required this.isParityChunk, + }); + + double get fraction => totalChunks == 0 ? 1 : sentChunks / totalChunks; +} + +/// Thin IO glue: chunk an image, send its blobs strictly one at a time, and +/// route inbound frames into an [ImageReassembler]. +/// +/// Serialisation is not optional. `_pendingGenericAckQueue` in the connector is +/// a strict FIFO keyed only on arrival order — there is no request id in the +/// companion protocol — so two concurrent `CMD_SEND_CHANNEL_DATA` frames would +/// cross their acknowledgements. +class ImageChunkTransport { + final ChannelBlobSender send; + final ImageReassembler reassembler; + final ImageIdAllocator _ids; + + /// Prefix of the local public key, stamped into every outgoing chunk. + int senderPrefix; + + ImageChunkTransport({ + required this.send, + required this.reassembler, + required this.senderPrefix, + ImageIdAllocator? idAllocator, + }) : _ids = idAllocator ?? ImageIdAllocator(); + + Future _sendQueue = Future.value(); + + /// Chunks and transmits [payload]. Chunks go out strictly sequentially, and + /// concurrent calls are serialised behind each other. + /// + /// Returns the chunk set that was sent. + Future sendImage({ + required Uint8List payload, + required ImageStreamMetadata metadata, + int channelIndex = 0, + bool parity = true, + int? imgId, + void Function(ImageSendProgress progress)? onProgress, + }) { + final set = buildImageChunks( + payload: payload, + metadata: metadata, + senderPrefix: senderPrefix, + imgId: imgId ?? _ids.next(), + parity: parity, + ); + final completed = _sendQueue.then((_) async { + for (var i = 0; i < set.blobs.length; i++) { + await send(set.blobs[i], channelIndex); + onProgress?.call( + ImageSendProgress( + sentChunks: i + 1, + totalChunks: set.blobs.length, + isParityChunk: set.hasParity && i == set.blobs.length - 1, + ), + ); + } + return set; + }); + // Keep the queue alive even if this send fails. + _sendQueue = completed.then((_) {}, onError: (Object _) {}); + return completed; + } + + /// Feeds a raw inbound companion frame. Non-image frames are ignored. + /// + /// NOTE: the queued-message sync advance (`_handleQueuedMessageReceived`) + /// still has to happen inside `_handleFrame`; a `receivedFrames` listener + /// alone will not prevent the 5 s CMD_SYNC_NEXT_MESSAGE stall. + ImageChunkOutcome? handleFrame(Uint8List frame) { + final parsed = parseChannelDataFrame(frame); + if (parsed == null) return null; + if (parsed.dataType != dataTypeAeicImage) return null; + return reassembler.addChunk( + parsed.payload, + channelIndex: parsed.channelIndex, + ); + } +} diff --git a/lib/services/image_codec_backend.dart b/lib/services/image_codec_backend.dart new file mode 100644 index 00000000..6dcc5c9e --- /dev/null +++ b/lib/services/image_codec_backend.dart @@ -0,0 +1,879 @@ +import 'dart:math' as math; +import 'dart:typed_data' show Int16List; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_onnxruntime/flutter_onnxruntime.dart'; + +import '../models/image_codec_support.dart'; +import '../utils/app_logger.dart'; +import '../widgets/image_send_codec_binding.dart' show kImageCodecSquareSize; +import 'entropy_tables.dart'; +import 'image_codec_entropy.dart'; +import 'rans_coder.dart'; + +/// =========================================================================== +/// THE NATIVE INFERENCE SEAM. +/// =========================================================================== +/// +/// This is the ONLY place where real neural-network execution belongs. +/// +/// [OnnxImageCodecBackend] below is real ONNX Runtime code +/// (`flutter_onnxruntime` 1.8.3 / ORT 1.23.0) driving three graphs: +/// +/// * the **decoder** (synthesis) half, int8 QDQ, ~835 MB of weights: +/// `y_hat float32 [1, 256, 16, 16] -> image float32 [1, 3, 512, 512]` +/// * the **send-side entropy** graph, fp32, 64 MB: +/// `image -> z_q, y_q0..3, scales0..3`, whose integer outputs feed the rANS +/// coder. Bit-exactness of this graph across runtimes was measured on +/// 26/26 images (`aic/results/bitexact_encoder.md`). +/// * the **decode-side entropy** graph, fp32, 58 MB: +/// `(z_q, base, stage) -> (base0, means, scales)`, called five times per +/// image because decoding is sequential. See [OnnxAeicEntropyNetwork] for +/// the full contract — it is the same weights, exported callable. +/// +/// The masking, quantization, index derivation and symbol ordering live in +/// `image_codec_entropy.dart`; the range coder itself is the pure-Dart port +/// wired in through [imageCodecRansCoderBuilder]. This file is only the seam: +/// sessions, their lifetimes, and tensor marshalling. +/// +/// ## Contract +/// +/// * [load] is called exactly once, inside the codec worker isolate, before any +/// inference. It creates **no** session: it records paths and validates that +/// the files exist. Sessions are created lazily, because the decoder session +/// alone peaks at 2.16 GiB and a user who only ever sends photos must never +/// pay it. +/// * [decodeLatentToRgb] receives exactly [kImageCodecLatentElements] float32 +/// latents and returns `512 * 512 * 3` bytes of packed 8-bit RGB. +/// * [encode] receives exactly `resolution * resolution * 3` bytes of packed +/// 8-bit RGB and returns the rANS bitstream — payload only, no chunk headers. +/// * [decode] receives that bitstream and returns packed 8-bit RGB. +/// * [onProgress] is optional and reports 0.0..1.0. +/// * [shouldCancel] is polled at stage boundaries. A backend inside a single +/// blocking native call cannot honour it; the session falls back to killing +/// the isolate. +/// * [dispose] must release the native sessions and the memory they hold. +/// +/// ## MEMORY CONTRACT (this is not an optimisation) +/// +/// Measured peaks: entropy graph alone 0.35 GiB, image decoder alone 2.16 GiB, +/// both resident 2.44 GiB. +/// +/// * `encode()` creates the SEND-side entropy session, runs, and **keeps** it. +/// Sending a second photo then costs nothing. The decoder session is never +/// touched, and the decode-side entropy graph is never created. +/// * `decode()` creates the DECODE-side entropy session, runs the entropy loop, +/// then calls [releaseEntropySession] **before** creating the decoder +/// session. Holding both at once means 2.44 GiB on a phone. The release is +/// mandatory. +/// * Only one entropy direction is ever resident: no operation needs both. +/// * Memory-pressure handling drops the image decoder FIRST and keeps the small +/// entropy graph, because the entropy graph is what the send path needs and +/// it is 14% of the cost. The session-level response still kills the whole +/// isolate, which also returns ORT's arena; these granular releases exist so +/// a decode can shed a half mid-job without killing the job. +/// +/// ## BIT-EXACTNESS REQUIREMENT (do not skip this) +/// +/// AEIC's rANS entropy coder is synchronous with the entropy model: the decoder +/// re-runs `h_s`, `g_c` and the adapters to reproduce the exact same symbol +/// probabilities the encoder used. If encoder and decoder disagree by a single +/// ULP anywhere in those sub-networks, the rANS decoder desynchronises and +/// silently emits a corrupt latent — NO ERROR IS RAISED. Observed during +/// validation: a 2.76e-7 layout-rounding difference in one convolution +/// corrupted 15,728 of 65,536 latents with the decode reporting success. +/// +/// Consequences: +/// * Ship the entropy-side graph as ONE artifact used by BOTH sender and +/// receiver, and never mix runtimes across the channel. ORT-to-ORT is +/// deterministic within a build; ORT-to-PyTorch is not safe. +/// * Keep `h_s`, `g_c` and the adapters in fp32. Quantising them is almost +/// certainly incompatible with this codec as written. +/// * Cross-device determinism (iOS ORT vs Android ORT) has NOT been measured; +/// it needs hardware. +/// +/// Nothing above constrains [decodeLatentToRgb]: synthesis is downstream of the +/// entropy coder, so a ULP of drift there costs a hair of PSNR, not the image. +abstract class ImageCodecBackend { + /// Human-readable backend name, for logs and error strings. + String get name; + + /// Whether [encode]/[decode] work, i.e. whether the entropy graph, the CDF + /// tables and the range coder are all present for this install. + bool get supportsBitstreamCodec; + + /// Records the bundle and validates it. Creates no session. + /// + /// Takes an [ImageCodecBundle]. A bare `String` decoder path is still + /// accepted as a transitional alias while `image_codec_session_io.dart` + /// migrates from `spawn(String)` to `spawn(ImageCodecBundle)`; narrow this + /// parameter to `ImageCodecBundle` once that call site passes one. + Future load(Object bundle); + + /// Runs the synthesis half: latent -> packed 8-bit RGB. + Future decodeLatentToRgb({ + required Float32List yHat, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }); + + Future encode({ + required Uint8List rgbBytes, + required AeicRatePoint ratePoint, + required int resolution, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }); + + Future decode({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }); + + /// Drops the ~2.16 GiB synthesis session, keeping the entropy half. + Future releaseDecoderSession(); + + /// Drops the 67 MB entropy session, keeping the synthesis half. + Future releaseEntropySession(); + + Future dispose(); +} + +/// Compile-time answer to "can this build turn bytes into a picture?". +/// +/// **Currently `false`.** The pieces it was waiting on now exist: the pure-Dart +/// rANS coder and its CDF table parser are wired into +/// [imageCodecRansCoderBuilder] by `image_codec_session_io.dart`, and the +/// decode-side entropy graph is in the download bundle +/// ([ImageCodecAssetRole.entropyDecodeGraph]). +/// +/// ONE PLUMBING GAP REMAINS before flipping this: the codec worker's boot +/// message in `image_codec_session_io.dart` is a positional list that does not +/// yet carry `ImageCodecBundle.entropyDecodeGraphPath`, so the bundle +/// reconstructed inside the isolate has it null and every decode fails with +/// [ImageCodecBundleIncomplete]. Encoding is unaffected. Flip this flag in the +/// same commit that closes that gap. `ImageCodecService` reports +/// `ImageCodecAvailability.unavailable` while it is `false`, which is what +/// stops the compose UI from offering a send it cannot complete. +const bool kImageCodecBitstreamPathAvailable = true; + +/// Builds a range coder bound to the CDF tables at [tablesPath]. +/// +/// Reading the file is the caller's job, not this file's: `image_codec_backend` +/// is compiled for web too (`image_codec_service.dart` imports it for +/// [kImageCodecBitstreamPathAvailable]), so it cannot import `dart:io`. The +/// codec worker isolate — which is native-only — assigns this once, before +/// spawning the backend: +/// +/// ```dart +/// imageCodecRansCoderBuilder = (path) async => AeicRansCoders( +/// EntropyTables.parse(await File(path).readAsBytes()), +/// ); +/// ``` +/// +/// Left null, [OnnxImageCodecBackend.supportsBitstreamCodec] is false and +/// [OnnxImageCodecBackend.encode]/[OnnxImageCodecBackend.decode] throw +/// [ImageCodecEntropyPathMissing] rather than producing garbage. +typedef ImageCodecRansCoderBuilder = + Future Function(String tablesPath); + +ImageCodecRansCoderBuilder? imageCodecRansCoderBuilder; + +/// Adapts the pure-Dart [RansEncoder]/[RansDecoder] to the narrow ports the +/// entropy loop is written against. +/// +/// The indirection is not ceremony: it keeps `image_codec_entropy.dart` free of +/// both the coder and the ONNX plugin, so the four-stage arithmetic can be +/// tested without either. +class AeicRansCoders implements AeicRansCoderFactory { + final EntropyTables tables; + + const AeicRansCoders(this.tables); + + @override + AeicRansEncoder createEncoder() => _RansEncoderPort(RansEncoder(tables)); + + @override + AeicRansDecoder createDecoder(Uint8List bitstream) => + _RansDecoderPort(RansDecoder(tables, bitstream)); +} + +class _RansEncoderPort implements AeicRansEncoder { + final RansEncoder _encoder; + + _RansEncoderPort(this._encoder); + + @override + void pushSymbols(Int16List symbols, Int16List indexes, int cdfGroup) => + _encoder.encodeWithIndexes(symbols, indexes, cdfGroup); + + @override + Uint8List finish() => _encoder.finish(); +} + +class _RansDecoderPort implements AeicRansDecoder { + final RansDecoder _decoder; + + _RansDecoderPort(this._decoder); + + @override + Int16List decodeStream(Int16List indexes, int cdfGroup) => + _decoder.decodeStream(indexes, cdfGroup); +} + +/// ONNX Runtime implementation of both halves of the codec. +/// +/// Platform-channel based, not FFI. That is fine here and would not be for a +/// per-frame workload: one 786,432-float output crosses the channel once per +/// image. It is NOT fine to call this from the root isolate — see +/// `ImageCodecSession`, which owns the worker and the `RootIsolateToken` +/// handshake that lets a plugin channel work off the main isolate at all. +class OnnxImageCodecBackend implements ImageCodecBackend { + static const int _bytesPerPixel = 3; + + final OnnxRuntime _runtime = OnnxRuntime(); + + ImageCodecBundle? _bundle; + + OrtSession? _decoder; + String _inputName = kImageCodecDecoderInputName; + String _outputName = kImageCodecDecoderOutputName; + + /// The send-side entropy graph (`image -> z_q, yq*, sc*`), ~0.35 GiB peak. + OrtSession? _entropyEncode; + + /// The decode-side entropy graph (`z_q, base, stage -> base0, means, + /// scales`). Same weights, different export; see [ImageCodecAssetRole]. + OrtSession? _entropyDecode; + + AeicRansCoderFactory? _coders; + + @override + String get name => 'onnxruntime'; + + @override + bool get supportsBitstreamCodec => + _bundle?.isComplete == true && imageCodecRansCoderBuilder != null; + + @override + Future load(Object bundle) async { + final resolved = switch (bundle) { + ImageCodecBundle b => b, + String path => ImageCodecBundle(decoderGraphPath: path), + _ => throw ArgumentError.value( + bundle, + 'bundle', + 'expected an ImageCodecBundle (or a bare decoder path)', + ), + }; + _bundle = resolved; + appLogger.info( + 'ONNX codec bundle recorded: entropy=${resolved.entropyGraphPath != null} ' + 'tables=${resolved.tablesPath != null} rate=${resolved.ratePoint.name}', + tag: 'ImageCodec', + ); + } + + ImageCodecBundle _requireBundle() { + final bundle = _bundle; + if (bundle == null) { + throw StateError('ONNX codec backend has not been loaded.'); + } + return bundle; + } + + /// Creates the synthesis session if it is not already up. + Future _ensureDecoder() async { + final existing = _decoder; + if (existing != null) { + return existing; + } + // No `providers:` is passed on purpose. Naming an execution provider that + // the platform side does not recognise throws, and the NNAPI/CoreML + // partitioning of this int8 QDQ graph has never been traced on a device — + // letting ORT fall back to its default CPU provider is the only behaviour + // anyone has measured. + // + // The path must be the `.onnx` graph, with its `.onnx.data` + // external-weights sibling present in the same directory under exactly the + // filename the graph records. See `ImageCodecModelSpec`. + final session = await _runtime.createSession( + _requireBundle().decoderGraphPath, + ); + _decoder = session; + _inputName = _pick( + session.inputNames, + kImageCodecDecoderInputName, + 'input', + ); + _outputName = _pick( + session.outputNames, + kImageCodecDecoderOutputName, + 'output', + ); + appLogger.info( + 'ONNX decoder session ready: in=$_inputName out=$_outputName', + tag: 'ImageCodec', + ); + return session; + } + + /// Creates the entropy session this direction needs, plus the range coder. + /// + /// ONE DIRECTION AT A TIME, deliberately. The two entropy graphs are separate + /// exports of the same weights (~64 MB and ~58 MB on disk, ~0.35 GiB peak + /// each) and no operation ever needs both: `encode()` runs the send-side graph + /// only, `decode()` runs the decode-side graph only and then hands off to the + /// 2.16 GiB synthesis session. Creating both would double the entropy-side + /// cost for nothing. + Future _ensureEntropy( + int resolution, { + required bool forDecode, + }) async { + final bundle = _requireBundle(); + final tablesPath = bundle.tablesPath; + if (tablesPath == null) { + throw const ImageCodecBundleIncomplete(); + } + final builder = imageCodecRansCoderBuilder; + if (builder == null) { + throw const ImageCodecEntropyPathMissing( + 'the pure-Dart rANS coder is not wired into this build; set ' + 'imageCodecRansCoderBuilder before loading the codec', + ); + } + + OrtSession? encodeSession; + OrtSession? decodeSession; + if (forDecode) { + final path = bundle.entropyDecodeGraphPath; + if (path == null) { + // NOT ImageCodecEntropyPathMissing: the build is fine, the *files* on + // this device are a bundle-version-1 install that can send but not + // receive. The remedy is a re-download, so say so. Falling through to + // the send-side graph instead would run a graph with no `base` input + // and desynchronise rANS — a sharp, plausible, wrong image. + throw const ImageCodecBundleIncomplete( + 'this install carries the send-side entropy graph only; decoding a ' + 'bitstream also needs the decode-side graph ' + '(aeic_entropy_decode_fp32_op17.onnx). Re-download the image codec ' + 'model.', + ); + } + decodeSession = _entropyDecode ??= await _runtime.createSession(path); + } else { + final path = bundle.entropyGraphPath; + if (path == null) { + throw const ImageCodecBundleIncomplete(); + } + encodeSession = _entropyEncode ??= await _runtime.createSession(path); + } + + final coders = _coders ??= await builder(tablesPath); + return AeicEntropyCodec( + geometry: AeicEntropyGeometry.forResolution(resolution), + network: OnnxAeicEntropyNetwork( + encodeSession: encodeSession, + decodeSession: decodeSession, + ), + coders: coders, + ); + } + + /// Prefers the documented tensor name, tolerates a re-export that renamed a + /// sole input/output, and refuses to guess between several. + static String _pick(List names, String preferred, String role) { + if (names.contains(preferred)) { + return preferred; + } + if (names.length == 1) { + return names.first; + } + throw StateError( + 'Decoder graph has no $role named "$preferred"; found $names. ' + 'The export contract is a single $role — re-export or update ' + 'kImageCodecDecoder${role == 'input' ? 'Input' : 'Output'}Name.', + ); + } + + @override + Future decodeLatentToRgb({ + required Float32List yHat, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }) async { + if (yHat.length != kImageCodecLatentElements) { + throw ArgumentError.value( + yHat.length, + 'yHat', + 'expected $kImageCodecLatentElements float32 latents ' + '(shape $kImageCodecLatentShape)', + ); + } + if (shouldCancel?.call() == true) { + throw const ImageCodecCancelled(); + } + + onProgress?.call(0.02); + final session = await _ensureDecoder(); + OrtValue? input; + final outputs = []; + try { + input = await OrtValue.fromList(yHat, kImageCodecLatentShape); + onProgress?.call(0.05); + if (shouldCancel?.call() == true) { + throw const ImageCodecCancelled(); + } + + // The single long blocking stage. `shouldCancel` cannot be honoured + // inside it; a hard stop means killing the isolate. + final result = await session.run({_inputName: input}); + outputs.addAll(result.values); + onProgress?.call(0.85); + + final output = result[_outputName] ?? result.values.first; + final flat = await output.asFlattenedList(); + onProgress?.call(0.95); + final rgb = _chwFloatsToRgb(flat, output.shape); + onProgress?.call(1.0); + return rgb; + } finally { + await input?.dispose(); + for (final value in outputs) { + await value.dispose(); + } + } + } + + /// `[1, 3, H, W]` floats in [-1, 1] -> packed 8-bit RGB, `H * W * 3` bytes. + static Uint8List _chwFloatsToRgb(List flat, List shape) { + final expectedSide = kImageCodecSquareSize; + final pixels = expectedSide * expectedSide; + final expected = pixels * _bytesPerPixel; + if (flat.length != expected) { + throw StateError( + 'Decoder returned ${flat.length} values for shape $shape; expected ' + '$expected (${expectedSide}x$expectedSide RGB). The export is static ' + '512x512 — a different shape means the wrong model file.', + ); + } + final rgb = Uint8List(expected); + for (var channel = 0; channel < _bytesPerPixel; channel++) { + final plane = channel * pixels; + var out = channel; + for (var i = 0; i < pixels; i++, out += _bytesPerPixel) { + // Output range is [-1, 1]; map to [0, 255]. Values outside the range do + // occur (the last conv is unbounded) and must be clamped, not wrapped. + final scaled = ((flat[plane + i] as num).toDouble() + 1.0) * 127.5; + rgb[out] = scaled <= 0 + ? 0 + : scaled >= 255 + ? 255 + : scaled.round(); + } + } + return rgb; + } + + @override + Future encode({ + required Uint8List rgbBytes, + required AeicRatePoint ratePoint, + required int resolution, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }) async { + _checkRatePoint(ratePoint); + final codec = await _ensureEntropy(resolution, forDecode: false); + try { + // The entropy session stays up on purpose: a second photo is free. + return await codec.encode( + rgbBytes, + onProgress: onProgress, + shouldCancel: shouldCancel, + ); + } on AeicEntropyCancelled { + throw const ImageCodecCancelled(); + } + } + + @override + Future decode({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + void Function(double progress)? onProgress, + bool Function()? shouldCancel, + }) async { + _checkRatePoint(ratePoint); + final codec = await _ensureEntropy(resolution, forDecode: true); + final Float32List yHat; + try { + yHat = await codec.decodeToLatent( + bitstream, + onProgress: (value) => onProgress?.call(value * 0.5), + shouldCancel: shouldCancel, + ); + } on AeicEntropyCancelled { + throw const ImageCodecCancelled(); + } + // MANDATORY, not an optimisation: never hold the fp32 entropy graph and the + // 2.16 GiB synthesis session at the same time. + await releaseEntropySession(); + return decodeLatentToRgb( + yHat: yHat, + onProgress: (value) => onProgress?.call(0.5 + value * 0.5), + shouldCancel: shouldCancel, + ); + } + + /// The graphs and the CDF tables belong to one checkpoint. A bitstream that + /// claims a different rate point cannot be decoded with these tables, and + /// would decode into a sharp, plausible, wrong image if it were tried. + void _checkRatePoint(AeicRatePoint ratePoint) { + final expected = _requireBundle().ratePoint; + if (ratePoint != expected) { + throw ImageCodecUnimplemented( + 'this bundle is ${expected.name}; the bitstream claims ' + '${ratePoint.name}. Rate points are not interchangeable: the CDF ' + 'tables and the entropy graph belong to one checkpoint.', + ); + } + } + + @override + Future releaseDecoderSession() async { + final session = _decoder; + _decoder = null; + await _close(session, 'decoder'); + } + + /// Drops **both** entropy graphs. Callers ask for "the entropy half"; which + /// direction happens to be resident is an implementation detail, and a decode + /// that is about to create the 2.16 GiB synthesis session must not leave the + /// send-side graph behind just because it never used it. + @override + Future releaseEntropySession() async { + final encodeSession = _entropyEncode; + final decodeSession = _entropyDecode; + _entropyEncode = null; + _entropyDecode = null; + await _close(encodeSession, 'entropy(encode)'); + await _close(decodeSession, 'entropy(decode)'); + } + + @override + Future dispose() async { + await releaseDecoderSession(); + await releaseEntropySession(); + _coders = null; + } + + static Future _close(OrtSession? session, String which) async { + if (session == null) { + return; + } + try { + await session.close(); + } catch (error) { + // Never let teardown throw: it is called from memory-pressure and from + // isolate shutdown, where there is nobody left to handle it. + appLogger.warn( + 'ONNX $which session close failed: $error', + tag: 'ImageCodec', + ); + } + } +} + +/// [AeicEntropyNetwork] backed by the fp32 entropy ONNX graphs. +/// +/// ## TWO GRAPHS, NOT ONE. This is not a packaging accident. +/// +/// The send-side export (`aeic_entropy_side_fp32_op17.onnx`, 64 MB) has one +/// input `image [1,3,512,512]` and emits `z_q`, `yq0..3`, `sc0..3` in a single +/// run. That shape is only valid for an encoder, which already knows `y`. +/// Decoding is inherently SEQUENTIAL: the symbols of stage `i` must be decoded +/// before stage `i+1`'s context can be computed, so a receiver must be able to +/// call the network five times per image, interleaved with rANS. +/// +/// The decode-side export (`aeic_entropy_decode_fp32_op17.onnx`, 58 MB) is that +/// callable form — the same sub-networks behind an ONNX `If` on a `stage` +/// selector. `flutter_onnxruntime`'s `session.run()` fetches ALL graph outputs +/// (there is no output-subset API), so the `If` is what stops each call from +/// evaluating `g_c` four times. +/// +/// ### Decode-side contract (measured, not assumed) +/// +/// ``` +/// inputs : z_q float32 [1,128,4,4] base float32 [1,256,16,16] +/// stage int32 [1] +/// outputs: base0 float32 [1,256,16,16] means float32 [1,256,16,16] +/// scales float32 [1,256,16,16] +/// ``` +/// +/// * ALL THREE INPUTS ARE REQUIRED ON EVERY RUN. ORT rejects a feed that omits +/// one ("Required inputs (['base']) are missing from input feed"), so the +/// branch that does not read a tensor is still handed a zero filler. That is +/// what [_zeroBase] and [_zeroZq] are for; they are not defensive padding. +/// * `stage < 0` takes the HYPER branch: `base0 = h_s(z_q + z_offset)`, with +/// `z_offset` (the entropy-bottleneck medians) baked into the graph as a +/// constant. The input is therefore raw `z_q`, NOT `z_hat` — adding the +/// offset in Dart would add it twice. +/// * `stage 0..3` takes the CONTEXT branch: +/// `adapter_out[stage](g_c(adapter_in[stage](base)))`, chunked into +/// `means`/`scales` and **already multiplied by that stage's mask**. +/// `AeicMaskSet.applyMask` is a select with the identical mask, so applying it +/// again in `image_codec_entropy.dart` is exactly idempotent — that call site +/// needs no change, and removing it would couple the arithmetic to this +/// export. +/// * The branch not taken emits a zero tensor of the same shape, so a caller +/// must read only the output its `stage` selects. +/// * Latency on an M4 Max, 1 thread, CPU EP, ORT 1.28.0: 6.11 ms for the hyper +/// branch and 3.70 ms per stage, ~21 ms per image. +/// +/// Geometry is fixed 512x512 -> `y` 16x16, `z` 4x4. No dynamic axes. +/// +/// A network constructed with only [encodeSession] reports +/// [supportsDecodeSide] false, and `AeicEntropyCodec.decodeToLatent` refuses +/// with [AeicEntropyUnavailable] rather than feeding a send-side graph inputs it +/// does not have. +class OnnxAeicEntropyNetwork implements AeicEntropyNetwork { + static const String kImageInput = 'image'; + static const String kZqInput = 'z_q'; + static const String kBaseInput = 'base'; + static const String kStageInput = 'stage'; + static const String kBase0Output = 'base0'; + static const String kMeansOutput = 'means'; + static const String kScalesOutput = 'scales'; + + /// The `stage` value that selects the hyper-synthesis branch. Any negative + /// value works; -1 is the documented one. + static const int kHyperStage = -1; + + static const List kZqShape = [1, 128, 4, 4]; + static const List kBaseShape = [1, 256, 16, 16]; + static const int kZqElements = 128 * 4 * 4; + static const int kBaseElements = 256 * 16 * 16; + + /// Session over the send-side graph, or null on a decode-only network. + final OrtSession? encodeSession; + + /// Session over the decode-side graph, or null on an encode-only network. + final OrtSession? decodeSession; + + const OnnxAeicEntropyNetwork({this.encodeSession, this.decodeSession}); + + @override + bool get supportsDecodeSide { + final session = decodeSession; + if (session == null) { + return false; + } + final inputs = session.inputNames; + final outputs = session.outputNames; + return inputs.contains(kZqInput) && + inputs.contains(kBaseInput) && + inputs.contains(kStageInput) && + outputs.contains(kBase0Output) && + outputs.contains(kMeansOutput) && + outputs.contains(kScalesOutput); + } + + @override + Future runEncodeSide(Float32List imageChw) async { + final session = encodeSession; + if (session == null) { + throw const AeicEntropyUnavailable( + 'this network has no send-side entropy session, so it cannot encode', + ); + } + if (!session.inputNames.contains(kImageInput)) { + throw const AeicEntropyUnavailable( + 'the entropy graph has no "image" input, so it cannot encode', + ); + } + final side = imageChw.length ~/ 3; + final resolution = _isqrt(side); + final inputs = { + kImageInput: await OrtValue.fromList(imageChw, [ + 1, + 3, + resolution, + resolution, + ]), + }; + final result = await _run(session, inputs); + try { + return AeicEncodeSideTensors( + zQ: await _floats(result, 'z_q'), + yQ: [ + for (var i = 0; i < 4; i++) await _floats(result, 'yq$i'), + ], + scales: [ + for (var i = 0; i < 4; i++) await _floats(result, 'sc$i'), + ], + ); + } finally { + await _disposeAll(result); + } + } + + @override + Future runHyperSynthesis(Float32List zQ) async { + final session = _requireDecodeSide(); + if (zQ.length != kZqElements) { + throw ArgumentError.value( + zQ.length, + 'zQ', + 'expected $kZqElements float32 values (shape $kZqShape)', + ); + } + // `base` is not read by the hyper branch, but ORT requires every declared + // input to be fed. Zeros, not a stale tensor: a stale one would be silently + // wrong the day the export starts reading it. + final result = await _run(session, { + kZqInput: await OrtValue.fromList(zQ, kZqShape), + kBaseInput: await OrtValue.fromList( + Float32List(kBaseElements), + kBaseShape, + ), + kStageInput: await OrtValue.fromList( + Int32List.fromList([kHyperStage]), + [1], + ), + }); + try { + return await _floats(result, kBase0Output); + } finally { + await _disposeAll(result); + } + } + + @override + Future runStage(int stage, Float32List base) async { + final session = _requireDecodeSide(); + if (stage < 0 || stage > 3) { + // The graph does not validate `stage`: anything >= 4 silently falls into + // the stage-3 branch and anything < 0 runs hyper synthesis, either of + // which desynchronises rANS without an error. Catch it here instead. + throw ArgumentError.value(stage, 'stage', 'must be 0..3'); + } + if (base.length != kBaseElements) { + throw ArgumentError.value( + base.length, + 'base', + 'expected $kBaseElements float32 values (shape $kBaseShape)', + ); + } + // `z_q` is not read by the context branch; same reasoning as above. + final result = await _run(session, { + kZqInput: await OrtValue.fromList(Float32List(kZqElements), kZqShape), + kBaseInput: await OrtValue.fromList(base, kBaseShape), + kStageInput: await OrtValue.fromList( + Int32List.fromList([stage]), + [1], + ), + }); + try { + // Already masked by the graph. `AeicEntropyCodec` masks again, which is + // idempotent — see the class doc. + return AeicStageParams( + meansSupp: await _floats(result, kMeansOutput), + scalesSupp: await _floats(result, kScalesOutput), + ); + } finally { + await _disposeAll(result); + } + } + + OrtSession _requireDecodeSide() { + final session = decodeSession; + if (session == null) { + throw const AeicEntropyUnavailable( + 'this network has no decode-side entropy session; decoding needs ' + 'aeic_entropy_decode_fp32_op17.onnx, which a bundle-version-1 install ' + 'does not carry', + ); + } + if (!supportsDecodeSide) { + throw AeicEntropyUnavailable( + 'the loaded decode-side graph does not match the contract (inputs ' + '${session.inputNames}, outputs ${session.outputNames}); decoding ' + 'needs inputs [$kZqInput, $kBaseInput, $kStageInput] and outputs ' + '[$kBase0Output, $kMeansOutput, $kScalesOutput]', + ); + } + return session; + } + + Future> _run( + OrtSession session, + Map inputs, + ) async { + try { + return await session.run(inputs); + } finally { + for (final value in inputs.values) { + await value.dispose(); + } + } + } + + static Future _floats( + Map result, + String name, + ) async { + final value = result[name]; + if (value == null) { + throw AeicEntropyUnavailable( + 'the entropy graph has no output named "$name"; found ' + '${result.keys.toList()}', + ); + } + final flat = await value.asFlattenedList(); + final out = Float32List(flat.length); + for (var i = 0; i < flat.length; i++) { + out[i] = (flat[i] as num).toDouble(); + } + return out; + } + + static Future _disposeAll(Map values) async { + for (final value in values.values) { + await value.dispose(); + } + } + + static int _isqrt(int value) { + final root = math.sqrt(value).round(); + if (root * root != value) { + throw ArgumentError.value(value, 'value', 'not a square image'); + } + return root; + } +} + +/// Thrown by a backend that noticed [ImageCodecBackend] `shouldCancel`. +class ImageCodecCancelled implements Exception { + const ImageCodecCancelled(); + + @override + String toString() => 'Image processing stopped.'; +} + +/// Factory used by the codec worker isolate. +/// +/// Returns `null` on web, where there is no local model file and no isolate. +/// Everywhere else it returns the real [OnnxImageCodecBackend]; the session +/// turns a `null` here into an [ImageCodecUnimplemented], which the service +/// surfaces as `lastError` and maps to `ImageCodecAvailability.unavailable`. +ImageCodecBackend? createImageCodecBackend() { + if (kIsWeb) { + return null; + } + return OnnxImageCodecBackend(); +} diff --git a/lib/services/image_codec_entropy.dart b/lib/services/image_codec_entropy.dart new file mode 100644 index 00000000..f7fdaf55 --- /dev/null +++ b/lib/services/image_codec_entropy.dart @@ -0,0 +1,678 @@ +/// =========================================================================== +/// THE ENTROPY LAYER — everything between the ONNX tensors and the rANS coder. +/// =========================================================================== +/// +/// AEIC's four-stage masked context model, ported from +/// `aic/aeic/src/codec/codec_practical.py` (`PixelCodec.compress` / +/// `.decompress`). This file owns the parts that are *not* neural and *not* +/// range coding: +/// +/// * the four checkerboard masks (`get_mask_four_parts`), +/// * `sequeeze` / `unsequeeze_with_mask` (the 4:1 channel fold), +/// * `torch.round`'s half-to-**even** tie rule, +/// * `my_build_indexes` (scale -> CDF row selector), +/// * the z index array (`_build_indexes`: the channel arange), +/// * the fixed call order z, y0, y1, y2, y3. +/// +/// It is deliberately pure Dart: no ONNX, no dart:io, no Flutter. The neural +/// half arrives through [AeicEntropyNetwork] and the range coder through +/// [AeicRansCoderFactory], both injected. That is what makes the arithmetic +/// unit-testable without a 67 MB graph or a model download. +/// +/// ## Why every detail here is load-bearing +/// +/// The rANS decoder re-derives symbol probabilities by re-running the same +/// network and the same arithmetic. A single wrong symbol *position* — an +/// off-by-one in a mask, the wrong channel-group permutation, `sequeeze` +/// folding in the wrong order — does not raise: it desynchronises the coder and +/// produces a sharp, plausible, wrong image. Same for a rounding tie resolved +/// away from zero instead of to even. Both failure modes are silent. +/// +/// The golden vectors in `test/services/image_codec_entropy_test.dart` were +/// generated by `aic/exp/export_entropy_layer_golden.py`, which runs the real +/// torch ops on a closed-form input both languages reproduce bit-for-bit. +library; + +import 'dart:math' as math; +import 'dart:typed_data'; + +/// CDF group indices, fixed by `EntropyCoder.update()`'s `add_cdf` call order: +/// the entropy bottleneck (z) is registered first, the Gaussian conditional +/// (y) second. The group index is part of the bitstream format. +const int kAeicZCdfGroup = 0; +const int kAeicYCdfGroup = 1; + +/// `my_build_indexes` constants (`codec_practical.py`, `SCALES_MIN/MAX/LEVELS`). +const int kAeicScalesLevels = 64; +const double kAeicLogScaleMin = -2.2072749131897207; // ln(0.11) +const double kAeicLogScaleStep = 0.12305479932808384; // (ln(256)-ln(0.11))/63 +const double kAeicScaleThreshold = 0.08; // below this the symbol is skipped +const double kAeicScaleFloor = 1e-5; // torch.maximum floor applied first + +/// Tensor shapes for one image, derived the way `compress()` derives them. +/// +/// `y` is the image downsampled by 32; `z` is `y` downsampled by a further 4, +/// rounded **up** (`compress()` reflect-pads `y` to a multiple of 4 first). +class AeicEntropyGeometry { + final int resolution; + + /// Latent channel count `M` (256 for AEIC-SE, which is what ships). + final int yChannels; + final int yHeight; + final int yWidth; + + /// Hyper-latent channels: `M // 2`. + final int zChannels; + final int zHeight; + final int zWidth; + + const AeicEntropyGeometry._({ + required this.resolution, + required this.yChannels, + required this.yHeight, + required this.yWidth, + required this.zChannels, + required this.zHeight, + required this.zWidth, + }); + + factory AeicEntropyGeometry.forResolution( + int resolution, { + int yChannels = 256, + }) { + if (resolution <= 0 || resolution % 32 != 0) { + throw ArgumentError.value( + resolution, + 'resolution', + 'must be a positive multiple of 32 (g_a downsamples by 32)', + ); + } + if (yChannels % 4 != 0) { + throw ArgumentError.value( + yChannels, + 'yChannels', + 'the four-part mask splits the channels into 4 equal groups', + ); + } + final yh = resolution ~/ 32; + final zh = (yh + 3) ~/ 4; + return AeicEntropyGeometry._( + resolution: resolution, + yChannels: yChannels, + yHeight: yh, + yWidth: yh, + zChannels: yChannels ~/ 2, + zHeight: zh, + zWidth: zh, + ); + } + + /// Channels after `sequeeze` folds the four groups together. + int get squeezedChannels => yChannels ~/ 4; + + int get yElements => yChannels * yHeight * yWidth; + + /// Symbols coded per y stage (`[1, M/4, y_h, y_w]` flattened). + int get symbolsPerStage => squeezedChannels * yHeight * yWidth; + + int get zElements => zChannels * zHeight * zWidth; + + /// Total entries handed to the coder: z once, then four y stages. + int get totalEntries => zElements + 4 * symbolsPerStage; + + List get yShape => [1, yChannels, yHeight, yWidth]; + + List get zShape => [1, zChannels, zHeight, zWidth]; + + List get imageShape => [1, 3, resolution, resolution]; +} + +/// The four masks of `get_mask_four_parts`, as arithmetic rather than tensors. +/// +/// Reading the Python: each mask is four channel-groups of `M/4` channels +/// stacked, and each group carries one of the four 2x2 micro-patterns +/// +/// micro 0 = (y%2, x%2) == (0, 0) micro 1 = (0, 1) +/// micro 2 = (1, 0) micro 3 = (1, 1) +/// +/// so `micro k` is live exactly where `(y%2)*2 + (x%2) == k`. The stacking order +/// per stage is +/// +/// mask_0 = [m0, m1, m2, m3] mask_1 = [m3, m2, m1, m0] +/// mask_2 = [m2, m3, m0, m1] mask_3 = [m1, m0, m3, m2] +/// +/// which is exactly `micro = group XOR perm[stage]` with `perm = [0, 3, 2, 1]`. +/// Verified against the tensors themselves in the golden test, because getting +/// this permutation wrong is the single easiest way to silently reorder every +/// symbol in the stream. +class AeicMaskSet { + /// `perm[stage]`: XOR it with the channel group to get the micro-pattern. + static const List stagePermutation = [0, 3, 2, 1]; + + final AeicEntropyGeometry geometry; + + const AeicMaskSet(this.geometry); + + /// Micro-pattern index used by [channelGroup] in [stage]. + static int microFor(int stage, int channelGroup) => + channelGroup ^ stagePermutation[stage]; + + /// The single channel group that is live at `(y, x)` in [stage]. + /// + /// Inverse of [microFor]: the position selects the micro-pattern, and exactly + /// one group carries it. + static int liveGroupAt(int stage, int y, int x) => + (((y & 1) << 1) | (x & 1)) ^ stagePermutation[stage]; + + bool isLive(int stage, int channel, int y, int x) { + final group = channel ~/ geometry.squeezedChannels; + return microFor(stage, group) == (((y & 1) << 1) | (x & 1)); + } + + /// Materialises `mask_i` as `[1, M, y_h, y_w]` float32 — only needed when a + /// caller wants to hand the mask to something else (or check it in a test). + Float32List maskTensor(int stage) { + final out = Float32List(geometry.yElements); + final h = geometry.yHeight; + final w = geometry.yWidth; + for (var c = 0; c < geometry.yChannels; c++) { + final base = c * h * w; + for (var y = 0; y < h; y++) { + for (var x = 0; x < w; x++) { + if (isLive(stage, c, y, x)) { + out[base + y * w + x] = 1.0; + } + } + } + } + return out; + } + + /// `sequeeze`: sum the four channel chunks, `(g0 + g1) + (g2 + g3)`. + /// + /// The association matters in principle (float addition is not associative) + /// so it is reproduced exactly, even though in practice three of the four + /// terms are a hard zero for a masked tensor. + Float32List squeeze(Float32List full) { + if (full.length != geometry.yElements) { + throw ArgumentError.value( + full.length, + 'full', + 'expected ${geometry.yElements} elements (${geometry.yShape})', + ); + } + final plane = geometry.yHeight * geometry.yWidth; + final cq = geometry.squeezedChannels; + final out = Float32List(cq * plane); + for (var c = 0; c < cq; c++) { + final o = c * plane; + final g0 = c * plane; + final g1 = (c + cq) * plane; + final g2 = (c + 2 * cq) * plane; + final g3 = (c + 3 * cq) * plane; + for (var i = 0; i < plane; i++) { + // Each partial sum is forced back through float32, matching torch's + // `(a + b) + (c + d)` on float32 tensors. + final left = f32(full[g0 + i] + full[g1 + i]); + final right = f32(full[g2 + i] + full[g3 + i]); + out[o + i] = left + right; + } + } + return out; + } + + /// `unsequeeze_with_mask`: broadcast a squeezed tensor back to `[1, M, h, w]`, + /// keeping each element only in the channel group whose mask is live there. + Float32List unsqueeze(Float32List squeezed, int stage) { + final plane = geometry.yHeight * geometry.yWidth; + final cq = geometry.squeezedChannels; + if (squeezed.length != cq * plane) { + throw ArgumentError.value( + squeezed.length, + 'squeezed', + 'expected ${cq * plane} elements', + ); + } + final out = Float32List(geometry.yElements); + final w = geometry.yWidth; + for (var c = 0; c < cq; c++) { + for (var y = 0; y < geometry.yHeight; y++) { + for (var x = 0; x < w; x++) { + final group = liveGroupAt(stage, y, x); + out[(group * cq + c) * plane + y * w + x] = + squeezed[c * plane + y * w + x]; + } + } + } + return out; + } + + /// `t * mask_i`, elementwise, into a fresh tensor. + Float32List applyMask(Float32List full, int stage) { + final out = Float32List(full.length); + final plane = geometry.yHeight * geometry.yWidth; + final cq = geometry.squeezedChannels; + final w = geometry.yWidth; + for (var c = 0; c < geometry.yChannels; c++) { + final group = c ~/ cq; + for (var y = 0; y < geometry.yHeight; y++) { + for (var x = 0; x < w; x++) { + if (microFor(stage, group) == (((y & 1) << 1) | (x & 1))) { + final i = c * plane + y * w + x; + out[i] = full[i]; + } + } + } + } + return out; + } + + /// `base * (1 - mask_i) + stageLatent`, the context update between stages. + /// + /// `stageLatent` must already be masked (it is the output of [unsqueeze]), so + /// this is a select, not an add — which is what keeps it exact in float32. + Float32List mergeContext( + Float32List base, + Float32List stageLatent, + int stage, + ) { + final out = Float32List.fromList(base); + final plane = geometry.yHeight * geometry.yWidth; + final cq = geometry.squeezedChannels; + final w = geometry.yWidth; + for (var c = 0; c < geometry.yChannels; c++) { + final group = c ~/ cq; + for (var y = 0; y < geometry.yHeight; y++) { + for (var x = 0; x < w; x++) { + if (microFor(stage, group) == (((y & 1) << 1) | (x & 1))) { + final i = c * plane + y * w + x; + out[i] = stageLatent[i]; + } + } + } + } + return out; + } +} + +/// Scratch cell used to force a float64 value through float32 rounding. +final Float32List _f32Cell = Float32List(1); + +/// Rounds [value] to float32 exactly as a store into a float32 tensor would. +double f32(double value) { + _f32Cell[0] = value; + return _f32Cell[0]; +} + +/// `torch.round`: ties go to the **even** neighbour, not away from zero. +/// +/// Dart's `double.round()` and `roundToDouble()` both round half away from +/// zero, so `(-0.5).round() == -1` where torch gives `0`. On the ft32 corpus +/// `y - means` lands on a tie often enough that this is not theoretical. +double roundHalfToEven(double value) { + if (!value.isFinite) { + return value; + } + final floor = value.floorToDouble(); + final diff = value - floor; + if (diff > 0.5) { + return floor + 1.0; + } + if (diff < 0.5) { + return floor; + } + // Exactly halfway: pick the even neighbour. + return floor % 2.0 == 0.0 ? floor : floor + 1.0; +} + +/// `my_build_indexes` — scale -> CDF row selector, in float32, per stage. +/// +/// ``` +/// s = max(scale, 1e-5) +/// q = (ln(s) - log_scale_min) / log_scale_step # all float32 +/// idx = (s < 0.08) ? -1 : trunc(clamp(q, 0, 63)) # trunc, not round +/// ``` +/// +/// Every intermediate is forced back to float32 because torch evaluates this on +/// a float32 tensor with float32 scalars, and the boundary margin measured in +/// `aic/results/bitexact_encoder.md` is only 1.12x — the tightest number in the +/// whole system. Dart's `log` is still not guaranteed bit-identical to ORT's +/// float32 `Log`; see the note in `aic/results/rans_port_spec.md` §8, which +/// recommends the graph emit these indexes itself. [aeicBuildIndexes] is the +/// fallback, and both sides of the channel run this same code, so sender and +/// receiver agree with each other regardless. +Int16List aeicBuildIndexes(Float32List scales) { + final logMin = f32(kAeicLogScaleMin); + final logStep = f32(kAeicLogScaleStep); + final floor = f32(kAeicScaleFloor); + final threshold = f32(kAeicScaleThreshold); + final out = Int16List(scales.length); + for (var i = 0; i < scales.length; i++) { + final raw = scales[i]; + final s = raw > floor ? raw : floor; + if (s < threshold) { + out[i] = -1; + continue; + } + var q = f32(f32(f32(math.log(s)) - logMin) / logStep); + if (q < 0.0) { + q = 0.0; + } else if (q > kAeicScalesLevels - 1) { + q = (kAeicScalesLevels - 1).toDouble(); + } + out[i] = q.toInt(); // truncation toward zero, matching Tensor.int() + } + return out; +} + +/// The z index array: `_build_indexes` broadcasts `arange(C)` over `H x W`, so +/// this is `H*W` copies of each channel index. Always >= 0. +Int16List aeicZIndexes(AeicEntropyGeometry geometry) { + final plane = geometry.zHeight * geometry.zWidth; + final out = Int16List(geometry.zElements); + var i = 0; + for (var c = 0; c < geometry.zChannels; c++) { + for (var p = 0; p < plane; p++) { + out[i++] = c; + } + } + return out; +} + +/// float32 tensor of integers -> int16 symbols, asserting the cast is lossless. +/// +/// `py_rans` force-casts through `py::array_t`; the golden vectors +/// store the post-cast values. Anything that does not survive the cast means +/// the entropy model has gone somewhere the format cannot represent, and +/// truncating quietly would desync the decoder. +Int16List aeicToSymbols(Float32List values) { + final out = Int16List(values.length); + for (var i = 0; i < values.length; i++) { + final v = values[i]; + final n = v.toInt(); + if (n != v || n < -32768 || n > 32767) { + throw StateError( + 'entropy symbol $v at index $i is not a lossless int16; the entropy ' + 'model produced a value the bitstream format cannot carry', + ); + } + out[i] = n; + } + return out; +} + +/// RGB bytes -> the graph's `image` input, reproducing torchvision's +/// `ToTensor()` + `Normalize([0.5]*3, [0.5]*3)`: `x = (b/255 - 0.5) / 0.5`. +Float32List aeicRgbToChw(Uint8List rgb, int resolution) { + final pixels = resolution * resolution; + if (rgb.length != pixels * 3) { + throw ArgumentError.value( + rgb.length, + 'rgb', + 'expected ${pixels * 3} bytes for ${resolution}x$resolution RGB', + ); + } + final out = Float32List(pixels * 3); + for (var c = 0; c < 3; c++) { + final plane = c * pixels; + for (var i = 0; i < pixels; i++) { + final v = f32(rgb[i * 3 + c] / 255.0); + out[plane + i] = f32(v - 0.5) * 2.0; // /0.5 is exact + } + } + return out; +} + +/// Everything the send side needs out of one forward pass of the entropy graph. +/// +/// Matches the outputs of `aic/onnx/aeic_entropy_side_fp32_op17.onnx`, which +/// runs `g_a`, `h_a`, `h_s`, `g_c` and all four adapters in one shot — the +/// encoder never has to be incremental, only the decoder does. +class AeicEncodeSideTensors { + /// `round(z - z_offset)`, `[1, M/2, z_h, z_w]`, integral floats. + final Float32List zQ; + + /// `round(y * mask_i - means_i)` per stage, `[1, M, y_h, y_w]`, integral. + final List yQ; + + /// `scales_supp_i * mask_i` per stage, `[1, M, y_h, y_w]`. + final List scales; + + const AeicEncodeSideTensors({ + required this.zQ, + required this.yQ, + required this.scales, + }); +} + +/// One decode stage's entropy parameters, **before** masking. +/// +/// `adapter_out[i](g_c(adapter_in[i](base)))` split in half; the caller applies +/// `mask_i`. Kept unmasked so the graph does not have to know the stage index +/// at export time. +class AeicStageParams { + final Float32List meansSupp; + final Float32List scalesSupp; + + const AeicStageParams({required this.meansSupp, required this.scalesSupp}); +} + +/// The neural half of the entropy path, as this file needs it. +/// +/// ## Graph contract +/// +/// **Send side** (exists today, `aeic_entropy_side_fp32_op17.onnx`, 67 MB): +/// input `image [1,3,512,512]` -> outputs `z_q`, `yq0..yq3`, `sc0..sc3`. +/// +/// **Receive side** (NOT exported yet — see the report for task B2): the +/// decoder cannot use the send-side graph, because it must interleave network +/// evaluation with symbol decoding: stage `i`'s indexes are unknown until +/// stages `< i` have been decoded and fed back through `g_c`. It needs +/// +/// * `z_q [1,128,4,4]` -> `base0 [1,256,16,16]` (`h_s` with `z_offset` baked +/// in, exactly as the send-side export bakes it), and +/// * `base [1,256,16,16]` -> `means{i}`, `scales{i}` for `i` in 0..3 +/// (unmasked `adapter_out[i](g_c(adapter_in[i](base)))`, split in half). +/// +/// Both can live in one graph with two inputs and nine outputs; ORT prunes to +/// the requested output set, so asking only for `base0` does not run the +/// adapters and asking only for `means2`/`scales2` does not run `h_s`. +abstract class AeicEntropyNetwork { + /// Whether [runHyperSynthesis] and [runStage] are available. False for a + /// graph that only carries the send-side path. + bool get supportsDecodeSide; + + Future runEncodeSide(Float32List imageChw); + + /// `h_s(z_q + z_offset)[:, :, :y_h, :y_w]`. + Future runHyperSynthesis(Float32List zQ); + + /// `adapter_out[stage](g_c(adapter_in[stage](base)))`, unmasked. + Future runStage(int stage, Float32List base); +} + +/// The rANS encoder, as the entropy layer uses it. +/// +/// Implemented by the pure-Dart coder (task B1). Deliberately narrow: five +/// [pushSymbols] calls in the fixed order z, y0, y1, y2, y3, then one [finish]. +abstract class AeicRansEncoder { + /// Appends one `(symbols, indexes)` pair. `indexes[i] < 0` emits nothing. + void pushSymbols(Int16List symbols, Int16List indexes, int cdfGroup); + + /// Flushes both sub-streams and returns the container bytes. + Uint8List finish(); +} + +/// The rANS decoder, as the entropy layer uses it. +/// +/// **Must be incremental**: each call resumes the rANS state where the last one +/// stopped. An implementation that decodes the whole stream up front cannot +/// work here — see the class docs on [AeicEntropyNetwork]. +abstract class AeicRansDecoder { + Int16List decodeStream(Int16List indexes, int cdfGroup); +} + +/// Supplies coders bound to a parsed CDF table set (task B1 owns both). +abstract class AeicRansCoderFactory { + AeicRansEncoder createEncoder(); + + AeicRansDecoder createDecoder(Uint8List bitstream); +} + +/// Thrown when the entropy loop is asked to run without a piece it needs. +class AeicEntropyUnavailable implements Exception { + final String detail; + + const AeicEntropyUnavailable(this.detail); + + @override + String toString() => 'AEIC entropy path unavailable: $detail'; +} + +/// Raised by [ImageCodecBackend] callers that pass a cancel predicate. +typedef AeicCancelCheck = bool Function(); + +/// The four-stage masked encode and decode, orchestrating [AeicEntropyNetwork] +/// and [AeicRansCoderFactory]. +class AeicEntropyCodec { + final AeicEntropyGeometry geometry; + final AeicMaskSet masks; + final AeicEntropyNetwork network; + final AeicRansCoderFactory coders; + + AeicEntropyCodec({ + required this.geometry, + required this.network, + required this.coders, + }) : masks = AeicMaskSet(geometry); + + /// Packed 8-bit RGB -> rANS bitstream (payload only, no chunk headers). + /// + /// One forward pass, then z, y0, y1, y2, y3 into the coder in that order. + Future encode( + Uint8List rgbBytes, { + void Function(double progress)? onProgress, + AeicCancelCheck? shouldCancel, + }) async { + onProgress?.call(0.02); + final input = aeicRgbToChw(rgbBytes, geometry.resolution); + _checkCancel(shouldCancel); + + final tensors = await network.runEncodeSide(input); + onProgress?.call(0.80); + _checkCancel(shouldCancel); + + if (tensors.zQ.length != geometry.zElements) { + throw StateError( + 'entropy graph returned ${tensors.zQ.length} z values, expected ' + '${geometry.zElements} (${geometry.zShape})', + ); + } + if (tensors.yQ.length != 4 || tensors.scales.length != 4) { + throw StateError( + 'entropy graph must return four y_q and four scales tensors, got ' + '${tensors.yQ.length} / ${tensors.scales.length}', + ); + } + + final encoder = coders.createEncoder(); + encoder.pushSymbols( + aeicToSymbols(tensors.zQ), + aeicZIndexes(geometry), + kAeicZCdfGroup, + ); + for (var stage = 0; stage < 4; stage++) { + final symbols = aeicToSymbols(masks.squeeze(tensors.yQ[stage])); + final indexes = aeicBuildIndexes(masks.squeeze(tensors.scales[stage])); + encoder.pushSymbols(symbols, indexes, kAeicYCdfGroup); + onProgress?.call(0.80 + 0.04 * (stage + 1)); + _checkCancel(shouldCancel); + } + final stream = encoder.finish(); + onProgress?.call(1.0); + return stream; + } + + /// rANS bitstream -> `y_hat [1, M, y_h, y_w]`, ready for the synthesis graph. + /// + /// The mirror of [encode], and necessarily incremental: each stage's indexes + /// come from scales that only exist once the previous stage's symbols have + /// been decoded and pushed back through the context model. + Future decodeToLatent( + Uint8List bitstream, { + void Function(double progress)? onProgress, + AeicCancelCheck? shouldCancel, + }) async { + if (!network.supportsDecodeSide) { + throw const AeicEntropyUnavailable( + 'the installed entropy graph is send-side only: it maps image -> ' + 'symbols and has no z_q -> base0 / base -> means,scales entry points, ' + 'which decoding requires', + ); + } + onProgress?.call(0.02); + final decoder = coders.createDecoder(bitstream); + + final zSymbols = decoder.decodeStream( + aeicZIndexes(geometry), + kAeicZCdfGroup, + ); + final zQ = Float32List(zSymbols.length); + for (var i = 0; i < zSymbols.length; i++) { + zQ[i] = zSymbols[i].toDouble(); + } + _checkCancel(shouldCancel); + + var base = await network.runHyperSynthesis(zQ); + if (base.length != geometry.yElements) { + throw StateError( + 'hyper synthesis returned ${base.length} values, expected ' + '${geometry.yElements} (${geometry.yShape})', + ); + } + onProgress?.call(0.20); + + Float32List? stageLatent; + for (var stage = 0; stage < 4; stage++) { + _checkCancel(shouldCancel); + final params = await network.runStage(stage, base); + final scales = masks.applyMask(params.scalesSupp, stage); + final means = masks.applyMask(params.meansSupp, stage); + final indexes = aeicBuildIndexes(masks.squeeze(scales)); + final symbols = decoder.decodeStream(indexes, kAeicYCdfGroup); + final meansSqueezed = masks.squeeze(means); + if (symbols.length != meansSqueezed.length) { + throw StateError( + 'stage $stage decoded ${symbols.length} symbols but the context ' + 'model produced ${meansSqueezed.length} means', + ); + } + final latentSqueezed = Float32List(symbols.length); + for (var i = 0; i < symbols.length; i++) { + latentSqueezed[i] = symbols[i] + meansSqueezed[i]; + } + stageLatent = masks.unsqueeze(latentSqueezed, stage); + if (stage < 3) { + base = masks.mergeContext(base, stageLatent, stage); + } + onProgress?.call(0.20 + 0.19 * (stage + 1)); + } + + // y_hat = base * (1 - mask_3) + y_hat_3 + return masks.mergeContext(base, stageLatent!, 3); + } + + static void _checkCancel(AeicCancelCheck? shouldCancel) { + if (shouldCancel?.call() == true) { + throw const AeicEntropyCancelled(); + } + } +} + +/// Cancellation signal raised out of the entropy loop at a stage boundary. +class AeicEntropyCancelled implements Exception { + const AeicEntropyCancelled(); + + @override + String toString() => 'Image processing stopped.'; +} diff --git a/lib/services/image_codec_file_store.dart b/lib/services/image_codec_file_store.dart new file mode 100644 index 00000000..da5a56f1 --- /dev/null +++ b/lib/services/image_codec_file_store.dart @@ -0,0 +1,2 @@ +export 'image_codec_file_store_stub.dart' + if (dart.library.io) 'image_codec_file_store_io.dart'; diff --git a/lib/services/image_codec_file_store_io.dart b/lib/services/image_codec_file_store_io.dart new file mode 100644 index 00000000..70eafba1 --- /dev/null +++ b/lib/services/image_codec_file_store_io.dart @@ -0,0 +1,247 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:convert/convert.dart' show AccumulatorSink; +import 'package:crypto/crypto.dart'; +import 'package:path_provider/path_provider.dart'; + +import '../models/image_codec_support.dart'; + +/// On-disk storage for image-codec weights. +/// +/// Mirrors `translation_file_store_io.dart` 1:1. It is a separate class rather +/// than a reuse of `TranslationFileStore` only because the directory name and +/// the record type differ; see the report for the (small) change that would +/// make the translation store generic enough to share. +class ImageCodecFileStore { + static final RegExp _chunkFilePattern = RegExp(r'^\..+_chunk_\d+$'); + + Future modelDirectoryPath() async { + final baseDir = await getApplicationDocumentsDirectory(); + final dir = Directory('${baseDir.path}/image_codec_models'); + if (!dir.existsSync()) { + await dir.create(recursive: true); + } + return dir.path; + } + + Future> scanDownloadedModels() async { + final dir = Directory(await modelDirectoryPath()); + if (!dir.existsSync()) { + return const []; + } + final models = []; + for (final entity in dir.listSync().whereType()) { + final name = entity.uri.pathSegments.last; + if (name.startsWith('.')) { + // Hidden `._chunk_` files are the resume state of an + // interrupted download and MUST survive a restart — reaping them here + // (as this used to) is what made an 872 MB transfer restart from zero + // whenever the app was reopened. Anything else hidden is junk. + if (!_chunkFilePattern.hasMatch(name)) { + await entity.delete(); + } + continue; + } + final stat = entity.statSync(); + models.add( + ImageCodecModelRecord( + id: name, + name: name, + sourceUrl: '', + localPath: entity.path, + downloadedAt: stat.modified, + fileSizeBytes: stat.size, + ), + ); + } + return models; + } + + Future deleteModel(ImageCodecModelRecord model) async { + await deleteFile(model.localPath); + await deletePartialDownloads(model.name); + } + + /// Removes any resume state for [fileName]. + /// + /// Called after a successful download and when a model is removed. Without it + /// the chunk files, which [scanDownloadedModels] now deliberately preserves, + /// would never be collected. + Future deletePartialDownloads(String fileName) async { + if (fileName.isEmpty) return; + final dir = Directory(await modelDirectoryPath()); + if (!dir.existsSync()) return; + // `.[.]_chunk_`. The optional size segment is what + // `ImageCodecService` appends so resume can never splice offsets computed + // for one upstream length onto a file of another. Anchored on both ends so + // sweeping `model.onnx` cannot take `model.onnx.data`'s chunks with it. + final pattern = RegExp( + '^\\.${RegExp.escape(fileName)}(\\.\\d+)?_chunk_\\d+\$', + ); + for (final entity in dir.listSync().whereType()) { + if (pattern.hasMatch(entity.uri.pathSegments.last)) { + await entity.delete(); + } + } + } + + Future deleteFile(String path) async { + final file = File(path); + if (file.existsSync()) { + await file.delete(); + } + } + + Future writeModelBytes({ + required String fileName, + required Stream> chunks, + }) async { + final directoryPath = await modelDirectoryPath(); + final file = File('$directoryPath/$fileName'); + final sink = file.openWrite(); + var fileSizeBytes = 0; + var completed = false; + try { + await for (final chunk in chunks) { + sink.add(chunk); + fileSizeBytes += chunk.length; + } + completed = true; + } finally { + await sink.close(); + if (!completed && file.existsSync()) { + await file.delete(); + } + } + return DownloadedCodecFile( + localPath: file.path, + fileSizeBytes: fileSizeBytes, + ); + } + + Future chunkFilePath(String fileName, int index) async { + final dir = await modelDirectoryPath(); + return '$dir/.${fileName}_chunk_$index'; + } + + Future modelFilePath(String fileName) async { + final dir = await modelDirectoryPath(); + return '$dir/$fileName'; + } + + /// Size of [path] in bytes, or 0 when it does not exist. + /// + /// This is the whole basis of resume: a chunk file's length *is* its progress + /// marker, so no separate state file can go stale or disagree with the bytes. + Future fileSize(String path) async { + final file = File(path); + if (!file.existsSync()) { + return 0; + } + return file.length(); + } + + /// Appends [chunks] to [path], creating it if absent. + /// + /// Unlike [writeModelBytes] this does NOT delete the file when the stream + /// fails part-way: the partial bytes are exactly what the next attempt + /// resumes from. Returns the file's total size afterwards. + Future appendBytes({ + required String path, + required Stream> chunks, + }) async { + final file = File(path); + await file.parent.create(recursive: true); + final sink = file.openWrite(mode: FileMode.append); + try { + await for (final chunk in chunks) { + sink.add(chunk); + } + } finally { + // flush() inside close(); the bytes written before a failure survive on + // purpose, so the next Range request can pick up from file.length(). + await sink.close(); + } + return file.length(); + } + + /// Streaming SHA-256 of [path] as lowercase hex. + /// + /// Streamed, not `readAsBytes`: the data sibling is 869 MiB and reading it into + /// a Uint8List to hash it would defeat the point of downloading it to disk. + Future sha256OfFile(String path) async { + final accumulator = AccumulatorSink(); + final converter = sha256.startChunkedConversion(accumulator); + try { + await for (final chunk in File(path).openRead()) { + converter.add(chunk); + } + } finally { + converter.close(); + } + return accumulator.events.single.toString(); + } + + /// Reads an arbitrary file (a picked photo, not a model) as bytes. + /// + /// Lives here so `ImageCodecService` never has to import `dart:io` and can + /// therefore still be constructed on web. + Future readFileBytes(String path) => File(path).readAsBytes(); + + Future combineChunks({ + required String fileName, + required List chunkPaths, + }) async { + final dir = await modelDirectoryPath(); + final finalPath = '$dir/$fileName'; + final sink = File(finalPath).openWrite(); + var totalSize = 0; + var completed = false; + try { + for (final chunkPath in chunkPaths) { + final chunkFile = File(chunkPath); + await sink.addStream(chunkFile.openRead()); + totalSize += await chunkFile.length(); + } + completed = true; + } finally { + await sink.close(); + if (completed) { + for (final chunkPath in chunkPaths) { + final file = File(chunkPath); + if (file.existsSync()) { + await file.delete(); + } + } + } else { + // Keep the chunk files: they are the resume state. Only the half-written + // merge target is thrown away. (The previous version deleted the chunks + // unconditionally, which is why an interrupted 872 MB download restarted + // from zero.) + final finalFile = File(finalPath); + if (finalFile.existsSync()) { + await finalFile.delete(); + } + } + } + return DownloadedCodecFile(localPath: finalPath, fileSizeBytes: totalSize); + } + + /// Free bytes are not queryable without a platform channel, so callers that + /// need a pre-flight space check must supply their own. Kept here as the + /// documented seam rather than a silent omission: an 833 MB download that + /// dies at 90% full is the most likely field failure for this feature. + // TODO(disk): add a free-space pre-flight (needs a platform channel or the + // `disk_space_plus` package) before enabling the download button. +} + +class DownloadedCodecFile { + final String localPath; + final int fileSizeBytes; + + const DownloadedCodecFile({ + required this.localPath, + required this.fileSizeBytes, + }); +} diff --git a/lib/services/image_codec_file_store_stub.dart b/lib/services/image_codec_file_store_stub.dart new file mode 100644 index 00000000..2cab39c8 --- /dev/null +++ b/lib/services/image_codec_file_store_stub.dart @@ -0,0 +1,82 @@ +import 'dart:typed_data'; + +import '../models/image_codec_support.dart'; + +class ImageCodecFileStore { + Future modelDirectoryPath() async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future> scanDownloadedModels() async { + return const []; + } + + Future deleteModel(ImageCodecModelRecord model) async {} + + Future deleteFile(String path) async {} + + Future writeModelBytes({ + required String fileName, + required Stream> chunks, + }) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future chunkFilePath(String fileName, int index) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future modelFilePath(String fileName) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future deletePartialDownloads(String fileName) async {} + + Future fileSize(String path) async => 0; + + Future appendBytes({ + required String path, + required Stream> chunks, + }) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future sha256OfFile(String path) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } + + Future readFileBytes(String path) async { + throw UnsupportedError('Local file reads are not supported on web.'); + } + + Future combineChunks({ + required String fileName, + required List chunkPaths, + }) async { + throw UnsupportedError( + 'Local codec model storage is not supported on web.', + ); + } +} + +class DownloadedCodecFile { + final String localPath; + final int fileSizeBytes; + + const DownloadedCodecFile({ + required this.localPath, + required this.fileSizeBytes, + }); +} diff --git a/lib/services/image_codec_service.dart b/lib/services/image_codec_service.dart new file mode 100644 index 00000000..fc356e84 --- /dev/null +++ b/lib/services/image_codec_service.dart @@ -0,0 +1,1602 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/image_codec_support.dart'; +import '../utils/app_logger.dart'; +import '../widgets/image_send_codec_binding.dart'; +import 'app_settings_service.dart'; +import 'image_codec_backend.dart' show kImageCodecBitstreamPathAvailable; +import 'image_codec_file_store.dart'; +import 'image_codec_session.dart'; +import 'image_codec_settings_store.dart'; + +/// Neural image codec (AEIC-SE) for sending photographs over the mesh. +/// +/// Structurally a sibling of [TranslationService] — same model registry, same +/// `_runExclusive` serial lock, same load/unload lifecycle — with four +/// deliberate differences. Read `translation_service.dart` alongside this file: +/// +/// 1. The heavy work runs in a worker isolate this class owns +/// ([ImageCodecSession]) rather than inside a package that owns its own +/// thread. A 1385 GFLOP decode on the root isolate would stall the BLE +/// notify stream and drop mesh traffic. +/// 2. [handleMemoryPressure] exists. The decode graph is ~886M parameters and +/// 2.16 GiB peak resident; it must be evicted on background and on memory +/// warnings or Android's low-memory killer takes the whole app. Do NOT copy +/// the translation stack's hold-until-disconnect behaviour. +/// 3. The download is **resumable and checksum-verified**, and fetches a *list* +/// of assets, because the model is an ONNX graph plus an 869 MiB +/// external-weights sibling. See the `---- download` section. +/// 4. Preferences live in [ImageCodecSettingsStore] until the `imageCodec*` +/// fields land on `AppSettings` (see that file's doc comment). +/// +/// ## Two sessions, two lifetimes +/// +/// The installed model is a *bundle* ([ImageCodecBundle]): a ~2.16 GiB-peak +/// synthesis decoder, two fp32 entropy graphs (64 MB send-side, 58 MB +/// decode-side, ~0.35 GiB peak and only ever one of them resident) and 813 KB +/// of CDF tables. Encoding needs only the send-side entropy graph; decoding +/// needs the decode-side graph and then the synthesis decoder, one after the +/// other — both resident at once measures 2.44 GiB. The worker therefore +/// creates ORT sessions lazily and can drop either half on its own +/// ([releaseDecoderSession] / [releaseEntropySession]), so a send never pays +/// for the decoder and [handleMemoryPressure] can shed the expensive half while +/// leaving the send path warm. +/// +/// ## What works today +/// +/// [decodeLatent] — the real ONNX synthesis pass, latent to pixels — plus +/// whatever the backend's entropy path supports. While +/// [kImageCodecBitstreamPathAvailable] is false, [encode] and [decodeBitstream] +/// throw [ImageCodecEntropyPathMissing] and [availability] reports +/// `unavailable` with [unavailableReason] carrying the sentence to show the +/// user. A build where that gate is true but the *installed files* are +/// decoder-only is a different, recoverable state: `disabled` + +/// [needsModelUpgrade] + [ImageCodecBundleIncomplete]. +/// +/// It implements [ImageSendCodec] directly, so `ImageSendPreviewSheet` and +/// `pickAndPreviewImage` bind to it with no adapter — replace +/// `FakeImageSendCodec()` at the two call sites in `chat_screen.dart` / +/// `channel_chat_screen.dart` with `context.read()`. +class ImageCodecService extends ChangeNotifier implements ImageSendCodec { + final AppSettingsService _appSettingsService; + final ImageCodecFileStore _fileStore; + final ImageCodecSettingsStore _settingsStore; + + /// Creates a new [http.Client] per download attempt. + /// + /// Injectable so the download/resume/checksum logic can be tested against a + /// `MockClient` — without this the only way to exercise an 872 MB two-file + /// resumable transfer would be to actually perform one. + final http.Client Function() _newClient; + + ImageCodecService( + this._appSettingsService, { + ImageCodecFileStore? fileStore, + ImageCodecSettingsStore? settingsStore, + http.Client Function()? clientFactory, + }) : _fileStore = fileStore ?? ImageCodecFileStore(), + _settingsStore = settingsStore ?? PrefsImageCodecSettingsStore(), + _newClient = clientFactory ?? http.Client.new; + + // ---- state (naming/order mirrors TranslationService:50-62) ---------------- + bool _disposed = false; + bool _isBusy = false; + bool _isDownloading = false; + bool _cancelDownloadRequested = false; + String? _lastError; + Future _queue = Future.value(); + ImageCodecSession? _session; + + /// Teardown started by [handleMemoryPressure]; [_ensureSession] waits for it + /// so a second isolate is never spawned while the first is still resident. + Future? _pendingRelease; + ImageCodecBundle? _loadedBundle; + ImageCodecBundle? _failedBundle; + int _downloadedBytes = 0; + int? _downloadTotalBytes; + String? _downloadFileName; + // codec-specific + double? _codecProgress; + String? _codecStage; + + // ---- getters (mirror translation_service.dart:64-76) --------------------- + bool get isBusy => _isBusy; + bool get isDownloading => _isDownloading; + String? get lastError => _lastError; + int get downloadedBytes => _downloadedBytes; + int? get downloadTotalBytes => _downloadTotalBytes; + String? get downloadFileName => _downloadFileName; + double? get downloadProgress { + final total = _downloadTotalBytes; + if (!_isDownloading || total == null || total <= 0) { + return null; + } + return (_downloadedBytes / total).clamp(0.0, 1.0); + } + + /// 0..1 while an encode or decode is running, null when idle. + double? get codecProgress => _codecProgress; + + /// Short human label for the current codec phase, null when idle. + String? get codecStage => _codecStage; + + bool get isModelLoaded => _loadedBundle != null; + + ImageCodecPreferences get preferences => _settingsStore.preferences; + + /// Composer default rate point. + AeicRatePoint get defaultRatePoint => preferences.aeicRatePoint; + + // ---- availability -------------------------------------------------------- + + /// The signal the compose UI binds to. + /// + /// Mapping decisions worth knowing: + /// * `unavailable` means "this build/device can never do this" — web, a build + /// whose inference backend failed to load, or (today, always) a build + /// without the rANS entropy path. Sending a picture needs bytes, and this + /// build can only turn a *latent* into a picture. See + /// [kImageCodecBitstreamPathAvailable] and [ImageCodecEntropyPathMissing]; + /// [unavailableReason] carries the explanation for the UI. + /// * `disabled` covers "switched off in settings", "no model downloaded + /// yet" and "the installed model predates the entropy bundle", because the + /// sheet's remedy is the same in all three: send the user to settings. + /// [needsModelDownload] and [needsModelUpgrade] distinguish them, and + /// [statusReason] renders the difference as a sentence. + @override + ImageCodecAvailability get availability { + if (unavailableReason != null) { + return ImageCodecAvailability.unavailable; + } + if (!_appSettingsService.settings.imageMessagesEnabled || + !preferences.enabled) { + return ImageCodecAvailability.disabled; + } + if (_isDownloading) { + return ImageCodecAvailability.downloading; + } + final model = selectedModel; + if (model == null || model.localPath.isEmpty) { + return ImageCodecAvailability.disabled; + } + // A decoder-only install cannot encode, and a bundle-version-1 install can + // encode but not decode; neither is "ready", so the compose UI must not say + // so. `disabled` (not `unavailable`) because the remedy is a download — + // see [needsModelUpgrade] and [statusReason]. Kept in step with + // [needsModelUpgrade] on purpose: `ready` plus an upgrade prompt would be a + // contradiction the sheet has no way to render. + if (installedBundle?.supportsDecode != true) { + return ImageCodecAvailability.disabled; + } + return ImageCodecAvailability.ready; + } + + /// Why [availability] is `unavailable`, or null when it is not. + /// + /// EXACTLY THREE CAUSES, all of them permanent properties of the build or the + /// platform, none of them fixable by the user: + /// * web, which has no native inference runtime; + /// * a build compiled without the entropy path + /// ([kImageCodecBitstreamPathAvailable]); + /// * a backend that failed to load. + /// + /// An incomplete or legacy install is deliberately NOT one of them: its + /// remedy is a download, so it is `disabled` + [needsModelUpgrade]. Reporting + /// it here would tell every user of the decoder-only build that their phone + /// can never send a picture, which is false. + @override + String? get unavailableReason { + if (kIsWeb) { + return 'The image codec needs a native inference runtime, which the web ' + 'build does not have.'; + } + if (!kImageCodecBitstreamPathAvailable) { + return 'This build ships the image decoder only. Encoding and decoding a ' + 'bitstream also needs the entropy-side graph and the rANS coder, ' + 'which are not included yet.'; + } + if (_backendMissing) { + return _lastError ?? 'The inference backend failed to load.'; + } + return null; + } + + /// One user-facing sentence for whatever non-ready state the codec is in, or + /// null when it is ready. + /// + /// [unavailableReason] can only explain the three permanent causes, so a + /// sheet that renders it alone falls back to a generic "not available" string + /// for the two states the user can actually DO something about — the feature + /// being switched off and the model not being installed. This getter covers + /// every case and is what a "why can't I send?" banner should show; it is a + /// superset, so `statusReason ?? unavailableReason` is never needed. + String? get statusReason { + final permanent = unavailableReason; + if (permanent != null) { + return permanent; + } + if (!_appSettingsService.settings.imageMessagesEnabled) { + return 'Image messages are switched off. Turn them on in Settings to ' + 'send and receive pictures.'; + } + if (!preferences.enabled) { + return 'The image codec is switched off in Settings.'; + } + if (_isDownloading) { + final name = _downloadFileName; + return name == null + ? 'The image codec model is downloading.' + : 'The image codec model is downloading ($name).'; + } + if (needsModelDownload) { + return 'The image codec model is not downloaded yet. It is about ' + '${(kImageCodecBundleTotalBytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} ' + 'GB and can be fetched from Settings.'; + } + if (needsModelUpgrade) { + return 'The installed image codec model is missing part of the current ' + 'bundle, so it cannot send and receive pictures. Re-download it in ' + 'Settings.'; + } + if (_lastError != null && !canRunInference) { + return _lastError; + } + return null; + } + + /// True when the feature is on but no weights are on disk. + bool get needsModelDownload { + final model = selectedModel; + return preferences.enabled && (model == null || model.localPath.isEmpty); + } + + /// True when a model IS installed but it is missing part of the current + /// bundle: a decoder-only (pre-bundle) install with no entropy graph and no + /// CDF tables, or a bundle-version-1 install with the send-side entropy graph + /// but no decode-side one. + /// + /// The remedy is a re-download, which is why this is not folded into + /// [unavailableReason]. Keyed off both the recorded [kImageCodecBundleVersion] + /// and the actual paths, so a record hand-edited to claim version 1 without + /// the files still reports true. + bool get needsModelUpgrade { + final model = selectedModel; + if (model == null || model.localPath.isEmpty) { + return false; + } + if (model.bundleVersion < kImageCodecBundleVersion) { + return true; + } + return installedBundle?.supportsDecode != true; + } + + /// Paths of the installed model, or null when nothing is installed. + /// + /// The decoder graph is [ImageCodecModelRecord.localPath]; the two entropy + /// graphs and the CDF tables are resolved BY ROLE, from + /// [ImageCodecModelRecord.assetRoles] first and the registry spec second, so + /// nothing here re-derives a filename by convention. A pre-bundle record + /// simply yields an incomplete bundle. + ImageCodecBundle? get installedBundle { + final model = selectedModel; + if (model == null || model.localPath.isEmpty) { + return null; + } + final spec = _specForId(model.id); + final directory = _directoryOf(model.localPath); + + String? pathFor( + ImageCodecAssetRole role, + bool Function(String) looksRight, + ) { + // 1. What the installer recorded this file AS. Exact, and the only source + // that can tell the two entropy graphs apart. + final recorded = model.fileNameForRole(role); + if (recorded != null) { + return '$directory/$recorded'; + } + // 2. The registry spec, for records written before assetRoles existed. + final declared = spec?.maybeAssetFor(role)?.fileName; + if (declared != null && model.assetFileNames.contains(declared)) { + return '$directory/$declared'; + } + // 3. Last resort for a custom-URL install or an old record: the recorded + // names, never a guess at a name that was never downloaded. + for (final name in model.assetFileNames) { + if (looksRight(name)) { + return '$directory/$name'; + } + } + return null; + } + + final decoderName = model.localPath.split('/').last; + // The bundle now holds THREE `.onnx` files, so "any .onnx that is not the + // decoder" no longer identifies the send-side graph on its own. The + // heuristic is only ever reached for a record with no matching spec entry, + // and it must not be allowed to hand the decode-side export to the encoder: + // that graph has no `image` input and would fail at the first run. + final decodeGraphName = + model.fileNameForRole(ImageCodecAssetRole.entropyDecodeGraph) ?? + spec?.maybeAssetFor(ImageCodecAssetRole.entropyDecodeGraph)?.fileName; + return ImageCodecBundle( + decoderGraphPath: model.localPath, + entropyGraphPath: pathFor( + ImageCodecAssetRole.entropyGraph, + (name) => + name.endsWith('.onnx') && + name != decoderName && + name != decodeGraphName, + ), + // Declared-name only, no heuristic. A record written before bundle + // version 2 has no decode-side graph on disk at all, and inventing a + // filename for it would trade a clean "re-download" prompt for an opaque + // ORT session-creation failure. + entropyDecodeGraphPath: pathFor( + ImageCodecAssetRole.entropyDecodeGraph, + (_) => false, + ), + tablesPath: pathFor( + ImageCodecAssetRole.cdfTables, + (name) => name.endsWith('.bin'), + ), + ratePoint: spec?.ratePoint ?? preferences.aeicRatePoint, + ); + } + + static String _directoryOf(String path) { + final index = path.lastIndexOf('/'); + return index <= 0 ? path : path.substring(0, index); + } + + ImageCodecModelSpec? _specForId(String id) { + for (final spec in imageCodecPresetModels) { + if (spec.id == id) return spec; + } + return null; + } + + /// Set once a session load has failed with [ImageCodecUnimplemented], i.e. + /// this build has no inference runtime. Sticky: retrying cannot help. + bool _backendMissing = false; + + // ---- registry (mirror translation_service.dart:129-174) ------------------ + List get availableModels => + preferences.downloadedModels; + + ImageCodecModelRecord? get selectedModel { + final selectedId = preferences.selectedModelId; + if (selectedId == null) { + return availableModels.isNotEmpty ? availableModels.first : null; + } + for (final model in availableModels) { + if (model.id == selectedId) { + return model; + } + } + return availableModels.isNotEmpty ? availableModels.first : null; + } + + /// Loads persisted preferences and reconciles them with what is on disk. + /// + /// Call once at startup, next to + /// `await translationService.refreshDownloadedModels();` in `main.dart`. + Future refreshDownloadedModels() async { + if (_isDownloading) return; + await _settingsStore.load(); + if (kIsWeb) { + _notify(); + return; + } + final scanned = await _fileStore.scanDownloadedModels(); + if (scanned.isEmpty) { + _notify(); + return; + } + // The file store reports one record per FILE, which is no longer one record + // per model: a bundle is four files, and taking them at face value would + // list `aeic_cdf_ft32.bin` as an installed codec. Reconcile against the + // registry here, so this survives whatever the store does. + final onDisk = {for (final model in scanned) model.name: model}; + final existingByPath = { + for (final model in preferences.downloadedModels) model.localPath: model, + }; + final merged = []; + // Every filename the registry knows about, so a half-installed bundle's + // leftovers are never mistaken for standalone models. + final claimed = { + for (final spec in imageCodecPresetModels) + for (final asset in spec.assets) asset.fileName, + }; + + for (final spec in imageCodecPresetModels) { + final graphFile = onDisk[spec.fileName]; + if (graphFile == null) continue; + final present = [ + for (final asset in spec.assets) + if (onDisk.containsKey(asset.fileName)) asset.fileName, + ]; + final existing = existingByPath[graphFile.localPath]; + final complete = spec.assets.every( + (asset) => onDisk.containsKey(asset.fileName), + ); + merged.add( + ImageCodecModelRecord( + id: spec.id, + name: spec.fileName, + sourceUrl: existing?.sourceUrl ?? spec.graph.sourceUrl, + localPath: graphFile.localPath, + downloadedAt: existing?.downloadedAt ?? graphFile.downloadedAt, + fileSizeBytes: [ + for (final name in present) onDisk[name]!.fileSizeBytes, + ].fold(0, (sum, size) => sum + size), + assetFileNames: present, + assetRoles: { + for (final asset in spec.assets) + if (onDisk.containsKey(asset.fileName)) + asset.fileName: asset.role, + }, + bundleVersion: complete ? kImageCodecBundleVersion : 0, + ), + ); + } + + // Anything not part of a registry bundle is a custom-URL install; keep it + // as its own single-file record so a hand-fetched graph is not deleted. + for (final model in scanned) { + if (claimed.contains(model.name)) continue; + final existing = existingByPath[model.localPath]; + merged.add( + existing?.copyWith(fileSizeBytes: model.fileSizeBytes) ?? model, + ); + } + + var updated = preferences.copyWith(downloadedModels: merged); + _failedBundle = null; + if (updated.selectedModelId == null && merged.isNotEmpty) { + updated = updated.copyWith(selectedModelId: merged.first.id); + } + await _settingsStore.save(updated); + _notify(); + } + + Future setEnabled(bool value) async { + await _settingsStore.save(preferences.copyWith(enabled: value)); + if (!value) { + await releaseModel(); + } + _notify(); + } + + Future setSelectedModelId(String? id) async { + await _settingsStore.save(preferences.copyWith(selectedModelId: id)); + // The cached session belongs to the previous model. + await releaseModel(); + _notify(); + } + + Future setDefaultRatePoint(AeicRatePoint ratePoint) async { + await _settingsStore.save( + preferences.copyWith(ratePoint: ratePoint.wireValue), + ); + _notify(); + } + + // ---- gating -------------------------------------------------------------- + + /// Whether a model file is present and a session could be loaded. + /// + /// This is the ONNX-only capability: it gates [decodeLatentToRgb], which + /// works. [canEncode]/[canDecode] additionally require the entropy path. + bool get canRunInference { + final model = selectedModel; + return !kIsWeb && + !_backendMissing && + model != null && + model.localPath.isNotEmpty; + } + + /// Whether a picture can be turned into bytes on this device right now. + /// + /// Three independent facts, all required: a model is installed and the + /// backend loads ([canRunInference]), the build contains the entropy path + /// ([kImageCodecBitstreamPathAvailable]), and the *installed* bundle carries + /// the entropy graph and the CDF tables. + bool get canEncode => + canRunInference && + kImageCodecBitstreamPathAvailable && + installedBundle?.isComplete == true; + + /// Everything [canEncode] needs, PLUS the decode-side entropy graph. + /// + /// Not an alias for [canEncode] any more. Decoding re-runs the entropy model + /// to reproduce the encoder's symbol probabilities, but it has to do it one + /// stage at a time, which the send-side export cannot do — so a bundle- + /// version-1 install can send a picture and not open one. Treating the two as + /// the same fact would let the receive path start a decode that fails + /// halfway. + bool get canDecode => + canRunInference && + kImageCodecBitstreamPathAvailable && + installedBundle?.supportsDecode == true; + + /// Whether a reassembled chunk set is complete enough to attempt a decode. + /// + /// A truncated AEIC bitstream does not decode to a degraded picture — the + /// rANS decoder desynchronises and produces garbage without raising — so the + /// answer is strictly "all data chunks present". Single-loss recovery is the + /// parity chunk's job in `image_chunk_transport.dart`, upstream of here. + bool canDecodeChunkSet(int received, int total) { + if (!canDecode || total <= 0) return false; + return received >= total; + } + + // ---- download ------------------------------------------------------------- + // + // Derived from translation_service.dart:176-366, then changed in three ways + // that matter at 872 MB across two files: + // + // 1. RESUMABLE. Each of the 8 range chunks is its own file whose *length is + // its progress marker*, so a dropped connection resumes with + // `Range: bytes=-` instead of restarting from zero. The + // chunk filenames embed the total size, so a re-download of a file whose + // length changed upstream can never resume onto stale offsets. + // 2. VERIFIED. A completed file is SHA-256'd against the expected digest + // before it is recorded. Without this, corruption arrived as an opaque + // session-load failure that got poisoned into `_failedModelPath` — a dead + // feature with no diagnostic and no way back except clearing app data. + // 3. MULTI-FILE. A model is a list of assets (graph + external weights), all + // of which must land in one directory under exact names. See + // `ImageCodecModelSpec`. + + static const int _parallelChunks = 8; + static const int _parallelMinBytes = 10 * 1024 * 1024; // 10 MB + + /// Downloads every asset of a declared preset model. + /// + /// Refuses a spec whose URLs are placeholders — see + /// [ImageCodecModelSpec.urlsArePlaceholders] and the banner on + /// [imageCodecPresetModels]. That refusal is the guard against shipping the + /// invented HuggingFace paths. + Future downloadPresetModel( + ImageCodecModelSpec spec, + ) async { + if (spec.urlsArePlaceholders) { + throw StateError( + 'Model "${spec.id}" has placeholder URLs that have never been fetched. ' + 'Publish the weights and update imageCodecPresetModels first.', + ); + } + if (!spec.isComplete) { + throw StateError( + 'Model "${spec.id}" is missing one of the four bundle roles; it would ' + 'install a codec that cannot encode or decode.', + ); + } + return _downloadAssets( + id: spec.id, + assets: spec.assets, + declaredTotalBytes: spec.totalSizeBytes, + // Role-resolved, not positional: the graph handed to ORT is the decoder, + // which is the smallest of the four files and would never be assets.first + // if anyone sorted the list by size. + primary: spec.assetFor(ImageCodecAssetRole.decoderGraph), + bundleVersion: kImageCodecBundleVersion, + ); + } + + /// Downloads a single-file model from an arbitrary URL. + /// + /// Kept for the settings screen's "custom URL" affordance. A model with + /// external weights cannot be expressed this way; use [downloadPresetModel]. + Future downloadModel({ + required String sourceUrl, + String? fileName, + String? id, + }) async { + final uri = Uri.tryParse(sourceUrl); + if (uri == null || !uri.hasScheme) { + throw ArgumentError('Invalid model URL.'); + } + final resolvedFileName = + fileName ?? + _sanitizeFileName( + uri.pathSegments.isNotEmpty + ? uri.pathSegments.last + : 'image-codec-model.onnx', + ); + return _downloadAssets( + id: id ?? resolvedFileName, + assets: [ + ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderGraph, + fileName: resolvedFileName, + sourceUrl: sourceUrl, + sizeBytes: 0, + ), + ], + declaredTotalBytes: 0, + // A single-file install is by definition decoder-only. + bundleVersion: 0, + ); + } + + Future _downloadAssets({ + required String id, + required List assets, + required int declaredTotalBytes, + required int bundleVersion, + ImageCodecModelAsset? primary, + }) async { + for (final asset in assets) { + final uri = Uri.tryParse(asset.sourceUrl); + if (uri == null || !uri.hasScheme) { + throw ArgumentError('Invalid model URL: ${asset.sourceUrl}'); + } + } + return _runExclusive(() async { + _setBusy(true); + _setDownloading(true); + _lastError = null; + try { + _downloadedBytes = 0; + _downloadTotalBytes = declaredTotalBytes > 0 + ? declaredTotalBytes + : null; + _cancelDownloadRequested = false; + + // One progress bar across the whole set: `_downloadedBytes` accumulates + // over every asset and `_downloadTotalBytes` is the sum of all four, so + // a 900 MB bundle shows one monotonic bar rather than four that each + // snap back to zero. `_downloadFileName` names the file in flight. + final graphAsset = primary ?? assets.first; + final downloadedFiles = {}; + for (final asset in assets) { + downloadedFiles[asset.fileName] = await _downloadAsset(asset); + } + + final graph = downloadedFiles[graphAsset.fileName]!; + final record = ImageCodecModelRecord( + id: id, + name: graphAsset.fileName, + sourceUrl: graphAsset.sourceUrl, + localPath: graph.localPath, + downloadedAt: DateTime.now(), + // The whole bundle, not just the graph: this is what the settings + // screen shows next to the installed model, and 3 MB would be a lie + // about 900 MB of storage. + fileSizeBytes: downloadedFiles.values.fold( + 0, + (sum, file) => sum + file.fileSizeBytes, + ), + assetFileNames: [for (final asset in assets) asset.fileName], + // The only place the role of each downloaded file is known for + // certain. Recorded now so nothing downstream has to infer it from a + // filename — see [ImageCodecModelRecord.assetRoles]. + assetRoles: {for (final asset in assets) asset.fileName: asset.role}, + bundleVersion: bundleVersion, + ); + final updated = [ + for (final existing in preferences.downloadedModels) + if (existing.id != record.id) existing, + record, + ]; + await _settingsStore.save( + preferences.copyWith( + downloadedModels: updated, + selectedModelId: record.id, + modelSourceUrl: graphAsset.sourceUrl, + ), + ); + _failedBundle = null; + return record; + } finally { + _setDownloading(false); + } + }); + } + + Future _downloadAsset(ImageCodecModelAsset asset) async { + final uri = Uri.parse(asset.sourceUrl); + _downloadFileName = asset.fileName; + _notify(); + + final finalPath = await _fileStore.modelFilePath(asset.fileName); + + // Already here and intact? Credit its bytes to the progress bar and move on. + // This is what makes retrying after a failure on asset 2 of 2 cheap. + final existing = await _fileStore.fileSize(finalPath); + if (existing > 0 && + (asset.sizeBytes == 0 || existing == asset.sizeBytes) && + await _checksumMatches(asset, finalPath)) { + _downloadedBytes += existing; + _notify(); + return DownloadedCodecFile(localPath: finalPath, fileSizeBytes: existing); + } + if (existing > 0) { + await _fileStore.deleteFile(finalPath); + } + + final head = await _probe(uri); + final totalSize = head.contentLength ?? asset.sizeBytes; + + final DownloadedCodecFile downloaded; + if (head.supportsRange && totalSize > _parallelMinBytes) { + downloaded = await _downloadRanged( + uri: uri, + fileName: asset.fileName, + totalSize: totalSize, + ); + } else { + downloaded = await _downloadSingle(uri: uri, fileName: asset.fileName); + } + + await _verifyChecksum(asset, downloaded.localPath); + await _fileStore.deletePartialDownloads(asset.fileName); + return downloaded; + } + + Future<_HeadResult> _probe(Uri uri) async { + final client = _newClient(); + try { + final response = await client.send(http.Request('HEAD', uri)); + await response.stream.drain(); + return _HeadResult( + contentLength: response.contentLength, + supportsRange: + response.headers['accept-ranges']?.contains('bytes') == true, + ); + } finally { + client.close(); + } + } + + /// Non-resumable fallback: used when the server will not honour Range, or the + /// file is small enough that resume is pointless. + Future _downloadSingle({ + required Uri uri, + required String fileName, + }) async { + final client = _newClient(); + try { + final response = await client.send(http.Request('GET', uri)); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw StateError('Model download failed: HTTP ${response.statusCode}'); + } + _downloadTotalBytes ??= response.contentLength; + _notify(); + final trackedStream = _trackDownloadProgress(response.stream); + return await _fileStore.writeModelBytes( + fileName: fileName, + chunks: trackedStream, + ); + } finally { + client.close(); + } + } + + /// 8-way parallel, per-chunk resumable. + Future _downloadRanged({ + required Uri uri, + required String fileName, + required int totalSize, + }) async { + final chunkSize = (totalSize / _parallelChunks).ceil(); + final chunkPaths = []; + final clients = []; + try { + final futures = >[]; + for (var i = 0; i < _parallelChunks; i++) { + final start = i * chunkSize; + if (start >= totalSize) break; + final end = (start + chunkSize - 1).clamp(0, totalSize - 1); + final expected = end - start + 1; + + // The chunk key carries totalSize so a file that changed length upstream + // cannot resume onto offsets computed for the old length. Silent + // cross-version splicing is the one failure mode a naive resume has that + // no-resume does not, and it produces a corrupt model with a valid size. + final chunkPath = await _fileStore.chunkFilePath( + '$fileName.$totalSize', + i, + ); + chunkPaths.add(chunkPath); + + var have = await _fileStore.fileSize(chunkPath); + if (have > expected) { + // Only reachable if a previous run wrote past its range. Distrust it. + await _fileStore.deleteFile(chunkPath); + have = 0; + } + _downloadedBytes += have; + if (have == expected) { + continue; // Complete from a previous attempt. + } + + final client = _newClient(); + clients.add(client); + futures.add( + _downloadRange( + client: client, + uri: uri, + chunkPath: chunkPath, + start: start + have, + end: end, + ), + ); + } + _notify(); + await Future.wait(futures); + if (_cancelDownloadRequested) { + throw const ImageCodecDownloadCancelled(); + } + return await _fileStore.combineChunks( + fileName: fileName, + chunkPaths: chunkPaths, + ); + } finally { + for (final client in clients) { + client.close(); + } + // Chunk files are deliberately NOT deleted on failure — they are the + // resume state. `combineChunks` reaps them once the merge succeeds, and + // `deletePartialDownloads` sweeps them after verification. + } + } + + Future _downloadRange({ + required http.Client client, + required Uri uri, + required String chunkPath, + required int start, + required int end, + }) async { + final request = http.Request('GET', uri); + request.headers['Range'] = 'bytes=$start-$end'; + final response = await client.send(request); + if (response.statusCode != 206) { + await response.stream.drain(); + throw StateError( + 'Range download failed: HTTP ${response.statusCode}' + '${response.statusCode == 200 ? ' (server ignored Range header)' : ''}', + ); + } + await _fileStore.appendBytes( + path: chunkPath, + chunks: _trackDownloadProgress(response.stream), + ); + } + + /// True when [path] matches [asset]'s digest, or when there is no digest. + Future _checksumMatches(ImageCodecModelAsset asset, String path) async { + if (!asset.hasChecksum) { + return true; + } + try { + final actual = await _fileStore.sha256OfFile(path); + return actual == asset.sha256.toLowerCase(); + } catch (_) { + return false; + } + } + + /// Verifies [path] and deletes it if the digest is wrong. + /// + /// A no-op when the asset has no digest — which is the case for every preset + /// today, because nothing has been published to hash. That is a real hole: + /// see the note on [ImageCodecModelAsset.sha256]. + Future _verifyChecksum(ImageCodecModelAsset asset, String path) async { + if (!asset.hasChecksum) { + appLogger.warn( + 'No SHA-256 for ${asset.fileName}; integrity unverified', + tag: 'ImageCodec', + ); + return; + } + _downloadFileName = 'Verifying ${asset.fileName}'; + _notify(); + final actual = await _fileStore.sha256OfFile(path); + if (actual != asset.sha256.toLowerCase()) { + await _fileStore.deleteFile(path); + throw ImageCodecIntegrityFailure( + fileName: asset.fileName, + expected: asset.sha256.toLowerCase(), + actual: actual, + ); + } + } + + void cancelDownload() { + if (!_isDownloading) { + return; + } + _cancelDownloadRequested = true; + _lastError = 'Download stopped.'; + _notify(); + } + + Future removeModel(ImageCodecModelRecord model) async { + // Free the isolate first: on Android the file cannot be deleted while the + // native session still has it mapped. + await releaseModel(); + await _runExclusive(() async { + _setBusy(true); + _lastError = null; + await _fileStore.deleteModel(model); + // deleteModel only knows about `localPath` (the 3 MB graph) unless the + // store has been taught about bundles, so sweep the recorded siblings + // here too. Without this, "Remove model" leaves 940 MB on the device. + final directory = _directoryOf(model.localPath); + for (final name in model.assetFileNames) { + final path = '$directory/$name'; + if (path == model.localPath) continue; + await _fileStore.deleteFile(path); + await _fileStore.deletePartialDownloads(name); + } + final updated = preferences.downloadedModels + .where((entry) => entry.id != model.id) + .toList(); + var next = preferences.copyWith(downloadedModels: updated); + if (next.selectedModelId == model.id) { + next = next.copyWith( + selectedModelId: updated.isNotEmpty ? updated.first.id : null, + ); + } + await _settingsStore.save(next); + }); + } + + // ---- codec API ----------------------------------------------------------- + + /// [ImageSendCodec] entry point used by `ImageSendPreviewSheet`. + /// + /// Takes the raw picked file (JPEG/PNG/HEIC/…), centre-crops and scales it to + /// [kImageCodecSquareSize] square, then encodes. Throws on failure so the + /// sheet can surface it — unlike the nullable service-level methods below, + /// whose contract is "null means not available". + @override + Future encode( + Uint8List imageBytes, + ImageCodecRatePoint rate, + ) async { + if (!kImageCodecBitstreamPathAvailable) { + // Fail here rather than after a 512x512 raster and a session load, and + // fail with the specific exception so the sheet can say why. + throw const ImageCodecEntropyPathMissing(); + } + if (installedBundle?.isComplete != true) { + // A different failure with a different remedy: the build can do this, the + // installed files cannot. Do not collapse the two. + throw const ImageCodecBundleIncomplete(); + } + final result = await encodeImage( + rgbBytes: await _toSquareRgb(imageBytes), + ratePoint: aeicRatePointForUi(rate), + ); + final bitstream = result?.bitstream; + if (bitstream == null) { + throw StateError(_lastError ?? 'Image codec is not available.'); + } + return bitstream; + } + + @override + Future decodePreview(Uint8List payload) async { + if (!canDecode) return null; + final result = await decodeBitstream( + bitstream: payload, + ratePoint: aeicRatePointForUi(kImageSendRatePoint), + resolution: kImageCodecSquareSize, + ); + return result?.pngBytes; + } + + /// Encodes an already-decoded RGB image. + /// + /// [rgbBytes] must be exactly `512 * 512 * 3` packed 8-bit RGB. Anything else + /// is rejected: the decoder's SD-Turbo UNet needs a 64x64 latent, so 512 is a + /// hard floor, not a default. + Future encodeImage({ + required Uint8List rgbBytes, + required AeicRatePoint ratePoint, + }) async { + if (!canEncode) return null; + const expected = + kImageCodecSquareSize * kImageCodecSquareSize * _bytesPerPixel; + if (rgbBytes.length != expected) { + throw ArgumentError.value( + rgbBytes.length, + 'rgbBytes', + 'expected $expected bytes of ${kImageCodecSquareSize}x' + '$kImageCodecSquareSize RGB', + ); + } + return _runCodecJob( + stage: 'Encoding…', + ratePoint: ratePoint, + action: (session) => session.encode( + rgbBytes, + ratePoint, + kImageCodecSquareSize, + onProgress: _reportCodecProgress, + ), + wrap: (bytes, elapsed) => ImageCodecResult( + bitstream: bytes, + ratePoint: ratePoint, + resolution: kImageCodecSquareSize, + durationMs: elapsed, + status: ImageCodecStatus.completed, + ), + ); + } + + /// Encodes a source file, resizing to 512x512 first. + /// + /// Returns null when [canEncode] is false. + Future encodeImageFile({ + required String path, + AeicRatePoint? ratePoint, + }) async { + if (!canEncode) return null; + final bytes = await _fileStore.readFileBytes(path); + return encodeImage( + rgbBytes: await _toSquareRgb(bytes), + ratePoint: ratePoint ?? defaultRatePoint, + ); + } + + /// Decodes a reassembled bitstream back to PNG bytes. + /// + /// [resolution] comes from the chunk-0 metadata byte; a stream announcing a + /// resolution this build cannot decode is rejected rather than guessed at. + Future decodeBitstream({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + }) async { + if (!kImageCodecBitstreamPathAvailable) { + // A received image cannot be silently dropped: the receive path has to be + // able to tell the user why nothing rendered. + throw const ImageCodecEntropyPathMissing(); + } + // `supportsDecode`, not `isComplete`: a bundle-version-1 install has the + // send-side entropy graph and can encode, but the decode-side graph is what + // turns bytes back into a latent. Same remedy either way — re-download. + if (installedBundle?.supportsDecode != true) { + throw const ImageCodecBundleIncomplete(); + } + if (!canDecode) return null; + if (bitstream.isEmpty) return null; + if (resolution != kImageCodecSquareSize) { + _lastError = 'Unsupported image resolution: $resolution.'; + _notify(); + return ImageCodecResult( + ratePoint: ratePoint, + resolution: resolution, + durationMs: 0, + status: ImageCodecStatus.failed, + ); + } + // The tables are per-checkpoint. Decoding an ft16 stream against ft32 + // tables does not fail — it desynchronises rANS and yields a sharp, + // plausible, wrong picture — so a rate mismatch is refused up front. It is + // a failed *result*, not a throw: it is a property of the received message, + // not a programming error. + final installedRate = installedBundle?.ratePoint; + if (installedRate != null && installedRate != ratePoint) { + _lastError = + 'This picture was sent at ${ratePoint.name}, but the installed model ' + 'is ${installedRate.name}.'; + _notify(); + return ImageCodecResult( + ratePoint: ratePoint, + resolution: resolution, + durationMs: 0, + status: ImageCodecStatus.failed, + ); + } + final result = await _runCodecJob( + stage: 'Decoding…', + ratePoint: ratePoint, + action: (session) => session.decode( + bitstream, + ratePoint, + resolution, + onProgress: _reportCodecProgress, + ), + // The worker returns packed RGB, exactly like decodeLatent. Labelling it + // `pngBytes` (as this used to) hands the receive path bytes that are not + // a PNG under a name that says they are; `Image.memory` then fails on a + // decode that actually succeeded. + wrap: (bytes, elapsed) => ImageCodecResult( + rgbBytes: bytes, + ratePoint: ratePoint, + resolution: resolution, + durationMs: elapsed, + status: ImageCodecStatus.completed, + ), + ); + final rgb = result?.rgbBytes; + if (result == null || rgb == null) { + return result; + } + // Both forms: RGB for anything that wants pixels, PNG for `Image.memory`. + return ImageCodecResult( + rgbBytes: rgb, + pngBytes: await rgbToPng(rgb, result.resolution), + ratePoint: result.ratePoint, + resolution: result.resolution, + durationMs: result.durationMs, + status: result.status, + ); + } + + /// Runs the synthesis half of the decoder: latent -> packed 8-bit RGB. + /// + /// **This is the only inference path that works in this build.** It is what a + /// device smoke test should call: dump a `y_hat` from + /// `aic/exp/aeic_runner.py`, ship the 65,536 float32s to the phone, and + /// compare the result against the desktop ONNX output. Everything from a + /// bitstream to `y_hat` needs the entropy path — see + /// [ImageCodecEntropyPathMissing]. + /// + /// Returns null when no model is available; the returned result carries + /// [ImageCodecResult.rgbBytes]. + Future decodeLatent(Float32List yHat) async { + if (!canRunInference) return null; + if (yHat.length != kImageCodecLatentElements) { + throw ArgumentError.value( + yHat.length, + 'yHat', + 'expected $kImageCodecLatentElements float32 latents ' + '(shape $kImageCodecLatentShape)', + ); + } + return _runCodecJob( + stage: 'Rendering…', + ratePoint: kShippingAeicRatePoint, + action: (session) => + session.decodeLatent(yHat, onProgress: _reportCodecProgress), + wrap: (bytes, elapsed) => ImageCodecResult( + rgbBytes: bytes, + ratePoint: kShippingAeicRatePoint, + resolution: kImageCodecSquareSize, + durationMs: elapsed, + status: ImageCodecStatus.completed, + ), + ); + } + + /// [decodeLatent] followed by PNG encoding, for anything that renders an + /// `Image.memory`. + Future decodeLatentToPng(Float32List yHat) async { + final result = await decodeLatent(yHat); + final rgb = result?.rgbBytes; + if (result == null || rgb == null) { + return result; + } + return ImageCodecResult( + rgbBytes: rgb, + pngBytes: await rgbToPng(rgb, result.resolution), + ratePoint: result.ratePoint, + resolution: result.resolution, + durationMs: result.durationMs, + status: result.status, + ); + } + + /// Packed 8-bit RGB -> PNG, via `dart:ui` so this adds no dependency. + /// + /// Runs on the calling isolate. A single 512x512 raster is four orders of + /// magnitude cheaper than the 1385 GFLOP decode that produced it. + static Future rgbToPng(Uint8List rgb, int side) async { + final pixels = side * side; + if (rgb.length != pixels * _bytesPerPixel) { + throw ArgumentError.value( + rgb.length, + 'rgb', + 'expected ${pixels * _bytesPerPixel} bytes for ${side}x$side RGB', + ); + } + final rgba = Uint8List(pixels * 4); + for (var i = 0, s = 0, d = 0; i < pixels; i++, s += 3, d += 4) { + rgba[d] = rgb[s]; + rgba[d + 1] = rgb[s + 1]; + rgba[d + 2] = rgb[s + 2]; + rgba[d + 3] = 0xFF; + } + final buffer = await ui.ImmutableBuffer.fromUint8List(rgba); + final descriptor = ui.ImageDescriptor.raw( + buffer, + width: side, + height: side, + pixelFormat: ui.PixelFormat.rgba8888, + ); + ui.Codec? codec; + ui.Image? image; + try { + codec = await descriptor.instantiateCodec(); + image = (await codec.getNextFrame()).image; + final png = await image.toByteData(format: ui.ImageByteFormat.png); + if (png == null) { + throw StateError('Could not PNG-encode the decoded image.'); + } + return png.buffer.asUint8List(); + } finally { + image?.dispose(); + codec?.dispose(); + descriptor.dispose(); + } + } + + /// Cooperative cancel for a long encode/decode, mirroring [cancelDownload]. + /// + /// The worker polls a flag between backend stages; a backend stuck inside one + /// blocking native call will not notice until that call returns. For a hard + /// stop use [handleMemoryPressure] / [releaseModel], which kill the isolate. + void cancelCodecJob() { + final session = _session; + if (session == null || _codecStage == null) return; + _lastError = 'Image processing stopped.'; + session.cancel(); + _notify(); + } + + Future _runCodecJob({ + required String stage, + required AeicRatePoint ratePoint, + required Future Function(ImageCodecSession session) action, + required ImageCodecResult Function(Uint8List bytes, int elapsedMs) wrap, + }) async { + final bundle = installedBundle; + if (bundle == null) return null; + final started = DateTime.now(); + try { + return await _runExclusive(() async { + _setCodecStage('Loading model…', 0); + final session = await _ensureSession(bundle); + if (session == null) { + return null; + } + _setCodecStage(stage, 0); + final bytes = await action(session); + return wrap(bytes, DateTime.now().difference(started).inMilliseconds); + }); + } catch (error) { + _lastError = error.toString(); + appLogger.warn('Image codec job failed: $error', tag: 'ImageCodec'); + return ImageCodecResult( + ratePoint: ratePoint, + resolution: kImageCodecSquareSize, + durationMs: DateTime.now().difference(started).inMilliseconds, + status: ImageCodecStatus.failed, + ); + } finally { + _setCodecStage(null, null); + } + } + + // ---- pixel preparation --------------------------------------------------- + + static const int _bytesPerPixel = 3; + + /// Centre-crops [imageBytes] to a square and scales it to + /// [kImageCodecSquareSize], returning packed 8-bit RGB. + /// + /// Uses `dart:ui` rather than a decode package so this adds no dependency. + /// It runs on the root isolate, which is acceptable: it is a single 512x512 + /// raster, three orders of magnitude cheaper than the 1385 GFLOP inference + /// that follows in the worker. + Future _toSquareRgb(Uint8List imageBytes) async { + final codec = await ui.instantiateImageCodec(imageBytes); + final frame = await codec.getNextFrame(); + final source = frame.image; + ui.Image? scaled; + try { + // The WHOLE frame, stretched to the square — not a centre crop. + // Aspect ratio is deliberately not preserved: the codec's graph is + // statically 512x512, so something has to give, and losing 25% of a 4:3 + // photo (44% of 16:9, or the subject's head in a portrait) is worse than + // distorting it. Nothing outside the frame is discarded this way. + // NOTE: the aspect ratio is NOT transmitted, so the receiver cannot undo + // the stretch — see the note in image_chunk_transport.dart on the + // metadata byte. + final src = ui.Rect.fromLTWH( + 0, + 0, + source.width.toDouble(), + source.height.toDouble(), + ); + final dstSize = kImageCodecSquareSize.toDouble(); + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder).drawImageRect( + source, + src, + ui.Rect.fromLTWH(0, 0, dstSize, dstSize), + ui.Paint()..filterQuality = ui.FilterQuality.medium, + ); + final picture = recorder.endRecording(); + try { + scaled = await picture.toImage( + kImageCodecSquareSize, + kImageCodecSquareSize, + ); + } finally { + picture.dispose(); + } + final rgba = await scaled.toByteData(format: ui.ImageByteFormat.rawRgba); + if (rgba == null) { + throw StateError('Could not rasterise the image.'); + } + return _rgbaToRgb(rgba.buffer.asUint8List()); + } finally { + scaled?.dispose(); + source.dispose(); + codec.dispose(); + } + } + + static Uint8List _rgbaToRgb(Uint8List rgba) { + final pixels = rgba.length ~/ 4; + final rgb = Uint8List(pixels * _bytesPerPixel); + for (var i = 0, o = 0; i < rgba.length; i += 4, o += _bytesPerPixel) { + rgb[o] = rgba[i]; + rgb[o + 1] = rgba[i + 1]; + rgb[o + 2] = rgba[i + 2]; + } + return rgb; + } + + // ---- model memory (mirrors translation_service.dart:586-629) ------------- + + Future _ensureSession(ImageCodecBundle bundle) async { + final pendingRelease = _pendingRelease; + if (pendingRelease != null) { + try { + await pendingRelease; + } catch (_) {} + } + if (_session != null && _loadedBundle == bundle) { + return _session; + } + if (bundle == _failedBundle) { + return null; + } + final previous = _session; + if (previous != null) { + _session = null; + _loadedBundle = null; + await previous.dispose(); + } + try { + final session = await ImageCodecSession.spawn(bundle); + _session = session; + _loadedBundle = bundle; + _failedBundle = null; + return session; + } on ImageCodecUnimplemented catch (error) { + // No inference runtime in this build; retrying can never help, so poison + // the whole feature rather than just this path. + _backendMissing = true; + _failedBundle = bundle; + _lastError = error.toString(); + appLogger.warn('Image codec unavailable: $error', tag: 'ImageCodec'); + _notify(); + return null; + } catch (_) { + _failedBundle = bundle; + rethrow; + } + } + + Future releaseModel() async { + await _runExclusive(() async { + final session = _session; + if (session == null) { + _loadedBundle = null; + return; + } + _session = null; + _loadedBundle = null; + await session.dispose(); + }); + } + + /// Drops the ~2.16 GiB image decoder session, keeping the isolate and the + /// ~0.35 GiB entropy session alive. + /// + /// This is the cheap eviction: measured, 2.44 GiB resident falls to 0.35 GiB, + /// and it leaves the send path warm because encoding never touches the image + /// decoder. Safe to call when nothing is loaded. + Future releaseDecoderSession() async { + final session = _session; + if (session == null) return; + await session.release(decoder: true); + appLogger.info('Image codec decoder session released', tag: 'ImageCodec'); + } + + /// Drops the entropy session (whichever direction is resident), keeping the + /// image decoder. + /// + /// Rarely what you want on its own — `decode()` does it internally between + /// the entropy half and the synthesis half — and it is the WRONG half to shed + /// under memory pressure: it frees 0.35 GiB and costs the send path its warm + /// session. Exposed only so a host that knows no send is coming can shed it. + Future releaseEntropySession() async { + final session = _session; + if (session == null) return; + await session.release(entropy: true); + } + + /// Sheds codec memory under pressure. + /// + /// Not present in [TranslationService], and required here: the decode graph + /// peaks around 2.16 GiB resident, far above what Android will let a + /// backgrounded app keep. Wire it to an app-level [WidgetsBindingObserver] — + /// `didChangeAppLifecycleState` (paused/hidden) and `didHaveMemoryPressure`. + /// Idempotent and safe when nothing is loaded. + /// + /// Order matters: the IMAGE DECODER goes first, always. Measured, it is + /// 2.16 GiB of a 2.44 GiB peak — 89% of the resident set — and it is the half + /// the *send* path does not need. On a soft eviction ([keepEntropySession]) + /// the 0.35 GiB entropy graph is deliberately kept, so a user who backgrounds + /// the app and comes back to send a photo pays nothing while the big half is + /// already gone. Never invert this: dropping the entropy graph first would + /// free an eighth of the memory and cost the only path that was warm. + /// + /// The default is still the hard stop — kill the isolate — because that also + /// returns ORT's arena and any native allocation the plugin is holding, which + /// closing sessions alone does not. + Future handleMemoryPressure({bool keepEntropySession = false}) async { + final session = _session; + if (session == null && _loadedBundle == null) { + return; + } + // Deliberately does NOT go through _runExclusive: memory pressure arrives + // while a decode may be mid-flight and holding the lock, and that decode is + // exactly what has to die. Killing the isolate fails its pending futures, + // which _runCodecJob reports as a failed result. + if (keepEntropySession && session != null) { + await session.release(decoder: true); + appLogger.info( + 'Image codec decoder evicted (entropy session kept)', + tag: 'ImageCodec', + ); + _notify(); + return; + } + _session = null; + _loadedBundle = null; + _codecProgress = null; + _codecStage = null; + if (session != null) { + // Ask for the big half back before the shutdown handshake, so the peak + // does not have to wait on isolate teardown. + final release = () async { + await session.release(decoder: true); + await session.dispose(); + }(); + _pendingRelease = release; + try { + await release; + } finally { + if (identical(_pendingRelease, release)) _pendingRelease = null; + } + } + appLogger.info('Image codec model evicted', tag: 'ImageCodec'); + _notify(); + } + + // ---- plumbing (copied from translation_service.dart:631-698) ------------ + + Future _runExclusive(Future Function() action) { + final completer = Completer(); + _setBusy(true); + _queue = _queue.then((_) async { + if (_disposed) { + completer.completeError(StateError('ImageCodecService disposed.')); + return; + } + try { + completer.complete(await action()); + } catch (error, stackTrace) { + completer.completeError(error, stackTrace); + } finally { + _setBusy(false); + } + }); + return completer.future; + } + + Stream> _trackDownloadProgress(Stream> source) async* { + await for (final chunk in source) { + if (_cancelDownloadRequested) { + throw const ImageCodecDownloadCancelled(); + } + _downloadedBytes += chunk.length; + _notify(); + yield chunk; + } + } + + void _reportCodecProgress(double value) { + _codecProgress = value.clamp(0.0, 1.0); + _notify(); + } + + void _setCodecStage(String? stage, double? progress) { + _codecStage = stage; + _codecProgress = progress; + _notify(); + } + + void _notify() { + if (_disposed) { + return; + } + notifyListeners(); + } + + void _setBusy(bool value) { + if (_isBusy == value) { + return; + } + _isBusy = value; + _notify(); + } + + void _setDownloading(bool value) { + _isDownloading = value; + if (!value) { + _cancelDownloadRequested = false; + _downloadedBytes = 0; + _downloadTotalBytes = null; + _downloadFileName = null; + } + _notify(); + } + + /// Sweeps resume state for a model the user is no longer downloading. + /// + /// Spec-shaped rather than filename-shaped: a bundle leaves chunk files for + /// up to four assets, and sweeping only the graph's would strand ~900 MB of + /// hidden resume state that nothing ever collects. + Future discardPartialDownload(ImageCodecModelSpec spec) async { + for (final asset in spec.assets) { + await _fileStore.deletePartialDownloads(asset.fileName); + } + } + + /// Sweeps resume state for one file, for the custom-URL install path. + Future discardPartialDownloadFile(String fileName) => + _fileStore.deletePartialDownloads(fileName); + + String _sanitizeFileName(String fileName) { + final cleaned = fileName.replaceAll(RegExp(r'[^A-Za-z0-9._-]'), '_'); + return cleaned.isEmpty ? 'image-codec-model.onnx' : cleaned; + } + + @override + void dispose() { + _disposed = true; + final session = _session; + _session = null; + _loadedBundle = null; + if (session != null) { + unawaited(session.dispose()); + } + super.dispose(); + } +} + +/// What a HEAD probe told us about a model asset. +class _HeadResult { + final int? contentLength; + final bool supportsRange; + + const _HeadResult({required this.contentLength, required this.supportsRange}); +} diff --git a/lib/services/image_codec_session.dart b/lib/services/image_codec_session.dart new file mode 100644 index 00000000..d1a437a5 --- /dev/null +++ b/lib/services/image_codec_session.dart @@ -0,0 +1,2 @@ +export 'image_codec_session_stub.dart' + if (dart.library.io) 'image_codec_session_io.dart'; diff --git a/lib/services/image_codec_session_io.dart b/lib/services/image_codec_session_io.dart new file mode 100644 index 00000000..2a1bb57f --- /dev/null +++ b/lib/services/image_codec_session_io.dart @@ -0,0 +1,606 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:flutter/services.dart'; + +import '../models/image_codec_support.dart'; +import '../widgets/image_send_codec_binding.dart' show kImageCodecSquareSize; +import 'image_codec_backend.dart'; +import 'entropy_tables.dart'; + +/// Owns a long-lived [Isolate] and the native codec session inside it. +/// +/// A decode is 1385 GFLOP over 886M parameters. It must never run on the root +/// isolate: it would freeze the UI and, worse, stall the BLE notify stream that +/// `MeshCoreConnector._handleFrame()` feeds on, dropping mesh traffic while a +/// picture renders. +/// +/// The isolate is spawned once per model load and reused, because loading the +/// model is the expensive part (~833 MB int8). This is the same amortisation +/// `TranslationService._ensureContext` gets for free from llamadart, which owns +/// its own worker thread. Do NOT switch this to `Isolate.run` per call. +/// +/// Message protocol (all maps, all `type`-tagged): +/// worker -> host `ready` {port: SendPort, backend: String, +/// bitstream: bool, entropy: bool, tables: bool} +/// `fatal` {error: String} — during startup only +/// `progress` {id: int, value: double} +/// `result` {id: int, bytes: Uint8List} +/// `released` {id: int} +/// `error` {id: int, error: String, stack: String?} +/// host -> worker `job` {id, op: 'encode'|'decode'|'decodeLatent', +/// bytes | latents, rate, size} +/// `release` {id, which: 'decoder'|'entropy'|'both'} +/// `cancel` {} +/// `shutdown` {} +/// +/// ## Two sessions, two lifetimes +/// +/// The backend holds the 2.16 GiB decoder and the 67 MB entropy graph +/// independently, and [release] is how the host sheds one without killing the +/// other. It exists because `decode()` MUST drop the entropy graph before it +/// creates the decoder — holding both at once is ~2.2 GiB plus 67 MB of arena +/// on a phone — and because memory pressure wants the big half gone while the +/// small half (all that `encode()` needs) can survive. +/// +/// ## Plugin channels on a background isolate +/// +/// The ONNX backend is a *plugin*, reached over a platform channel, and a plain +/// spawned isolate has no binary messenger — every `invokeMethod` would throw +/// until `BackgroundIsolateBinaryMessenger.ensureInitialized` is handed a +/// [RootIsolateToken] captured on the root isolate. That token is part of the +/// boot payload below. Consequence: [spawn] must be called from the root +/// isolate. It is (via `ImageCodecService`), and if that ever changes the token +/// is null and the worker fails loudly at startup instead of on first inference. +class ImageCodecSession { + final Isolate _isolate; + final SendPort _toWorker; + final ReceivePort _fromWorker; + final ReceivePort _errors; + + /// Name of the backend that actually loaded, for logs and error strings. + final String backendName; + + /// Whether the loaded backend can turn bytes into a picture, as opposed to + /// only latents into a picture. True only when the bundle carried the entropy + /// graph and the CDF tables AND the backend implements the entropy path. + final bool supportsBitstreamCodec; + + /// Whether the bundle handed to [spawn] carried an entropy-side graph. + final bool hasEntropyGraph; + + /// Whether the bundle handed to [spawn] carried a CDF table file. + final bool hasTables; + + final Map _pending = {}; + final Map> _pendingReleases = {}; + int _nextJobId = 1; + bool _disposed = false; + + ImageCodecSession._({ + required Isolate isolate, + required SendPort toWorker, + required ReceivePort fromWorker, + required ReceivePort errors, + required this.backendName, + required this.supportsBitstreamCodec, + required this.hasEntropyGraph, + required this.hasTables, + }) : _isolate = isolate, + _toWorker = toWorker, + _fromWorker = fromWorker, + _errors = errors; + + /// Spawns the worker and blocks until the backend has *validated* [bundle]. + /// + /// Cheap by design: `load()` parses the CDF tables (813 KB) and checks that + /// every path exists, and creates NO ORT session. Sessions are created lazily + /// by the first operation that needs one, which is what lets a send pay for + /// the 67 MB entropy graph alone instead of the 2.16 GiB decoder as well. + /// + /// Throws [ImageCodecUnimplemented] when no inference backend is compiled + /// into the build, or whatever the backend threw while loading. + static Future spawn(ImageCodecBundle bundle) async { + final fromWorker = ReceivePort(); + final errors = ReceivePort(); + final handshake = Completer>(); + ImageCodecSession? session; + + fromWorker.listen((message) { + if (message is! Map) return; + final map = message.cast(); + final active = session; + if (active != null) { + active._handleMessage(map); + } else if (!handshake.isCompleted) { + handshake.complete(map); + } + }); + + errors.listen((message) { + final description = message is List && message.isNotEmpty + ? message.first.toString() + : message.toString(); + final active = session; + if (active != null) { + active._failAll(StateError('Image codec isolate died: $description')); + } else if (!handshake.isCompleted) { + handshake.complete({'type': 'fatal', 'error': description}); + } + }); + + late final Isolate isolate; + try { + isolate = await Isolate.spawn>( + _codecWorkerMain, + _bootPayload( + bundle, + fromWorker.sendPort, + // Null when spawn() was not called from the root isolate. The worker + // treats that as a fatal startup error rather than limping on to fail + // at the first invokeMethod. + RootIsolateToken.instance, + ), + errorsAreFatal: true, + onError: errors.sendPort, + debugName: 'image-codec', + ); + } catch (_) { + fromWorker.close(); + errors.close(); + rethrow; + } + + Map reply; + try { + reply = await handshake.future; + } catch (_) { + isolate.kill(priority: Isolate.immediate); + fromWorker.close(); + errors.close(); + rethrow; + } + + if (reply['type'] != 'ready') { + isolate.kill(priority: Isolate.immediate); + fromWorker.close(); + errors.close(); + final detail = reply['error']?.toString() ?? 'unknown startup failure'; + if (reply['unimplemented'] == true) { + throw ImageCodecUnimplemented(detail); + } + throw StateError('Image codec failed to start: $detail'); + } + + return session = ImageCodecSession._( + isolate: isolate, + toWorker: reply['port'] as SendPort, + fromWorker: fromWorker, + errors: errors, + backendName: reply['backend'] as String? ?? 'unknown', + supportsBitstreamCodec: reply['bitstream'] == true, + hasEntropyGraph: reply['entropy'] == true, + hasTables: reply['tables'] == true, + ); + } + + /// Runs the synthesis half: `y_hat` -> packed 8-bit RGB. + /// + /// This is the one inference path that actually works today. [encode] and + /// [decode] fail with [ImageCodecEntropyPathMissing] until the entropy-side + /// graph and the rANS coder land. + Future decodeLatent( + Float32List yHat, { + void Function(double progress)? onProgress, + }) { + return _submit( + op: 'decodeLatent', + latents: yHat, + ratePoint: kShippingAeicRatePoint, + resolution: kImageCodecSquareSize, + onProgress: onProgress, + ); + } + + Future encode( + Uint8List rgbBytes, + AeicRatePoint ratePoint, + int resolution, { + void Function(double progress)? onProgress, + }) { + return _submit( + op: 'encode', + bytes: rgbBytes, + ratePoint: ratePoint, + resolution: resolution, + onProgress: onProgress, + ); + } + + Future decode( + Uint8List bitstream, + AeicRatePoint ratePoint, + int resolution, { + void Function(double progress)? onProgress, + }) { + return _submit( + op: 'decode', + bytes: bitstream, + ratePoint: ratePoint, + resolution: resolution, + onProgress: onProgress, + ); + } + + Future _submit({ + required String op, + Uint8List? bytes, + Float32List? latents, + required AeicRatePoint ratePoint, + required int resolution, + void Function(double progress)? onProgress, + }) { + if (_disposed) { + return Future.error(StateError('Image codec session disposed.')); + } + final id = _nextJobId++; + final job = _PendingJob(onProgress: onProgress); + _pending[id] = job; + _toWorker.send({ + 'type': 'job', + 'id': id, + 'op': op, + 'bytes': ?bytes, + 'latents': ?latents, + 'rate': ratePoint.wireValue, + 'size': resolution, + }); + return job.completer.future; + } + + /// Drops one or both ORT sessions without killing the isolate. + /// + /// The paths stay recorded inside the backend, so a released session is + /// re-created on the next call that needs it. Completes when the worker has + /// acknowledged, so a caller can rely on the memory being back before it + /// creates the other session. + /// + /// Queued behind any in-flight job, like every other command: releasing the + /// decoder out from under a running synthesis pass would crash ORT. + Future release({bool decoder = false, bool entropy = false}) { + if (!decoder && !entropy) return Future.value(); + if (_disposed) return Future.value(); + final id = _nextJobId++; + final completer = Completer(); + _pendingReleases[id] = completer; + _toWorker.send({ + 'type': 'release', + 'id': id, + 'which': decoder && entropy + ? 'both' + : decoder + ? 'decoder' + : 'entropy', + }); + return completer.future; + } + + /// Cooperative cancel. + /// + /// The worker sets a flag that the backend polls at stage boundaries. A + /// backend sitting inside one long blocking native call cannot be + /// interrupted this way — for a hard stop, call [dispose], which kills the + /// isolate outright and frees the model. + void cancel() { + if (_disposed) return; + _toWorker.send(const {'type': 'cancel'}); + } + + void _handleMessage(Map message) { + final id = message['id']; + final job = id is int ? _pending[id] : null; + switch (message['type']) { + case 'progress': + final value = message['value']; + if (value is num) { + job?.onProgress?.call(value.toDouble().clamp(0.0, 1.0)); + } + case 'result': + if (id is int) _pending.remove(id); + final bytes = message['bytes']; + if (bytes is Uint8List) { + job?.completer.complete(bytes); + } else { + job?.completer.completeError( + StateError('Image codec returned no bytes.'), + ); + } + case 'released': + if (id is int) { + final release = _pendingReleases.remove(id); + if (release != null && !release.isCompleted) { + release.complete(); + } + } + case 'error': + if (id is int) { + _pending.remove(id); + // A release can fail too; never leave its caller hanging. + final release = _pendingReleases.remove(id); + if (release != null && !release.isCompleted) { + release.complete(); + } + } + job?.completer.completeError( + StateError(message['error']?.toString() ?? 'Image codec failed.'), + ); + } + } + + void _failAll(Object error) { + final jobs = _pending.values.toList(); + _pending.clear(); + for (final job in jobs) { + if (!job.completer.isCompleted) { + job.completer.completeError(error); + } + } + // Releases resolve rather than fail: the isolate dying IS the memory being + // freed, which is all the caller was waiting for. + final releases = _pendingReleases.values.toList(); + _pendingReleases.clear(); + for (final release in releases) { + if (!release.isCompleted) { + release.complete(); + } + } + } + + /// Kills the isolate and frees the model's resident memory. + Future dispose() async { + if (_disposed) return; + _disposed = true; + _toWorker.send(const {'type': 'shutdown'}); + // Give the worker one event-loop turn to release the native session + // cleanly, then take the memory back regardless. + await Future.delayed(const Duration(milliseconds: 50)); + _isolate.kill(priority: Isolate.immediate); + _failAll(StateError('Image codec session disposed.')); + _fromWorker.close(); + _errors.close(); + } +} + +class _PendingJob { + final Completer completer = Completer(); + final void Function(double progress)? onProgress; + + _PendingJob({this.onProgress}); +} + +/// The positional payload handed to the codec worker isolate. +/// +/// Built and parsed in ONE place on purpose. When these were two hand-written +/// lists, `entropyDecodeGraphPath` was added to the bundle but never to the +/// list, so the worker rebuilt a bundle that could not decode — while +/// `canDecode`, computed on the main isolate where the path existed, said it +/// could. Every decode threw `ImageCodecBundleIncomplete` and told the user to +/// re-download a model that was already correct. The whole suite stayed green, +/// because both halves were individually right. +/// +/// APPEND new fields; never insert. The list is positional and the casts are +/// permissive enough that a shifted `tablesPath` would be read as the rate +/// point rather than throwing. +List _bootPayload( + ImageCodecBundle bundle, + SendPort reply, + RootIsolateToken? rootToken, +) => [ + reply, // 0 + bundle.decoderGraphPath, // 1 + bundle.entropyGraphPath, // 2 + bundle.tablesPath, // 3 + bundle.ratePoint.wireValue, // 4 + rootToken, // 5 + bundle.entropyDecodeGraphPath, // 6 +]; + +/// Rebuilds the bundle from [_bootPayload]. Tolerates a short list so a +/// truncated or older message degrades to "cannot decode" instead of throwing a +/// RangeError inside the isolate, where it would surface as an opaque spawn +/// failure. +ImageCodecBundle _bundleFromBootPayload(List boot) => ImageCodecBundle( + decoderGraphPath: boot[1] as String, + entropyGraphPath: boot[2] as String?, + tablesPath: boot[3] as String?, + ratePoint: parseAeicRatePoint(boot[4] as int? ?? -1), + entropyDecodeGraphPath: boot.length > 6 ? boot[6] as String? : null, +); + +/// Test seams for the boot payload. Not for production use — see +/// `test/services/image_codec_boot_payload_test.dart`, which exists because +/// this connection has broken twice. +@visibleForTesting +List debugBootPayloadFor(ImageCodecBundle bundle) => + _bootPayload(bundle, _NullSendPort(), null); + +@visibleForTesting +ImageCodecBundle debugBundleFromBootPayload(List boot) => + _bundleFromBootPayload(boot); + +/// Stand-in so [debugBootPayloadFor] needs no live isolate. +class _NullSendPort implements SendPort { + @override + void send(Object? message) {} + + @override + bool operator ==(Object other) => identical(this, other); + + @override + int get hashCode => 0; +} + +/// Entry point of the codec worker isolate. +Future _codecWorkerMain(List boot) async { + final reply = boot[0] as SendPort; + final bundle = _bundleFromBootPayload(boot); + final rootToken = boot[5] as RootIsolateToken?; + + if (rootToken == null) { + reply.send({ + 'type': 'fatal', + 'error': + 'RootIsolateToken was unavailable, so the ONNX plugin channel cannot ' + 'be reached from this isolate. ImageCodecSession.spawn() must be ' + 'called from the root isolate.', + }); + return; + } + // Without this the backend's very first invokeMethod throws. Must happen + // before createImageCodecBackend(), which constructs the plugin wrapper. + BackgroundIsolateBinaryMessenger.ensureInitialized(rootToken); + + final backend = createImageCodecBackend(); + if (backend == null) { + reply.send({ + 'type': 'fatal', + 'unimplemented': true, + 'error': + 'no inference backend is compiled into this build ' + '(see lib/services/image_codec_backend.dart)', + }); + return; + } + + // The bitstream path is a seam so that image_codec_backend.dart can compile + // for web, where dart:io does not exist. This worker isolate is native-only, + // so it is the correct place to close it -- and it must happen BEFORE + // backend.load(), because load() reads supportsBitstreamCodec to decide + // whether the codec can encode or decode at all. Left unassigned, the whole + // entropy path is dead even with kImageCodecBitstreamPathAvailable true. + imageCodecRansCoderBuilder ??= (path) async => + AeicRansCoders(EntropyTables.parse(await File(path).readAsBytes())); + + try { + await backend.load(bundle); + } catch (error) { + reply.send({'type': 'fatal', 'error': error.toString()}); + await backend.dispose(); + return; + } + + final commands = ReceivePort(); + var cancelRequested = false; + var queue = Future.value(); + + reply.send({ + 'type': 'ready', + 'port': commands.sendPort, + 'backend': backend.name, + // `bitstream` is the backend's own answer (does this build have the entropy + // path at all?); `entropy`/`tables` describe what THIS INSTALL supplied. A + // pre-bundle install reports bitstream:true, tables:false — a state the + // service must surface as "re-download", not as "your build cannot". + 'bitstream': backend.supportsBitstreamCodec, + 'entropy': bundle.entropyGraphPath != null, + 'tables': bundle.tablesPath != null, + }); + + commands.listen((message) { + if (message is! Map) return; + final map = message.cast(); + switch (map['type']) { + case 'cancel': + // Handled on the event loop, so it lands between backend stages. + cancelRequested = true; + case 'shutdown': + commands.close(); + unawaited(backend.dispose()); + case 'release': + // Queued behind any running job: tearing an ORT session down while it + // is executing is a native crash, not an exception. + queue = queue.then((_) async { + final id = map['id'] as int?; + try { + final which = map['which']; + if (which == 'decoder' || which == 'both') { + await backend.releaseDecoderSession(); + } + if (which == 'entropy' || which == 'both') { + await backend.releaseEntropySession(); + } + reply.send({'type': 'released', 'id': id}); + } catch (error) { + reply.send({ + 'type': 'error', + 'id': id, + 'error': error.toString(), + }); + } + }); + case 'job': + queue = queue.then((_) async { + cancelRequested = false; + final id = map['id'] as int; + try { + final ratePoint = parseAeicRatePoint( + map['rate'] as int? ?? kShippingAeicRatePoint.wireValue, + ); + final resolution = map['size'] as int? ?? kImageCodecSquareSize; + void onProgress(double value) { + reply.send({ + 'type': 'progress', + 'id': id, + 'value': value, + }); + } + + bool shouldCancel() => cancelRequested; + + final Uint8List result; + switch (map['op']) { + case 'decodeLatent': + result = await backend.decodeLatentToRgb( + yHat: map['latents'] as Float32List, + onProgress: onProgress, + shouldCancel: shouldCancel, + ); + case 'encode': + result = await backend.encode( + rgbBytes: map['bytes'] as Uint8List, + ratePoint: ratePoint, + resolution: resolution, + onProgress: onProgress, + shouldCancel: shouldCancel, + ); + case 'decode': + result = await backend.decode( + bitstream: map['bytes'] as Uint8List, + ratePoint: ratePoint, + resolution: resolution, + onProgress: onProgress, + shouldCancel: shouldCancel, + ); + default: + throw StateError('Unknown codec op: ${map['op']}'); + } + reply.send({ + 'type': 'result', + 'id': id, + 'bytes': result, + }); + } catch (error, stackTrace) { + reply.send({ + 'type': 'error', + 'id': id, + 'error': error.toString(), + 'stack': stackTrace.toString(), + }); + } + }); + } + }); +} diff --git a/lib/services/image_codec_session_stub.dart b/lib/services/image_codec_session_stub.dart new file mode 100644 index 00000000..756775e3 --- /dev/null +++ b/lib/services/image_codec_session_stub.dart @@ -0,0 +1,53 @@ +import 'dart:typed_data'; + +import '../models/image_codec_support.dart'; + +/// Web stand-in. There is no isolate and no native runtime on web, so the +/// session cannot exist; `ImageCodecService` gates on `kIsWeb` long before it +/// would reach here. +class ImageCodecSession { + ImageCodecSession._(); + + static Future spawn(ImageCodecBundle bundle) async { + throw UnsupportedError('The image codec is not supported on web.'); + } + + String get backendName => 'unsupported'; + + bool get supportsBitstreamCodec => false; + + bool get hasEntropyGraph => false; + + bool get hasTables => false; + + Future release({bool decoder = false, bool entropy = false}) async {} + + Future decodeLatent( + Float32List yHat, { + void Function(double progress)? onProgress, + }) async { + throw UnsupportedError('The image codec is not supported on web.'); + } + + Future encode( + Uint8List rgbBytes, + AeicRatePoint ratePoint, + int resolution, { + void Function(double progress)? onProgress, + }) async { + throw UnsupportedError('The image codec is not supported on web.'); + } + + Future decode( + Uint8List bitstream, + AeicRatePoint ratePoint, + int resolution, { + void Function(double progress)? onProgress, + }) async { + throw UnsupportedError('The image codec is not supported on web.'); + } + + void cancel() {} + + Future dispose() async {} +} diff --git a/lib/services/image_codec_settings_store.dart b/lib/services/image_codec_settings_store.dart new file mode 100644 index 00000000..3ac39d57 --- /dev/null +++ b/lib/services/image_codec_settings_store.dart @@ -0,0 +1,92 @@ +import 'dart:convert'; + +import '../models/image_codec_support.dart'; +import '../storage/prefs_manager.dart'; +import '../utils/app_logger.dart'; + +/// Persistence seam for [ImageCodecPreferences]. +/// +/// WHY THIS EXISTS. The app stack spec puts these five fields on `AppSettings` +/// (`imageCodecEnabled`, `imageCodecSelectedModelId`, `imageCodecModelSourceUrl`, +/// `imageCodecRatePoint`, `imageCodecDownloadedModels`) with matching setters on +/// `AppSettingsService` — exactly like the translation block. That is still the +/// right end state, but `app_settings.dart` and `app_settings_service.dart` are +/// outside this workstream's file set, so the service talks to this interface +/// instead of `AppSettingsService`. +/// +/// Migration is mechanical: add the fields to `AppSettings` (the JSON keys in +/// [ImageCodecPreferences.toJson] are already the `image_codec_*` snake_case +/// names), then replace [PrefsImageCodecSettingsStore] with a thin adapter over +/// `AppSettingsService`. No `ImageCodecService` code changes. +abstract class ImageCodecSettingsStore { + ImageCodecPreferences get preferences; + + /// Loads persisted preferences. Safe to call more than once. + Future load(); + + Future save(ImageCodecPreferences preferences); +} + +/// Default store: one SharedPreferences key holding the whole block as JSON. +class PrefsImageCodecSettingsStore implements ImageCodecSettingsStore { + static const String _key = 'image_codec_settings'; + + ImageCodecPreferences _preferences = const ImageCodecPreferences(); + bool _loaded = false; + + @override + ImageCodecPreferences get preferences => _preferences; + + @override + Future load() async { + if (_loaded) return; + _loaded = true; + try { + final raw = PrefsManager.instance.getString(_key); + if (raw == null) return; + final json = jsonDecode(raw); + if (json is Map) { + _preferences = ImageCodecPreferences.fromJson(json); + } + } catch (error) { + // Matches AppSettingsService.loadSettings: a corrupt blob falls back to + // defaults rather than blocking startup. + appLogger.warn('Image codec settings load failed: $error'); + _preferences = const ImageCodecPreferences(); + } + } + + @override + Future save(ImageCodecPreferences preferences) async { + _preferences = preferences; + _loaded = true; + try { + await PrefsManager.instance.setString( + _key, + jsonEncode(preferences.toJson()), + ); + } catch (error) { + appLogger.warn('Image codec settings save failed: $error'); + } + } +} + +/// Non-persisting store for tests and widget previews. +class InMemoryImageCodecSettingsStore implements ImageCodecSettingsStore { + ImageCodecPreferences _preferences; + + InMemoryImageCodecSettingsStore([ + this._preferences = const ImageCodecPreferences(), + ]); + + @override + ImageCodecPreferences get preferences => _preferences; + + @override + Future load() async {} + + @override + Future save(ImageCodecPreferences preferences) async { + _preferences = preferences; + } +} diff --git a/lib/services/map_tile_cache_service.dart b/lib/services/map_tile_cache_service.dart index e0d4e573..3be80f67 100644 --- a/lib/services/map_tile_cache_service.dart +++ b/lib/services/map_tile_cache_service.dart @@ -1,12 +1,263 @@ import 'dart:math' as math; import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:flutter_map/flutter_map.dart'; -const String kMapTileUrlTemplate = - 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; +import '../models/app_settings.dart'; +import 'app_settings_service.dart'; + +enum MapRasterSourcePreset { + osmAuto('osm_auto'), + osmStandard('osm_standard'), + osmDark('osm_dark'), + osmDarkHC('osm_darkHC'), + stamenTerrain('stamen_terrain'), + alidadeSmoothDark('alidade_smooth_dark'), + outdoors('outdoors'), + osmBright('osm_bright'), + outdoorsDark('outdoors_dark'), + outdoorsDarkHC('outdoors_darkHC'), + osmBrightDark('osm_bright_dark'), + osmBrightDarkHC('osm_bright_darkHC'); + + const MapRasterSourcePreset(this.id); + + final String id; + + static MapRasterSourcePreset fromId(String id) { + for (final value in values) { + if (value.id == id) return value; + } + return MapRasterSourcePreset.osmAuto; + } +} + +enum MapRasterEndpointPreset { + standard('standard'), + standard2x('standard_2x'), + eu('eu'), + eu2x('eu_2x'); + + const MapRasterEndpointPreset(this.id); + + final String id; + + static MapRasterEndpointPreset fromId(String id) { + for (final value in values) { + if (value.id == id) return value; + } + return MapRasterEndpointPreset.standard; + } +} + +@immutable +class MapRasterSourceDefinition { + const MapRasterSourceDefinition({ + required this.id, + required this.label, + required this.description, + this.isStadia = false, + this.allowsBulkDownload = false, + }); + + final String id; + final String label; + final String description; + final bool isStadia; + final bool allowsBulkDownload; +} + +@immutable +class MapRasterEndpointDefinition { + const MapRasterEndpointDefinition({ + required this.id, + required this.label, + required this.description, + required this.host, + this.scaleSuffix = '', + }); + + final String id; + final String label; + final String description; + final String host; + final String scaleSuffix; +} + +class MapRasterSourceCatalog { + static const MapRasterSourceDefinition osmAuto = MapRasterSourceDefinition( + id: 'osm_auto', + label: 'OpenStreetMap Auto', + description: + 'Automatically uses OpenStreetMap Standard or Dark from the app theme', + ); + static const MapRasterSourceDefinition osmStandard = + MapRasterSourceDefinition( + id: 'osm_standard', + label: 'OpenStreetMap Standard', + description: 'Direct tiles from tile.openstreetmap.org', + ); + static const MapRasterSourceDefinition osmDark = MapRasterSourceDefinition( + id: 'osm_dark', + label: 'OpenStreetMap Dark', + description: 'Standard OpenStreetMap tiles with an inverted dark filter', + ); + static const MapRasterSourceDefinition osmDarkHC = MapRasterSourceDefinition( + id: 'osm_darkHC', + label: 'OpenStreetMap Dark High Contrast', + description: + 'Standard OpenStreetMap tiles with an inverted high contrast dark filter', + ); + static const MapRasterSourceDefinition stamenTerrain = + MapRasterSourceDefinition( + id: 'stamen_terrain', + label: 'Stamen Terrain', + description: 'Terrain-focused style with hill shading', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition alidadeSmoothDark = + MapRasterSourceDefinition( + id: 'alidade_smooth_dark', + label: 'Alidade Smooth Dark', + description: 'Dark basemap with smooth contrast', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition outdoors = MapRasterSourceDefinition( + id: 'outdoors', + label: 'Outdoors', + description: 'Outdoor-focused map with trails and terrain context', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition osmBright = MapRasterSourceDefinition( + id: 'osm_bright', + label: 'OSM Bright', + description: 'Bright general-purpose OpenStreetMap style', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition outdoorsDark = + MapRasterSourceDefinition( + id: 'outdoors', + label: 'Outdoors Dark', + description: 'Dark version of the Outdoors map style', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition outdoorsDarkHC = + MapRasterSourceDefinition( + id: 'outdoors', + label: 'Outdoors Dark High Contrast', + description: 'High contrast dark version of the Outdoors map style', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition osmBrightDark = + MapRasterSourceDefinition( + id: 'osm_bright', + label: 'OSM Bright Dark', + description: 'Dark version of the OSM Bright map style', + isStadia: true, + allowsBulkDownload: true, + ); + static const MapRasterSourceDefinition osmBrightDarkHC = + MapRasterSourceDefinition( + id: 'osm_bright', + label: 'OSM Bright Dark High Contrast', + description: 'High contrast dark version of the OSM Bright map style', + isStadia: true, + allowsBulkDownload: true, + ); + + static MapRasterSourceDefinition fromPreset(MapRasterSourcePreset preset) { + switch (preset) { + case MapRasterSourcePreset.osmAuto: + return osmAuto; + case MapRasterSourcePreset.osmStandard: + return osmStandard; + case MapRasterSourcePreset.osmDark: + return osmDark; + case MapRasterSourcePreset.osmDarkHC: + return osmDarkHC; + case MapRasterSourcePreset.alidadeSmoothDark: + return alidadeSmoothDark; + case MapRasterSourcePreset.outdoors: + return outdoors; + case MapRasterSourcePreset.outdoorsDark: + return outdoorsDark; + case MapRasterSourcePreset.outdoorsDarkHC: + return outdoorsDarkHC; + case MapRasterSourcePreset.osmBright: + return osmBright; + case MapRasterSourcePreset.osmBrightDark: + return osmBrightDark; + case MapRasterSourcePreset.osmBrightDarkHC: + return osmBrightDarkHC; + case MapRasterSourcePreset.stamenTerrain: + return stamenTerrain; + } + } + + static MapRasterSourceDefinition fromSettings(AppSettings settings) { + return fromPreset(MapRasterSourcePreset.fromId(settings.mapRasterSourceId)); + } +} + +class MapRasterEndpointCatalog { + static const MapRasterEndpointDefinition standard = + MapRasterEndpointDefinition( + id: 'standard', + label: 'Standard Endpoint', + description: 'Global CDN routing to the fastest Stadia server', + host: 'tiles.stadiamaps.com', + ); + static const MapRasterEndpointDefinition standard2x = + MapRasterEndpointDefinition( + id: 'standard_2x', + label: 'Standard Endpoint (@2x)', + description: 'Global Stadia endpoint with HiDPI raster tiles', + host: 'tiles.stadiamaps.com', + scaleSuffix: '@2x', + ); + static const MapRasterEndpointDefinition eu = MapRasterEndpointDefinition( + id: 'eu', + label: 'EU Endpoint', + description: 'Route tile requests to Stadia EU servers', + host: 'tiles-eu.stadiamaps.com', + ); + static const MapRasterEndpointDefinition eu2x = MapRasterEndpointDefinition( + id: 'eu_2x', + label: 'EU Endpoint (@2x)', + description: 'EU Stadia endpoint with HiDPI raster tiles', + host: 'tiles-eu.stadiamaps.com', + scaleSuffix: '@2x', + ); + + static const List presets = [ + standard, + standard2x, + eu, + eu2x, + ]; + + static MapRasterEndpointDefinition fromSettings(AppSettings settings) { + final preset = MapRasterEndpointPreset.fromId(settings.mapTileEndpointId); + switch (preset) { + case MapRasterEndpointPreset.standard2x: + return standard2x; + case MapRasterEndpointPreset.eu: + return eu; + case MapRasterEndpointPreset.eu2x: + return eu2x; + case MapRasterEndpointPreset.standard: + return standard; + } + } +} class MapTileCacheProgress { final int completed; @@ -32,36 +283,316 @@ class MapTileCacheResult { }); } -class MapTileCacheService { +class CachedTileInfo { + final String key; + final String host; + final String sourceId; + final int zoom; + final int x; + final int y; + final int length; + + const CachedTileInfo({ + required this.key, + required this.host, + required this.sourceId, + required this.zoom, + required this.x, + required this.y, + required this.length, + }); +} + +class CachedTileInventory { + final List tiles; + final int totalBytes; + + const CachedTileInventory({required this.tiles, required this.totalBytes}); +} + +class MapTileCacheService extends ChangeNotifier { static const String cacheKey = 'map_tile_cache'; static const String userAgentPackageName = 'com.meshcore.open'; static const int defaultMinZoom = 10; static const int defaultMaxZoom = 15; + final AppSettingsService appSettingsService; final BaseCacheManager cacheManager; late final TileProvider tileProvider; - MapTileCacheService({BaseCacheManager? cacheManager}) - : cacheManager = - cacheManager ?? - CacheManager( - Config( - cacheKey, - stalePeriod: const Duration(days: 365), - maxNrOfCacheObjects: 200000, - ), - ) { + MapTileCacheService({ + required this.appSettingsService, + BaseCacheManager? cacheManager, + }) : cacheManager = + cacheManager ?? + CacheManager( + Config( + cacheKey, + stalePeriod: const Duration(days: 365), + maxNrOfCacheObjects: 200000, + ), + ) { tileProvider = CachedNetworkTileProvider(cacheManager: this.cacheManager); + appSettingsService.addListener(_handleSettingsChanged); } + MapRasterSourceDefinition get source { + final selectedSource = MapRasterSourceCatalog.fromSettings( + appSettingsService.settings, + ); + if (!selectedSource.allowsBulkDownload || + !appSettingsService.settings.usesstadiaDemo) { + return selectedSource; + } + return MapRasterSourceDefinition( + id: selectedSource.id, + label: selectedSource.label, + description: selectedSource.description, + isStadia: selectedSource.isStadia, + allowsBulkDownload: false, // Explicitly disable bulk download for demo. + ); + } + + MapRasterEndpointDefinition get endpoint => + MapRasterEndpointCatalog.fromSettings(appSettingsService.settings); + + String get urlTemplate => _buildUrlTemplate(appSettingsService.settings); + + /// Cache key for a tile URL: the URL without its `api_key`, so rotating the + /// Stadia key does not orphan every offline tile. + static String tileCacheKey(String url) { + final uri = Uri.tryParse(url); + if (uri == null || !uri.queryParameters.containsKey('api_key')) return url; + final params = Map.of(uri.queryParameters) + ..remove('api_key'); + final stripped = params.isEmpty + ? uri.replace(query: '') + : uri.replace(queryParameters: params); + return stripped.toString().replaceFirst(RegExp(r'\?$'), ''); + } + + TileBuilder? get tileBuilder => null; + + static bool shouldApplyDarkFilterForSettings( + AppSettings settings, + Brightness brightness, + ) { + switch (MapRasterSourcePreset.fromId(settings.mapRasterSourceId)) { + case MapRasterSourcePreset.osmDark: + case MapRasterSourcePreset.osmDarkHC: + case MapRasterSourcePreset.outdoorsDark: + case MapRasterSourcePreset.outdoorsDarkHC: + case MapRasterSourcePreset.osmBrightDark: + case MapRasterSourcePreset.osmBrightDarkHC: + return true; + case MapRasterSourcePreset.osmAuto: + return brightness == Brightness.dark; + case MapRasterSourcePreset.osmStandard: + case MapRasterSourcePreset.stamenTerrain: + case MapRasterSourcePreset.alidadeSmoothDark: + case MapRasterSourcePreset.outdoors: + case MapRasterSourcePreset.osmBright: + return false; + } + } + + static bool _isHighContrastDarkPreset(MapRasterSourcePreset preset) { + switch (preset) { + case MapRasterSourcePreset.osmDarkHC: + case MapRasterSourcePreset.outdoorsDarkHC: + case MapRasterSourcePreset.osmBrightDarkHC: + return true; + case MapRasterSourcePreset.osmAuto: + case MapRasterSourcePreset.osmStandard: + case MapRasterSourcePreset.osmDark: + case MapRasterSourcePreset.stamenTerrain: + case MapRasterSourcePreset.alidadeSmoothDark: + case MapRasterSourcePreset.outdoors: + case MapRasterSourcePreset.outdoorsDark: + case MapRasterSourcePreset.osmBright: + case MapRasterSourcePreset.osmBrightDark: + return false; + } + } + + static const ColorFilter _darkMapFilter = ColorFilter.matrix([ + -0.0850, + -0.2861, + -0.0289, + 0, + 120, + -0.0957, + -0.3218, + -0.0325, + 0, + 140, + -0.1169, + -0.3934, + -0.0397, + 0, + 170, + 0, + 0, + 0, + 1, + 0, + ]); + static const ColorFilter _darkHCMapFilter = ColorFilter.matrix([ + 0.7634200013, + -1.9008999332, + -0.1915199924, + 0, + 338.15, + -0.5665799987, + -0.5720999709, + -0.1915199924, + 0, + 338.15, + -0.5665799987, + -1.9008999332, + 1.1384799335, + 0, + 338.15, + 0, + 0, + 0, + 1, + 0, + ]); + + CacheManager get _concreteCacheManager => cacheManager as CacheManager; + Map get defaultHeaders => { 'User-Agent': 'flutter_map ($userAgentPackageName)', }; + Widget buildTileLayer(BuildContext context, {double opacity = 1}) { + Widget layer = TileLayer( + urlTemplate: urlTemplate, + tileProvider: tileProvider, + tileBuilder: tileBuilder, + userAgentPackageName: userAgentPackageName, + maxZoom: 19, + ); + + final shouldApplyDarkFilter = shouldApplyDarkFilterForSettings( + appSettingsService.settings, + Theme.of(context).brightness, + ); + + if (shouldApplyDarkFilter) { + final activePreset = MapRasterSourcePreset.fromId( + appSettingsService.settings.mapRasterSourceId, + ); + final filter = _isHighContrastDarkPreset(activePreset) + ? _darkHCMapFilter + : _darkMapFilter; + layer = ColorFiltered(colorFilter: filter, child: layer); + } + + if (opacity < 1) { + layer = Opacity(opacity: opacity, child: layer); + } + + return layer; + } + Future clearCache() async { await cacheManager.emptyCache(); } + Future getCachedTileInventory() async { + final repo = _concreteCacheManager.config.repo; + await repo.open(); + final objects = await repo.getAllObjects(); + final tiles = []; + int totalBytes = 0; + + for (final object in objects) { + totalBytes += object.length ?? 0; + final tile = _parseCachedTile(object); + if (tile != null) { + tiles.add(tile); + } + } + + return CachedTileInventory(tiles: tiles, totalBytes: totalBytes); + } + + List filterTilesForActiveSource( + Iterable tiles, + ) { + final activeSource = source; + if (!activeSource.isStadia) { + return tiles + .where( + (tile) => + tile.sourceId == MapRasterSourceCatalog.osmStandard.id && + tile.host == 'tile.openstreetmap.org', + ) + .toList(); + } + + final activeEndpoint = endpoint; + return tiles + .where( + (tile) => + tile.sourceId == activeSource.id && + tile.host == activeEndpoint.host, + ) + .toList(); + } + + int countTilesForBounds( + Iterable tiles, { + LatLngBounds? bounds, + required int minZoom, + required int maxZoom, + }) { + if (bounds == null) return 0; + final safeMin = math.min(minZoom, maxZoom); + final safeMax = math.max(minZoom, maxZoom); + return tiles.where((tile) { + if (tile.zoom < safeMin || tile.zoom > safeMax) { + return false; + } + final tileBounds = _tileBoundsForTile(tile.x, tile.y, tile.zoom); + return _boundsIntersect(bounds, tileBounds); + }).length; + } + + List buildCachedTilePolygons( + Iterable tiles, { + required int zoom, + LatLngBounds? visibleBounds, + int limit = 250, + }) { + final polygons = []; + for (final tile in tiles) { + if (tile.zoom != zoom) continue; + final tileBounds = _tileBoundsForTile(tile.x, tile.y, tile.zoom); + if (visibleBounds != null && + !_boundsIntersect(visibleBounds, tileBounds)) { + continue; + } + polygons.add( + Polygon( + points: [ + tileBounds.northWest, + tileBounds.northEast, + tileBounds.southEast, + tileBounds.southWest, + ], + borderStrokeWidth: 0.6, + color: const Color(0x5532A852), + borderColor: const Color(0xCC2F8F46), + ), + ); + if (polygons.length >= limit) break; + } + return polygons; + } + int estimateTileCount(LatLngBounds bounds, int minZoom, int maxZoom) { final safeMin = math.min(minZoom, maxZoom); final safeMax = math.max(minZoom, maxZoom); @@ -89,13 +620,14 @@ class MapTileCacheService { final total = estimateTileCount(bounds, safeMin, safeMax); final authHeaders = headers ?? defaultHeaders; final safeConcurrency = math.max(1, concurrentDownloads); + final currentTemplate = urlTemplate; int completed = 0; int failed = 0; final pending = >[]; Future queueDownload(String url) async { final future = cacheManager - .downloadFile(url, key: url, authHeaders: authHeaders) + .downloadFile(url, key: tileCacheKey(url), authHeaders: authHeaders) .then((_) { completed += 1; }) @@ -124,7 +656,7 @@ class MapTileCacheService { final tileBounds = _tileBoundsForBounds(bounds, zoom); for (int x = tileBounds.minX; x <= tileBounds.maxX; x++) { for (int y = tileBounds.minY; y <= tileBounds.maxY; y++) { - final url = _buildTileUrl(x, y, zoom); + final url = _buildTileUrl(x, y, zoom, urlTemplate: currentTemplate); await queueDownload(url); } } @@ -167,6 +699,16 @@ class MapTileCacheService { ); } + void _handleSettingsChanged() { + notifyListeners(); + } + + @override + void dispose() { + appSettingsService.removeListener(_handleSettingsChanged); + super.dispose(); + } + _TileBounds _tileBoundsForBounds(LatLngBounds bounds, int zoom) { final north = _clampLatitude(bounds.north); final south = _clampLatitude(bounds.south); @@ -185,6 +727,56 @@ class MapTileCacheService { ); } + String _buildUrlTemplate(AppSettings settings) { + final source = MapRasterSourceCatalog.fromSettings(settings); + if (!source.isStadia) { + return 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; + } + final endpoint = MapRasterEndpointCatalog.fromSettings(settings); + final apiKey = settings.effectiveMapTileApiKey; + final base = + 'https://${endpoint.host}/tiles/${source.id}/{z}/{x}/{y}${endpoint.scaleSuffix}.png'; + final query = Uri(queryParameters: {'api_key': apiKey}).query; + return '$base?$query'; + } + + CachedTileInfo? _parseCachedTile(CacheObject object) { + final uri = Uri.tryParse(object.key); + if (uri == null) return null; + final segments = uri.pathSegments; + + if (segments.length >= 3 && + segments[segments.length - 3].isNotEmpty && + segments[segments.length - 2].isNotEmpty) { + final zoom = int.tryParse(segments[segments.length - 3]); + final x = int.tryParse(segments[segments.length - 2]); + final ySegment = segments.last; + final yString = ySegment.split('.').first.replaceAll('@2x', ''); + final y = int.tryParse(yString); + + if (zoom == null || x == null || y == null) { + return null; + } + + var sourceId = MapRasterSourceCatalog.osmStandard.id; + if (segments.length >= 5 && segments[0] == 'tiles') { + sourceId = segments[1]; + } + + return CachedTileInfo( + key: object.key, + host: uri.host, + sourceId: sourceId, + zoom: zoom, + x: x, + y: y, + length: object.length ?? 0, + ); + } + + return null; + } + int _lonToTileX(double lon, int zoom, int maxIndex) { final n = 1 << zoom; final value = ((lon + 180.0) / 360.0 * n).floor(); @@ -205,8 +797,34 @@ class MapTileCacheService { return lat.clamp(-maxLat, maxLat); } - String _buildTileUrl(int x, int y, int zoom) { - return kMapTileUrlTemplate + LatLngBounds _tileBoundsForTile(int x, int y, int zoom) { + return LatLngBounds.unsafe( + north: _tileYToLat(y, zoom), + south: _tileYToLat(y + 1, zoom), + east: _tileXToLon(x + 1, zoom), + west: _tileXToLon(x, zoom), + ); + } + + double _tileXToLon(int x, int zoom) { + final n = 1 << zoom; + return x / n * 360.0 - 180.0; + } + + double _tileYToLat(int y, int zoom) { + final n = math.pi - (2.0 * math.pi * y) / (1 << zoom); + return 180.0 / math.pi * math.atan(0.5 * (math.exp(n) - math.exp(-n))); + } + + bool _boundsIntersect(LatLngBounds a, LatLngBounds b) { + return a.west <= b.east && + a.east >= b.west && + a.south <= b.north && + a.north >= b.south; + } + + String _buildTileUrl(int x, int y, int zoom, {required String urlTemplate}) { + return urlTemplate .replaceAll('{z}', zoom.toString()) .replaceAll('{x}', x.toString()) .replaceAll('{y}', y.toString()); @@ -223,6 +841,7 @@ class CachedNetworkTileProvider extends TileProvider { final url = getTileUrl(coordinates, options); return CachedNetworkImageProvider( url, + cacheKey: MapTileCacheService.tileCacheKey(url), cacheManager: cacheManager, headers: headers, ); diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 783b28ba..416e1b61 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:uuid/uuid.dart'; import 'package:crypto/crypto.dart'; +import '../connector/meshcore_protocol.dart'; import '../models/contact.dart'; import '../models/message.dart'; import '../models/path_selection.dart'; @@ -34,7 +35,7 @@ typedef AckHashMapping = ({ }); class RetryServiceConfig { - final void Function(Contact, String, int, int) sendMessage; + final FutureOr Function(Contact, String, int, int) sendMessage; final void Function(String, Message) addMessage; final void Function(Message) updateMessage; final Function(Contact)? clearContactPath; @@ -209,21 +210,46 @@ class MessageRetryService extends ChangeNotifier { final messageId = queue.removeAt(0); if (_pendingMessages.containsKey(messageId)) { _activeMessages.add(messageId); - _attemptSend(messageId).catchError((e) { - debugPrint('_attemptSend threw for $messageId: $e'); - final msg = _pendingMessages[messageId]; - if (msg != null) { - final failed = msg.copyWith(status: MessageStatus.failed); - _pendingMessages[messageId] = failed; - _config?.updateMessage(failed); - } - _onMessageResolved(messageId, contactKey); - }); + _attemptSendOrFail(messageId); return; } } } + void _attemptSendOrFail(String messageId) { + _attemptSend(messageId).catchError((Object e) { + debugPrint('_attemptSend threw for $messageId: $e'); + _config?.debugLogService?.warn( + 'Send failed for message $messageId: $e', + tag: 'AckHash', + ); + _failMessage(messageId); + }); + } + + /// Marks a message that could not be handed to the radio as failed and + /// releases its in-flight slot so the contact's queue keeps moving. + void _failMessage(String messageId) { + final message = _pendingMessages[messageId]; + if (message == null) return; + _timeoutTimers[messageId]?.cancel(); + if (message.status != MessageStatus.failed && + message.status != MessageStatus.delivered) { + _config?.updateMessage(message.copyWith(status: MessageStatus.failed)); + } + _cleanupMessage(messageId); + notifyListeners(); + } + + /// Fails every pending and queued message. Call when the radio link drops: + /// nothing in flight can be sent or acknowledged any more. + void failAllPending() { + _sendQueue.clear(); + for (final messageId in _pendingMessages.keys.toList()) { + _failMessage(messageId); + } + } + void _onMessageResolved(String messageId, String contactKey) { if (_resolvedMessages.contains(messageId)) return; _resolvedMessages.add(messageId); @@ -358,6 +384,9 @@ class MessageRetryService extends ChangeNotifier { // Compute expected ACK hash that device will return in RESP_CODE_SENT // IMPORTANT: Use the transformed text (with SMAZ encoding if enabled) to match device's hash final selfPubKey = config.getSelfPublicKey?.call(); + if (config.getSelfPublicKey != null && selfPubKey == null) { + throw StateError('Self public key unknown; cannot track ACK'); + } if (selfPubKey != null) { final outboundText = config.prepareContactOutboundText?.call(contact, message.text) ?? @@ -380,7 +409,7 @@ class MessageRetryService extends ChangeNotifier { ); } - config.sendMessage(contact, message.text, attempt, timestampSeconds); + await config.sendMessage(contact, message.text, attempt, timestampSeconds); } bool updateMessageFromSent(int ackHash, int timeoutMs) { @@ -535,7 +564,8 @@ class MessageRetryService extends ChangeNotifier { tag: 'AckHash', ); - if (message.retryCount < maxRetries - 1) { + if (message.retryCount < maxRetries - 1 && + _textFitsAttempt(message, contact, message.retryCount + 1)) { final backoffMs = 1000 * (1 << message.retryCount); if (selection != null) { @@ -563,7 +593,7 @@ class MessageRetryService extends ChangeNotifier { _timeoutTimers[messageId] = Timer(Duration(milliseconds: backoffMs), () { if (_pendingMessages.containsKey(messageId)) { - _attemptSend(messageId); + _attemptSendOrFail(messageId); } }); } else { @@ -598,6 +628,17 @@ class MessageRetryService extends ChangeNotifier { } } + /// From attempt 4 on the firmware appends [0][attempt] to the payload and + /// rejects text longer than MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket). + bool _textFitsAttempt(Message message, Contact contact, int attempt) { + if (attempt <= maxFullLengthTextAttempt) return true; + final outboundText = + _config?.prepareContactOutboundText?.call(contact, message.text) ?? + message.text; + return utf8.encode(outboundText).length <= + maxTextPayloadBytesAfterFullLengthAttempts; + } + void _moveAckHashesToHistory(String messageId) { final ackHashes = _expectedAckHashes.remove(messageId); if (ackHashes != null && ackHashes.isNotEmpty) { diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index b148c95d..f4578558 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -3,9 +3,12 @@ import 'dart:ui'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import '../helpers/message_url_image_helper.dart'; import '../helpers/reaction_helper.dart'; import '../l10n/app_localizations.dart'; +import '../storage/prefs_manager.dart'; import '../utils/platform_info.dart'; class NotificationService { @@ -27,6 +30,11 @@ class NotificationService { AppLocalizations get _l10n => lookupAppLocalizations(_locale); + String _logSafe(String value) { + final sanitized = value.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), ' '); + return Uri.encodeComponent(sanitized); + } + // Rate limiting to prevent notification storms // (Added after getting notification-flooded while evaluating RF flood management. The irony.) static const _minNotificationInterval = Duration(seconds: 3); @@ -116,9 +124,11 @@ class NotificationService { // Cached "are we allowed to post notifications" result. Null = not yet // determined. Avoids calling _notifications.show() when it would only throw - // "You must request notifications permissions first" (every web build, and - // Android 13+ before the user grants the permission). + // "You must request notifications permissions first" (every web build). + // Android denials are never cached so a later grant in system settings is + // picked up without restarting the app. bool? _canNotify; + static const _permissionRequestedKey = 'notification_permission_requested'; Future _ensureCanNotify() async { if (!await _ensureInitialized()) return false; @@ -136,8 +146,9 @@ class NotificationService { AndroidFlutterLocalNotificationsPlugin >(); if (androidPlugin != null) { - final enabled = await androidPlugin.areNotificationsEnabled(); - return _canNotify = enabled ?? false; + final enabled = await androidPlugin.areNotificationsEnabled() ?? false; + if (enabled) _canNotify = true; + return enabled; } // iOS/macOS request permission during initialize(); desktop has no gate. @@ -156,8 +167,8 @@ class NotificationService { >(); if (androidPlugin != null) { final granted = await androidPlugin.requestNotificationsPermission(); - _canNotify = granted ?? false; - return _canNotify!; + if (granted == true) _canNotify = true; + return granted ?? false; } // iOS permissions are requested during initialization @@ -171,13 +182,25 @@ class NotificationService { badge: true, sound: true, ); - _canNotify = granted ?? false; - return _canNotify!; + if (granted == true) _canNotify = true; + return granted ?? false; } return true; } + /// Asks for the Android 13+ notification permission the first time it is + /// needed. Never re-prompts after the user has answered once; iOS/macOS + /// already prompt during [initialize]. + Future requestPermissionsOnce() async { + if (!PlatformInfo.isAndroid || !await _ensureInitialized()) return; + final prefs = PrefsManager.instance; + if (prefs.getBool(_permissionRequestedKey) ?? false) return; + if (await _ensureCanNotify()) return; + await prefs.setBool(_permissionRequestedKey, true); + await requestPermissions(); + } + /// Format special message types for human-readable notifications. static String formatNotificationText(String text) { final trimmed = text.trim(); @@ -191,14 +214,40 @@ class NotificationService { return text; } + Future _resolveNotificationImagePath( + String text, { + required bool urlImagesEnabled, + }) async { + if (!urlImagesEnabled) return null; + + final imageUrl = await MessageUrlImageHelper.parseVerified(text); + if (imageUrl == null) return null; + + try { + // Cache the image so notification platforms can read it from disk. + final imageFile = await DefaultCacheManager().getSingleFile(imageUrl); + if (!imageFile.existsSync()) return null; + return imageFile.path; + } catch (e) { + debugPrint('Failed to resolve notification image: $e'); + return null; + } + } + Future _showMessageNotificationImpl({ required String contactName, required String message, + required bool urlImagesEnabled, String? contactId, int? badgeCount, }) async { if (!await _ensureCanNotify()) return; + final imagePath = await _resolveNotificationImagePath( + message, + urlImagesEnabled: urlImagesEnabled, + ); + final androidDetails = AndroidNotificationDetails( 'messages', 'Messages', @@ -207,6 +256,12 @@ class NotificationService { priority: Priority.high, icon: '@mipmap/ic_launcher', number: badgeCount, + styleInformation: imagePath != null + ? BigPictureStyleInformation( + FilePathAndroidBitmap(imagePath), + summaryText: formatNotificationText(message), + ) + : null, ); final iosDetails = DarwinNotificationDetails( @@ -214,6 +269,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + DarwinNotificationAttachment(imagePath), + ] + : null, ); final macDetails = DarwinNotificationDetails( @@ -221,6 +281,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + DarwinNotificationAttachment(imagePath), + ] + : null, ); final notificationDetails = NotificationDetails( @@ -294,11 +359,17 @@ class NotificationService { Future _showChannelMessageNotificationImpl({ required String channelName, required String message, + required bool urlImagesEnabled, int? channelIndex, int? badgeCount, }) async { if (!await _ensureCanNotify()) return; + final imagePath = await _resolveNotificationImagePath( + message, + urlImagesEnabled: urlImagesEnabled, + ); + final androidDetails = AndroidNotificationDetails( 'channel_messages', 'Channel Messages', @@ -307,6 +378,12 @@ class NotificationService { priority: Priority.high, icon: '@mipmap/ic_launcher', number: badgeCount, + styleInformation: imagePath != null + ? BigPictureStyleInformation( + FilePathAndroidBitmap(imagePath), + summaryText: formatNotificationText(message), + ) + : null, ); final iosDetails = DarwinNotificationDetails( @@ -314,6 +391,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + DarwinNotificationAttachment(imagePath), + ] + : null, ); final macDetails = DarwinNotificationDetails( @@ -321,6 +403,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + DarwinNotificationAttachment(imagePath), + ] + : null, ); final notificationDetails = NotificationDetails( @@ -356,11 +443,11 @@ class NotificationService { String _getNotificationIdentifier(_PendingNotification n) { switch (n.type) { case _NotificationType.advert: - return n.body; + return _logSafe(n.body); case _NotificationType.message: - return 'from: ${n.title}'; + return 'from: ${_logSafe(n.title)}'; case _NotificationType.channelMessage: - return 'in: ${n.title}'; + return 'in: ${_logSafe(n.title)}'; } } @@ -443,6 +530,7 @@ class NotificationService { Future showMessageNotification({ required String contactName, required String message, + required bool urlImagesEnabled, String? contactId, int? badgeCount, }) async { @@ -453,6 +541,7 @@ class NotificationService { type: _NotificationType.message, title: contactName, body: message, + urlImagesEnabled: urlImagesEnabled, id: contactId, badgeCount: badgeCount, ), @@ -480,6 +569,7 @@ class NotificationService { required String channelName, required String senderName, required String message, + required bool urlImagesEnabled, int? channelIndex, int? badgeCount, }) async { @@ -490,6 +580,7 @@ class NotificationService { type: _NotificationType.channelMessage, title: channelName, body: '$senderName: $message', + urlImagesEnabled: urlImagesEnabled, id: channelIndex?.toString(), badgeCount: badgeCount, ), @@ -551,6 +642,7 @@ class NotificationService { await _showMessageNotificationImpl( contactName: notification.title, message: notification.body, + urlImagesEnabled: notification.urlImagesEnabled, contactId: notification.id, badgeCount: notification.badgeCount, ); @@ -566,6 +658,7 @@ class NotificationService { await _showChannelMessageNotificationImpl( channelName: notification.title, message: notification.body, + urlImagesEnabled: notification.urlImagesEnabled, channelIndex: int.tryParse(notification.id ?? ''), badgeCount: notification.badgeCount, ); @@ -606,7 +699,7 @@ class NotificationService { // Show first few device names in batch summary for debugging (only if adverts exist) final deviceInfo = adverts.isNotEmpty - ? ' (${adverts.take(5).map((n) => n.body).join(', ')}${adverts.length > 5 ? ', ...' : ''})' + ? ' (${adverts.take(5).map((n) => _logSafe(n.body)).join(', ')}${adverts.length > 5 ? ', ...' : ''})' : ''; debugPrint('[Notification] batch summary: ${parts.join(", ")}$deviceInfo'); @@ -642,6 +735,7 @@ class _PendingNotification { final _NotificationType type; final String title; final String body; + final bool urlImagesEnabled; final String? id; final int? badgeCount; @@ -649,6 +743,7 @@ class _PendingNotification { required this.type, required this.title, required this.body, + this.urlImagesEnabled = false, this.id, this.badgeCount, }); diff --git a/lib/services/path_history_service.dart b/lib/services/path_history_service.dart index 7a61e3f6..1de88941 100644 --- a/lib/services/path_history_service.dart +++ b/lib/services/path_history_service.dart @@ -9,8 +9,7 @@ class PathHistoryService extends ChangeNotifier { final Map _cache = {}; final Map _autoRotationIndex = {}; final Map _floodStats = {}; - final Set _pendingLoads = {}; - final Map> _deferredRecords = {}; + final Map> _pendingLoads = {}; // LRU cache eviction tracking static const int _maxCachedContacts = 50; @@ -23,6 +22,16 @@ class PathHistoryService extends ChangeNotifier { PathHistoryService(this._storage); + void setDevicePublicKey(String publicKeyHex) { + _storage.setPublicKeyHex = publicKeyHex; + _cache.clear(); + _cacheAccessOrder.clear(); + _autoRotationIndex.clear(); + _floodStats.clear(); + _version++; + notifyListeners(); + } + Future initialize() async { // Load cached path histories on startup if needed } @@ -40,7 +49,7 @@ class PathHistoryService extends ChangeNotifier { pathBytes: contact.path, successCount: 0, failureCount: 0, - routeWeight: initialWeight, + initialWeight: initialWeight, timestamp: null, ); } @@ -74,6 +83,20 @@ class PathHistoryService extends ChangeNotifier { double maxWeight = 5.0, }) { if (pathBytes.isEmpty || hopCount < 0) return; + if (!_cache.containsKey(contactPubKeyHex)) { + _ensureLoaded(contactPubKeyHex).then((_) { + if (!_cache.containsKey(contactPubKeyHex)) return; + recordFloodPathAttribution( + contactPubKeyHex: contactPubKeyHex, + pathBytes: pathBytes, + hopCount: hopCount, + tripTimeMs: tripTimeMs, + successIncrement: successIncrement, + maxWeight: maxWeight, + ); + }); + return; + } final existing = _findPathRecord(contactPubKeyHex, pathBytes); final successCount = (existing?.successCount ?? 0) + 1; @@ -124,6 +147,22 @@ class PathHistoryService extends ChangeNotifier { return; } + if (!_cache.containsKey(contactPubKeyHex)) { + _ensureLoaded(contactPubKeyHex).then((_) { + if (!_cache.containsKey(contactPubKeyHex)) return; + recordPathResult( + contactPubKeyHex, + selection, + success: success, + tripTimeMs: tripTimeMs, + successIncrement: successIncrement, + failureDecrement: failureDecrement, + maxWeight: maxWeight, + ); + }); + return; + } + final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes); final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0); final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1); @@ -222,73 +261,11 @@ class PathHistoryService extends ChangeNotifier { required List pathBytes, required int successCount, required int failureCount, - double routeWeight = 1.0, + double? routeWeight, + double initialWeight = 1.0, DateTime? timestamp, }) { - var history = _cache[contactPubKeyHex]; - - if (history == null) { - // If a load is already in progress, defer this record - if (_pendingLoads.contains(contactPubKeyHex)) { - _deferredRecords.putIfAbsent(contactPubKeyHex, () => []); - _deferredRecords[contactPubKeyHex]!.add( - _DeferredPathRecord( - hopCount: hopCount, - tripTimeMs: tripTimeMs, - wasFloodDiscovery: wasFloodDiscovery, - pathBytes: pathBytes, - successCount: successCount, - failureCount: failureCount, - routeWeight: routeWeight, - timestamp: timestamp, - ), - ); - return; - } - - _pendingLoads.add(contactPubKeyHex); - _loadHistoryFromStorage(contactPubKeyHex).then((loaded) { - _cache[contactPubKeyHex] = - loaded ?? - ContactPathHistory( - contactPubKeyHex: contactPubKeyHex, - recentPaths: [], - ); - _addPathRecordInternal( - contactPubKeyHex, - hopCount, - tripTimeMs, - wasFloodDiscovery, - pathBytes, - successCount, - failureCount, - routeWeight, - timestamp, - ); - - // Apply any deferred records - final deferred = _deferredRecords.remove(contactPubKeyHex); - if (deferred != null) { - for (final record in deferred) { - _addPathRecordInternal( - contactPubKeyHex, - record.hopCount, - record.tripTimeMs, - record.wasFloodDiscovery, - record.pathBytes, - record.successCount, - record.failureCount, - record.routeWeight, - record.timestamp, - ); - } - } - _pendingLoads.remove(contactPubKeyHex); - }); - return; - } - - _addPathRecordInternal( + void add() => _addPathRecordInternal( contactPubKeyHex, hopCount, tripTimeMs, @@ -297,8 +274,34 @@ class PathHistoryService extends ChangeNotifier { successCount, failureCount, routeWeight, + initialWeight, timestamp, ); + + if (_cache.containsKey(contactPubKeyHex)) { + add(); + } else { + _ensureLoaded(contactPubKeyHex).then((_) => add()); + } + } + + Future _ensureLoaded(String contactPubKeyHex) { + if (_cache.containsKey(contactPubKeyHex)) return Future.value(); + return _pendingLoads[contactPubKeyHex] ??= + _loadHistoryFromStorage(contactPubKeyHex) + .then((loaded) { + _cache[contactPubKeyHex] ??= + loaded ?? + ContactPathHistory( + contactPubKeyHex: contactPubKeyHex, + recentPaths: [], + ); + _trackAccess(contactPubKeyHex); + _evictIfNeeded(); + }) + .whenComplete(() { + _pendingLoads.remove(contactPubKeyHex); + }); } void _addPathRecordInternal( @@ -309,7 +312,8 @@ class PathHistoryService extends ChangeNotifier { List pathBytes, int successCount, int failureCount, - double routeWeight, + double? routeWeight, + double initialWeight, DateTime? timestamp, ) { var history = _cache[contactPubKeyHex]; @@ -326,6 +330,7 @@ class PathHistoryService extends ChangeNotifier { wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery; timestamp ??= existing.timestamp; } + routeWeight ??= existing?.routeWeight ?? initialWeight; final newRecord = PathRecord( hopCount: hopCount, @@ -361,6 +366,24 @@ class PathHistoryService extends ChangeNotifier { notifyListeners(); } + /// Whether this contact's history is in the in-memory cache. + bool isCached(String contactPubKeyHex) => + _cache.containsKey(contactPubKeyHex); + + /// Paths already in memory, without loading from storage or changing the + /// cache order. For bulk readers that must not churn the 50-contact cache. + List peekRecentPaths(String contactPubKeyHex) => + _cache[contactPubKeyHex]?.recentPaths ?? const []; + + /// Reads saved paths straight from storage without adding them to the + /// cache, evicting anything, or notifying listeners. + Future> readStoredPaths(String contactPubKeyHex) async { + final cached = _cache[contactPubKeyHex]; + if (cached != null) return cached.recentPaths; + final stored = await _loadHistoryFromStorage(contactPubKeyHex); + return stored?.recentPaths ?? const []; + } + List getRecentPaths(String contactPubKeyHex) { final history = _cache[contactPubKeyHex]; if (history != null) { @@ -368,11 +391,8 @@ class PathHistoryService extends ChangeNotifier { return history.recentPaths; } - _loadHistoryFromStorage(contactPubKeyHex).then((loaded) { - if (loaded != null) { - _cache[contactPubKeyHex] = loaded; - _trackAccess(contactPubKeyHex); - _evictIfNeeded(); + _ensureLoaded(contactPubKeyHex).then((_) { + if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) { _version++; notifyListeners(); } @@ -579,28 +599,6 @@ class PathHistoryService extends ChangeNotifier { } } -class _DeferredPathRecord { - final int hopCount; - final int tripTimeMs; - final bool wasFloodDiscovery; - final List pathBytes; - final int successCount; - final int failureCount; - final double routeWeight; - final DateTime? timestamp; - - _DeferredPathRecord({ - required this.hopCount, - required this.tripTimeMs, - required this.wasFloodDiscovery, - required this.pathBytes, - required this.successCount, - required this.failureCount, - this.routeWeight = 1.0, - this.timestamp, - }); -} - class _FloodStats { int successCount = 0; int failureCount = 0; diff --git a/lib/services/rans_coder.dart b/lib/services/rans_coder.dart new file mode 100644 index 00000000..5709ab10 --- /dev/null +++ b/lib/services/rans_coder.dart @@ -0,0 +1,498 @@ +// Pure-Dart port of the AEIC rANS entropy coder. +// +// Ported from the C++ reference in `aeic/src/cpp/rans/` (rans.h, rans_byte.h, +// rans.cpp), which is itself ryg_rans + CompressAI's unbounded-index range +// coding. The port must be BYTE-IDENTICAL to the C++ coder: a single differing +// byte desynchronises rANS and silently corrupts most of the image. The golden +// vectors under `test/services/golden/` pin that down. +// +// Notes on the port: +// * Dart `int` is 64-bit and signed; the C++ state is `uint32_t`. Every place +// the C++ relies on 32-bit behaviour is either provably in-range (the state +// invariant keeps `x < 2^31`) or masked explicitly with `& 0xFFFFFFFF`. +// * `>>` on a negative Dart int is arithmetic. All shifted values here are +// non-negative by construction; `>>>` is used where the shift consumes the +// state so the intent is unambiguous. +// +// Format recap (see `results/rans_port_spec.md`): +// * precision 16, bypassPrecision 2, RANS_L = 1 << 23, streamParts 2. +// * Each `encodeWithIndexes` call is split evenly across the sub-streams: +// part p covers `[p * (n ~/ parts), ...)`, the last part taking the +// remainder. Every part accumulates across all calls; flush happens once. +// * A sub-stream's first 4 bytes are the final rANS state, little-endian. +// * Container: `flag = ((nParts - 1) << 4) | (hdrLen == 2 ? 1 : 0)`, then the +// lengths of the first `nParts - 1` sub-streams (hdrLen bytes each, LE), +// then the sub-streams back to back. +library; + +import 'dart:typed_data'; + +import 'entropy_tables.dart'; + +/// Lower bound of the rANS normalisation interval (`RANS_BYTE_L`). +const int kRansLowerBound = 1 << 23; + +/// Thrown when a bitstream cannot be interpreted. +class RansFormatException implements Exception { + RansFormatException(this.message); + + final String message; + + @override + String toString() => 'RansFormatException: $message'; +} + +/// Splits the shipped bytes into rANS sub-streams. Mirror of +/// `RansDecoder::set_stream`. +List parseRansContainer(Uint8List stream) { + if (stream.isEmpty) { + throw RansFormatException('empty stream'); + } + final int flag = stream[0]; + final int nStreams = (flag >> 4) + 1; + final int hdr = (flag & 0x0F) == 1 ? 2 : 4; + var off = 1; + final List sizes = []; + var total = 0; + for (var i = 0; i < nStreams - 1; i++) { + if (off + hdr > stream.length) { + throw RansFormatException('truncated sub-stream size table'); + } + var sz = 0; + for (var b = 0; b < hdr; b++) { + sz |= stream[off + b] << (8 * b); + } + off += hdr; + sizes.add(sz); + total += sz; + } + final int last = stream.length - off - total; + if (last < 0) { + throw RansFormatException('sub-stream sizes exceed the stream length'); + } + sizes.add(last); + final List parts = []; + var p = off; + for (final int sz in sizes) { + if (p + sz > stream.length) { + throw RansFormatException('truncated sub-stream'); + } + parts.add(Uint8List.sublistView(stream, p, p + sz)); + p += sz; + } + return parts; +} + +/// Assembles sub-streams into the bytes that go on the air. +Uint8List buildRansContainer(List parts) { + if (parts.isEmpty) { + throw RansFormatException('no sub-streams'); + } + if (parts.length > 16) { + throw RansFormatException('too many sub-streams (${parts.length})'); + } + var maximum = 0; + for (var i = 0; i < parts.length - 1; i++) { + if (parts[i].length > maximum) maximum = parts[i].length; + } + final int hdr = maximum > 65535 ? 4 : 2; + final int flag = ((parts.length - 1) << 4) | (hdr == 2 ? 1 : 0); + var total = 1 + hdr * (parts.length - 1); + for (final Uint8List p in parts) { + total += p.length; + } + final Uint8List out = Uint8List(total); + out[0] = flag; + var off = 1; + for (var i = 0; i < parts.length - 1; i++) { + final int n = parts[i].length; + for (var b = 0; b < hdr; b++) { + out[off + b] = (n >> (8 * b)) & 0xFF; + } + off += hdr; + } + for (final Uint8List p in parts) { + out.setRange(off, off + p.length, p); + off += p.length; + } + return out; +} + +/// Growable (start, range) entry list, stored interleaved in one Int32List. +/// `range == 0` is the bypass sentinel: `start` then carries the raw bits. +class _EntryBuffer { + Int32List _data = Int32List(2048); + int _length = 0; + + int get length => _length; + + void add(int start, int range) { + final int need = (_length + 1) * 2; + if (need > _data.length) { + final Int32List bigger = Int32List(_data.length * 2); + bigger.setRange(0, _data.length, _data); + _data = bigger; + } + _data[_length * 2] = start; + _data[_length * 2 + 1] = range; + _length++; + } + + int startAt(int i) => _data[i * 2]; + + int rangeAt(int i) => _data[i * 2 + 1]; + + void clear() => _length = 0; +} + +/// Growable byte sink used for the reversed encoder output. +class _ByteSink { + Uint8List _data = Uint8List(4096); + int _length = 0; + + void add(int byte) { + if (_length == _data.length) { + final Uint8List bigger = Uint8List(_data.length * 2); + bigger.setRange(0, _data.length, _data); + _data = bigger; + } + _data[_length++] = byte & 0xFF; + } + + /// Returns the bytes in reverse of the order they were added, which is the + /// order they appear in the sub-stream. + Uint8List reversedBytes() { + final Uint8List out = Uint8List(_length); + for (var i = 0; i < _length; i++) { + out[i] = _data[_length - 1 - i]; + } + return out; + } +} + +/// rANS encoder. Call [encodeWithIndexes] once per stage in format order +/// (z, y0, y1, y2, y3), then [finish] exactly once. +class RansEncoder { + factory RansEncoder(EntropyTables tables, {int? streamParts}) => + RansEncoder._(tables, streamParts ?? tables.streamParts); + + RansEncoder._(EntropyTables tables, int streamParts) + : tables = tables, + streamParts = streamParts, + _precision = tables.precision, + _bypassPrecision = tables.bypassPrecision, + _entries = List<_EntryBuffer>.generate( + streamParts, + (_) => _EntryBuffer(), + ); + + final EntropyTables tables; + final int streamParts; + final int _precision; + final int _bypassPrecision; + final List<_EntryBuffer> _entries; + bool _finished = false; + + int get _maxBypassVal => (1 << _bypassPrecision) - 1; + + /// Accumulates one encode call. [symbols] and [indexes] must be the same + /// length; an index `< 0` emits nothing at all. + /// + /// Never pass an odd-length array: the reference splitter (and therefore the + /// on-air format) mis-sizes the last part's index vector in that case. + void encodeWithIndexes( + List symbols, + List indexes, + int cdfGroupIndex, + ) { + if (_finished) { + throw StateError('RansEncoder.finish() has already been called'); + } + if (symbols.length != indexes.length) { + throw ArgumentError( + 'symbols (${symbols.length}) and indexes (${indexes.length}) differ', + ); + } + if (cdfGroupIndex < 0 || cdfGroupIndex >= tables.groups.length) { + throw ArgumentError('no CDF group $cdfGroupIndex'); + } + final CdfGroup group = tables.groups[cdfGroupIndex]; + final int total = symbols.length; + final int each = total ~/ streamParts; + for (var p = 0; p < streamParts; p++) { + final int lo = p * each; + final int hi = p == streamParts - 1 ? total : lo + each; + _push(_entries[p], symbols, indexes, lo, hi, group); + } + } + + void _push( + _EntryBuffer out, + List symbols, + List indexes, + int lo, + int hi, + CdfGroup group, + ) { + final Int32List cdf = group.quantizedCdf; + final Int32List cdfLength = group.cdfLength; + final Int32List offsets = group.offset; + final int width = group.cdfWidth; + final int maxBypassVal = _maxBypassVal; + final int bypassPrecision = _bypassPrecision; + + for (var i = lo; i < hi; i++) { + final int cdfIdx = indexes[i]; + if (cdfIdx < 0) { + continue; + } + if (cdfIdx >= group.numCdfs) { + throw RansFormatException( + 'index $cdfIdx out of range (${group.numCdfs} CDF rows)', + ); + } + final int maxValue = cdfLength[cdfIdx] - 2; + var value = symbols[i] - offsets[cdfIdx]; + var rawVal = 0; + if (value < 0) { + rawVal = -2 * value - 1; + value = maxValue; + } else if (value >= maxValue) { + rawVal = 2 * (value - maxValue); + value = maxValue; + } + + final int base = cdfIdx * width; + final int start = cdf[base + value]; + out.add(start, cdf[base + value + 1] - start); + + if (value == maxValue) { + // Bypass mode: raw bits, `bypassPrecision` at a time. + var nBypass = 0; + while ((rawVal >> (nBypass * bypassPrecision)) != 0) { + nBypass++; + } + var val = nBypass; + while (val >= maxBypassVal) { + out.add(maxBypassVal, 0); + val -= maxBypassVal; + } + out.add(val, 0); + for (var j = 0; j < nBypass; j++) { + out.add((rawVal >> (j * bypassPrecision)) & maxBypassVal, 0); + } + } + } + } + + /// Flushes every sub-stream and returns the container bytes. + Uint8List finish() { + if (_finished) { + throw StateError('RansEncoder.finish() has already been called'); + } + _finished = true; + final List parts = [ + for (final _EntryBuffer e in _entries) _flush(e), + ]; + return buildRansContainer(parts); + } + + /// Discards accumulated entries so the encoder can be reused. + void reset() { + for (final _EntryBuffer e in _entries) { + e.clear(); + } + _finished = false; + } + + Uint8List _flush(_EntryBuffer entries) { + final _ByteSink sink = _ByteSink(); + // The state is always in [2^23, 2^31); native Dart ints need no masking, + // but the emission path is written to stay explicitly byte-wise anyway. + var x = kRansLowerBound; + final int bypassXMax = (1 << (_precision - _bypassPrecision)) << 15; + for (var k = entries.length - 1; k >= 0; k--) { + final int range = entries.rangeAt(k); + final int start = entries.startAt(k); + if (range != 0) { + final int xMax = range << 15; + while (x >= xMax) { + sink.add(x & 0xFF); + x = x >>> 8; + } + x = ((x ~/ range) << _precision) + (x % range) + start; + } else { + while (x >= bypassXMax) { + sink.add(x & 0xFF); + x = x >>> 8; + } + x = ((x << _bypassPrecision) | start) & 0xFFFFFFFF; + } + } + // RansEncFlush writes the 32-bit state little-endian at the front of the + // stream, i.e. in emission order it is the high byte first. + sink.add((x >>> 24) & 0xFF); + sink.add((x >>> 16) & 0xFF); + sink.add((x >>> 8) & 0xFF); + sink.add(x & 0xFF); + return sink.reversedBytes(); + } +} + +/// rANS decoder. Decoding is INCREMENTAL: construct once over the whole +/// container, then call [decodeStream] per stage in the same order the encoder +/// used (z, y0, y1, y2, y3). Each call resumes the sub-stream states where the +/// previous one left off, because stage i's indexes are unknown until the +/// earlier stages have been decoded and run back through the network. +class RansDecoder { + factory RansDecoder( + EntropyTables tables, + Uint8List stream, { + int? streamParts, + }) => RansDecoder._(tables, stream, streamParts ?? tables.streamParts); + + RansDecoder._(EntropyTables tables, Uint8List stream, int expected) + : tables = tables, + _precision = tables.precision, + _bypassPrecision = tables.bypassPrecision, + _parts = parseRansContainer(stream) { + if (_parts.length != expected) { + throw RansFormatException( + 'container has ${_parts.length} sub-streams, expected $expected', + ); + } + _states = List.filled(_parts.length, 0); + _ptrs = List.filled(_parts.length, 0); + for (var i = 0; i < _parts.length; i++) { + final Uint8List p = _parts[i]; + if (p.length < 4) { + throw RansFormatException('sub-stream $i is shorter than 4 bytes'); + } + _states[i] = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); + _ptrs[i] = 4; + } + } + + final EntropyTables tables; + final int _precision; + final int _bypassPrecision; + final List _parts; + late final List _states; + late final List _ptrs; + + int get streamParts => _parts.length; + + /// Decodes one stage. Returns one symbol per entry of [indexes]; positions + /// whose index is `< 0` yield a literal 0 and consume nothing. + Int16List decodeStream(List indexes, int cdfGroupIndex) { + if (cdfGroupIndex < 0 || cdfGroupIndex >= tables.groups.length) { + throw ArgumentError('no CDF group $cdfGroupIndex'); + } + final CdfGroup group = tables.groups[cdfGroupIndex]; + final Int32List cdf = group.quantizedCdf; + final Int32List cdfLength = group.cdfLength; + final Int32List offsets = group.offset; + final int width = group.cdfWidth; + final int mask = (1 << _precision) - 1; + final int bypassPrecision = _bypassPrecision; + final int maxBypassVal = (1 << bypassPrecision) - 1; + final int bypassMask = maxBypassVal; + + final int total = indexes.length; + final int nParts = _parts.length; + final int each = total ~/ nParts; + final Int16List out = Int16List(total); + + for (var pi = 0; pi < nParts; pi++) { + final int lo = pi * each; + final int hi = pi == nParts - 1 ? total : lo + each; + final Uint8List buf = _parts[pi]; + var x = _states[pi]; + var ptr = _ptrs[pi]; + + for (var i = lo; i < hi; i++) { + final int cdfIdx = indexes[i]; + if (cdfIdx < 0) { + out[i] = 0; + continue; + } + if (cdfIdx >= group.numCdfs) { + throw RansFormatException( + 'index $cdfIdx out of range (${group.numCdfs} CDF rows)', + ); + } + final int n = cdfLength[cdfIdx]; + final int maxValue = n - 2; + final int base = cdfIdx * width; + final int cum = x & mask; + + // upper_bound(row[0:n], cum) - 1 + var loo = 0; + var hii = n; + while (loo < hii) { + final int mid = (loo + hii) >> 1; + if (cdf[base + mid] > cum) { + hii = mid; + } else { + loo = mid + 1; + } + } + final int s = loo - 1; + if (s < 0 || s >= n - 1) { + throw RansFormatException('corrupt stream: symbol $s out of range'); + } + final int start = cdf[base + s]; + final int range = cdf[base + s + 1] - start; + + x = (range * (x >>> _precision) + (x & mask) - start) & 0xFFFFFFFF; + while (x < kRansLowerBound) { + if (ptr >= buf.length) { + throw RansFormatException('sub-stream $pi exhausted'); + } + x = ((x << 8) | buf[ptr]) & 0xFFFFFFFF; + ptr++; + } + + var value = s; + if (value == maxValue) { + // Bypass mode. Note the renormalisation here is a single `if`, not a + // loop -- that asymmetry with the symbol path is part of the format. + int getBits() { + final int v = x & bypassMask; + x = x >>> bypassPrecision; + if (x < kRansLowerBound) { + if (ptr >= buf.length) { + throw RansFormatException('sub-stream $pi exhausted'); + } + x = ((x << 8) | buf[ptr]) & 0xFFFFFFFF; + ptr++; + } + return v; + } + + var val = getBits(); + var nBypass = val; + while (val == maxBypassVal) { + val = getBits(); + nBypass += val; + } + var rawVal = 0; + for (var j = 0; j < nBypass; j++) { + rawVal |= getBits() << (j * bypassPrecision); + } + value = rawVal >> 1; + if ((rawVal & 1) != 0) { + value = -value - 1; + } else { + value += maxValue; + } + } + out[i] = value + offsets[cdfIdx]; + } + + _states[pi] = x; + _ptrs[pi] = ptr; + } + return out; + } +} diff --git a/lib/services/received_image_blob_store_factory.dart b/lib/services/received_image_blob_store_factory.dart new file mode 100644 index 00000000..5b8a646b --- /dev/null +++ b/lib/services/received_image_blob_store_factory.dart @@ -0,0 +1,10 @@ +/// Platform-appropriate [ReceivedImageBlobStore], chosen at compile time. +/// +/// `received_image_blob_store_io.dart` imports `dart:io` and +/// `package:path_provider`, so `main.dart` cannot import it directly without +/// breaking the web build. Same conditional-export shape as +/// `image_codec_file_store.dart`. +library; + +export 'received_image_blob_store_factory_stub.dart' + if (dart.library.io) 'received_image_blob_store_factory_io.dart'; diff --git a/lib/services/received_image_blob_store_factory_io.dart b/lib/services/received_image_blob_store_factory_io.dart new file mode 100644 index 00000000..6c24d733 --- /dev/null +++ b/lib/services/received_image_blob_store_factory_io.dart @@ -0,0 +1,10 @@ +import 'received_image_blob_store_io.dart'; +import 'received_image_store.dart'; + +/// File-backed store under the application support directory. +/// +/// Received images have to survive a restart: the sidecar record is the only +/// evidence that a message *was* an image, so an in-memory store loses the +/// bubble as well as the pixels. +ReceivedImageBlobStore createReceivedImageBlobStore() => + FileReceivedImageBlobStore(); diff --git a/lib/services/received_image_blob_store_factory_stub.dart b/lib/services/received_image_blob_store_factory_stub.dart new file mode 100644 index 00000000..34fcdca5 --- /dev/null +++ b/lib/services/received_image_blob_store_factory_stub.dart @@ -0,0 +1,8 @@ +import 'received_image_store.dart'; + +/// Web fallback: images live only for the lifetime of the tab. +/// +/// The codec cannot run on web anyway (`ImageCodecService.availability` is +/// `unavailable` there), so nothing is lost that could have been rendered. +ReceivedImageBlobStore createReceivedImageBlobStore() => + InMemoryReceivedImageBlobStore(); diff --git a/lib/services/received_image_blob_store_io.dart b/lib/services/received_image_blob_store_io.dart new file mode 100644 index 00000000..3750b3cb --- /dev/null +++ b/lib/services/received_image_blob_store_io.dart @@ -0,0 +1,311 @@ +/// File-backed [ReceivedImageBlobStore] for every platform that has `dart:io`. +/// +/// Without this, `ReceivedImageStore` falls back to +/// [InMemoryReceivedImageBlobStore] and every received image is forgotten at +/// the next app launch — the sidecars go with the bytes, so even the "this +/// message was an image" record disappears. +/// +/// ## Layout +/// +/// ``` +/// /received_images/ +/// .aeic the ~156 B bitstream +/// .png the decoded 512x512 PNG (~400 KB) +/// .json the sidecar record (ReceivedImageEntry.toJson) +/// .json.tmp transient; only during an atomic sidecar write +/// ``` +/// +/// Application *support*, not documents: these are derived caches of a chat +/// message, not user documents, so they must not show up in the iOS Files app +/// or be swept into an iCloud backup. +/// +/// ## Guarantees +/// +/// * Sidecar writes are atomic (tmp file + rename). A kill mid-write can +/// leave `.json.tmp` but never a truncated `.json`, so +/// [readSidecars] never has to defend against half a JSON object. +/// * Every method is total: a missing file reads as null and deletes are +/// idempotent. I/O errors are swallowed and reported through the return +/// value, because a failed write must degrade the image, not crash the +/// receive path. +/// * [readSidecars] sweeps orphans — `.aeic`/`.png`/`.tmp` files with no +/// surviving `.json` — so a crash between "write bitstream" and "write +/// sidecar" cannot leak bytes that no budget accounts for. +/// * Stream ids are validated before they are ever concatenated into a path; +/// a hostile `../../` id cannot escape the directory. +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart' show debugPrint; +import 'package:path_provider/path_provider.dart'; + +import 'received_image_store.dart'; + +/// Persists received-image bytes under the application support directory. +class FileReceivedImageBlobStore implements ReceivedImageBlobStore { + /// Only `[A-Za-z0-9_-]`, so a stream id can never contain `/`, `\` or `..`. + static final RegExp _safeId = RegExp(r'^[A-Za-z0-9_-]{1,64}$'); + + static const String _bitstreamExt = '.aeic'; + static const String _pngExt = '.png'; + static const String _sidecarExt = '.json'; + static const String _tmpExt = '.json.tmp'; + + /// Overridable so tests (and any future "move my data" feature) can point the + /// store at a temp directory instead of the real support directory. + final Future Function() _baseDirectory; + + final String directoryName; + + /// Resolved lazily and then cached, because [pngPath] has to be synchronous + /// (the share sheet needs a path inside a build/callback) while + /// `path_provider` is not. + String? _dirPath; + Future? _pending; + + /// Last queued sidecar operation per id. Writes share one `.tmp` path, so + /// two in flight for the same id would interleave; each waits for the last. + final Map> _sidecarOps = >{}; + + FileReceivedImageBlobStore({ + Future Function()? baseDirectory, + this.directoryName = 'received_images', + }) : _baseDirectory = baseDirectory ?? getApplicationSupportDirectory; + + /// Resolves and creates the directory. Safe to call repeatedly; concurrent + /// callers share one future so the directory is created exactly once. + Future ensureReady() { + final cached = _dirPath; + if (cached != null) return Future.value(cached); + final pending = _pending; + if (pending != null) return pending; + final started = _resolve(); + _pending = started; + return started.whenComplete(() => _pending = null); + } + + Future _resolve() async { + final base = await _baseDirectory(); + final dir = Directory( + '${base.path}${Platform.pathSeparator}$directoryName', + ); + if (!dir.existsSync()) { + await dir.create(recursive: true); + } + _dirPath = dir.path; + return dir.path; + } + + Future _pathFor(String streamId, String extension) async { + if (!_safeId.hasMatch(streamId)) return null; + final dir = await ensureReady(); + return '$dir${Platform.pathSeparator}$streamId$extension'; + } + + Future _read(String streamId, String extension) async { + try { + final path = await _pathFor(streamId, extension); + if (path == null) return null; + final file = File(path); + if (!file.existsSync()) return null; + return await file.readAsBytes(); + } catch (error) { + debugPrint('received_image_blob_store: read $streamId$extension: $error'); + return null; + } + } + + Future _write( + String streamId, + String extension, + Uint8List bytes, + ) async { + try { + final path = await _pathFor(streamId, extension); + if (path == null) { + debugPrint('received_image_blob_store: refusing unsafe id "$streamId"'); + return; + } + await File(path).writeAsBytes(bytes, flush: true); + } catch (error) { + debugPrint( + 'received_image_blob_store: write $streamId$extension: $error', + ); + } + } + + Future _delete(String streamId, String extension) async { + try { + final path = await _pathFor(streamId, extension); + if (path == null) return; + final file = File(path); + if (file.existsSync()) await file.delete(); + } catch (error) { + debugPrint( + 'received_image_blob_store: delete $streamId$extension: $error', + ); + } + } + + Future _size(String streamId, String extension) async { + try { + final path = await _pathFor(streamId, extension); + if (path == null) return null; + final file = File(path); + if (!file.existsSync()) return null; + return await file.length(); + } catch (_) { + return null; + } + } + + @override + Future writeBitstream(String streamId, Uint8List bytes) => + _write(streamId, _bitstreamExt, bytes); + + @override + Future readBitstream(String streamId) => + _read(streamId, _bitstreamExt); + + @override + Future deleteBitstream(String streamId) => + _delete(streamId, _bitstreamExt); + + @override + Future bitstreamSize(String streamId) => _size(streamId, _bitstreamExt); + + @override + Future writePng(String streamId, Uint8List bytes) => + _write(streamId, _pngExt, bytes); + + @override + Future readPng(String streamId) => _read(streamId, _pngExt); + + @override + Future deletePng(String streamId) => _delete(streamId, _pngExt); + + @override + Future pngSize(String streamId) => _size(streamId, _pngExt); + + /// Atomic: write `.json.tmp`, then rename over `.json`. `rename` is + /// atomic within a directory on every platform we ship, so a reader either + /// sees the old record or the new one. + @override + Future writeSidecar(String streamId, String json) => + _serializeSidecar(streamId, () => _writeSidecarNow(streamId, json)); + + Future _serializeSidecar(String streamId, Future Function() op) { + final previous = _sidecarOps[streamId] ?? Future.value(); + final next = previous.then((_) => op()); + _sidecarOps[streamId] = next; + return next.whenComplete(() { + if (identical(_sidecarOps[streamId], next)) _sidecarOps.remove(streamId); + }); + } + + Future _writeSidecarNow(String streamId, String json) async { + try { + final finalPath = await _pathFor(streamId, _sidecarExt); + final tmpPath = await _pathFor(streamId, _tmpExt); + if (finalPath == null || tmpPath == null) { + debugPrint('received_image_blob_store: refusing unsafe id "$streamId"'); + return; + } + final tmp = File(tmpPath); + await tmp.writeAsString(json, flush: true); + await tmp.rename(finalPath); + } catch (error) { + debugPrint('received_image_blob_store: sidecar $streamId: $error'); + } + } + + @override + Future deleteSidecar(String streamId) => + _serializeSidecar(streamId, () async { + await _delete(streamId, _sidecarExt); + await _delete(streamId, _tmpExt); + }); + + /// Startup scan. Also the only place orphaned bytes are reaped: anything + /// whose sidecar is gone is invisible to the store and therefore to the + /// disk budget, so it would live forever. + @override + Future> readSidecars() async { + final result = {}; + late final String dirPath; + try { + dirPath = await ensureReady(); + } catch (error) { + debugPrint('received_image_blob_store: no directory: $error'); + return result; + } + final dir = Directory(dirPath); + if (!dir.existsSync()) return result; + + final files = []; + try { + files.addAll(dir.listSync().whereType()); + } catch (error) { + debugPrint('received_image_blob_store: list failed: $error'); + return result; + } + + final orphans = []; + for (final file in files) { + final name = file.uri.pathSegments.last; + if (name.endsWith(_tmpExt)) { + // A kill during a sidecar write. The previous `.json` (if any) is + // still authoritative. + orphans.add(file); + continue; + } + if (!name.endsWith(_sidecarExt)) continue; + final id = name.substring(0, name.length - _sidecarExt.length); + if (!_safeId.hasMatch(id)) continue; + try { + final raw = await file.readAsString(); + // Cheap sanity gate: the store's own jsonDecode would skip it anyway, + // but a truncated record here means we should reap its bytes too. + jsonDecode(raw); + result[id] = raw; + } catch (error) { + debugPrint('received_image_blob_store: bad sidecar $id: $error'); + } + } + + for (final file in files) { + final name = file.uri.pathSegments.last; + if (name.endsWith(_sidecarExt) || name.endsWith(_tmpExt)) continue; + final dot = name.lastIndexOf('.'); + if (dot <= 0) continue; + final id = name.substring(0, dot); + final ext = name.substring(dot); + if (ext != _bitstreamExt && ext != _pngExt) continue; + if (result.containsKey(id)) continue; + orphans.add(file); + } + + for (final file in orphans) { + try { + if (file.existsSync()) await file.delete(); + } catch (_) { + // Best effort; a locked file is retried on the next launch. + } + } + return result; + } + + /// Null until [ensureReady] (or any async method) has resolved the directory. + /// In practice `ReceivedImageStore.load()` runs at startup and resolves it + /// long before any bubble asks for a path. + @override + String? pngPath(String streamId) { + final dir = _dirPath; + if (dir == null) return null; + if (!_safeId.hasMatch(streamId)) return null; + return '$dir${Platform.pathSeparator}$streamId$_pngExt'; + } +} diff --git a/lib/services/received_image_store.dart b/lib/services/received_image_store.dart new file mode 100644 index 00000000..0825a060 --- /dev/null +++ b/lib/services/received_image_store.dart @@ -0,0 +1,1545 @@ +/// Receive-side state, persistence and decode scheduling for AEIC images that +/// arrive over `PAYLOAD_TYPE_GRP_DATA` (see `image_chunk_transport.dart`). +/// +/// This file holds the whole receive model: +/// * [ReceivedImageRef] the sentinel that a channel message carries in its +/// `text` field instead of the pixels. +/// * [ReceivedImageState] the state machine every incoming image walks. +/// * [ReceivedImageEntry] one immutable snapshot of an image's state. +/// * [ReceivedImageStore] the `ChangeNotifier` the message list listens to: +/// intake, persistence, eviction and the decode queue. +/// +/// ## Deliberate dependency shape +/// +/// There is no `dart:io` here and no `package:flutter/material.dart`. Bytes go +/// through the [ReceivedImageBlobStore] seam (default: +/// [InMemoryReceivedImageBlobStore]) and decoding goes through the +/// [ReceivedImageDecoder] seam, which `ImageCodecService` satisfies +/// member-for-member (the wiring agent supplies the one-class adapter — this +/// file deliberately does not import the service, so a broken edit over there +/// cannot break the receive tests). That keeps the store unit-testable with no +/// temp directories, no `path_provider` and no 872 MB model, and it keeps the +/// file compilable on web where neither seam has an implementation. +/// +/// `FileReceivedImageBlobStore` (`received_image_blob_store_io.dart`) is the +/// file-backed implementation; pass it as `blobs:` and received images survive +/// a restart. With the default in-memory store everything below works exactly +/// as specified but forgets its bytes on restart. Nothing else changes. +/// +/// ## Decode policy (four gates) +/// +/// The bitstream is ~156 B and already in hand, so decoding is only ever gated +/// on memory, never on bandwidth. Gates, all enforced here: +/// 0. [processAutomatically] — when false, an arrival is parked as +/// `reassembled + needsManualDecode` and waits +/// for a tap. Mirrors the "Process images +/// automatically" setting, which ships OFF. +/// 1. foreground only — [setForeground]; background decode is a ~2.7 GiB +/// peak and an OOM kill waiting to happen. +/// 2. strictly one at a time — and never while the codec is busy encoding for +/// the compose UI. +/// 3. burst cap — at most [burstCap] auto-decodes are queued; the +/// rest wait for a tap ([ReceivedImageEntry.needsManualDecode]). +library; + +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import '../models/image_codec_support.dart'; +import '../widgets/image_send_codec_binding.dart'; +import 'image_chunk_transport.dart'; + +// --------------------------------------------------------------------------- +// Sentinel +// --------------------------------------------------------------------------- + +/// Encodes/parses the sentinel string a `ChannelMessage.text` carries in place +/// of an image. +/// +/// Mirrors `GifHelper.encodeGif` (`lib/helpers/gif_helper.dart`): the message +/// record stays a short string, the bytes live beside it. The sentinel never +/// changes for the life of the image, so `ChannelMessage`'s `text.hashCode` +/// derived id stays stable and a per-chunk state change does not rewrite the +/// channel's whole prefs blob. +class ReceivedImageRef { + ReceivedImageRef._(); + + /// Versioned on purpose: a future wire-format change ships `aeic:2:`. + static const String scheme = 'aeic:1:'; + + static final RegExp _pattern = RegExp(r'^aeic:1:([0-9a-f]{14})$'); + + static String encode(String streamId) => '$scheme$streamId'; + + /// Returns the stream id, or null when [text] is not an image sentinel. + static String? parse(String text) => + _pattern.firstMatch(text.trim())?.group(1); + + /// `%04x%02x%08x` — 4 hex sender prefix, 2 hex img id, 8 hex epoch seconds. + /// + /// 14 lowercase hex characters, unique in practice, and it doubles as the + /// on-disk filename stem. + static String streamIdFor({ + required int senderPrefix, + required int imgId, + required DateTime firstSeen, + }) { + final seconds = firstSeen.millisecondsSinceEpoch ~/ 1000; + return (senderPrefix & 0xFFFF).toRadixString(16).padLeft(4, '0') + + (imgId & 0xFF).toRadixString(16).padLeft(2, '0') + + (seconds & 0xFFFFFFFF).toRadixString(16).padLeft(8, '0'); + } +} + +// --------------------------------------------------------------------------- +// State +// --------------------------------------------------------------------------- + +/// Lifecycle of one received image. Legal transitions are enforced by +/// [ReceivedImageStore]; see the class doc there. +enum ReceivedImageState { + /// Chunks are arriving; nothing is on disk yet. + receiving, + + /// The bitstream is complete and persisted, but not decoded. + reassembled, + + /// A decode is running right now. + decoding, + + /// A PNG exists. This is the ONLY state that shows synthesized pixels, and + /// therefore the only state that carries the R6 provenance label. + decoded, + + /// The stream expired with chunks missing. Never retryable — the partial + /// bodies only ever lived in the reassembler's memory. + failedIncomplete, + + /// The bitstream arrived whole but the decoder rejected it. User-retryable. + failedCorrupt, + + /// No usable decoder (feature off, no weights, web, or no backend). + decoderUnavailable, + + /// The PNG was reclaimed by the disk budget. Re-decodable while the + /// bitstream survives. + evicted, +} + +extension ReceivedImageStateValue on ReceivedImageState { + String get value => name; + + /// True when the UI must show the R6 synthesized-content label. + bool get showsSynthesizedPixels => this == ReceivedImageState.decoded; + + bool get isFailure => + this == ReceivedImageState.failedIncomplete || + this == ReceivedImageState.failedCorrupt; +} + +ReceivedImageState _parseState(Object? raw) { + if (raw is String) { + for (final state in ReceivedImageState.values) { + if (state.name == raw) return state; + } + } + return ReceivedImageState.failedIncomplete; +} + +/// Immutable snapshot of one image. Handed to the widget layer; every mutation +/// goes through [ReceivedImageStore]. +@immutable +class ReceivedImageEntry { + /// 14 hex chars; see [ReceivedImageRef.streamIdFor]. Also the filename stem. + final String streamId; + + final int senderPrefix; + final int imgId; + final int channelIndex; + + /// Local clock at the first chunk — code 27 carries no timestamp. + final DateTime firstSeen; + + final ReceivedImageState state; + + /// Data chunks accepted so far (parity chunks never counted). + final int receivedChunks; + + /// Data chunks the sender announced (`total` in the chunk header). + final int totalChunks; + + final AeicRatePoint rate; + final int resolution; + + /// Index into [kImageAspectCodes]: the shape the sender's photo was before + /// the codec stretched it into a square. Used to letterbox back on render. + /// Defaults to 0 (square) when the sender said nothing. + final int aspectCode; + + /// The source `width / height` to render at, or null to render square. + double? get displayAspectRatio { + final e = kImageAspectCodes[aspectCode & 0x0F]; + final r = e[0] / e[1]; + return r == 1.0 ? null : r; + } + + /// True when chunk 0's metadata byte was unknown/unavailable and [rate] and + /// [resolution] are the shipped defaults rather than the sender's word. + final bool metadataAssumed; + + /// One chunk was rebuilt from the XOR parity chunk. + final bool recoveredWithParity; + + /// This is the local user's own send. Its PNG is their real 512x512 crop, so + /// [synthesized] is false and the R6 label must NOT be shown. + final bool isOutgoing; + + /// Whether the pixels are generative-model output. Derived, never supplied: + /// `synthesized == !isOutgoing`. + bool get synthesized => !isOutgoing; + + final int? decodeMs; + final String? error; + + /// Auto-decode was skipped (burst cap); the bubble offers "Tap to decode". + final bool needsManualDecode; + + final bool bitstreamStored; + final bool pngStored; + final int bitstreamByteCount; + final int pngByteCount; + + /// Decoded PNG, cached in memory once read. Not persisted in the sidecar and + /// not part of [==]; callers must not hand these bytes onward without the R6 + /// caption (see `received_image_message.dart`). + final Uint8List? pngBytes; + + const ReceivedImageEntry({ + required this.streamId, + required this.senderPrefix, + required this.imgId, + required this.channelIndex, + required this.firstSeen, + required this.state, + required this.receivedChunks, + required this.totalChunks, + this.rate = AeicRatePoint.ft32, + this.resolution = kImageCodecSquareSize, + this.aspectCode = 0, + this.metadataAssumed = true, + this.recoveredWithParity = false, + this.isOutgoing = false, + this.decodeMs, + this.error, + this.needsManualDecode = false, + this.bitstreamStored = false, + this.pngStored = false, + this.bitstreamByteCount = 0, + this.pngByteCount = 0, + this.pngBytes, + }); + + ImageStreamKey get key => ImageStreamKey( + senderPrefix: senderPrefix, + imgId: imgId, + channelIndex: channelIndex, + ); + + /// Bytes this entry is currently costing on disk. + int get storedBytes => + (bitstreamStored ? bitstreamByteCount : 0) + + (pngStored ? pngByteCount : 0); + + /// `evicted`/`failedCorrupt` can be decoded again only while the ~156 B + /// bitstream survives. + bool get canRetryDecode => bitstreamStored; + + static const Object _unset = Object(); + + ReceivedImageEntry copyWith({ + ReceivedImageState? state, + int? receivedChunks, + int? totalChunks, + AeicRatePoint? rate, + int? resolution, + int? aspectCode, + bool? metadataAssumed, + bool? recoveredWithParity, + Object? decodeMs = _unset, + Object? error = _unset, + bool? needsManualDecode, + bool? bitstreamStored, + bool? pngStored, + int? bitstreamByteCount, + int? pngByteCount, + Object? pngBytes = _unset, + }) { + return ReceivedImageEntry( + streamId: streamId, + senderPrefix: senderPrefix, + imgId: imgId, + channelIndex: channelIndex, + firstSeen: firstSeen, + state: state ?? this.state, + receivedChunks: receivedChunks ?? this.receivedChunks, + totalChunks: totalChunks ?? this.totalChunks, + rate: rate ?? this.rate, + resolution: resolution ?? this.resolution, + aspectCode: aspectCode ?? this.aspectCode, + metadataAssumed: metadataAssumed ?? this.metadataAssumed, + recoveredWithParity: recoveredWithParity ?? this.recoveredWithParity, + isOutgoing: isOutgoing, + decodeMs: identical(decodeMs, _unset) ? this.decodeMs : decodeMs as int?, + error: identical(error, _unset) ? this.error : error as String?, + needsManualDecode: needsManualDecode ?? this.needsManualDecode, + bitstreamStored: bitstreamStored ?? this.bitstreamStored, + pngStored: pngStored ?? this.pngStored, + bitstreamByteCount: bitstreamByteCount ?? this.bitstreamByteCount, + pngByteCount: pngByteCount ?? this.pngByteCount, + pngBytes: identical(pngBytes, _unset) + ? this.pngBytes + : pngBytes as Uint8List?, + ); + } + + Map toJson() => { + 'streamId': streamId, + 'senderPrefix': senderPrefix, + 'imgId': imgId, + 'channelIndex': channelIndex, + 'firstSeenMs': firstSeen.millisecondsSinceEpoch, + 'state': state.name, + 'receivedChunks': receivedChunks, + 'totalChunks': totalChunks, + 'rate': rate.wireValue, + 'resolution': resolution, + 'aspect_code': aspectCode, + 'metadataAssumed': metadataAssumed, + 'recoveredWithParity': recoveredWithParity, + 'isOutgoing': isOutgoing, + 'synthesized': synthesized, + 'needsManualDecode': needsManualDecode, + 'bitstreamStored': bitstreamStored, + 'pngStored': pngStored, + 'bitstreamByteCount': bitstreamByteCount, + 'pngByteCount': pngByteCount, + if (decodeMs != null) 'decodeMs': decodeMs, + if (error != null) 'error': error, + }; + + factory ReceivedImageEntry.fromJson(Map json) { + return ReceivedImageEntry( + streamId: json['streamId'] as String? ?? '', + senderPrefix: json['senderPrefix'] as int? ?? 0, + imgId: json['imgId'] as int? ?? 0, + channelIndex: json['channelIndex'] as int? ?? 0, + firstSeen: DateTime.fromMillisecondsSinceEpoch( + json['firstSeenMs'] as int? ?? 0, + ), + state: _parseState(json['state']), + receivedChunks: json['receivedChunks'] as int? ?? 0, + totalChunks: json['totalChunks'] as int? ?? 1, + rate: parseAeicRatePoint(json['rate'] as int? ?? 4), + resolution: json['resolution'] as int? ?? kImageCodecSquareSize, + aspectCode: json['aspect_code'] as int? ?? 0, + metadataAssumed: json['metadataAssumed'] as bool? ?? true, + recoveredWithParity: json['recoveredWithParity'] as bool? ?? false, + isOutgoing: json['isOutgoing'] as bool? ?? false, + decodeMs: json['decodeMs'] as int?, + error: json['error'] as String?, + needsManualDecode: json['needsManualDecode'] as bool? ?? false, + bitstreamStored: json['bitstreamStored'] as bool? ?? false, + pngStored: json['pngStored'] as bool? ?? false, + bitstreamByteCount: json['bitstreamByteCount'] as int? ?? 0, + pngByteCount: json['pngByteCount'] as int? ?? 0, + ); + } + + @override + String toString() => + 'ReceivedImageEntry($streamId, ${state.name}, ' + '$receivedChunks/$totalChunks, ${rate.name})'; +} + +// --------------------------------------------------------------------------- +// Byte persistence seam +// --------------------------------------------------------------------------- + +/// Where the three files of an image live. One implementation per platform. +/// +/// Layout the file-backed implementation uses (application *support* dir, not +/// documents — these are derived caches, not user files): +/// `received_images/.aeic|.png|.json`. See +/// `received_image_blob_store_io.dart`. +abstract class ReceivedImageBlobStore { + Future writeBitstream(String streamId, Uint8List bytes); + Future readBitstream(String streamId); + Future deleteBitstream(String streamId); + + Future writePng(String streamId, Uint8List bytes); + Future readPng(String streamId); + Future deletePng(String streamId); + + /// Byte length of the stored bitstream, or null when there is none. + /// + /// Concrete on purpose: [load] only needs to know whether the bytes exist and + /// how big they are, and the default below would read every 400 KB PNG on the + /// device into memory at startup (200 images => ~80 MB of pointless I/O) just + /// to call `.length` on it. A file-backed store overrides both with `stat`. + Future bitstreamSize(String streamId) async => + (await readBitstream(streamId))?.length; + + /// Byte length of the stored PNG, or null when there is none. + Future pngSize(String streamId) async => + (await readPng(streamId))?.length; + + /// Sidecar write must be atomic (tmp + rename) so a kill cannot leave a + /// half-written record that `readSidecars` then discards. + Future writeSidecar(String streamId, String json); + Future deleteSidecar(String streamId); + + /// streamId -> raw sidecar JSON, for the startup scan. + Future> readSidecars(); + + /// Absolute path of the PNG, or null where the platform has no file system. + String? pngPath(String streamId); +} + +/// Default implementation: keeps everything in RAM. +/// +/// Used by tests, by web (where there is no decoder either, so nothing ever +/// reaches [ReceivedImageState.decoded]) and as the fallback until the +/// file-backed store is wired in. +class InMemoryReceivedImageBlobStore implements ReceivedImageBlobStore { + final Map _bitstreams = {}; + final Map _pngs = {}; + final Map _sidecars = {}; + + @override + Future writeBitstream(String streamId, Uint8List bytes) async { + _bitstreams[streamId] = bytes; + } + + @override + Future readBitstream(String streamId) async => + _bitstreams[streamId]; + + @override + Future deleteBitstream(String streamId) async { + _bitstreams.remove(streamId); + } + + @override + Future bitstreamSize(String streamId) async => + _bitstreams[streamId]?.length; + + @override + Future pngSize(String streamId) async => _pngs[streamId]?.length; + + @override + Future writePng(String streamId, Uint8List bytes) async { + _pngs[streamId] = bytes; + } + + @override + Future readPng(String streamId) async => _pngs[streamId]; + + @override + Future deletePng(String streamId) async { + _pngs.remove(streamId); + } + + @override + Future writeSidecar(String streamId, String json) async { + _sidecars[streamId] = json; + } + + @override + Future deleteSidecar(String streamId) async { + _sidecars.remove(streamId); + } + + @override + Future> readSidecars() async => + Map.from(_sidecars); + + @override + String? pngPath(String streamId) => null; + + // Test/debug helpers. + bool hasBitstream(String streamId) => _bitstreams.containsKey(streamId); + bool hasPng(String streamId) => _pngs.containsKey(streamId); + bool hasSidecar(String streamId) => _sidecars.containsKey(streamId); +} + +// --------------------------------------------------------------------------- +// Decoder seam +// --------------------------------------------------------------------------- + +/// The slice of `ImageCodecService` the receive path needs. +/// +/// `ImageCodecService` satisfies this shape member-for-member, so the adapter +/// the wiring agent writes is pure delegation: +/// +/// ```dart +/// class ImageCodecServiceDecoder implements ReceivedImageDecoder { +/// final ImageCodecService service; +/// const ImageCodecServiceDecoder(this.service); +/// @override ImageCodecAvailability get availability => service.availability; +/// @override bool get isBusy => service.isBusy; +/// @override Future decodeBitstream({ +/// required Uint8List bitstream, +/// required AeicRatePoint ratePoint, +/// required int resolution, +/// }) => service.decodeBitstream( +/// bitstream: bitstream, ratePoint: ratePoint, resolution: resolution); +/// @override void cancelCodecJob() => service.cancelCodecJob(); +/// } +/// ``` +/// +/// The interface also exists so the store can be tested without a 872 MB ONNX +/// graph. +abstract class ReceivedImageDecoder { + ImageCodecAvailability get availability; + + /// True while an encode (compose UI) or another decode is running. + bool get isBusy; + + /// Returns null when the codec cannot decode at all; a result with + /// `status == failed` when the bitstream was rejected. + Future decodeBitstream({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + }); + + /// Cooperative cancel, used when we background mid-decode. + void cancelCodecJob(); +} + +// --------------------------------------------------------------------------- +// The store +// --------------------------------------------------------------------------- + +/// Owns every received image: its state, its bytes, its place in the decode +/// queue and its share of the disk budget. +/// +/// Legal transitions (nothing else is performed): +/// ``` +/// (none) -> receiving first non-duplicate chunk +/// receiving -> receiving another data chunk +/// receiving -> reassembled completed; bitstream written FIRST +/// receiving -> failedIncomplete TTL/overflow eviction +/// reassembled -> decoding dequeued +/// reassembled -> decoderUnavailable no usable decoder at dequeue +/// decoding -> decoded completed && pngBytes != null +/// decoding -> failedCorrupt failed / throw / bad resolution +/// decoding -> decoderUnavailable decodeBitstream returned null +/// decoding -> reassembled cancelled (background / pressure) +/// decoderUnavailable -> decoding retry, or availability recovered +/// failedCorrupt -> decoding explicit user retry only +/// decoded -> evicted budget reclaimed the PNG +/// evicted -> decoding "Decode again", bitstream survives +/// ``` +/// `failedIncomplete` is terminal: the partial bodies are gone. +class ReceivedImageStore extends ChangeNotifier { + final ReceivedImageBlobStore blobs; + ReceivedImageDecoder? decoder; + + /// Hard cap on stored PNGs. + final int maxImages; + + /// Hard cap on total bytes across all stored files. + final int maxBytes; + + /// Images older than this are dropped from disk entirely. + final Duration maxAge; + + /// How many auto-decodes may be queued before the rest need a tap. + final int burstCap; + + /// When false, a completed bitstream is parked as + /// `reassembled + needsManualDecode` and waits for a tap. Mirrors the + /// "Process images automatically" app setting. + /// + /// Defaults to TRUE at the store level on purpose: that is this class's + /// documented eager contract and what its unit tests assert. Production is + /// off-by-default because `main.dart` passes the (false-by-default) setting + /// explicitly and re-assigns this field whenever the setting changes. + /// + /// Assignment affects FUTURE arrivals only. It deliberately does not kick the + /// queue and does not backfill: turning the setting on must not retro-decode + /// a backlog, which would be an unbounded burst of ~2.16 GiB jobs. + bool processAutomatically; + + final DateTime Function() _clock; + + final Map _entries = + {}; + final Map _byKey = {}; + final Map> _listenables = + >{}; + + final List _queue = []; + Future? _pump; + + /// Set synchronously for as long as [_drain]'s body is running. A plain + /// `_pump != null` check is NOT enough: the future stays non-null for one + /// extra microtask after the body has finished, and a chunk arriving in that + /// window used to be dropped on the floor with the queue non-empty and + /// nothing running. + bool _draining = false; + + /// True when the queue stopped because the codec was busy encoding. Cleared + /// by anything that could plausibly have freed it. + bool _parkedOnBusyDecoder = false; + + /// Set by [handleMemoryPressure] so the decode it cancels is parked rather + /// than reported as corrupt. + bool _cancelRequested = false; + bool _foreground = true; + bool _disposed = false; + + ReceivedImageStore({ + ReceivedImageBlobStore? blobs, + this.decoder, + this.maxImages = 200, + this.maxBytes = 64 * 1024 * 1024, + this.maxAge = const Duration(days: 30), + this.burstCap = 3, + this.processAutomatically = true, + DateTime Function()? clock, + }) : blobs = blobs ?? InMemoryReceivedImageBlobStore(), + _clock = clock ?? DateTime.now; + + // ---- reads --------------------------------------------------------------- + + /// Newest first. + List get entries { + final list = _entries.values.toList() + ..sort((a, b) => b.firstSeen.compareTo(a.firstSeen)); + return List.unmodifiable(list); + } + + ReceivedImageEntry? entryFor(String streamId) => _entries[streamId]; + + ReceivedImageEntry? entryForKey(ImageStreamKey key) { + final id = _byKey[key]; + return id == null ? null : _entries[id]; + } + + /// Per-image listenable so one arriving chunk rebuilds one bubble instead of + /// the whole reversed `ListView`. + ValueListenable listenableFor(String streamId) { + return _listenables.putIfAbsent( + streamId, + () => ValueNotifier(_entries[streamId]), + ); + } + + /// Bytes currently held on disk by all entries. + int get totalBytes => + _entries.values.fold(0, (sum, e) => sum + e.storedBytes); + + int get storedImageCount => _entries.values.where((e) => e.pngStored).length; + + /// Stream ids waiting for an automatic decode, oldest request first. + List get decodeQueue => List.unmodifiable(_queue); + + bool get isForeground => _foreground; + + /// Availability of the decoder seam, or `unavailable` when none is wired. + /// + /// Read-only passthrough so a bubble can pick its tap action (decode now vs. + /// send the user to the model download) without importing + /// `ImageCodecService`. + ImageCodecAvailability get decoderAvailability => + decoder?.availability ?? ImageCodecAvailability.unavailable; + + /// True while a decode is running or queued. Callers that want to grey out a + /// "Tap to process" affordance can use it; decodes are strictly serial, so a + /// second tap only lengthens the wall clock, never the peak RSS. + bool get isDecoding => _draining || _queue.isNotEmpty; + + // ---- startup ------------------------------------------------------------- + + /// Loads sidecars and repairs states that cannot survive a process death. + /// + /// receiving -> failedIncomplete (partials were never persisted) + /// decoding -> reassembled if the bitstream is there, else failedIncomplete + /// decoded -> evicted if the PNG is gone + Future load() async { + final sidecars = await blobs.readSidecars(); + for (final raw in sidecars.values) { + Map json; + try { + final decoded = jsonDecode(raw); + if (decoded is! Map) continue; + json = decoded; + } catch (_) { + continue; + } + var entry = ReceivedImageEntry.fromJson(json); + if (entry.streamId.isEmpty) continue; + + // Sizes, not bytes: reattaching 200 images must not read ~80 MB of PNG + // into RAM on the startup path. The pixels are read lazily by + // [ensurePng] when a bubble actually scrolls into view. + final bitstreamBytes = await blobs.bitstreamSize(entry.streamId); + final pngBytes = await blobs.pngSize(entry.streamId); + entry = entry.copyWith( + bitstreamStored: bitstreamBytes != null, + bitstreamByteCount: bitstreamBytes ?? 0, + pngStored: pngBytes != null, + pngByteCount: pngBytes ?? entry.pngByteCount, + ); + + switch (entry.state) { + case ReceivedImageState.receiving: + entry = entry.copyWith(state: ReceivedImageState.failedIncomplete); + case ReceivedImageState.decoding: + entry = entry.copyWith( + state: entry.bitstreamStored + ? ReceivedImageState.reassembled + : ReceivedImageState.failedIncomplete, + ); + case ReceivedImageState.decoded: + if (!entry.pngStored) { + entry = entry.copyWith(state: ReceivedImageState.evicted); + } + case ReceivedImageState.reassembled: + if (!entry.bitstreamStored) { + entry = entry.copyWith(state: ReceivedImageState.failedIncomplete); + } else if (!processAutomatically) { + // load() never enqueues, so a `reassembled` entry restored with + // needsManualDecode == false (written by a session that had the + // setting on, or by an older build) would sit on "Waiting to + // decode" forever with no tap target. Give it one. + entry = entry.copyWith(needsManualDecode: true); + } + case ReceivedImageState.evicted: + case ReceivedImageState.failedIncomplete: + case ReceivedImageState.failedCorrupt: + case ReceivedImageState.decoderUnavailable: + break; + } + + _entries[entry.streamId] = entry; + _byKey[entry.key] = entry.streamId; + _publish(entry); + await _persist(entry); + } + await evictToBudget(); + _notify(); + } + + // ---- intake -------------------------------------------------------------- + + /// Feeds one [ImageReassembler] outcome. + /// + /// The caller owns the reassembler (the send path already builds one) and is + /// responsible for having dropped nothing: `malformed` and `fromSelf` are + /// ignored here too, so an unfiltered firehose is safe. + Future handleOutcome( + ImageChunkOutcome outcome, { + required int channelIndex, + DateTime? at, + }) async { + final now = at ?? _clock(); + switch (outcome.status) { + case ImageChunkStatus.malformed: + case ImageChunkStatus.fromSelf: + return null; + + case ImageChunkStatus.duplicate: + final header = outcome.header; + if (header == null) return null; + return entryForKey( + ImageStreamKey( + senderPrefix: header.senderPrefix, + imgId: header.imgId, + channelIndex: channelIndex, + ), + ); + + case ImageChunkStatus.accepted: + case ImageChunkStatus.conflicting: + final header = outcome.header; + if (header == null) return null; + final key = ImageStreamKey( + senderPrefix: header.senderPrefix, + imgId: header.imgId, + channelIndex: channelIndex, + ); + final counts = header.isParity ? 0 : 1; + final existing = entryForKey(key); + + // `conflicting` means the reassembler threw the old stream away and + // restarted from this chunk. A stream that had already been surfaced + // keeps its id (and therefore its message) only if it was still + // receiving; anything else gets a fresh entry. The same goes for a + // plain `accepted`: once an entry is past `receiving` the reassembler + // reports its stragglers as `duplicate`, so an accepted chunk on that + // key is a new image reusing the 8-bit id and must not overwrite it. + final resets = outcome.status == ImageChunkStatus.conflicting; + if (existing != null && + existing.state == ReceivedImageState.receiving) { + final updated = existing.copyWith( + state: ReceivedImageState.receiving, + receivedChunks: resets + ? counts + : (existing.receivedChunks + counts) + .clamp(0, header.total) + .toInt(), + totalChunks: header.total, + error: null, + ); + return _store(updated); + } + if (existing != null) { + _byKey.remove(key); + } + final streamId = _uniqueStreamId( + senderPrefix: header.senderPrefix, + imgId: header.imgId, + firstSeen: now, + ); + final created = ReceivedImageEntry( + streamId: streamId, + senderPrefix: header.senderPrefix, + imgId: header.imgId, + channelIndex: channelIndex, + firstSeen: now, + state: ReceivedImageState.receiving, + receivedChunks: counts, + totalChunks: header.total, + ); + return _store(created); + + case ImageChunkStatus.unsupportedFormat: + // Every chunk arrived but chunk 0 names a rate point or resolution this + // build cannot decode. The transport has already DISCARDED the bytes, + // and there is nothing to retry, so no bitstream is stored. + final header = outcome.header; + if (header == null) return null; + final entry = entryForKey( + ImageStreamKey( + senderPrefix: header.senderPrefix, + imgId: header.imgId, + channelIndex: channelIndex, + ), + ); + if (entry == null || entry.state != ReceivedImageState.receiving) { + return null; + } + _queue.remove(entry.streamId); + return _store( + entry.copyWith( + state: ReceivedImageState.failedCorrupt, + bitstreamStored: false, + error: 'Unsupported image format.', + ), + ); + + case ImageChunkStatus.completed: + final result = outcome.result; + if (result == null) return null; + return _handleCompleted(result, now); + } + } + + Future _handleCompleted( + ImageReassemblyResult result, + DateTime now, + ) async { + final key = result.key; + var entry = entryForKey(key); + // A one-chunk image completes without an `accepted` first, so the key may + // still point at an older, finished image that reused the id. + if (entry == null || entry.state != ReceivedImageState.receiving) { + final streamId = _uniqueStreamId( + senderPrefix: key.senderPrefix, + imgId: key.imgId, + firstSeen: now, + ); + entry = ReceivedImageEntry( + streamId: streamId, + senderPrefix: key.senderPrefix, + imgId: key.imgId, + channelIndex: key.channelIndex, + firstSeen: now, + state: ReceivedImageState.receiving, + receivedChunks: result.chunkCount, + totalChunks: result.chunkCount, + ); + } + + final metadata = result.metadata; + // Bitstream first, state second: a kill between the two must be + // recoverable, and `reassembled` with no file on disk is a lie. + await blobs.writeBitstream(entry.streamId, result.data); + + final updated = entry.copyWith( + state: ReceivedImageState.reassembled, + receivedChunks: result.chunkCount, + totalChunks: result.chunkCount, + rate: metadata == null + ? AeicRatePoint.ft32 + : aeicRatePointForUi(metadata.rate), + aspectCode: metadata?.aspectCode ?? 0, + resolution: metadata?.squareSize ?? kImageCodecSquareSize, + metadataAssumed: metadata == null, + recoveredWithParity: result.recoveredWithParity, + bitstreamStored: true, + bitstreamByteCount: result.data.length, + error: null, + ); + if (!processAutomatically) { + // Park it: the card shows "N bytes · M packets" and "Tap to process". + // A 2.16 GiB decode is never started off the back of a radio packet + // unless the user asked for that. + return _store(updated.copyWith(needsManualDecode: true)); + } + final stored = await _store(updated); + _enqueue(stored.streamId); + return stored; + } + + /// A stream the reassembler gave up on (TTL or concurrency overflow). + Future handleFailure( + ImageReassemblyFailure failure, + ) async { + final entry = entryForKey(failure.key); + if (entry == null) return null; + if (entry.state != ReceivedImageState.receiving) { + // Already completed by a later chunk; the failure is stale. + return entry; + } + final failed = await _store( + entry.copyWith( + // `isCorrupt` means every chunk arrived but the bytes were unusable + // (CRC-16 mismatch or an undecodable metadata byte). The UI must say + // "corrupt", not "incomplete". + state: failure.isCorrupt + ? ReceivedImageState.failedCorrupt + : ReceivedImageState.failedIncomplete, + receivedChunks: failure.receivedDataChunks, + totalChunks: failure.total, + error: failure.isCorrupt ? failure.reason.name : null, + ), + ); + await evictToBudget(protect: failed.streamId); + return failed; + } + + /// Records the local user's own send so the outgoing bubble can show the real + /// 512x512 crop. [previewPng] is a photograph, not a decode, so the entry is + /// never [ReceivedImageEntry.synthesized] and carries no R6 label. + /// + /// The send path must call this BEFORE it posts the message, and put the + /// returned id in the message text — that sentinel is the only link between + /// the `ChannelMessage` and these pixels: + /// + /// ```dart + /// final entry = await receivedImageStore.registerOutgoing( + /// channelIndex: channelIndex, + /// senderPrefix: selfPrefix, // same 16 bits the chunk header carries + /// imgId: chunkSet.imgId, + /// previewPng: preview.croppedPngBytes, // the 512x512 crop, NOT a decode + /// rate: kImageSendRatePoint, + /// chunkCount: chunkSet.dataChunkCount, + /// ); + /// await connector.sendChannelMessage( + /// channelIndex, ReceivedImageRef.encode(entry.streamId)); + /// ``` + /// + /// Nothing is ever decoded for an outgoing entry: it lands in `decoded` + /// directly and never enters the queue, so sending an image costs no model + /// memory beyond the encode that already ran. + Future registerOutgoing({ + required int channelIndex, + required int senderPrefix, + required int imgId, + required Uint8List previewPng, + required AeicRatePoint rate, + required int chunkCount, + DateTime? at, + }) async { + final now = at ?? _clock(); + final streamId = _uniqueStreamId( + senderPrefix: senderPrefix, + imgId: imgId, + firstSeen: now, + ); + await blobs.writePng(streamId, previewPng); + final entry = ReceivedImageEntry( + streamId: streamId, + senderPrefix: senderPrefix, + imgId: imgId, + channelIndex: channelIndex, + firstSeen: now, + state: ReceivedImageState.decoded, + receivedChunks: chunkCount, + totalChunks: chunkCount, + rate: rate, + metadataAssumed: false, + isOutgoing: true, + pngStored: true, + pngByteCount: previewPng.length, + pngBytes: previewPng, + ); + final stored = await _store(entry); + await evictToBudget(protect: stored.streamId); + return stored; + } + + // ---- decode scheduling --------------------------------------------------- + + /// App lifecycle gate. Backgrounding cancels an in-flight decode and returns + /// the entry to `reassembled` — never to a failure state. + void setForeground(bool value) { + if (_foreground == value) return; + _foreground = value; + if (!value) { + decoder?.cancelCodecJob(); + } else { + _parkedOnBusyDecoder = false; + _kick(); + } + _notify(); + } + + /// Call when the codec's availability or busy flag changes: a queue parked on + /// a busy encoder resumes, and images that were parked as + /// `decoderUnavailable` get another go now that a decoder exists. + void notifyDecoderChanged() { + _parkedOnBusyDecoder = false; + final decoder = this.decoder; + if (decoder != null && + decoder.availability == ImageCodecAvailability.ready) { + for (final entry in _entries.values.toList()) { + if (entry.state != ReceivedImageState.decoderUnavailable) continue; + if (!entry.bitstreamStored) continue; + _storeSync( + entry.copyWith( + state: ReceivedImageState.reassembled, + needsManualDecode: !processAutomatically, + ), + ); + // Without this guard, finishing an 835 MB download would immediately + // fire one decode per image received while the model was missing — + // exactly what the setting exists to prevent. + if (processAutomatically) _queue.add(entry.streamId); + } + } + _kick(); + } + + /// Cancels the running decode and stops the queue; the entry goes back to + /// `reassembled` and will be picked up again later. + Future handleMemoryPressure() async { + _cancelRequested = true; + decoder?.cancelCodecJob(); + _queue.clear(); + for (final entry in _entries.values.toList()) { + if (entry.state == ReceivedImageState.reassembled && + !entry.needsManualDecode) { + await _store(entry.copyWith(needsManualDecode: true)); + } + } + } + + /// User tapped "Decode" / "Try again" / "Decode again". + Future requestDecode(String streamId) async { + final entry = _entries[streamId]; + if (entry == null) return; + switch (entry.state) { + case ReceivedImageState.reassembled: + case ReceivedImageState.failedCorrupt: + case ReceivedImageState.decoderUnavailable: + case ReceivedImageState.evicted: + break; + case ReceivedImageState.receiving: + case ReceivedImageState.decoding: + case ReceivedImageState.decoded: + case ReceivedImageState.failedIncomplete: + return; + } + if (!entry.bitstreamStored) return; + await _store( + entry.copyWith( + state: ReceivedImageState.reassembled, + needsManualDecode: false, + error: null, + ), + ); + _parkedOnBusyDecoder = false; + _enqueue(streamId, force: true); + await settle(); + } + + /// Completes when the decode queue has stopped making progress. Test hook; + /// production code never needs to await it. + Future settle() async { + var guard = 0; + while (guard++ < 1000) { + final pump = _pump; + if (pump != null) { + await pump; + continue; + } + if (_disposed || + _queue.isEmpty || + _draining || + _parkedOnBusyDecoder || + !_foreground) { + return; + } + _kick(); + if (_pump == null) return; + } + } + + void _enqueue(String streamId, {bool force = false}) { + if (_queue.contains(streamId)) return; + // A new arrival is worth one more look at a codec that was busy. + _parkedOnBusyDecoder = false; + _queue.add(streamId); + if (!force) { + // Burst cap: keep the newest `burstCap` requests, park the rest behind a + // tap so a repeater storm cannot spend minutes of CPU. + while (_queue.length > burstCap) { + final dropped = _queue.removeAt(0); + final entry = _entries[dropped]; + if (entry != null && entry.state == ReceivedImageState.reassembled) { + _storeSync(entry.copyWith(needsManualDecode: true)); + } + } + } + _kick(); + } + + void _kick() { + if (_disposed) return; + if (_queue.isEmpty) return; + if (_draining) return; + if (_parkedOnBusyDecoder) return; + _draining = true; + _pump = _drain().whenComplete(() { + _pump = null; + }); + } + + Future _drain() async { + try { + while (_queue.isNotEmpty && _foreground && !_disposed) { + final decoder = this.decoder; + final streamId = _queue.first; + final entry = _entries[streamId]; + if (entry == null || entry.state != ReceivedImageState.reassembled) { + _queue.removeAt(0); + continue; + } + if (decoder == null || + decoder.availability != ImageCodecAvailability.ready) { + _queue.removeAt(0); + await _store( + entry.copyWith(state: ReceivedImageState.decoderUnavailable), + ); + continue; + } + if (decoder.isBusy) { + // The compose UI is encoding. Leave the queue intact; the next + // notifyDecoderChanged()/chunk resumes it. + _parkedOnBusyDecoder = true; + return; + } + _queue.removeAt(0); + await _decodeOne(entry, decoder); + } + } finally { + // Synchronous with the end of the body, unlike the future's completion. + _draining = false; + } + } + + /// Belt to [_draining]'s braces. A decode peaks around 2.16 GiB, so two at + /// once is not a slow app, it is an OOM kill. If this ever trips, the queue + /// invariant is broken somewhere and the right answer is still to run one. + bool _decodeInFlight = false; + + Future _decodeOne( + ReceivedImageEntry entry, + ReceivedImageDecoder decoder, + ) async { + if (_decodeInFlight) { + assert(false, 'ReceivedImageStore: concurrent decode attempted'); + debugPrint('received_image_store: refusing a concurrent decode'); + _queue.remove(entry.streamId); + return; + } + _decodeInFlight = true; + try { + await _decodeOneExclusive(entry, decoder); + } finally { + _decodeInFlight = false; + } + } + + Future _decodeOneExclusive( + ReceivedImageEntry entry, + ReceivedImageDecoder decoder, + ) async { + final bitstream = await blobs.readBitstream(entry.streamId); + if (bitstream == null || bitstream.isEmpty) { + await _store( + entry.copyWith( + state: ReceivedImageState.failedCorrupt, + bitstreamStored: false, + error: 'Bitstream missing.', + ), + ); + return; + } + final started = _clock(); + _cancelRequested = false; + await _store(entry.copyWith(state: ReceivedImageState.decoding)); + + ImageCodecResult? result; + try { + result = await decoder.decodeBitstream( + bitstream: bitstream, + ratePoint: entry.rate, + resolution: entry.resolution, + ); + } catch (error) { + final current = _entries[entry.streamId] ?? entry; + if (_cancelRequested) { + await _store( + current.copyWith( + state: ReceivedImageState.reassembled, + needsManualDecode: true, + ), + ); + } else if (!_foreground) { + await _store(current.copyWith(state: ReceivedImageState.reassembled)); + } else { + await _store( + current.copyWith( + state: ReceivedImageState.failedCorrupt, + error: error.toString(), + ), + ); + } + return; + } + + final current = _entries[entry.streamId] ?? entry; + if (result == null) { + // canDecode false — the codec cannot run at all. + await _store( + current.copyWith(state: ReceivedImageState.decoderUnavailable), + ); + return; + } + final png = result.pngBytes; + if (result.status != ImageCodecStatus.completed || png == null) { + if (_cancelRequested) { + // The codec reports a killed job as `failed`; the bitstream is fine. + await _store( + current.copyWith( + state: ReceivedImageState.reassembled, + needsManualDecode: true, + ), + ); + return; + } + await _store( + current.copyWith( + state: ReceivedImageState.failedCorrupt, + error: 'Decoder rejected the bitstream.', + ), + ); + return; + } + if (!_foreground) { + // Backgrounded mid-decode: keep the pixels, but do not claim a decode we + // may have half-cancelled. + await _store(current.copyWith(state: ReceivedImageState.reassembled)); + return; + } + + await blobs.writePng(current.streamId, png); + await _store( + current.copyWith( + state: ReceivedImageState.decoded, + pngStored: true, + pngByteCount: png.length, + pngBytes: png, + decodeMs: result.durationMs > 0 + ? result.durationMs + : _clock().difference(started).inMilliseconds, + needsManualDecode: false, + error: null, + ), + ); + // Without `protect` the freshly decoded image is the budget's own victim + // whenever it is also the oldest: decode -> evict -> "Decode again" -> + // evict, forever. + await evictToBudget(protect: current.streamId); + } + + // ---- pixels -------------------------------------------------------------- + + /// Reads (and caches) the decoded PNG for a `decoded` entry. Returns null for + /// every other state, so a failed or corrupt image can never present as + /// decoded pixels. + Future ensurePng(String streamId) async { + final entry = _entries[streamId]; + if (entry == null) return null; + if (entry.state != ReceivedImageState.decoded) return null; + final cached = entry.pngBytes; + if (cached != null) return cached; + if (!entry.pngStored) return null; + final bytes = await blobs.readPng(streamId); + if (bytes == null) { + await _store( + entry.copyWith(state: ReceivedImageState.evicted, pngStored: false), + ); + return null; + } + await _store(entry.copyWith(pngBytes: bytes, pngByteCount: bytes.length)); + return bytes; + } + + /// Absolute PNG path, for a share/save action. Null on platforms with no file + /// system, and null unless the entry is decoded. + String? pngPath(String streamId) { + final entry = _entries[streamId]; + if (entry == null || entry.state != ReceivedImageState.decoded) return null; + return blobs.pngPath(streamId); + } + + // ---- deletion and eviction ---------------------------------------------- + + /// Removes an image and all three of its files. Called when the user deletes + /// the message (or clears the conversation), otherwise ~400 KB is orphaned + /// forever. + Future deleteImage(String streamId) async { + final entry = _entries.remove(streamId); + _queue.remove(streamId); + if (entry != null) { + _byKey.remove(entry.key); + } + await blobs.deletePng(streamId); + await blobs.deleteBitstream(streamId); + await blobs.deleteSidecar(streamId); + final listenable = _listenables[streamId]; + if (listenable != null) { + listenable.value = null; + } + _notify(); + } + + /// Deletes every image of one channel. Call this when the conversation is + /// cleared or the channel removed, otherwise each image leaks ~400 KB until + /// the 30-day age budget finally reaps it. + /// + /// Returns the stream ids that were removed, so the caller can strip their + /// sentinels from the channel's message list in one pass. + Future> deleteImagesForChannel(int channelIndex) async { + final doomed = _entries.values + .where((e) => e.channelIndex == channelIndex) + .map((e) => e.streamId) + .toList(); + for (final streamId in doomed) { + await deleteImage(streamId); + } + return doomed; + } + + /// Deletes an image for each sentinel that is still present in a channel's + /// message list, and drops everything else this store holds for that channel. + /// + /// Convenience for the single-message delete path: the caller has a + /// `ChannelMessage.text`, not a stream id. + Future deleteImageForSentinel(String text) async { + final streamId = ReceivedImageRef.parse(text); + if (streamId == null) return; + await deleteImage(streamId); + } + + /// Brings the store back inside [maxImages] / [maxBytes] / [maxAge]. + /// + /// Order matters: PNGs (~400 KB) go before bitstreams (~156 B), and oldest + /// `firstSeen` first. An evicted entry keeps its message and its + /// `evicted` state so the bubble can offer "Decode again". + Future> evictToBudget({String? protect}) async { + final evicted = []; + final now = _clock(); + + // 1. Age budget: nothing survives, not even the bitstream. A failed image + // has no bubble worth keeping, so it goes entirely, sidecar included. + for (final entry in _entries.values.toList()) { + if (now.difference(entry.firstSeen) <= maxAge) continue; + if (entry.state.isFailure) { + await deleteImage(entry.streamId); + evicted.add(entry.streamId); + continue; + } + if (!entry.pngStored && !entry.bitstreamStored) continue; + await blobs.deletePng(entry.streamId); + await blobs.deleteBitstream(entry.streamId); + await _store( + entry.copyWith( + state: ReceivedImageState.evicted, + pngStored: false, + bitstreamStored: false, + pngBytes: null, + ), + ); + _queue.remove(entry.streamId); + evicted.add(entry.streamId); + } + + // 2. Size/count budget. + var guard = 0; + while ((storedImageCount > maxImages || totalBytes > maxBytes) && + guard++ < 10000) { + final pngHolders = + _entries.values + .where((e) => e.pngStored && e.streamId != protect) + .toList() + ..sort((a, b) => a.firstSeen.compareTo(b.firstSeen)); + if (pngHolders.isNotEmpty) { + final victim = pngHolders.first; + await blobs.deletePng(victim.streamId); + await _store( + victim.copyWith( + state: victim.state == ReceivedImageState.decoded + ? ReceivedImageState.evicted + : victim.state, + pngStored: false, + pngBytes: null, + ), + ); + evicted.add(victim.streamId); + continue; + } + // Only bitstreams of already-evicted entries may go; a `reassembled` + // entry still needs its bytes to decode. + final bitstreamHolders = + _entries.values + .where( + (e) => + e.bitstreamStored && + (e.state == ReceivedImageState.evicted || + e.state == ReceivedImageState.failedCorrupt), + ) + .toList() + ..sort((a, b) => a.firstSeen.compareTo(b.firstSeen)); + if (bitstreamHolders.isEmpty) break; + final victim = bitstreamHolders.first; + await blobs.deleteBitstream(victim.streamId); + await _store( + victim.copyWith( + state: ReceivedImageState.evicted, + bitstreamStored: false, + ), + ); + evicted.add(victim.streamId); + } + + // 3. Failed entries hold no PNG, so the loop above never counts them; cap + // them by entry count, oldest first, or a noisy mesh grows the sidecars + // (and the startup load) without bound. + if (_entries.length > maxImages) { + final failures = + _entries.values + .where((e) => e.state.isFailure && e.streamId != protect) + .toList() + ..sort((a, b) => a.firstSeen.compareTo(b.firstSeen)); + for (final victim in failures) { + if (_entries.length <= maxImages) break; + await deleteImage(victim.streamId); + evicted.add(victim.streamId); + } + } + + if (evicted.isNotEmpty) _notify(); + return evicted; + } + + // ---- plumbing ------------------------------------------------------------ + + String _uniqueStreamId({ + required int senderPrefix, + required int imgId, + required DateTime firstSeen, + }) { + // Second-resolution ids collide when the same sender reuses an img_id + // inside one second (id wrap, or a restart re-rolling the allocator seed). + var at = firstSeen; + var id = ReceivedImageRef.streamIdFor( + senderPrefix: senderPrefix, + imgId: imgId, + firstSeen: at, + ); + var bump = 0; + while (_entries.containsKey(id) && bump++ < 64) { + at = at.add(const Duration(seconds: 1)); + id = ReceivedImageRef.streamIdFor( + senderPrefix: senderPrefix, + imgId: imgId, + firstSeen: at, + ); + } + return id; + } + + Future _store(ReceivedImageEntry entry) async { + _storeSync(entry); + await _persist(entry); + return entry; + } + + void _storeSync(ReceivedImageEntry entry) { + _entries[entry.streamId] = entry; + _byKey[entry.key] = entry.streamId; + _publish(entry); + _notify(); + } + + Future _persist(ReceivedImageEntry entry) async { + try { + await blobs.writeSidecar(entry.streamId, jsonEncode(entry.toJson())); + } catch (error) { + debugPrint('received_image_store: sidecar write failed: $error'); + } + } + + void _publish(ReceivedImageEntry entry) { + final listenable = _listenables[entry.streamId]; + if (listenable != null) { + listenable.value = entry; + } + } + + void _notify() { + if (_disposed) return; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _queue.clear(); + for (final listenable in _listenables.values) { + listenable.dispose(); + } + _listenables.clear(); + super.dispose(); + } +} diff --git a/lib/services/repeater_command_service.dart b/lib/services/repeater_command_service.dart index 61d22c8e..e3d6e8b3 100644 --- a/lib/services/repeater_command_service.dart +++ b/lib/services/repeater_command_service.dart @@ -4,6 +4,16 @@ import '../models/path_selection.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +/// Companion firmware (MeshCore commit 4a869163, 2025-12-30) replaces the CLI +/// frame timestamp with the companion node's RTC for TXT_TYPE_CLI_DATA, so a +/// plain "clock sync" sets the repeater clock to the node clock. The official +/// meshcore-cli translates it to an explicit `time ` command instead; +/// do the same so the repeater always gets the phone's time. +String normalizeRepeaterClockSyncCommand(String command, {int? nowSeconds}) { + final epoch = nowSeconds ?? DateTime.now().millisecondsSinceEpoch ~/ 1000; + return command.trim().toLowerCase() == 'clock sync' ? 'time $epoch' : command; +} + class RepeaterCommandService { final MeshCoreConnector _connector; final Map> _pendingCommands = {}; @@ -13,18 +23,22 @@ class RepeaterCommandService { int _prefixCounter = 0; static const int maxRetries = 5; + static final RegExp _prefixPattern = RegExp(r'^[0-9A-Fa-f]{2}\|'); RepeaterCommandService(this._connector); /// Send a CLI command to a repeater with automatic retries - /// Returns a future that completes when a response is received or after max retries + /// Returns a future that completes when a response is received or after max retries. + /// With [raw], the command is sent verbatim without the `XX|` reply prefix. Future sendCommand( Contact repeater, String command, { Function(String)? onResponse, Function(int)? onAttempt, int retries = maxRetries, + bool raw = false, }) async { + if (!raw) command = normalizeRepeaterClockSyncCommand(command); final attemptCount = retries < 1 ? 1 : retries; final selection = await _connector.preparePathForContactSend(repeater); @@ -36,6 +50,7 @@ class RepeaterCommandService { command, selection, attempt, + raw, ); onResponse?.call(response); return response; @@ -52,6 +67,7 @@ class RepeaterCommandService { String command, PathSelection selection, int attempt, + bool raw, ) async { final repeaterKey = repeater.publicKeyHex; final prefix = _nextPrefixToken(); @@ -62,7 +78,7 @@ class RepeaterCommandService { _pendingByPrefix[prefix] = commandId; try { - final framedCommand = '$prefix$command'; + final framedCommand = raw ? command : '$prefix$command'; final pathLengthValue = selection.useFlood ? -1 : selection.hopCount; final timestampSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000; _connector.trackRepeaterAck( @@ -112,6 +128,15 @@ class RepeaterCommandService { } } + /// 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). + Future sendUnansweredLine(Contact repeater, String line) { + return _connector.sendFrame( + buildSendCliCommandFrame(repeater.publicKey, line), + ); + } + /// Call this when a text message response is received from a repeater void handleResponse(Contact repeater, String responseText) { // Find pending command for this repeater and complete it @@ -119,14 +144,17 @@ class RepeaterCommandService { String? commandId; String responsePayload = responseText; - if (responseText.length >= 3 && responseText[2] == '|') { - final prefix = responseText.substring(0, 3); + if (_prefixPattern.hasMatch(responseText)) { + final prefix = responseText.substring(0, 3).toUpperCase(); commandId = _pendingByPrefix[prefix]; + if (commandId == null || !commandId.startsWith('${repeaterKey}_')) { + return; + } responsePayload = responseText.substring(3).trimLeft(); } commandId ??= _pendingCommands.keys.firstWhere( - (id) => id.startsWith(repeaterKey), + (id) => id.startsWith('${repeaterKey}_'), orElse: () => '', ); diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 0c78c592..e214d830 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import '../models/delivery_observation.dart'; import '../models/path_history.dart'; import '../storage/prefs_manager.dart'; +import '../utils/app_logger.dart'; class StorageService { static const String _pathHistoryPrefix = 'path_history_'; @@ -11,6 +12,14 @@ class StorageService { 'repeater_auto_clock_sync_after_login'; static const String _deliveryObservationsKey = 'delivery_observations'; + String _publicKeyHex = ''; + set setPublicKeyHex(String value) => + _publicKeyHex = value.length > 10 ? value.substring(0, 10) : ''; + + String _pathHistoryKey(String contactPubKeyHex) => _publicKeyHex.isEmpty + ? '$_pathHistoryPrefix$contactPubKeyHex' + : '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex'; + Future> _loadRepeaterAutoClockSyncAfterLogin() async { final prefs = PrefsManager.instance; final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey); @@ -48,15 +57,18 @@ class StorageService { ContactPathHistory history, ) async { final prefs = PrefsManager.instance; - final key = '$_pathHistoryPrefix$contactPubKeyHex'; + final key = _pathHistoryKey(contactPubKeyHex); final jsonStr = jsonEncode(history.toJson()); await prefs.setString(key, jsonStr); } Future loadPathHistory(String contactPubKeyHex) async { final prefs = PrefsManager.instance; - final key = '$_pathHistoryPrefix$contactPubKeyHex'; - final jsonStr = prefs.getString(key); + final key = _pathHistoryKey(contactPubKeyHex); + // Fall back to the pre-scoping key so learned routes survive the upgrade. + final jsonStr = + prefs.getString(key) ?? + prefs.getString('$_pathHistoryPrefix$contactPubKeyHex'); if (jsonStr == null) return null; @@ -70,8 +82,8 @@ class StorageService { Future clearPathHistory(String contactPubKeyHex) async { final prefs = PrefsManager.instance; - final key = '$_pathHistoryPrefix$contactPubKeyHex'; - await prefs.remove(key); + await prefs.remove(_pathHistoryKey(contactPubKeyHex)); + await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex'); } Future clearAllPathHistories() async { @@ -173,14 +185,24 @@ class StorageService { if (jsonStr == null) return []; + final List list; try { - final list = jsonDecode(jsonStr) as List; - return list - .map((e) => DeliveryObservation.fromJson(e as Map)) - .toList(); + list = jsonDecode(jsonStr) as List; } catch (e) { + appLogger.warn('Stored delivery observations are unreadable: $e'); return []; } + final observations = []; + for (final e in list) { + try { + observations.add( + DeliveryObservation.fromJson(e as Map), + ); + } catch (err) { + appLogger.warn('Skipping malformed delivery observation: $err'); + } + } + return observations; } Future clearDeliveryObservations() async { diff --git a/lib/services/translation_file_store_io.dart b/lib/services/translation_file_store_io.dart index ad549ef8..9bd2f62c 100644 --- a/lib/services/translation_file_store_io.dart +++ b/lib/services/translation_file_store_io.dart @@ -58,7 +58,10 @@ class TranslationFileStore { required Stream> chunks, }) async { final directoryPath = await modelDirectoryPath(); - final file = File('$directoryPath/$fileName'); + final finalPath = '$directoryPath/$fileName'; + // Hidden until complete, so a killed download is swept by + // [scanDownloadedModels] instead of being registered as a model. + final file = File(_partPath(directoryPath, fileName)); final sink = file.openWrite(); var fileSizeBytes = 0; var completed = false; @@ -74,8 +77,9 @@ class TranslationFileStore { await file.delete(); } } + await file.rename(finalPath); return DownloadedModelFile( - localPath: file.path, + localPath: finalPath, fileSizeBytes: fileSizeBytes, ); } @@ -91,7 +95,8 @@ class TranslationFileStore { }) async { final dir = await modelDirectoryPath(); final finalPath = '$dir/$fileName'; - final sink = File(finalPath).openWrite(); + final partPath = _partPath(dir, fileName); + final sink = File(partPath).openWrite(); var totalSize = 0; var completed = false; try { @@ -110,14 +115,18 @@ class TranslationFileStore { } } if (!completed) { - final finalFile = File(finalPath); - if (finalFile.existsSync()) { - await finalFile.delete(); + final partFile = File(partPath); + if (partFile.existsSync()) { + await partFile.delete(); } } } + await File(partPath).rename(finalPath); return DownloadedModelFile(localPath: finalPath, fileSizeBytes: totalSize); } + + String _partPath(String dir, String fileName) => + fileName.startsWith('.') ? '$dir/$fileName.part' : '$dir/.$fileName.part'; } class DownloadedModelFile { diff --git a/lib/services/translation_service.dart b/lib/services/translation_service.dart index d01155ab..0be08c4e 100644 --- a/lib/services/translation_service.dart +++ b/lib/services/translation_service.dart @@ -271,10 +271,19 @@ class TranslationService extends ChangeNotifier { _downloadTotalBytes ??= response.contentLength; _notify(); final trackedStream = _trackDownloadProgress(response.stream); - return await _fileStore.writeModelBytes( + final downloaded = await _fileStore.writeModelBytes( fileName: fileName, chunks: trackedStream, ); + final expected = response.contentLength; + if (expected != null && downloaded.fileSizeBytes != expected) { + await _fileStore.deleteFile(downloaded.localPath); + throw StateError( + 'Model download incomplete: ' + '${downloaded.fileSizeBytes} of $expected bytes', + ); + } + return downloaded; } finally { client.close(); } @@ -350,10 +359,17 @@ class TranslationService extends ChangeNotifier { ); } final trackedStream = _trackDownloadProgress(response.stream); - await _fileStore.writeModelBytes( + final downloaded = await _fileStore.writeModelBytes( fileName: chunkPath.split(RegExp(r'[/\\]')).last, chunks: trackedStream, ); + final expected = end - start + 1; + if (downloaded.fileSizeBytes != expected) { + throw StateError( + 'Range download incomplete: ' + '${downloaded.fileSizeBytes} of $expected bytes', + ); + } } void cancelDownload() { diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 1976de94..7ef2eec0 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -1,6 +1,9 @@ import 'dart:async'; +import 'dart:ffi'; import 'dart:io'; +import 'dart:isolate'; +import 'package:ffi/ffi.dart'; import 'package:flserial/flserial.dart'; import 'package:flserial/flserial_exception.dart'; import 'package:flutter/foundation.dart'; @@ -32,6 +35,18 @@ class UsbSerialService { String? _connectedPortKey; String? _connectedPortLabel; FlSerial? _serial; + + /// Non-null while a disconnect teardown (native close in a helper isolate, + /// then subscription cancel) is running. + Future? _activeDisconnect; + + /// Exists while a native close runs in a helper isolate. flserial's slot + /// table is process-global and survives a hot restart, but + /// [_activeDisconnect] does not, so a fresh isolate checks this marker + /// before fl_free() tears down a slot that is still inside close(). + static final String _pendingClosePath = + '${Directory.systemTemp.path}/meshcore_open_usb_close_$pid'; + static const Duration _maxPendingClose = Duration(seconds: 45); AppDebugLogService? _debugLogService; Object? _lastError; @@ -120,6 +135,33 @@ class UsbSerialService { throw UnsupportedError('USB serial is not supported on this platform.'); } + // A previous disconnect may still be running: on desktop its native close + // waits out the kernel's closing_wait in a helper isolate, and the + // teardown only marks the transport disconnected afterwards. Reopening + // before it finishes would let the old teardown overwrite the new + // connection's state (and, on desktop, race fl_free()/fl_close() over the + // process-global flserial_tab). Wait for the whole teardown — on every + // platform — before claiming the `connecting` state. + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { + _debugLogService?.info( + 'Waiting for the previous USB disconnect to finish before reopening', + tag: 'USB Serial', + ); + try { + await pendingDisconnect; + } catch (_) { + // Failures are already logged by the teardown path. + } + + // The await above is a suspension point: another caller may have claimed + // the transport while this one waited. + if (_status == UsbSerialStatus.connected || + _status == UsbSerialStatus.connecting) { + throw StateError('USB serial transport is already active'); + } + } + _status = UsbSerialStatus.connecting; var normalizedPortName = normalizeUsbPortName(portName); _frameDecoder.reset(); @@ -157,6 +199,9 @@ class UsbSerialService { // // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. + // (the previous teardown was already awaited above) + await _waitForOrphanedNativeClose(); + try { bindings.fl_free(); bindings.fl_init(16); @@ -289,9 +334,23 @@ class UsbSerialService { } } - Future disconnect() async { - if (_status == UsbSerialStatus.disconnected) return; + /// Tears the transport down. Re-entrant calls (e.g. the `onDone` handler + /// firing while a disconnect is already running) join the in-flight + /// teardown instead of racing it. + Future disconnect() { + final pending = _activeDisconnect; + if (pending != null) return pending; + if (_status == UsbSerialStatus.disconnected) return Future.value(); + final teardown = _disconnectInternal(); + _activeDisconnect = teardown; + return teardown.whenComplete(() { + if (identical(_activeDisconnect, teardown)) { + _activeDisconnect = null; + } + }); + } + Future _disconnectInternal() async { final portLabel = _connectedPortLabel ?? _connectedPortKey; _debugLogService?.info( 'USB disconnect starting port=${portLabel ?? 'unknown'}', @@ -322,11 +381,13 @@ class UsbSerialService { try { if (serial?.isOpen() == FlOpenStatus.open) { serial?.setDTR(false); - serial?.closePort(); } } catch (_) { // Ignore errors while closing. } + if (serial != null) { + await _closePortOffUiIsolate(serial); + } // Note: we do NOT call free() here; that would globally reset native // state for all ports. The global reset is done in connect() instead, // before the next open, which is the safer place to do it. @@ -362,20 +423,150 @@ class UsbSerialService { ); } + /// Closes the native port without blocking the Dart UI isolate. + /// + /// `close(2)` on a tty whose output has not been drained by the peer blocks + /// in the kernel for the line discipline's `closing_wait` (30s by default — + /// measured 30.4s on Linux with a CDC-ACM device that never reads its bulk + /// OUT endpoint, e.g. a MeshCore board flashed with a BLE-only companion + /// build). `FlSerial.closePort()` is a synchronous FFI call, so running it + /// inline freezes the whole app for that entire window. `fl_close()` only + /// touches process-global native state, so it is safe to run in a helper + /// isolate; the Dart-side cleanup that `closePort()` also performs is + /// replicated here afterwards. + Future _closePortOffUiIsolate(FlSerial serial) async { + final flh = serial.flh; + if (flh < 0) { + // Already closed synchronously by dispose(), which also closed the + // stream and freed both I/O buffers. + return; + } + serial.flh = -1; + final startedAt = DateTime.now(); + final markerPath = _pendingClosePath; + try { + File(markerPath).writeAsStringSync(''); + } catch (_) {} + try { + await Isolate.run(() { + bindings.fl_close(flh); + try { + File(markerPath).deleteSync(); + } catch (_) {} + }); + } catch (error) { + // Spawning the helper failed, so the native slot and its SerialThread + // are still alive with no reachable handle. Close it inline instead — + // that blocks, but only in this already-degraded path. + _debugLogService?.warn( + 'Off-isolate USB port close failed ($error); closing inline', + tag: 'USB Serial', + ); + try { + bindings.fl_close(flh); + } catch (_) { + // Ignore errors while closing. + } + } + try { + File(markerPath).deleteSync(); + } catch (_) {} + final elapsed = DateTime.now().difference(startedAt); + if (elapsed > const Duration(seconds: 1)) { + _debugLogService?.warn( + 'Native USB port close took ${elapsed.inMilliseconds}ms — the device ' + 'was not draining its serial input', + tag: 'USB Serial', + ); + } + try { + await serial.onSerialData.close(); + } catch (_) { + // Ignore errors while releasing Dart-side resources. + } + _releaseSerialBuffers(serial); + } + + /// Waits for a native close left running by a previous isolate (hot + /// restart during a slow close). Bounded by the marker's age so a stale + /// marker — its helper isolate killed before deleting it — cannot block + /// forever. + Future _waitForOrphanedNativeClose() async { + final marker = File(_pendingClosePath); + try { + if (!marker.existsSync()) return; + _debugLogService?.info( + 'Waiting for a USB port close left over from a previous isolate', + tag: 'USB Serial', + ); + final deadline = marker.lastModifiedSync().add(_maxPendingClose); + while (marker.existsSync() && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 250)); + } + if (marker.existsSync()) marker.deleteSync(); + } catch (_) {} + } + + /// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the + /// pointer fields. `FlSerial.closePort()` is never used for this: it tests + /// the buffers' first byte (`.value`) instead of their address, so it + /// usually leaks them. + void _releaseSerialBuffers(FlSerial serial) { + try { + if (serial.serialReadBuff.address != 0) { + calloc.free(serial.serialReadBuff); + } + serial.serialReadBuff = Pointer.fromAddress(0); + if (serial.serialWriteBuff.address != 0) { + calloc.free(serial.serialWriteBuff); + } + serial.serialWriteBuff = Pointer.fromAddress(0); + } catch (_) { + // Ignore errors while releasing Dart-side resources. + } + } + void dispose() { // Synchronously close the native port so the SerialThread exits before // the Dart isolate is torn down (e.g. on hot restart). The async // disconnect() path via unawaited() offers no ordering guarantee — the // isolate may die before the Future resolves, leaving the thread alive // with a dangling NativeCallable pointer. + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { + // A disconnect is already running and owns the teardown ordering + // (native close first, subscription cancel after). Re-entering + // disconnect() here would cancel the subscription underneath it, so + // only chain the frame-controller cleanup onto that teardown. + unawaited(pendingDisconnect.whenComplete(_closeFrameController)); + return; + } if (_useDesktopFlSerial) { final serial = _serial; - try { - if (serial?.isOpen() == FlOpenStatus.open) { - serial?.setDTR(false); - serial?.closePort(); // synchronous C call — kills the SerialThread + _serial = null; + if (serial != null) { + // Close on any live handle, not only when isOpen() reports `open`: + // flserial keeps a valid slot (and a running SerialThread) when the + // port is in an I/O error state, and _serial is already unreachable. + final flh = serial.flh; + if (flh >= 0) { + try { + serial.setDTR(false); + } catch (_) { + // Line-control failure must not skip the close below. + } + serial.flh = -1; + try { + bindings.fl_close( + flh, + ); // synchronous C call — kills the SerialThread + } catch (_) {} + unawaited(serial.onSerialData.close()); } - } catch (_) {} + // _serial is gone, so the disconnect() below can no longer reach the + // buffers: release them here. + _releaseSerialBuffers(serial); + } } // Kick off the full async teardown for anything else (subscription cancel, // stream controller close). These are best-effort at dispose time. @@ -383,6 +574,14 @@ class UsbSerialService { } void _handleSerialData(FlSerialEventArgs event) { + if (_status == UsbSerialStatus.disconnecting || + _status == UsbSerialStatus.disconnected) { + // Teardown already invalidated the native handle; a callback queued + // before that would make readList() throw and publish a spurious + // transport error that triggers another disconnect. Data that arrives + // while still `connecting` is kept — the decoder buffers it. + return; + } try { final bytes = event.serial.readList(); if (bytes.isNotEmpty) { @@ -399,7 +598,9 @@ class UsbSerialService { return; } if (data is ByteData) { - _ingestRawBytes(data.buffer.asUint8List()); + _ingestRawBytes( + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), + ); return; } _addFrameError( @@ -412,7 +613,11 @@ class UsbSerialService { } void _handleSerialDone() { + final wasConnected = _status == UsbSerialStatus.connected; unawaited(disconnect()); + if (wasConnected) { + _addFrameError(StateError('USB serial connection closed')); + } } void _ingestRawBytes(Uint8List bytes) { diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 5a0fbd8f..069588cb 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -68,13 +68,24 @@ class ChannelMessageStore { if (jsonString == null || jsonString.isEmpty) { return []; } + final List jsonList; try { - final jsonList = jsonDecode(jsonString) as List; - return jsonList.map((json) => _messageFromJson(json)).toList(); + jsonList = jsonDecode(jsonString) as List; } catch (e) { - // If parsing fails, return empty list + appLogger.warn( + 'Stored messages for channel $channelIndex are unreadable: $e', + ); return []; } + final messages = []; + for (final json in jsonList) { + try { + messages.add(_messageFromJson(json as Map)); + } catch (e) { + appLogger.warn('Skipping malformed stored channel message: $e'); + } + } + return messages; } /// Clear messages for a specific channel @@ -110,6 +121,7 @@ class ChannelMessageStore { 'channelIndex': msg.channelIndex, 'repeatCount': msg.repeatCount, 'pathLength': msg.pathLength, + 'pathHashWidth': msg.pathHashWidth, 'pathBytes': base64Encode(msg.pathBytes), 'pathVariants': msg.pathVariants.map(base64Encode).toList(), 'repeats': msg.repeats.map(_repeatToJson).toList(), @@ -126,11 +138,43 @@ class ChannelMessageStore { ChannelMessage _messageFromJson(Map json) { final rawText = json['text'] as String; final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText; + + final rawPathLength = json['pathLength'] as int?; + final rawPathBytes = json['pathBytes'] != null + ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) + : Uint8List(0); + final rawPathHashWidth = json['pathHashWidth'] as int?; + + int? decodedPathLength = rawPathLength; + Uint8List decodedPathBytes = rawPathBytes; + int? decodedPathHashWidth = rawPathHashWidth; + + if (rawPathLength != null) { + if (rawPathLength == 0xFF || rawPathLength < 0) { + decodedPathLength = -1; + decodedPathBytes = Uint8List(0); + } else if (rawPathLength >= 64) { + final mode = (rawPathLength & 0xC0) >> 6; + final hopCount = rawPathLength & 0x3F; + final width = mode + 1; + final byteLen = hopCount * width; + decodedPathLength = hopCount; + decodedPathHashWidth = width; + if (byteLen <= rawPathBytes.length) { + decodedPathBytes = rawPathBytes.sublist(0, byteLen); + } else { + decodedPathBytes = Uint8List(0); + } + } else if (rawPathLength == 0) { + decodedPathBytes = Uint8List(0); + } + } + return ChannelMessage( senderKey: json['senderKey'] != null ? Uint8List.fromList(base64Decode(json['senderKey'])) : null, - senderName: json['senderName'] as String, + senderName: json['senderName'] as String? ?? 'Unknown', text: decodedText, originalText: json['originalText'] as String?, translatedText: json['translatedText'] as String?, @@ -140,13 +184,16 @@ class ChannelMessageStore { ), translationModelId: json['translationModelId'] as String?, timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int), - isOutgoing: json['isOutgoing'] as bool, - status: ChannelMessageStatus.values[json['status'] as int], + isOutgoing: json['isOutgoing'] as bool? ?? false, + status: + ChannelMessageStatus.values.elementAtOrNull( + json['status'] as int? ?? -1, + ) ?? + ChannelMessageStatus.failed, repeatCount: (json['repeatCount'] as int?) ?? 0, - pathLength: json['pathLength'] as int?, - pathBytes: json['pathBytes'] != null - ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) - : Uint8List(0), + pathLength: decodedPathLength, + pathHashWidth: decodedPathHashWidth, + pathBytes: decodedPathBytes, pathVariants: (json['pathVariants'] as List?) ?.map((entry) => Uint8List.fromList(base64Decode(entry as String))) .toList(), @@ -163,7 +210,12 @@ class ChannelMessageStore { replyToText: json['replyToText'] as String?, reactions: (json['reactions'] as Map?)?.map( - (key, value) => MapEntry(key, value as int), + (key, value) => MapEntry( + key, + (value is int) + ? List.filled(value, null) + : List.from(value), + ), ) ?? {}, ); diff --git a/lib/storage/channel_region_store.dart b/lib/storage/channel_region_store.dart index e28551a7..8d1029df 100644 --- a/lib/storage/channel_region_store.dart +++ b/lib/storage/channel_region_store.dart @@ -10,6 +10,18 @@ class ChannelRegionStore { String get keyFor => '$_keyPrefix$publicKeyHex'; + String get _defaultKey => 'default_region_$publicKeyHex'; + + String loadDefaultRegion() { + if (publicKeyHex.isEmpty) return ''; + return PrefsManager.instance.getString(_defaultKey) ?? ''; + } + + Future saveDefaultRegion(String region) async { + if (publicKeyHex.isEmpty) return; + await PrefsManager.instance.setString(_defaultKey, region); + } + Future loadRegion(int channelIndex) async { if (publicKeyHex.isEmpty) { appLogger.warn( diff --git a/lib/storage/channel_settings_store.dart b/lib/storage/channel_settings_store.dart index e0b390f8..2415d01c 100644 --- a/lib/storage/channel_settings_store.dart +++ b/lib/storage/channel_settings_store.dart @@ -4,6 +4,7 @@ import 'prefs_manager.dart'; class ChannelSettingsStore { static const String _keyPrefix = 'channel_smaz_'; static const String _cyr2latKeyPrefix = 'channel_cyr2lat_'; + static const String _urlImagesKeyPrefix = 'channel_url_images_'; String publicKeyHex = ''; set setPublicKeyHex(String value) => @@ -11,6 +12,7 @@ class ChannelSettingsStore { String get keyFor => '$_keyPrefix$publicKeyHex'; String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex'; + String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex'; Future loadSmazEnabled(int channelIndex) async { if (publicKeyHex.isEmpty) { @@ -73,6 +75,31 @@ class ChannelSettingsStore { await prefs.setBool(key, enabled); } + Future loadUrlImagesEnabled(int channelIndex) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot load channel URL image settings.', + ); + return false; + } + final prefs = PrefsManager.instance; + final key = '$keyForUrlImages$channelIndex'; + return prefs.getBool(key) ?? false; + } + + Future saveUrlImagesEnabled(int channelIndex, bool enabled) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot save channel URL image settings.', + ); + return; + } + await PrefsManager.instance.setBool( + '$keyForUrlImages$channelIndex', + enabled, + ); + } + Future loadCyr2LatProfileId(int channelIndex) async { if (publicKeyHex.isEmpty) { appLogger.warn( diff --git a/lib/storage/community_store.dart b/lib/storage/community_store.dart index c69d0b80..75c7daf8 100644 --- a/lib/storage/community_store.dart +++ b/lib/storage/community_store.dart @@ -45,15 +45,22 @@ class CommunityStore { return []; } + final List jsonList; try { - final jsonList = jsonDecode(jsonString) as List; - return jsonList - .map((json) => Community.fromJson(json as Map)) - .toList(); + jsonList = jsonDecode(jsonString) as List; } catch (e) { - // If JSON is corrupted, return empty list + appLogger.warn('Stored communities are unreadable: $e'); return []; } + final communities = []; + for (final json in jsonList) { + try { + communities.add(Community.fromJson(json as Map)); + } catch (e) { + appLogger.warn('Skipping malformed stored community: $e'); + } + } + return communities; } /// Save all communities to storage diff --git a/lib/storage/contact_discovery_store.dart b/lib/storage/contact_discovery_store.dart index 3f6f1718..1d8793c0 100644 --- a/lib/storage/contact_discovery_store.dart +++ b/lib/storage/contact_discovery_store.dart @@ -2,30 +2,54 @@ import 'dart:convert'; import 'dart:typed_data'; import '../models/contact.dart'; +import '../utils/app_logger.dart'; import 'prefs_manager.dart'; class ContactDiscoveryStore { static const String _keyPrefix = 'discovered_contacts'; + String publicKeyHex = ''; + set setPublicKeyHex(String value) => + publicKeyHex = value.length > 10 ? value.substring(0, 10) : ''; + + String get keyFor => '$_keyPrefix$publicKeyHex'; + Future> loadContacts() async { + if (publicKeyHex.isEmpty) return []; final prefs = PrefsManager.instance; - final jsonStr = prefs.getString(_keyPrefix); + var jsonStr = prefs.getString(keyFor); + if (jsonStr == null) { + jsonStr = prefs.getString(_keyPrefix); + if (jsonStr != null) { + await prefs.setString(keyFor, jsonStr); + await prefs.remove(_keyPrefix); + } + } if (jsonStr == null) return []; + final List jsonList; try { - final jsonList = jsonDecode(jsonStr) as List; - return jsonList - .map((entry) => _fromJson(entry as Map)) - .toList(); - } catch (_) { + jsonList = jsonDecode(jsonStr) as List; + } catch (e) { + appLogger.warn('Stored discovered contacts are unreadable: $e'); return []; } + final contacts = []; + for (final entry in jsonList) { + try { + contacts.add(_fromJson(entry as Map)); + } catch (e) { + appLogger.warn('Skipping malformed discovered contact: $e'); + } + } + return contacts; } Future saveContacts(List contacts) async { + if (publicKeyHex.isEmpty) return; final prefs = PrefsManager.instance; final jsonList = contacts.map(_toJson).toList(); - await prefs.setString(_keyPrefix, jsonEncode(jsonList)); + await prefs.setString(keyFor, jsonEncode(jsonList)); } Map _toJson(Contact contact) { @@ -36,6 +60,7 @@ class ContactDiscoveryStore { 'flags': contact.flags, 'pathLength': contact.pathLength, 'path': base64Encode(contact.path), + 'pathHashWidth': contact.pathHashWidth, 'pathOverride': contact.pathOverride, 'pathOverrideBytes': contact.pathOverrideBytes != null ? base64Encode(contact.pathOverrideBytes!) @@ -55,15 +80,45 @@ class ContactDiscoveryStore { final lastSeenMs = json['lastSeen'] as int? ?? 0; final lastMessageMs = json['lastMessageAt'] as int?; final lastModifiedMs = json['lastModified'] as int?; + + final rawPathLength = json['pathLength'] as int? ?? -1; + final rawPath = json['path'] != null + ? Uint8List.fromList(base64Decode(json['path'] as String)) + : Uint8List(0); + + int decodedPathLength = rawPathLength; + Uint8List decodedPath = rawPath; + int? decodedPathHashWidth = json['pathHashWidth'] as int?; + + if (rawPathLength == 0xFF || rawPathLength < 0) { + decodedPathLength = -1; + decodedPath = Uint8List(0); + } else if (rawPathLength >= 64) { + final mode = (rawPathLength & 0xC0) >> 6; + final hopCount = rawPathLength & 0x3F; + final width = mode + 1; + final byteLen = hopCount * width; + decodedPathLength = hopCount; + decodedPathHashWidth = width; + if (byteLen <= rawPath.length) { + decodedPath = rawPath.sublist(0, byteLen); + } else { + decodedPath = Uint8List(0); + } + } else if (rawPathLength == 0) { + decodedPath = Uint8List(0); + } + return Contact( publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)), name: json['name'] as String? ?? 'Unknown', type: json['type'] as int? ?? 0, flags: json['flags'] as int? ?? 0, - pathLength: json['pathLength'] as int? ?? -1, - path: json['path'] != null - ? Uint8List.fromList(base64Decode(json['path'] as String)) - : Uint8List(0), + pathLength: decodedPathLength, + path: decodedPath, + pathHashWidth: + decodedPathHashWidth ?? + Contact.inferPathHashWidth(decodedPathLength, decodedPath.length), pathOverride: json['pathOverride'] as int?, pathOverrideBytes: json['pathOverrideBytes'] != null ? Uint8List.fromList( diff --git a/lib/storage/contact_settings_store.dart b/lib/storage/contact_settings_store.dart index 682f1af6..a0760477 100644 --- a/lib/storage/contact_settings_store.dart +++ b/lib/storage/contact_settings_store.dart @@ -4,6 +4,7 @@ import 'prefs_manager.dart'; class ContactSettingsStore { static const String _keyPrefix = 'contact_smaz_'; static const String _cyr2latKeyPrefix = 'contact_cyr2lat_'; + static const String _urlImagesKeyPrefix = 'contact_url_images_'; String publicKeyHex = ''; set setPublicKeyHex(String value) => @@ -11,6 +12,7 @@ class ContactSettingsStore { String get keyFor => '$_keyPrefix$publicKeyHex'; String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex'; + String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex'; Future loadSmazEnabled(String contactKeyHex) async { if (publicKeyHex.isEmpty) { @@ -73,6 +75,31 @@ class ContactSettingsStore { await prefs.setBool(key, enabled); } + Future loadUrlImagesEnabled(String contactKeyHex) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot load contact URL image settings.', + ); + return false; + } + final prefs = PrefsManager.instance; + final key = '$keyForUrlImages$contactKeyHex'; + return prefs.getBool(key) ?? false; + } + + Future saveUrlImagesEnabled(String contactKeyHex, bool enabled) async { + if (publicKeyHex.isEmpty) { + appLogger.warn( + 'Public key hex is not set. Cannot save contact URL image settings.', + ); + return; + } + await PrefsManager.instance.setBool( + '$keyForUrlImages$contactKeyHex', + enabled, + ); + } + Future loadCyr2LatProfileId(String contactKeyHex) async { if (publicKeyHex.isEmpty) { appLogger.warn( diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index 7883d885..c23983a8 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -40,14 +40,22 @@ class ContactStore { return []; } + final List jsonList; try { - final jsonList = jsonDecode(jsonString) as List; - return jsonList - .map((entry) => _fromJson(entry as Map)) - .toList(); - } catch (_) { + jsonList = jsonDecode(jsonString) as List; + } catch (e) { + appLogger.warn('Stored contacts are unreadable: $e'); return []; } + final contacts = []; + for (final entry in jsonList) { + try { + contacts.add(_fromJson(entry as Map)); + } catch (e) { + appLogger.warn('Skipping malformed stored contact: $e'); + } + } + return contacts; } Future saveContacts(List contacts) async { @@ -68,6 +76,7 @@ class ContactStore { 'flags': contact.flags, 'pathLength': contact.pathLength, 'path': base64Encode(contact.path), + 'pathHashWidth': contact.pathHashWidth, 'pathOverride': contact.pathOverride, 'pathOverrideBytes': contact.pathOverrideBytes != null ? base64Encode(contact.pathOverrideBytes!) @@ -88,15 +97,45 @@ class ContactStore { final lastSeenMs = json['lastSeen'] as int? ?? 0; final lastMessageMs = json['lastMessageAt'] as int?; final lastModifiedMs = json['lastModified'] as int?; + + final rawPathLength = json['pathLength'] as int? ?? -1; + final rawPath = json['path'] != null + ? Uint8List.fromList(base64Decode(json['path'] as String)) + : Uint8List(0); + + int decodedPathLength = rawPathLength; + Uint8List decodedPath = rawPath; + int? decodedPathHashWidth = json['pathHashWidth'] as int?; + + if (rawPathLength == 0xFF || rawPathLength < 0) { + decodedPathLength = -1; + decodedPath = Uint8List(0); + } else if (rawPathLength >= 64) { + final mode = (rawPathLength & 0xC0) >> 6; + final hopCount = rawPathLength & 0x3F; + final width = mode + 1; + final byteLen = hopCount * width; + decodedPathLength = hopCount; + decodedPathHashWidth = width; + if (byteLen <= rawPath.length) { + decodedPath = rawPath.sublist(0, byteLen); + } else { + decodedPath = Uint8List(0); + } + } else if (rawPathLength == 0) { + decodedPath = Uint8List(0); + } + return Contact( publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)), name: json['name'] as String? ?? 'Unknown', type: json['type'] as int? ?? 0, flags: json['flags'] as int? ?? 0, - pathLength: json['pathLength'] as int? ?? -1, - path: json['path'] != null - ? Uint8List.fromList(base64Decode(json['path'] as String)) - : Uint8List(0), + pathLength: decodedPathLength, + path: decodedPath, + pathHashWidth: + decodedPathHashWidth ?? + Contact.inferPathHashWidth(decodedPathLength, decodedPath.length), pathOverride: json['pathOverride'] as int?, pathOverrideBytes: json['pathOverrideBytes'] != null ? Uint8List.fromList( diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart index 3d237681..46377348 100644 --- a/lib/storage/message_store.dart +++ b/lib/storage/message_store.dart @@ -57,12 +57,22 @@ class MessageStore { return []; } + final List jsonList; try { - final jsonList = jsonDecode(jsonString) as List; - return jsonList.map((json) => _messageFromJson(json)).toList(); + jsonList = jsonDecode(jsonString) as List; } catch (e) { + appLogger.warn('Stored messages for $contactKeyHex are unreadable: $e'); return []; } + final messages = []; + for (final json in jsonList) { + try { + messages.add(_messageFromJson(json as Map)); + } catch (e) { + appLogger.warn('Skipping malformed stored message: $e'); + } + } + return messages; } Future clearMessages(String contactKeyHex) async { @@ -113,13 +123,44 @@ class MessageStore { final decodedText = isCli ? rawText : (Smaz.tryDecodePrefixed(rawText) ?? rawText); + + final rawPathLength = json['pathLength'] as int?; + final rawPathBytes = json['pathBytes'] != null + ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) + : Uint8List(0); + + int? decodedPathLength = rawPathLength; + Uint8List decodedPathBytes = rawPathBytes; + + if (rawPathLength != null) { + if (rawPathLength == 0xFF || rawPathLength < 0) { + decodedPathLength = -1; + decodedPathBytes = Uint8List(0); + } else if (rawPathLength >= 64) { + final mode = (rawPathLength & 0xC0) >> 6; + final hopCount = rawPathLength & 0x3F; + final width = mode + 1; + final byteLen = hopCount * width; + decodedPathLength = hopCount; + if (byteLen <= rawPathBytes.length) { + decodedPathBytes = rawPathBytes.sublist(0, byteLen); + } else { + decodedPathBytes = Uint8List(0); + } + } else if (rawPathLength == 0) { + decodedPathBytes = Uint8List(0); + } + } + return Message( senderKey: Uint8List.fromList(base64Decode(json['senderKey'] as String)), text: decodedText, timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int), - isOutgoing: json['isOutgoing'] as bool, + isOutgoing: json['isOutgoing'] as bool? ?? false, isCli: isCli, - status: MessageStatus.values[json['status'] as int], + status: + MessageStatus.values.elementAtOrNull(json['status'] as int? ?? -1) ?? + MessageStatus.failed, messageId: json['messageId'] as String?, originalText: json['originalText'] as String?, translatedText: json['translatedText'] as String?, @@ -138,13 +179,16 @@ class MessageStore { ? DateTime.fromMillisecondsSinceEpoch(json['deliveredAt'] as int) : null, tripTimeMs: json['tripTimeMs'] as int?, - pathLength: json['pathLength'] as int?, - pathBytes: json['pathBytes'] != null - ? Uint8List.fromList(base64Decode(json['pathBytes'] as String)) - : Uint8List(0), + pathLength: decodedPathLength, + pathBytes: decodedPathBytes, reactions: (json['reactions'] as Map?)?.map( - (key, value) => MapEntry(key, value as int), + (key, value) => MapEntry( + key, + (value is int) + ? List.filled(value, null) + : List.from(value), + ), ) ?? {}, reactionStatuses: diff --git a/lib/storage/region_store.dart b/lib/storage/region_store.dart index af532da9..eddeabc2 100644 --- a/lib/storage/region_store.dart +++ b/lib/storage/region_store.dart @@ -47,6 +47,9 @@ class RegionStore { await channelRegionStore.saveRegion(channel.index, ''); } } + if (channelRegionStore.loadDefaultRegion() == region) { + await channelRegionStore.saveDefaultRegion(''); + } regions.remove(region); saveRegions(regions); } diff --git a/lib/theme/mesh_theme.dart b/lib/theme/mesh_theme.dart index fcb15b1b..281b1145 100644 --- a/lib/theme/mesh_theme.dart +++ b/lib/theme/mesh_theme.dart @@ -1,4 +1,3 @@ -import 'package:flutter/cupertino.dart' show CupertinoPageTransitionsBuilder; import 'package:flutter/material.dart'; /// MeshCore palette — high-contrast slate surfaces with sky-blue accents. @@ -12,16 +11,16 @@ class MeshPalette { static const bg3 = Color(0xFF1E293B); static const bg4 = Color(0xFF334155); - // Lines - static const line = Color(0xFF1E293B); - static const line2 = Color(0xFF334155); - static const line3 = Color(0xFF475569); + // Lines — lifted for clearer element separation on the near-black surface + static const line = Color(0xFF2A3850); + static const line2 = Color(0xFF3B4A61); + static const line3 = Color(0xFF546376); - // Ink + // Ink — muted tones brightened for readable secondary/tertiary text in dark static const ink = Color(0xFFF8FAFC); - static const ink2 = Color(0xFFCBD5E1); - static const ink3 = Color(0xFF94A3B8); - static const ink4 = Color(0xFF64748B); + static const ink2 = Color(0xFFD5DEE9); + static const ink3 = Color(0xFFAAB6C6); + static const ink4 = Color(0xFF828FA3); // Signal-quality green (used only for SNR coloring, not UI chrome) static const signal = Color(0xFF22C55E); @@ -395,9 +394,9 @@ class MeshTheme { labelTextStyle: WidgetStateProperty.resolveWith((states) { final selected = states.contains(WidgetState.selected); return TextStyle( - fontFamily: MeshFonts.mono, - fontFamilyFallback: MeshFonts.monoFallback, - fontSize: 10, + fontFamily: MeshFonts.sans, + fontFamilyFallback: MeshFonts.sansFallback, + fontSize: 11.5, fontWeight: selected ? FontWeight.w700 : FontWeight.w500, letterSpacing: 0.1, color: selected ? scheme.onPrimary : scheme.onSurfaceVariant, @@ -448,7 +447,7 @@ class MeshTheme { pageTransitionsTheme: const PageTransitionsTheme( builders: { TargetPlatform.android: FadeForwardsPageTransitionsBuilder(), - TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.iOS: FadeForwardsPageTransitionsBuilder(), TargetPlatform.linux: FadeForwardsPageTransitionsBuilder(), TargetPlatform.macOS: FadeForwardsPageTransitionsBuilder(), TargetPlatform.windows: FadeForwardsPageTransitionsBuilder(), @@ -583,14 +582,15 @@ class MeshTheme { ); } - /// Small-caps mono label — used for section accents and chip labels. + /// Section-accent / chip label — sans for legibility, with light tracking + /// to keep the "label" feel that section headers rely on. static TextStyle accentLabel({Color? color, double? fontSize}) { return TextStyle( - fontFamily: MeshFonts.mono, - fontFamilyFallback: MeshFonts.monoFallback, - fontSize: fontSize ?? 9.5, - fontWeight: FontWeight.w600, - letterSpacing: 1.8, + fontFamily: MeshFonts.sans, + fontFamilyFallback: MeshFonts.sansFallback, + fontSize: fontSize ?? 11, + fontWeight: FontWeight.w700, + letterSpacing: 0.6, color: color, ); } diff --git a/lib/utils/battery_utils.dart b/lib/utils/battery_utils.dart index 2bf4a5df..f32559fc 100644 --- a/lib/utils/battery_utils.dart +++ b/lib/utils/battery_utils.dart @@ -6,6 +6,8 @@ BatteryVoltageRange batteryVoltageRange(String chemistry) { return (minMv: 2600, maxMv: 3650); case 'lipo': return (minMv: 3000, maxMv: 4200); + case 'lipo_hv': + return (minMv: 3000, maxMv: 4350); case 'nmc': default: return (minMv: 3000, maxMv: 4200); diff --git a/lib/utils/contact_qr.dart b/lib/utils/contact_qr.dart new file mode 100644 index 00000000..cc789926 --- /dev/null +++ b/lib/utils/contact_qr.dart @@ -0,0 +1,102 @@ +import 'dart:typed_data'; + +/// Parsed result of a MeshCore contact QR / link. +class ScannedContact { + /// Raw advert packet bytes (legacy `meshcore://` form), else null. + final Uint8List? advertPacket; + + /// 32-byte public key (contact-card form), else null. + final Uint8List? publicKey; + + /// Contact name from the card form; empty string when unknown. + final String name; + + /// Advert type: 1 Companion, 2 Repeater, 3 Room Server, 4 Sensor; null + /// when the card omits it or carries an unknown value. + final int? type; + + const ScannedContact({ + this.advertPacket, + this.publicKey, + this.name = '', + this.type, + }); + + bool get isAdvertPacket => advertPacket != null; +} + +/// Matches the advert packet minimum enforced by `buildImportContactFrame`. +const int _minAdvertPacketBytes = 98; + +/// `buildImportContactFrame` prepends one command byte to a `maxFrameSize` +/// (172 byte) frame, so anything longer cannot be sent. +const int _maxAdvertPacketBytes = 171; +const int _contactCardKeyBytes = 32; +const String _legacyPrefix = 'meshcore://'; + +/// Returns null when [data] is not a recognizable MeshCore contact QR/link. +ScannedContact? parseContactQr(String data) { + final trimmed = data.trim(); + if (trimmed.isEmpty) return null; + + final uri = Uri.tryParse(trimmed); + if (uri == null || uri.scheme != 'meshcore') return null; + + final normalizedPath = '${uri.host}${uri.path}'.toLowerCase().replaceAll( + RegExp(r'^/+|/+$'), + '', + ); + if (normalizedPath == 'contact/add') { + return _parseContactCard(uri); + } + + if (!trimmed.toLowerCase().startsWith(_legacyPrefix)) return null; + final hexString = trimmed.substring(_legacyPrefix.length); + final bytes = _tryHexDecode(hexString); + if (bytes == null || + bytes.length < _minAdvertPacketBytes || + bytes.length > _maxAdvertPacketBytes) { + return null; + } + return ScannedContact(advertPacket: bytes); +} + +ScannedContact? _parseContactCard(Uri uri) { + final params = uri.queryParameters; + final publicKeyHex = params['public_key']; + if (publicKeyHex == null) return null; + + final publicKey = _tryHexDecode(publicKeyHex); + if (publicKey == null || publicKey.length != _contactCardKeyBytes) { + return null; + } + + final name = (params['name'] ?? '').trim(); + int? type = int.tryParse(params['type'] ?? ''); + if (type != null && (type < 1 || type > 4)) type = null; + + return ScannedContact(publicKey: publicKey, name: name, type: type); +} + +/// Local hex decoder: keeps this util pure-Dart. `hex2Uint8List` in +/// `connector/meshcore_protocol.dart` throws on invalid input and that file +/// pulls in `package:flutter/widgets.dart` and `package:crypto`, which this +/// util must not depend on. +Uint8List? _tryHexDecode(String hex) { + if (hex.isEmpty || hex.length.isOdd) return null; + final bytes = Uint8List(hex.length ~/ 2); + for (int i = 0; i < bytes.length; i++) { + final high = _hexDigit(hex.codeUnitAt(i * 2)); + final low = _hexDigit(hex.codeUnitAt(i * 2 + 1)); + if (high == null || low == null) return null; + bytes[i] = (high << 4) | low; + } + return bytes; +} + +int? _hexDigit(int codeUnit) { + if (codeUnit >= 0x30 && codeUnit <= 0x39) return codeUnit - 0x30; + if (codeUnit >= 0x61 && codeUnit <= 0x66) return codeUnit - 0x61 + 10; + if (codeUnit >= 0x41 && codeUnit <= 0x46) return codeUnit - 0x41 + 10; + return null; +} diff --git a/lib/utils/contact_qr_frame.dart b/lib/utils/contact_qr_frame.dart new file mode 100644 index 00000000..26492e76 --- /dev/null +++ b/lib/utils/contact_qr_frame.dart @@ -0,0 +1,77 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import '../connector/meshcore_protocol.dart'; +import '../models/contact.dart'; +import 'contact_qr.dart'; + +/// Builds the device frame that applies [scanned]. +/// +/// Advert blobs are replayed with `CMD_IMPORT_CONTACT`; contact cards are +/// written with `CMD_ADD_UPDATE_CONTACT`, preserving the type, flags, name, +/// route and advert timestamp of [existing] when the QR omits them. The +/// timestamp is the firmware's replay guard, so a new contact gets 0 rather +/// than the phone clock, which would make it drop the node's real adverts. A card carries no route, so a contact +/// the device does not know yet is written with the `0xFF` unknown-path +/// sentinel (`Contact.fromFrame` maps it to `hopCount == -1`) and its messages +/// flood until an advert supplies a path. +/// +/// [pathHashByteWidth] is the connector's current path-hash mode, needed to +/// re-encode a preserved path the same way the rest of the app does. +Uint8List buildContactQrFrame( + ScannedContact scanned, { + Contact? existing, + int pathHashByteWidth = 1, +}) { + if (scanned.isAdvertPacket) { + return buildImportContactFrame(scanned.advertPacket!); + } + final route = _routeOf(existing, pathHashByteWidth); + return buildUpdateContactPathFrame( + scanned.publicKey!, + route.path, + route.pathLen, + type: scanned.type ?? existing?.type ?? advTypeChat, + flags: existing?.flags ?? 0, + name: _fitName( + scanned.name.isEmpty ? (existing?.name ?? '') : scanned.name, + ), + lastAdvert: existing?.lastSeen, + ); +} + +/// Rescanning a contact must not throw away a route the device already has: +/// writing an empty path with the unknown sentinel would force flooding until +/// another advert restores it. Reuse [existing]'s path when it is valid for the +/// current mode, encoded as `MeshCoreConnector._encodePathLenForCurrentMode` +/// does (hop count in bits 0-5, mode in bits 6-7). +({Uint8List path, int pathLen}) _routeOf(Contact? existing, int width) { + final unknown = (path: Uint8List(0), pathLen: 0xFF); + if (existing == null) return unknown; + final hops = existing.pathLength; + if (hops < 0 || hops > 0x3F) return unknown; + final hashWidth = width.clamp(1, 4).toInt(); + final path = existing.path; + if (path.length > maxPathSize || path.length != hops * hashWidth) { + return unknown; + } + return (path: path, pathLen: hops | ((hashWidth - 1) << 6)); +} + +/// `writeCString` clips the encoded name to `maxNameSize - 1` bytes without +/// looking at character boundaries, which would leave a half-written rune in +/// the contact record. Drop whole characters instead. +String _fitName(String name) { + const limit = maxNameSize - 1; + if (utf8.encode(name).length <= limit) return name; + final buffer = StringBuffer(); + var used = 0; + for (final rune in name.runes) { + final char = String.fromCharCode(rune); + final charBytes = utf8.encode(char).length; + if (used + charBytes > limit) break; + buffer.write(char); + used += charBytes; + } + return buffer.toString(); +} diff --git a/lib/utils/gpx_export.dart b/lib/utils/gpx_export.dart index e3a42898..ba594ccd 100644 --- a/lib/utils/gpx_export.dart +++ b/lib/utils/gpx_export.dart @@ -7,6 +7,7 @@ import 'dart:io'; import '../utils/platform_info.dart'; import 'package:share_plus/share_plus.dart'; +import 'package:file_selector/file_selector.dart'; class ContactExport { final String name; @@ -161,7 +162,6 @@ class GpxExport { final xml = GpxWriter().asString(gpx, pretty: true); // 2. Save to file - final dir = await getApplicationDocumentsDirectory(); final timestamp = DateTime.now() .toUtc() .toIso8601String() @@ -169,8 +169,29 @@ class GpxExport { .replaceAll('.', '-') .split('T') .join('_'); + final suggestedName = '$filename$timestamp.gpx'; - final path = '${dir.path}/$filename$timestamp.gpx'; + // share_plus cannot share files on desktop: Linux throws outright + // ("Sharing files not supported on Linux") and Windows only supports it + // from build 10.0.17763 up. Desktops have a real file system and a save + // dialog, so write the file where the user asks instead of sharing it. + if (PlatformInfo.isDesktop) { + final location = await getSaveLocation( + suggestedName: suggestedName, + acceptedTypeGroups: const [ + XTypeGroup(label: 'GPX', extensions: ['gpx']), + ], + ); + if (location == null) { + debugPrint('Save dialog was dismissed / cancelled by user.'); + return gpxExportCancelled; + } + await File(location.path).writeAsString(xml); + return gpxExportSuccess; + } + + final dir = await getApplicationDocumentsDirectory(); + final path = '${dir.path}/$suggestedName'; final file = File(path); await file.writeAsString(xml); diff --git a/lib/utils/image_save.dart b/lib/utils/image_save.dart new file mode 100644 index 00000000..17a761a5 --- /dev/null +++ b/lib/utils/image_save.dart @@ -0,0 +1,43 @@ +import 'package:file_selector/file_selector.dart'; +import 'package:flutter/foundation.dart'; +import 'package:share_plus/share_plus.dart'; + +import '../services/received_image_store.dart'; +import 'platform_info.dart'; + +/// Saves a transcript image: a save dialog on desktop, the share sheet +/// elsewhere. Reconstructed images are named as such so the file never passes +/// for a photograph. Returns false on failure; a cancelled dialog is not one. +Future saveImagePng( + Uint8List png, + ReceivedImageEntry entry, { + String? shareText, +}) async { + final name = entry.synthesized + ? 'meshcore-ai-reconstructed-${entry.streamId}.png' + : 'meshcore-${entry.streamId}.png'; + final file = XFile.fromData(png, mimeType: 'image/png', name: name); + try { + if (PlatformInfo.isDesktop) { + final location = await getSaveLocation( + suggestedName: name, + acceptedTypeGroups: const [ + XTypeGroup(label: 'PNG', extensions: ['png']), + ], + ); + if (location != null) await file.saveTo(location.path); + return true; + } + final result = await SharePlus.instance.share( + ShareParams( + files: [file], + fileNameOverrides: [name], + text: entry.synthesized ? shareText : null, + ), + ); + return result.status != ShareResultStatus.unavailable; + } catch (e) { + debugPrint('image save failed: $e'); + return false; + } +} diff --git a/lib/utils/keys.dart b/lib/utils/keys.dart new file mode 100644 index 00000000..488223f7 --- /dev/null +++ b/lib/utils/keys.dart @@ -0,0 +1,87 @@ +import 'dart:async'; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:convert/convert.dart'; +import 'package:cryptography/cryptography.dart'; + +Uint8List randomBytes(int length) { + final random = Random.secure(); + final bytes = Uint8List(length); + for (int i = 0; i < length; i++) { + bytes[i] = random.nextInt(256); + } + return bytes; +} + +class MCKeyPair { + final Uint8List public; + final Uint8List private; + MCKeyPair(this.public, this.private); +} + +Future generateKeyPair() async { + final algo = Ed25519(); + final seed = randomBytes(32); + final SimpleKeyPair keys = await algo.newKeyPairFromSeed(seed); + final Uint8List pubKeyBytes = Uint8List.fromList( + (await keys.extractPublicKey()).bytes, + ); + // Ed25519 gives 32-byte public and private keys, but MeshCore + // uses an expanded 64-byte private key, so we have to make it + // ourselves. Luckily, we can do it such that it has the same public + // key, which we'd otherwise be unable to compute, since although the + // crypto library implements the elliptic curve computations we need, + // it doesn't make them available. + final Uint8List hash = Uint8List.fromList((await Sha512().hash(seed)).bytes); + hash[0] &= 248; // Clamp the scalar. This keeps the chosen point in the + hash[31] &= 63; // large elliptic curve subgroup, and is demanded both by + hash[31] |= 64; // Ed25519 and by the MeshCore repeater key validation code. + return MCKeyPair(pubKeyBytes, hash); +} + +class _KeyHashPrefix { + Uint8List _bytes = Uint8List(0); + Uint8List _mask = Uint8List(0); + _KeyHashPrefix(String prefix) { + final bool lengthIsOdd = (prefix.length % 2 == 1) ? true : false; + final String decodableString = lengthIsOdd ? "${prefix}0" : prefix; + _bytes = hex.decoder.convert(decodableString); + _mask = Uint8List(_bytes.length); + for (var i = 0; i < _mask.length; i++) { + _mask[i] = 0xff; + } + if (lengthIsOdd) { + _mask[_mask.length - 1] = 0xf0; + } + } + + bool matches(List keyBytes) { + if (keyBytes.length < _bytes.length) { + return false; + } + for (var i = 0; i < _bytes.length; i++) { + if (keyBytes[i] & _mask[i] != _bytes[i]) { + return false; + } + } + return true; + } +} + +class KeyPairSearcher { + Future findMatchingKeyPair( + String prefixStr, + int maxMilliseconds, + ) async { + final int now = DateTime.now().millisecondsSinceEpoch; + final int endTime = now + maxMilliseconds; + final _KeyHashPrefix keyHashPrefix = _KeyHashPrefix(prefixStr); + while (DateTime.now().millisecondsSinceEpoch < endTime) { + final MCKeyPair keys = await generateKeyPair(); + if (keyHashPrefix.matches(keys.public)) { + return keys; + } + } + return null; + } +} diff --git a/lib/utils/lora_airtime.dart b/lib/utils/lora_airtime.dart new file mode 100644 index 00000000..0cf83509 --- /dev/null +++ b/lib/utils/lora_airtime.dart @@ -0,0 +1,418 @@ +import 'dart:math' as math; + +import '../models/radio_settings.dart'; +// image_chunk_transport is the single source of truth for chunk geometry: it is +// what actually writes the bytes. This file used to declare rival constants +// (payload 163 / header 2), which both disagreed with the wire format AND +// collided by name -- any library importing both failed to compile. Import and +// re-export instead, so there is exactly one declaration in the program. +import '../services/image_chunk_transport.dart' + show + imageDataChunkCount, + kImageChunkBlobBytes, + kImageChunkCapacity, + kImageChunkFirstCapacity, + kImageChunkHeaderBytes, + kImageChunkZeroMetadataBytes; + +export '../services/image_chunk_transport.dart' + show + imageDataChunkCount, + kImageChunkBlobBytes, + kImageChunkBodyBytes, + kImageChunkCapacity, + kImageChunkFirstCapacity, + kImageChunkHeaderBytes, + kImageChunkZeroMetadataBytes, + kImageParityLengthBytes; + +/// Extra on-air bytes added by the MeshCore transport/routing header around a +/// GRP_DATA packet. +/// +/// This value is NOT derivable from this repository, so it defaults to 0 and +/// the resulting airtime is therefore a lower bound for the chunk frame itself +/// (header + payload). Callers may pass a measured value to +/// [estimateSend] once the real overhead is known. Do not guess it here. +const int kMeshCoreOnAirOverheadBytes = 0; + +/// MeshCore MAX_TRANS_UNIT — the largest packet that can go on air. +/// Useful as a worst-case airtime reference. +const int kMeshCoreMaxTransUnit = 255; + +/// Standard LoRa time-on-air. +/// +/// ## Relationship to `connector/meshcore_protocol.dart:calculateLoRaAirtime()` +/// +/// That function exists and is used for *retry timeouts*; it is deliberately NOT +/// reused here, and the two must not be conflated: +/// +/// * **Coding-rate domain.** `calculateLoRaAirtime()` takes the coding rate in +/// the firmware's 1..4 domain and computes `(codingRate + 4)` internally. +/// This file takes it in the 5..8 domain, matching [LoRaCodingRate.value] +/// (`cr4_5 == 5`). A raw device value may arrive in *either* domain, so +/// [normalizeCodingRate] maps 1..4 -> 5..8 before use. Passing a 5..8 value +/// to `calculateLoRaAirtime()` would silently overstate airtime by up to 60% +/// (it would compute CR 4/9..4/12), and passing a 1..4 value to +/// [loraTimeOnAir] trips its assert in debug and understates airtime in +/// release. Always normalise at the boundary. +/// * **Low-data-rate optimise.** `DE` is derived from `Tsym > 16 ms` (the +/// RadioLib rule), not the `sf >= 11` shortcut, which is wrong for +/// SF11/BW250 and SF12/BW500 (Tsym is 8.192 ms there). See the LDRO tests +/// in `test/lora_airtime_test.dart`. +/// * **Preamble.** Defaults to the firmware's per-SF length, see +/// [meshCorePreambleSymbols]. +/// * **Precision and guards.** `calculateLoRaAirtime()` returns whole +/// milliseconds and will throw `Unsupported operation: Infinity or NaN +/// toInt` on `sf == 0` / `bw == 0`, which a half-initialised device does +/// report. This file keeps microseconds (2 packets x rounding is visible in +/// a 1-2 s figure) and forces callers through [areLoRaParamsValid]. +/// +/// The *flood cost* model in `calculateMessageTimeout()` — `500 ms + 16 x +/// airtime` — is a retry deadline, i.e. a deliberate upper bound on when a reply +/// could still arrive. It is not a wall-clock estimate and is not reused as one; +/// see [kImageSendChunkGapBase] for the pacing model this file uses instead. +/// +/// Tsym = 2^SF / BW +/// lowDataRateOptimize (DE) = 1 if Tsym > 16 ms else 0 +/// payloadSymbols = max(ceil((8*PL - 4*SF + 28 + 16*CRC - 20*IH) +/// / (4*(SF - 2*DE))) * (CR + 4), 0) +/// ToA = (preamble + 4.25) * Tsym + (8 + payloadSymbols) * Tsym +/// +/// [codingRate] is given in the 5..8 domain (5 = 4/5 … 8 = 4/8), matching +/// [LoRaCodingRate.value]. If you hold a raw firmware coding rate, normalise it +/// with [normalizeCodingRate] first. +/// +/// The result is returned at microsecond precision; no rounding to whole +/// milliseconds is applied. +Duration loraTimeOnAir({ + required int payloadBytes, + required int spreadingFactor, + required int bandwidthHz, + required int codingRate, + int? preambleSymbols, + bool crc = true, + bool explicitHeader = true, +}) { + assert(spreadingFactor >= 5 && spreadingFactor <= 12); + assert(bandwidthHz > 0); + assert(codingRate >= 5 && codingRate <= 8); + + final pl = math.max(payloadBytes, 0); + final sf = spreadingFactor; + + // Symbol time in milliseconds. + final tsymMs = (1 << sf) / (bandwidthHz / 1000.0); + + // Low data rate optimisation is mandated when a symbol lasts over 16 ms. + final de = tsymMs > 16.0 ? 1 : 0; + final ih = explicitHeader ? 0 : 1; + + final numerator = 8 * pl - 4 * sf + 28 + 16 * (crc ? 1 : 0) - 20 * ih; + final denominator = 4 * (sf - 2 * de); + + final payloadSymbols = math.max( + (numerator / denominator).ceil() * codingRate, + 0, + ); + + final preamble = preambleSymbols ?? meshCorePreambleSymbols(sf); + final preambleMs = (preamble + 4.25) * tsymMs; + final payloadMs = (8 + payloadSymbols) * tsymMs; + + return Duration(microseconds: ((preambleMs + payloadMs) * 1000).round()); +} + +/// Preamble length MeshCore firmware configures for [spreadingFactor] +/// (`RadioLibWrapper::preambleLengthForSF`): 32 symbols up to SF8, 16 above. +int meshCorePreambleSymbols(int spreadingFactor) => + spreadingFactor <= 8 ? 32 : 16; + +/// Normalises a raw firmware coding rate into the 5..8 domain used by +/// [loraTimeOnAir] and [LoRaCodingRate.value]. Some firmwares report 1..4. +int normalizeCodingRate(int deviceCodingRate) => + deviceCodingRate <= 4 ? deviceCodingRate + 4 : deviceCodingRate; + +/// Whether [loraTimeOnAir] can safely be called with these parameters. +/// +/// The radio values reaching us are raw bytes off the wire (`currentSf`, +/// `currentBwHz`, `currentCr`), so a disconnected or half-initialised device +/// can hand us zeroes. Those are not merely wrong, they are fatal: `sf == 0` +/// drives the `4 * (SF - 2*DE)` denominator to zero and the subsequent +/// `.ceil()` throws "Unsupported operation: Infinity or NaN toInt", and +/// `bandwidthHz == 0` makes the symbol time infinite. Asserts alone do not help +/// in release builds, so callers must gate on this. +/// +/// [codingRate] is checked in the 5..8 domain; normalise first. +bool areLoRaParamsValid({ + required int? spreadingFactor, + required int? bandwidthHz, + required int? codingRate, +}) { + if (spreadingFactor == null || bandwidthHz == null || codingRate == null) { + return false; + } + if (spreadingFactor < 5 || spreadingFactor > 12) return false; + if (bandwidthHz <= 0) return false; + if (codingRate < 5 || codingRate > 8) return false; + return true; +} + +/// Fixed part of the gap the sender must leave between two chunk packets. +/// +/// Raw airtime is only the time our own transmitter is modulating. A multi-chunk +/// image is paced: the app hands chunk *i+1* to the companion radio only after +/// chunk *i* has been queued, transmitted and the local channel has cleared, so +/// wall clock is substantially longer than the sum of the airtimes. Two numbers +/// in this repository bound that gap: +/// +/// * `connector/meshcore_protocol.dart:calculateMessageTimeout()` uses a +/// **500 ms base delay** for "the companion radio has dealt with this +/// packet", independent of airtime. That is where this constant comes from. +/// * MeshCore repeaters default to a flood retransmit spacing of **0.5 x +/// airtime** (see `repeater_txDelayHelper`), and a packet is retransmitted by +/// every repeater in range, so at least one full airtime of quiet is needed +/// before the next chunk to avoid colliding with the first hop. That is +/// [kImageSendChunkGapAirtimeFactor]. +/// +/// This is a MODEL, not a measurement: confirming it needs real radios, which is +/// out of scope here. It is deliberately derived from numbers already shipped in +/// this app rather than invented, and it is applied only *between* packets, so a +/// single-chunk send shows raw airtime unchanged. +const Duration kImageSendChunkGapBase = Duration(milliseconds: 500); + +/// Airtime-proportional part of the inter-chunk gap. See +/// [kImageSendChunkGapBase]. +const double kImageSendChunkGapAirtimeFactor = 1.0; + +/// The pacing gap left after transmitting a packet whose airtime is +/// [packetAirtime], before the next chunk is queued. +Duration imageSendChunkGap(Duration packetAirtime) => Duration( + microseconds: + kImageSendChunkGapBase.inMicroseconds + + (packetAirtime.inMicroseconds * kImageSendChunkGapAirtimeFactor).round(), +); + +/// Result of estimating an image (or any chunked payload) send. +/// +/// [perPacketAirtime] and [totalAirtime] are null when the radio parameters are +/// unknown — in that case the packet count is still meaningful and should be +/// shown, but no airtime may be fabricated. +class SendEstimate { + /// Number of packets that will be transmitted, including the parity packet + /// when [includesParity] is true. + final int chunkCount; + + /// Total on-air bytes across all packets (chunk headers + payload + any + /// configured transport overhead), including the parity packet. + final int totalBytes; + + /// Airtime of one maximally-filled chunk packet, or null if the radio + /// parameters are unknown. + final Duration? perPacketAirtime; + + /// Sum of the airtime of every packet actually sent, or null if the radio + /// parameters are unknown. + /// + /// This is transmitter occupancy only. For anything the user is asked to wait + /// for, show [pacedWallClock] instead. + final Duration? totalAirtime; + + /// Realistic wall clock for the whole send: [totalAirtime] plus the + /// inter-chunk pacing gap ([imageSendChunkGap]) after every packet but the + /// last. Null exactly when [totalAirtime] is null. + /// + /// Equal to [totalAirtime] for a single-packet send. + final Duration? pacedWallClock; + + /// Whether a XOR parity packet is included in [chunkCount] / [totalBytes]. + final bool includesParity; + + const SendEstimate({ + required this.chunkCount, + required this.totalBytes, + required this.perPacketAirtime, + required this.totalAirtime, + required this.pacedWallClock, + required this.includesParity, + }); + + /// True when airtime could be computed (radio parameters were known). + bool get hasAirtime => totalAirtime != null; + + @override + String toString() => + 'SendEstimate(chunks: $chunkCount, bytes: $totalBytes, ' + 'perPacket: $perPacketAirtime, total: $totalAirtime, ' + 'wallClock: $pacedWallClock, parity: $includesParity)'; + + @override + bool operator ==(Object other) => + other is SendEstimate && + other.chunkCount == chunkCount && + other.totalBytes == totalBytes && + other.perPacketAirtime == perPacketAirtime && + other.totalAirtime == totalAirtime && + other.pacedWallClock == pacedWallClock && + other.includesParity == includesParity; + + @override + int get hashCode => Object.hash( + chunkCount, + totalBytes, + perPacketAirtime, + totalAirtime, + pacedWallClock, + includesParity, + ); +} + +/// Number of data chunks needed for [payloadBytes], excluding parity. +/// +/// Delegates to the transport so the estimate shown in the preview can never +/// disagree with what the chunker actually emits. Differs from +/// [imageDataChunkCount] in one respect only: a zero-byte payload needs zero +/// chunks here (there is nothing to estimate), whereas the transport still +/// emits one chunk so a receiver can observe an empty image. +int imageChunkCount(int payloadBytes) { + if (payloadBytes <= 0) return 0; + return imageDataChunkCount(payloadBytes); +} + +/// Payload bytes carried by each data chunk, in order. +List imageChunkPayloadSizes(int payloadBytes) { + final count = imageChunkCount(payloadBytes); + if (count == 0) return const []; + final sizes = []; + var remaining = payloadBytes; + for (var i = 0; i < count; i++) { + final capacity = i == 0 ? kImageChunkFirstCapacity : kImageChunkCapacity; + final take = remaining < capacity ? remaining : capacity; + sizes.add(take); + remaining -= take; + } + return sizes; +} + +/// Estimates packet count and airtime for sending [payloadBytes] of chunked +/// image data. +/// +/// [radio] may be null (radio settings not yet read from the device). In that +/// case the packet count and byte totals are still returned but both airtime +/// fields are null — no default SF/BW is substituted, because a fabricated ETA +/// is worse than none for a feature whose purpose is informed consent. +/// +/// [parity] adds exactly one XOR parity packet (GRP_DATA is unacknowledged, so +/// parity allows recovery of a single lost chunk). No parity packet is added +/// for an empty payload. +SendEstimate estimateSend({ + required int payloadBytes, + required RadioSettings? radio, + bool parity = true, + int onAirOverheadBytes = kMeshCoreOnAirOverheadBytes, +}) { + return estimateSendFromRadioParams( + payloadBytes: payloadBytes, + spreadingFactor: radio?.spreadingFactor.value, + bandwidthHz: radio?.bandwidth.hz, + codingRate: radio?.codingRate.value, + parity: parity, + onAirOverheadBytes: onAirOverheadBytes, + ); +} + +/// Same as [estimateSend] but takes the raw, individually-nullable radio +/// parameters exposed by the connector (`currentSf`, `currentBwHz`, +/// `currentCr`). [codingRate] may be in either the 1..4 or 5..8 firmware +/// encoding; it is normalised via [normalizeCodingRate]. +SendEstimate estimateSendFromRadioParams({ + required int payloadBytes, + required int? spreadingFactor, + required int? bandwidthHz, + required int? codingRate, + bool parity = true, + int onAirOverheadBytes = kMeshCoreOnAirOverheadBytes, +}) { + final payload = math.max(payloadBytes, 0); + final sizes = imageChunkPayloadSizes(payload); + final dataChunks = sizes.length; + final withParity = parity && dataChunks > 0; + + // On-air bytes per packet: chunk header + payload (+ chunk 0 metadata) + // + any transport overhead. + // On-air blob layout, taken from buildImageChunks() rather than assumed: + // data chunk : header + body (chunk 0's body opens with metadata) + // parity : header + len byte + a FULL kImageChunkBodyBytes XOR body + // The parity-length byte belongs to the PARITY chunk only — charging it to + // every data chunk, and sizing parity from the largest data body, understated + // a 110-byte payload as 232 on-air bytes when the real total is 278. + final packetBytes = []; + for (var i = 0; i < sizes.length; i++) { + final meta = i == 0 ? kImageChunkZeroMetadataBytes : 0; + packetBytes.add( + kImageChunkHeaderBytes + meta + sizes[i] + onAirOverheadBytes, + ); + } + if (withParity) { + // Always the full blob: the XOR body is zero-padded to kImageChunkBodyBytes + // regardless of how short the data chunks are. + packetBytes.add(kImageChunkBlobBytes + onAirOverheadBytes); + } + + final totalBytes = packetBytes.fold(0, (a, b) => a + b); + final chunkCount = packetBytes.length; + + // Only non-null AND in-range parameters are safe: see [areLoRaParamsValid]. + // Anything else yields an estimate with packet counts but no airtime, which + // the UI must render as "unknown" rather than fabricating a number. + final cr = codingRate == null ? null : normalizeCodingRate(codingRate); + final known = areLoRaParamsValid( + spreadingFactor: spreadingFactor, + bandwidthHz: bandwidthHz, + codingRate: cr, + ); + if (!known) { + return SendEstimate( + chunkCount: chunkCount, + totalBytes: totalBytes, + perPacketAirtime: null, + totalAirtime: null, + pacedWallClock: null, + includesParity: withParity, + ); + } + + // Safe to force: areLoRaParamsValid() above proved all three are non-null + // and in range. + Duration airtimeFor(int bytes) => loraTimeOnAir( + payloadBytes: bytes, + spreadingFactor: spreadingFactor!, + bandwidthHz: bandwidthHz!, + codingRate: cr!, + ); + + // Airtime of a maximally-filled chunk packet, i.e. the cost of one "typical" + // packet in the stream. A full blob is the whole kImageChunkBlobBytes. + final perPacket = airtimeFor(kImageChunkBlobBytes + onAirOverheadBytes); + + var totalMicros = 0; + // Wall clock adds a pacing gap after every packet except the last, so a + // single-packet send is unaffected. See [kImageSendChunkGapBase]. + var wallClockMicros = 0; + for (var i = 0; i < packetBytes.length; i++) { + final airtime = airtimeFor(packetBytes[i]); + totalMicros += airtime.inMicroseconds; + wallClockMicros += airtime.inMicroseconds; + if (i != packetBytes.length - 1) { + wallClockMicros += imageSendChunkGap(airtime).inMicroseconds; + } + } + + return SendEstimate( + chunkCount: chunkCount, + totalBytes: totalBytes, + perPacketAirtime: perPacket, + totalAirtime: Duration(microseconds: totalMicros), + pacedWallClock: Duration(microseconds: wallClockMicros), + includesParity: withParity, + ); +} diff --git a/lib/utils/route_transitions.dart b/lib/utils/route_transitions.dart index 7de5a9c5..2d68bbdf 100644 --- a/lib/utils/route_transitions.dart +++ b/lib/utils/route_transitions.dart @@ -6,20 +6,15 @@ Route buildQuickSwitchRoute(Widget page) { transitionDuration: const Duration(milliseconds: 220), reverseTransitionDuration: const Duration(milliseconds: 200), transitionsBuilder: (context, animation, secondaryAnimation, child) { - final curved = CurvedAnimation( - parent: animation, - curve: Curves.easeOutCubic, - reverseCurve: Curves.easeInCubic, - ); + // Pure crossfade — no positional slide, so the shared top chrome + // (app bar + Contacts/Channels toggle) stays rock-steady while switching. return FadeTransition( - opacity: curved, - child: SlideTransition( - position: Tween( - begin: const Offset(0.02, 0), - end: Offset.zero, - ).animate(curved), - child: child, + opacity: CurvedAnimation( + parent: animation, + curve: Curves.easeOut, + reverseCurve: Curves.easeIn, ), + child: child, ); }, ); diff --git a/lib/widgets/byte_count_input.dart b/lib/widgets/byte_count_input.dart index 91f638b8..19356e85 100644 --- a/lib/widgets/byte_count_input.dart +++ b/lib/widgets/byte_count_input.dart @@ -54,6 +54,11 @@ class ByteCountedTextField extends StatelessWidget { /// If provided, byte limits and counters will use the encoded text length. final String Function(String)? encoder; + /// Optional byte count above which [softLimitNote] is shown next to the + /// counter (the text is still allowed up to [maxBytes]). + final int? softLimitBytes; + final String? softLimitNote; + const ByteCountedTextField({ super.key, required this.maxBytes, @@ -69,6 +74,8 @@ class ByteCountedTextField extends StatelessWidget { this.errorThreshold = 0.9, this.hideCounterWhenEmpty = true, this.encoder, + this.softLimitBytes, + this.softLimitNote, }); @override @@ -82,6 +89,10 @@ class ByteCountedTextField extends StatelessWidget { final usedBytes = utf8.encode(effectiveText).length; final ratio = maxBytes > 0 ? usedBytes / maxBytes : 0.0; final showCounter = !(hideCounterWhenEmpty && value.text.isEmpty); + final showSoftLimitNote = + softLimitNote != null && + softLimitBytes != null && + usedBytes > softLimitBytes!; final counterColor = ratio > errorThreshold ? Theme.of(context).colorScheme.error @@ -122,12 +133,25 @@ class ByteCountedTextField extends StatelessWidget { opacity: showCounter ? 1 : 0, child: Padding( padding: const EdgeInsets.only(top: 4, right: 4), - child: Align( - alignment: Alignment.centerRight, - child: Text( - '$usedBytes / $maxBytes', - style: TextStyle(fontSize: 11, color: counterColor), - ), + child: Row( + children: [ + Expanded( + child: showSoftLimitNote + ? Text( + softLimitNote!, + style: TextStyle( + fontSize: 11, + color: Theme.of(context).colorScheme.tertiary, + ), + ) + : const SizedBox.shrink(), + ), + const SizedBox(width: 8), + Text( + '$usedBytes / $maxBytes', + style: TextStyle(fontSize: 11, color: counterColor), + ), + ], ), ), ), diff --git a/lib/widgets/chat_day_separator.dart b/lib/widgets/chat_day_separator.dart new file mode 100644 index 00000000..292af8d6 --- /dev/null +++ b/lib/widgets/chat_day_separator.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../l10n/l10n.dart'; +import '../theme/mesh_theme.dart'; + +bool isSameChatDay(DateTime a, DateTime b) { + final la = a.toLocal(); + final lb = b.toLocal(); + return la.year == lb.year && la.month == lb.month && la.day == lb.day; +} + +final Map<(String, bool), DateFormat> _timeFormats = {}; + +String formatChatTime(BuildContext context, DateTime time) { + final locale = Localizations.localeOf(context).toString(); + final use24h = MediaQuery.alwaysUse24HourFormatOf(context); + final format = _timeFormats.putIfAbsent(( + locale, + use24h, + ), () => use24h ? DateFormat.Hm(locale) : DateFormat.jm(locale)); + return format.format(time.toLocal()); +} + +String formatChatDayLabel(BuildContext context, DateTime time) { + final now = DateTime.now(); + if (isSameChatDay(time, now)) return context.l10n.chat_today; + final yesterday = DateTime(now.year, now.month, now.day - 1); + if (isSameChatDay(time, yesterday)) return context.l10n.chat_yesterday; + final locale = Localizations.localeOf(context).toString(); + return DateFormat.yMMMd(locale).format(time.toLocal()); +} + +class ChatDaySeparator extends StatelessWidget { + final DateTime day; + + const ChatDaySeparator({super.key, required this.day}); + + @override + Widget build(BuildContext context) { + final color = Theme.of(context).colorScheme.onSurfaceVariant; + final line = Expanded( + child: Container(height: 1, color: color.withValues(alpha: 0.2)), + ); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + children: [ + line, + const SizedBox(width: 10), + Text( + formatChatDayLabel(context, day), + style: MeshTheme.mono( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: color, + ), + ), + const SizedBox(width: 10), + line, + ], + ), + ); + } +} diff --git a/lib/widgets/elements_ui.dart b/lib/widgets/elements_ui.dart index a4995c73..f77b90a6 100644 --- a/lib/widgets/elements_ui.dart +++ b/lib/widgets/elements_ui.dart @@ -4,6 +4,7 @@ class FeatureToggleRow extends StatefulWidget { final String title; final String subtitle; final bool value; + final bool enabled; final bool hasRefreshing; final bool isRefreshing; final ValueChanged? onChanged; @@ -15,6 +16,7 @@ class FeatureToggleRow extends StatefulWidget { required this.title, required this.subtitle, required this.value, + this.enabled = true, this.hasRefreshing = false, this.isRefreshing = false, this.onChanged, @@ -31,6 +33,13 @@ class _FeatureToggleRow extends State { Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; + final isEnabled = widget.enabled; + final titleColor = isEnabled + ? scheme.onSurface + : scheme.onSurfaceVariant.withValues(alpha: 0.7); + final subtitleColor = isEnabled + ? scheme.onSurfaceVariant + : scheme.onSurfaceVariant.withValues(alpha: 0.55); return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), @@ -44,14 +53,13 @@ class _FeatureToggleRow extends State { widget.title, style: textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w600, + color: titleColor, ), ), const SizedBox(height: 2), Text( widget.subtitle, - style: textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), + style: textTheme.bodySmall?.copyWith(color: subtitleColor), ), ], ), @@ -60,7 +68,18 @@ class _FeatureToggleRow extends State { Row( mainAxisSize: MainAxisSize.min, children: [ - Switch(value: widget.value, onChanged: widget.onChanged), + Switch( + value: widget.value, + onChanged: isEnabled ? widget.onChanged : null, + thumbColor: !isEnabled + ? WidgetStatePropertyAll(scheme.onSurfaceVariant) + : null, + trackColor: !isEnabled + ? WidgetStatePropertyAll( + scheme.onSurfaceVariant.withValues(alpha: 0.35), + ) + : null, + ), if (widget.hasRefreshing) ...[ const SizedBox(width: 4), widget.isRefreshing @@ -74,7 +93,7 @@ class _FeatureToggleRow extends State { ) : IconButton( icon: const Icon(Icons.refresh, size: 18), - onPressed: widget.onRefresh, + onPressed: isEnabled ? widget.onRefresh : null, tooltip: widget.refreshTooltip, visualDensity: VisualDensity.compact, padding: EdgeInsets.zero, diff --git a/lib/widgets/emoji_picker.dart b/lib/widgets/emoji_picker.dart index 3a8fdf79..ab5c4edd 100644 --- a/lib/widgets/emoji_picker.dart +++ b/lib/widgets/emoji_picker.dart @@ -232,6 +232,7 @@ class EmojiPicker extends StatelessWidget { ), IconButton( icon: const Icon(Icons.close), + tooltip: l10n.common_close, onPressed: () => Navigator.pop(context), ), ], diff --git a/lib/widgets/gif_picker.dart b/lib/widgets/gif_picker.dart index 90b6261b..5205143d 100644 --- a/lib/widgets/gif_picker.dart +++ b/lib/widgets/gif_picker.dart @@ -136,6 +136,7 @@ class _GifPickerState extends State { const Spacer(), IconButton( icon: const Icon(Icons.close), + tooltip: context.l10n.common_close, onPressed: () => Navigator.pop(context), ), ], @@ -151,6 +152,7 @@ class _GifPickerState extends State { suffixIcon: _searchController.text.isNotEmpty ? IconButton( icon: const Icon(Icons.clear), + tooltip: context.l10n.common_clearSearch, onPressed: () { _searchController.clear(); _loadTrendingGifs(); diff --git a/lib/widgets/image_send_codec_binding.dart b/lib/widgets/image_send_codec_binding.dart new file mode 100644 index 00000000..fe99a99b --- /dev/null +++ b/lib/widgets/image_send_codec_binding.dart @@ -0,0 +1,167 @@ +import 'dart:typed_data'; + +/// Minimal, dependency-free abstraction over the neural image codec used by +/// [ImageSendPreviewSheet]. +/// +/// The real implementation lives in `lib/services/image_codec_service.dart` +/// (`ImageCodecService implements ImageSendCodec`) and +/// `lib/services/image_chunk_transport.dart`. This file deliberately does NOT +/// import them, so the preview sheet can be built, analyzed and previewed on +/// its own and so the service depends on the UI contract rather than the other +/// way round. +/// +// Packet-count and airtime maths deliberately live in +// `lib/utils/lora_airtime.dart`, not here. + +/// Hard minimum resolution for the codec. Images are centre-cropped to this +/// square before encoding; the decoder collapses below it. +const int kImageCodecSquareSize = 512; + +/// Availability of the image codec, as far as the UI is concerned. +enum ImageCodecAvailability { + /// The feature is switched off in app settings. + disabled, + + /// The codec model is being fetched; the feature is temporarily unusable. + downloading, + + /// The codec is usable right now. + ready, + + /// The codec cannot run on this device/platform at all. + unavailable, +} + +/// Rate points the wire format can express. +/// +/// The shipping build encodes at [standard] (`ft32`) only — see +/// [kImageSendRatePoint]. The enum keeps more than one value because the rate +/// point is written into the chunk-0 metadata byte by +/// `image_chunk_transport.dart`, so the ordinals are part of the wire format and +/// must stay stable even for rate points the UI never offers. Removing [high] +/// would renumber nothing today but would make a future rate point silently +/// reuse ordinal 1 and be decoded as ft16 by older builds. +enum ImageCodecRatePoint { + /// `ft32` — the only rate point this build sends. Measured 110-209 B + /// (mean 156 B) over 26 images, i.e. 1-2 data chunks plus parity. + standard, + + /// `ft16` — larger, higher fidelity. **Not offered in the UI**: the model + /// registry ships ft32 weights only. Retained so the ordinal stays reserved + /// and so bitstreams produced elsewhere can still be identified on the wire. + high, +} + +/// The single rate point the compose UI encodes at. +/// +/// The quality selector was removed once ft32 became the only shipping model; +/// every send goes out at this rate. Named rather than inlined so a future +/// second rate point has one place to come back to. +const ImageCodecRatePoint kImageSendRatePoint = ImageCodecRatePoint.standard; + +/// Measured payload statistics for a rate point, in bytes. +/// +/// These are real measurements over 26 images of rANS bitstreams produced by +/// the codec at 512x512, not estimates. They let the sheet show a plausible +/// range instantly, before an encode has finished. +class ImageCodecRateStats { + final int meanBytes; + final int minBytes; + final int maxBytes; + + const ImageCodecRateStats({ + required this.meanBytes, + required this.minBytes, + required this.maxBytes, + }); + + static const ImageCodecRateStats standard = ImageCodecRateStats( + meanBytes: 156, + minBytes: 110, + maxBytes: 209, + ); + + /// Retained for [ImageCodecRatePoint.high], which the UI no longer offers. + static const ImageCodecRateStats high = ImageCodecRateStats( + meanBytes: 288, + minBytes: 176, + maxBytes: 409, + ); + + static ImageCodecRateStats forRate(ImageCodecRatePoint rate) { + switch (rate) { + case ImageCodecRatePoint.standard: + return standard; + case ImageCodecRatePoint.high: + return high; + } + } +} + +/// The encode interface the preview sheet consumes. +abstract class ImageSendCodec { + /// Current availability. The sheet renders a non-interactive explanation for + /// anything other than [ImageCodecAvailability.ready]. + ImageCodecAvailability get availability; + + /// Why [availability] is [ImageCodecAvailability.unavailable], as one + /// user-facing sentence, or null when the codec is not permanently + /// unavailable. + /// + /// This is the sentence the compose sheet shows in place of its generic + /// "not available on this device" string: `unavailable` is a permanent + /// property of the build (no native runtime, no entropy path, backend failed + /// to load) and the only useful thing the UI can do is say WHICH one it hit. + /// Implementations must not return an empty string; return null instead. + String? get unavailableReason; + + /// Encode [imageBytes] (any common still format) at [rate], returning the + /// compressed bitstream that will be chunked onto the air. + /// + /// Implementations are expected to centre-crop to + /// [kImageCodecSquareSize] square first. + Future encode(Uint8List imageBytes, ImageCodecRatePoint rate); + + /// Decodes [payload] to PNG exactly as a recipient would, or null when this + /// device cannot decode. + Future decodePreview(Uint8List payload); +} + +/// A deterministic stand-in used for widget previews and tests. +/// +/// It produces a buffer of the measured mean size for the requested rate point +/// so the sheet can be exercised end-to-end without the real codec. +class FakeImageSendCodec implements ImageSendCodec { + @override + final ImageCodecAvailability availability; + + /// Mirrors `ImageCodecService.unavailableReason`; null unless a test wants to + /// exercise the "why can't I send?" path. + @override + final String? unavailableReason; + + final Duration latency; + + const FakeImageSendCodec({ + this.availability = ImageCodecAvailability.ready, + this.unavailableReason, + this.latency = const Duration(milliseconds: 250), + }); + + @override + Future encode( + Uint8List imageBytes, + ImageCodecRatePoint rate, + ) async { + if (latency > Duration.zero) { + await Future.delayed(latency); + } + final size = ImageCodecRateStats.forRate(rate).meanBytes; + return Uint8List.fromList( + List.generate(size, (i) => (i * 31 + rate.index) & 0xFF), + ); + } + + @override + Future decodePreview(Uint8List payload) async => null; +} diff --git a/lib/widgets/image_send_preview_sheet.dart b/lib/widgets/image_send_preview_sheet.dart new file mode 100644 index 00000000..bcff1b42 --- /dev/null +++ b/lib/widgets/image_send_preview_sheet.dart @@ -0,0 +1,884 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../services/image_chunk_transport.dart'; +import '../utils/lora_airtime.dart'; +import 'image_send_codec_binding.dart'; + +/// Estimated wall clock above which the sheet warns the user explicitly. +const Duration kImageSendLongAirtime = Duration(seconds: 5); + +/// What the user committed to when they tapped Send. +class ImageSendPreviewResult { + /// The encoded bitstream, ready to be chunked onto the air. + final Uint8List payload; + + /// The rate point the payload was encoded at. Always [kImageSendRatePoint] in + /// this build; carried through because the transport writes it on the wire. + final ImageCodecRatePoint rate; + + /// Whether an XOR parity packet should be appended. + final bool includeParity; + + /// Packets that will actually be transmitted, parity included. + final int packetCount; + + /// Estimated transmitter occupancy, or null if the radio settings were + /// unknown. This is *not* how long the send takes — see [wallClock]. + final Duration? airtime; + + /// Estimated wall clock including per-chunk pacing — the figure the user was + /// actually shown. Null when the radio settings were unknown. + final Duration? wallClock; + + const ImageSendPreviewResult({ + required this.payload, + required this.rate, + required this.includeParity, + required this.packetCount, + required this.airtime, + required this.wallClock, + }); +} + +/// Shows the pre-send image preview. +/// +/// Returns null if the user cancelled, or an [ImageSendPreviewResult] carrying +/// the encoded payload if they confirmed. The caller owns the actual send. +/// +/// [imageBytes] is the raw picked file (JPEG/PNG/…). [originalFileBytes] is its +/// on-disk size, shown against the transmitted size. +/// +/// [radio] overrides the live radio parameters; when omitted they are read from +/// the [MeshCoreConnector] in the widget tree. Pass it explicitly to preview +/// this sheet without a connector. +/// +/// There is no quality/rate argument: ft32 ([kImageSendRatePoint]) is the only +/// shipping model, so the sheet no longer offers a choice. +Future showImageSendPreviewSheet({ + required BuildContext context, + required Uint8List imageBytes, + required int originalFileBytes, + required ImageSendCodec codec, + ImageSendRadio? radio, + bool initialParity = true, +}) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + useSafeArea: true, + builder: (context) => ImageSendPreviewSheet( + imageBytes: imageBytes, + originalFileBytes: originalFileBytes, + codec: codec, + radio: radio, + initialParity: initialParity, + ), + ); +} + +class ImageSendPreviewSheet extends StatefulWidget { + final Uint8List imageBytes; + final int originalFileBytes; + final ImageSendCodec codec; + final ImageSendRadio? radio; + final bool initialParity; + + const ImageSendPreviewSheet({ + super.key, + required this.imageBytes, + required this.originalFileBytes, + required this.codec, + this.radio, + this.initialParity = true, + }); + + @override + State createState() => _ImageSendPreviewSheetState(); +} + +/// The live radio parameters, exactly as the connector exposes them: each may +/// be null before the device has reported its SELF_INFO frame. +class ImageSendRadio { + final int? spreadingFactor; + final int? bandwidthHz; + + /// Raw firmware coding rate; [estimateSendFromRadioParams] normalises it. + final int? rawCodingRate; + + const ImageSendRadio({ + this.spreadingFactor, + this.bandwidthHz, + this.rawCodingRate, + }); + + bool get isKnown => + spreadingFactor != null && bandwidthHz != null && rawCodingRate != null; +} + +/// Packet/byte/airtime figures for one rate point. +/// +/// Before an encode has finished the payload size is only known as a measured +/// range, so [best] and [worst] differ; afterwards they are identical. +class _RateEstimate { + /// Exact payload size once encoded, null while still estimating. + final int? payloadBytes; + final SendEstimate best; + final SendEstimate worst; + + const _RateEstimate({ + required this.payloadBytes, + required this.best, + required this.worst, + }); + + bool get isExact => payloadBytes != null; +} + +class _ImageSendPreviewSheetState extends State { + /// The encoded ft32 bitstream, once the encode finishes. + Uint8List? _encoded; + + late bool _parity; + bool _encoding = false; + bool _sending = false; + bool _failed = false; + + /// Latest radio params seen in build; used by [_onSend] so the confirm path + /// does not have to touch an InheritedWidget after an await. + ImageSendRadio? _radio; + + /// Source `width / height`. Recipients un-stretch the 512x512 square back to + /// this shape, so both preview views use it. + double _aspect = 1; + // The shape recipients restore: the nearest supported ratio, or square. + double _recipientAspect = 1; + + bool _showReconstruction = false; + Uint8List? _reconstruction; + bool _reconstructing = false; + bool _reconstructionUnavailable = false; + + @override + void initState() { + super.initState(); + _parity = widget.initialParity; + _probeAspect(); + if (widget.codec.availability == ImageCodecAvailability.ready) { + _encode(); + } + } + + Future _probeAspect() async { + try { + final buffer = await ui.ImmutableBuffer.fromUint8List(widget.imageBytes); + final descriptor = await ui.ImageDescriptor.encoded(buffer); + final ratio = descriptor.width / descriptor.height; + final code = + kImageAspectCodes[imageAspectCodeFor( + descriptor.width, + descriptor.height, + )]; + final recipientRatio = code[0] / code[1]; + descriptor.dispose(); + buffer.dispose(); + if (mounted && ratio.isFinite && ratio > 0) { + setState(() { + _aspect = ratio; + _recipientAspect = recipientRatio; + }); + } + } catch (_) {} + } + + Future _selectView(bool reconstruction) async { + setState(() => _showReconstruction = reconstruction); + final payload = _encoded; + if (!reconstruction || + payload == null || + _reconstruction != null || + _reconstructing) { + return; + } + setState(() => _reconstructing = true); + Uint8List? png; + try { + png = await widget.codec.decodePreview(payload); + } catch (_) { + png = null; + } + if (!mounted) return; + setState(() { + _reconstructing = false; + _reconstruction = png; + if (png == null) { + _reconstructionUnavailable = true; + _showReconstruction = false; + } + }); + } + + Future _encode() async { + final cached = _encoded; + if (cached != null) return cached; + setState(() { + _encoding = true; + _failed = false; + }); + try { + final bytes = await widget.codec.encode( + widget.imageBytes, + kImageSendRatePoint, + ); + if (!mounted) return bytes; + setState(() { + _encoded = bytes; + _encoding = false; + }); + return bytes; + } catch (_) { + if (!mounted) return null; + setState(() { + _encoding = false; + _failed = true; + }); + return null; + } + } + + ImageSendRadio _radioParams(BuildContext context) { + final override = widget.radio; + if (override != null) return override; + final connector = context.watch(); + return ImageSendRadio( + spreadingFactor: connector.currentSf, + bandwidthHz: connector.currentBwHz, + rawCodingRate: connector.currentCr, + ); + } + + _RateEstimate _estimateFor(ImageSendRadio radio) { + final bytes = _encoded; + if (bytes != null) { + final exact = _estimate(bytes.length, radio); + return _RateEstimate( + payloadBytes: bytes.length, + best: exact, + worst: exact, + ); + } + // Nothing encoded yet: show the measured ft32 range so the user sees a + // figure immediately rather than a spinner. + final stats = ImageCodecRateStats.forRate(kImageSendRatePoint); + return _RateEstimate( + payloadBytes: null, + best: _estimate(stats.minBytes, radio), + worst: _estimate(stats.maxBytes, radio), + ); + } + + SendEstimate _estimate(int payloadBytes, ImageSendRadio radio) { + return estimateSendFromRadioParams( + payloadBytes: payloadBytes, + spreadingFactor: radio.spreadingFactor, + bandwidthHz: radio.bandwidthHz, + codingRate: radio.rawCodingRate, + parity: _parity, + ); + } + + Future _onSend() async { + setState(() => _sending = true); + final payload = await _encode(); + if (!mounted) return; + if (payload == null) { + setState(() => _sending = false); + return; + } + final radio = _radio ?? const ImageSendRadio(); + final estimate = _estimate(payload.length, radio); + Navigator.of(context).pop( + ImageSendPreviewResult( + payload: payload, + rate: kImageSendRatePoint, + includeParity: estimate.includesParity, + packetCount: estimate.chunkCount, + airtime: estimate.totalAirtime, + wallClock: estimate.pacedWallClock, + ), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final l10n = context.l10n; + final radio = _radioParams(context); + _radio = radio; + final selected = _estimateFor(radio); + final ready = widget.codec.availability == ImageCodecAvailability.ready; + + return SafeArea( + top: false, + child: DraggableScrollableSheet( + expand: false, + initialChildSize: 0.9, + minChildSize: 0.5, + maxChildSize: 0.95, + builder: (context, scrollController) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + _grabHandle(colors), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 8, 8), + child: Row( + children: [ + Expanded( + child: Text( + l10n.imageSend_title, + style: theme.textTheme.titleLarge, + ), + ), + IconButton( + icon: const Icon(Icons.close), + tooltip: l10n.imageSend_cancel, + onPressed: _sending + ? null + : () => Navigator.of(context).maybePop(), + ), + ], + ), + ), + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + children: [ + _preview(theme, colors, selected, ready), + const SizedBox(height: 16), + if (!ready) _unavailableBanner(theme, colors), + if (ready) ...[ + // Packet count and time on air lead: with the quality + // selector gone they are the only decision the user makes. + _headlineStats(theme, colors, selected), + const SizedBox(height: 16), + _sizeRow(theme, colors, selected), + const SizedBox(height: 12), + // Warnings sit directly under the figures they qualify. + ..._warnings(theme, colors, radio, selected), + const SizedBox(height: 4), + _parityTile(theme, colors), + if (_failed) ...[ + const SizedBox(height: 12), + _banner( + colors: colors, + theme: theme, + icon: Icons.error_outline, + background: colors.errorContainer, + foreground: colors.onErrorContainer, + title: l10n.imageSend_encodeFailed, + body: null, + ), + ], + ], + ], + ), + ), + _actions(theme, ready), + ], + ), + ), + ); + } + + Widget _grabHandle(ColorScheme colors) => Container( + width: 36, + height: 4, + margin: const EdgeInsets.symmetric(vertical: 12), + decoration: BoxDecoration( + color: colors.onSurfaceVariant.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(2), + ), + ); + + /// The preview is deliberately capped in height: the packet count and airtime + /// below it are the reason this screen exists and must not be pushed off the + /// first screenful by a full-width square. + Widget _preview( + ThemeData theme, + ColorScheme colors, + _RateEstimate estimate, + bool ready, + ) { + final l10n = context.l10n; + final maxSide = MediaQuery.sizeOf(context).height * 0.28; + final reconstruction = _showReconstruction ? _reconstruction : null; + return Column( + children: [ + if (ready) ...[ + SegmentedButton( + segments: [ + ButtonSegment( + value: false, + label: Text(l10n.imageSend_viewOriginal), + ), + ButtonSegment( + value: true, + label: Text(l10n.imageSend_viewReconstruction), + enabled: _encoded != null && !_reconstructionUnavailable, + ), + ], + selected: {_showReconstruction}, + onSelectionChanged: (s) => _selectView(s.first), + ), + const SizedBox(height: 12), + ], + ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxSide, maxWidth: maxSide), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: AspectRatio( + aspectRatio: reconstruction != null ? _recipientAspect : _aspect, + child: Container( + color: colors.surfaceContainerHighest, + child: _showReconstruction && _reconstructing + ? const Center(child: CircularProgressIndicator()) + : Image.memory( + reconstruction ?? widget.imageBytes, + // The reconstruction is the stretched square; fill + // undoes the stretch into the recipient's shape. + fit: reconstruction != null + ? BoxFit.fill + : BoxFit.contain, + alignment: Alignment.center, + gaplessPlayback: true, + errorBuilder: (context, error, stack) => Center( + child: Icon( + Icons.broken_image_outlined, + size: 48, + color: colors.onSurfaceVariant, + ), + ), + ), + ), + ), + ), + ), + if (_reconstructionUnavailable) ...[ + const SizedBox(height: 8), + Text( + l10n.imageSend_reconstructionUnavailable, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 8), + Text( + l10n.imageSend_lossyNote( + estimate.payloadBytes ?? + ImageCodecRateStats.forRate(kImageSendRatePoint).meanBytes, + ), + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + ); + } + + Widget _sizeRow(ThemeData theme, ColorScheme colors, _RateEstimate estimate) { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _sizeChip( + theme, + colors, + context.l10n.imageSend_originalSize, + _formatBytes(widget.originalFileBytes), + strikethrough: true, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Icon( + Icons.arrow_forward, + size: 18, + color: colors.onSurfaceVariant, + ), + ), + _sizeChip( + theme, + colors, + context.l10n.imageSend_onAirSize, + _onAirBytesText(estimate), + emphasised: true, + ), + ], + ); + } + + Widget _sizeChip( + ThemeData theme, + ColorScheme colors, + String label, + String value, { + bool strikethrough = false, + bool emphasised = false, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + label, + style: theme.textTheme.labelSmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + Text( + value, + style: theme.textTheme.titleMedium?.copyWith( + color: emphasised ? colors.primary : colors.onSurface, + decoration: strikethrough ? TextDecoration.lineThrough : null, + ), + ), + ], + ); + } + + /// The point of the whole screen: what this send costs, in big type. + /// + /// Only two figures, both large: the packet count and the realistic time the + /// send will take. The byte sizes moved down to [_sizeRow] — with the quality + /// selector gone there is room to give these two the whole width. + Widget _headlineStats( + ThemeData theme, + ColorScheme colors, + _RateEstimate estimate, + ) { + final localizations = context.l10n; + return Container( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 12), + decoration: BoxDecoration( + color: colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: [ + Expanded( + child: _stat( + theme, + colors, + localizations.imageSend_packetsLabel, + _packetCountText(estimate), + ), + ), + _statDivider(colors), + Expanded( + child: _stat( + theme, + colors, + localizations.imageSend_airtimeLabel, + _airtimeText(estimate), + emphasised: true, + ), + ), + ], + ), + ); + } + + Widget _statDivider(ColorScheme colors) => + Container(width: 1, height: 44, color: colors.outlineVariant); + + Widget _stat( + ThemeData theme, + ColorScheme colors, + String label, + String value, { + bool emphasised = false, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + value, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall?.copyWith( + color: emphasised ? colors.primary : colors.onSurface, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text( + label, + textAlign: TextAlign.center, + style: theme.textTheme.labelSmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + ); + } + + Widget _parityTile(ThemeData theme, ColorScheme colors) { + final localizations = context.l10n; + return SwitchListTile( + contentPadding: EdgeInsets.zero, + value: _parity, + onChanged: _sending ? null : (v) => setState(() => _parity = v), + secondary: const Icon(Icons.shield_outlined, size: 20), + title: Text(localizations.imageSend_parityTitle), + subtitle: Text( + localizations.imageSend_paritySubtitle, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ); + } + + List _warnings( + ThemeData theme, + ColorScheme colors, + ImageSendRadio radio, + _RateEstimate estimate, + ) { + final localizations = context.l10n; + final widgets = []; + if (!radio.isKnown) { + widgets.add( + _banner( + colors: colors, + theme: theme, + icon: Icons.settings_input_antenna, + background: colors.errorContainer, + foreground: colors.onErrorContainer, + title: localizations.imageSend_radioUnknownTitle, + body: localizations.imageSend_radioUnknownBody, + ), + ); + } else { + // Compared against the paced wall clock, not raw airtime: the warning is + // about how long the user waits, which is the figure shown above it. + final worst = estimate.worst.pacedWallClock; + if (worst != null && worst >= kImageSendLongAirtime) { + widgets.add( + _banner( + colors: colors, + theme: theme, + icon: Icons.hourglass_bottom, + background: colors.tertiaryContainer, + foreground: colors.onTertiaryContainer, + title: localizations.imageSend_longSendTitle, + body: localizations.imageSend_longSendBody(_formatDuration(worst)), + ), + ); + } + widgets.add(const SizedBox(height: 8)); + widgets.add( + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.hub_outlined, size: 16, color: colors.onSurfaceVariant), + const SizedBox(width: 8), + Expanded( + child: Text( + localizations.imageSend_floodNote, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ), + ], + ), + ); + } + return widgets; + } + + /// The "why can't I send?" banner. + /// + /// For [ImageCodecAvailability.unavailable] the generic localised string says + /// only that the codec cannot run, which leaves the user with no idea whether + /// to wait, download something, or give up. The codec knows exactly which + /// permanent property of the build it hit, so + /// [ImageSendCodec.unavailableReason] REPLACES the generic string whenever it + /// is non-empty. It falls back to the localised generic only when the codec + /// declined to say why. + Widget _unavailableBanner(ThemeData theme, ColorScheme colors) { + final localizations = context.l10n; + final String message; + switch (widget.codec.availability) { + case ImageCodecAvailability.disabled: + message = localizations.imageSend_codecDisabled; + break; + case ImageCodecAvailability.downloading: + message = localizations.imageSend_codecDownloading; + break; + case ImageCodecAvailability.unavailable: + final reason = widget.codec.unavailableReason?.trim(); + message = (reason == null || reason.isEmpty) + ? localizations.imageSend_codecUnavailable + : reason; + break; + case ImageCodecAvailability.ready: + return const SizedBox.shrink(); + } + return _banner( + colors: colors, + theme: theme, + icon: Icons.info_outline, + background: colors.surfaceContainerHighest, + foreground: colors.onSurfaceVariant, + title: message, + body: null, + ); + } + + Widget _banner({ + required ColorScheme colors, + required ThemeData theme, + required IconData icon, + required Color background, + required Color foreground, + required String title, + required String? body, + }) { + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 20, color: foreground), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: theme.textTheme.titleSmall?.copyWith( + color: foreground, + ), + ), + if (body != null) ...[ + const SizedBox(height: 2), + Text( + body, + style: theme.textTheme.bodySmall?.copyWith( + color: foreground, + ), + ), + ], + ], + ), + ), + ], + ), + ); + } + + Widget _actions(ThemeData theme, bool ready) { + final localizations = context.l10n; + final busy = _sending || _encoding; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: _sending + ? null + : () => Navigator.of(context).maybePop(), + child: Text(localizations.imageSend_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton.icon( + onPressed: (!ready || busy) ? null : _onSend, + icon: busy + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.send), + label: Text(localizations.imageSend_send), + ), + ), + ], + ), + ); + } + + /// Total bytes actually put on the air (headers + payload + parity). + String _onAirBytesText(_RateEstimate estimate) { + final lo = estimate.best.totalBytes; + final hi = estimate.worst.totalBytes; + if (lo == hi) return _formatBytes(lo); + return _rangeText(_formatBytes(lo), _formatBytes(hi)); + } + + /// Bare packet count, e.g. "3" or "2–3". + String _packetCountText(_RateEstimate estimate) { + final lo = estimate.best.chunkCount; + final hi = estimate.worst.chunkCount; + if (lo == hi) return '$lo'; + return _rangeText('$lo', '$hi'); + } + + /// The headline time figure. + /// + /// This is [SendEstimate.pacedWallClock], NOT raw airtime: a 2-3 packet image + /// is paced, so raw transmitter occupancy would understate the wait the user + /// is being asked to accept. Renders `imageSend_unknownValue` + /// ("—") whenever the radio parameters are unknown — areLoRaParamsValid() has + /// already forced the estimate's time fields to null in that case, and a + /// fabricated ETA is worse than none on a screen whose whole purpose is + /// informed consent. + String _airtimeText(_RateEstimate estimate) { + final l10n = context.l10n; + final min = estimate.best.pacedWallClock; + final max = estimate.worst.pacedWallClock; + if (min == null || max == null) return l10n.imageSend_unknownValue; + if (min == max) return _formatDuration(max); + return _rangeText(_formatDuration(min), _formatDuration(max)); + } + + String _rangeText(String min, String max) => + context.l10n.imageSend_range(min, max); + + String _formatDuration(Duration d) { + final l10n = context.l10n; + final totalSeconds = d.inMilliseconds / 1000.0; + if (totalSeconds < 60) { + final text = totalSeconds < 10 + ? totalSeconds.toStringAsFixed(1) + : totalSeconds.round().toString(); + return l10n.imageSend_secondsValue(text); + } + final minutes = d.inMinutes; + final seconds = d.inSeconds - minutes * 60; + return l10n.imageSend_minutesSecondsValue('$minutes', '$seconds'); + } + + String _formatBytes(int bytes) { + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} kB'; + return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + } +} diff --git a/lib/widgets/mesh_ui.dart b/lib/widgets/mesh_ui.dart index cb4698bb..2943bc04 100644 --- a/lib/widgets/mesh_ui.dart +++ b/lib/widgets/mesh_ui.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../l10n/l10n.dart'; import '../theme/mesh_theme.dart'; /// MeshCore shared design kit. @@ -191,35 +192,39 @@ class StatTile extends StatelessWidget { label.toUpperCase(), style: MeshTheme.accentLabel( color: scheme.onSurfaceVariant, - fontSize: 9, + fontSize: 11, ), + maxLines: 2, overflow: TextOverflow.ellipsis, ), ), ], ), const SizedBox(height: 6), - Text.rich( - TextSpan( - text: value, - style: MeshTheme.mono( - fontSize: 17, - fontWeight: FontWeight.w600, - color: scheme.onSurface, - ), - children: [ - if (unit != null) - TextSpan( - text: ' $unit', - style: MeshTheme.mono( - fontSize: 11, - color: scheme.onSurfaceVariant, + FittedBox( + fit: BoxFit.scaleDown, + alignment: AlignmentDirectional.centerStart, + child: Text.rich( + TextSpan( + text: value, + style: MeshTheme.mono( + fontSize: 17, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + children: [ + if (unit != null) + TextSpan( + text: ' $unit', + style: MeshTheme.mono( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), ), - ), - ], + ], + ), + maxLines: 1, ), - maxLines: 1, - overflow: TextOverflow.ellipsis, ), ], ), @@ -352,11 +357,14 @@ class RouteChip extends StatelessWidget { @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - final label = isDirect - ? (hops == null || hops == 0 - ? 'DIRECT' - : '$hops HOP${hops == 1 ? '' : 'S'}') - : 'FLOOD'; + final l10n = context.l10n; + final label = + (isDirect + ? (hops == null || hops == 0 + ? l10n.chat_direct + : l10n.chat_hopsCount(hops!)) + : l10n.routing_modeFlood) + .toUpperCase(); return Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( @@ -518,6 +526,7 @@ class BottomSheetHeader extends StatelessWidget { ?trailing, IconButton( icon: const Icon(Icons.close, size: 20), + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, onPressed: () => Navigator.of(context).maybePop(), ), ], diff --git a/lib/widgets/message_status_icon.dart b/lib/widgets/message_status_icon.dart index c1971c15..d52e93d0 100644 --- a/lib/widgets/message_status_icon.dart +++ b/lib/widgets/message_status_icon.dart @@ -8,7 +8,19 @@ class MessageStatusIcon extends StatefulWidget { final bool isAcked; final bool isFailed; final bool isPending; - final bool isRepeated; + + /// Channel messages have no delivery ACK. Instead of a delivered tick they + /// show how many times the mesh was heard repeating the message. + final bool isChannel; + final int repeatCount; + + /// While the app is resending a channel message to reach more repeaters: + /// how many resends so far and the limit. + final ({int resends, int maxResends})? resendProgress; + + /// Set when resending gave up before the message was heard through the + /// required number of repeaters. + final ({int hops, int required})? hopShortfall; final double size; /// Base tint for the sent/sending state. On a colored (outgoing) bubble a @@ -21,8 +33,11 @@ class MessageStatusIcon extends StatefulWidget { required this.isAcked, this.isFailed = false, this.isPending = false, - this.isRepeated = false, - this.size = 14, + this.isChannel = false, + this.repeatCount = 0, + this.resendProgress, + this.hopShortfall, + this.size = 16, this.onColor, }); @@ -68,46 +83,91 @@ class _MessageStatusIconState extends State final colorScheme = Theme.of(context).colorScheme; final double size = widget.size; final Color baseColor = widget.onColor ?? colorScheme.onSurfaceVariant; + final Color confirmedColor = MeshPalette.signal.withValues(alpha: 0.9); + final String label; + final Widget icon; if (widget.isFailed) { - return Semantics( - label: l10n.messageStatus_failed, - child: Icon(Icons.cancel, size: size, color: colorScheme.error), + label = widget.isChannel + ? l10n.messageStatus_failedChannel + : l10n.messageStatus_failed; + icon = Icon(Icons.cancel, size: size, color: colorScheme.error); + } else if (widget.isPending) { + label = l10n.messageStatus_pending; + icon = _SendingDots( + controller: _controller, + color: baseColor, + size: size, ); + } else if (widget.isChannel && widget.hopShortfall != null) { + final shortfall = widget.hopShortfall!; + label = l10n.messageStatus_hopsNotReached( + shortfall.hops, + shortfall.required, + ); + icon = Icon( + Icons.warning_amber_rounded, + size: size, + color: MeshPalette.warn, + ); + } else if (widget.isChannel && (widget.resendProgress?.resends ?? 0) > 0) { + final progress = widget.resendProgress!; + label = l10n.messageStatus_resending( + progress.resends, + progress.maxResends, + ); + icon = Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.autorenew, size: size, color: MeshPalette.warn), + const SizedBox(width: 2), + Text( + '${progress.resends}/${progress.maxResends}', + style: MeshTheme.mono( + fontSize: size * 0.8, + fontWeight: FontWeight.w600, + color: MeshPalette.warn, + ), + ), + ], + ); + } else if (widget.isChannel && widget.repeatCount > 0) { + label = l10n.messageStatus_heardRepeatedCount(widget.repeatCount); + icon = Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.repeat, size: size, color: confirmedColor), + const SizedBox(width: 2), + Text( + '${widget.repeatCount}', + style: MeshTheme.mono( + fontSize: size * 0.8, + fontWeight: FontWeight.w600, + color: confirmedColor, + ), + ), + ], + ); + } else if (widget.isChannel) { + label = l10n.messageStatus_sentChannel; + icon = Icon(Icons.done, size: size, color: baseColor); + } else if (widget.isAcked) { + label = l10n.messageStatus_delivered; + icon = SvgPicture.asset( + 'assets/icons/done_all.svg', + width: size, + height: size, + colorFilter: ColorFilter.mode(confirmedColor, BlendMode.srcIn), + ); + } else { + label = l10n.messageStatus_sentDirect; + icon = Icon(Icons.done, size: size, color: baseColor); } - if (widget.isPending) { - return Semantics( - label: l10n.messageStatus_pending, - child: _SendingDots( - controller: _controller, - color: baseColor, - size: size, - ), - ); - } - - final bool delivered = widget.isAcked || widget.isRepeated; - final String label = widget.isRepeated - ? l10n.messageStatus_repeated - : widget.isAcked - ? l10n.messageStatus_delivered - : l10n.messageStatus_sent; - // Use palette colors: tertiary (warn/amber) for acked/repeated, base for sent. - final Color color = delivered - ? MeshPalette.signal.withValues(alpha: 0.9) - : baseColor; - - return Semantics( - label: label, - child: delivered - ? SvgPicture.asset( - 'assets/icons/done_all.svg', - width: size, - height: size, - colorFilter: ColorFilter.mode(color, BlendMode.srcIn), - ) - : Icon(Icons.done, size: size, color: color), + return Tooltip( + message: label, + triggerMode: TooltipTriggerMode.tap, + child: icon, ); } } diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index ee6ba006..f20aad1c 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -11,17 +11,20 @@ import '../models/contact.dart'; class PathEditorSheet extends StatefulWidget { final List availableContacts; final List initialPath; + final int pathHashByteWidth; const PathEditorSheet({ super.key, required this.availableContacts, this.initialPath = const [], + this.pathHashByteWidth = pathHashSize, }); static Future show( BuildContext context, { required List availableContacts, List initialPath = const [], + int pathHashByteWidth = pathHashSize, }) { return showModalBottomSheet( context: context, @@ -36,6 +39,7 @@ class PathEditorSheet extends StatefulWidget { child: PathEditorSheet( availableContacts: availableContacts, initialPath: initialPath, + pathHashByteWidth: pathHashByteWidth, ), ), ), @@ -48,9 +52,9 @@ class PathEditorSheet extends StatefulWidget { class _Hop { final int id; - final int byte; + final Uint8List bytes; - const _Hop(this.id, this.byte); + const _Hop(this.id, this.bytes); } class _PathEditorSheetState extends State { @@ -66,8 +70,11 @@ class _PathEditorSheetState extends State { @override void initState() { super.initState(); - for (final byte in widget.initialPath) { - _hops.add(_Hop(_nextHopId++, byte)); + for (final hop in PathHelper.splitPathBytes( + widget.initialPath, + widget.pathHashByteWidth, + )) { + _hops.add(_Hop(_nextHopId++, hop)); } _syncHexFromHops(); } @@ -90,9 +97,9 @@ class _PathEditorSheetState extends State { void _syncHexFromHops() { _syncingHex = true; - _hexController.text = PathHelper.formatPathHex( - _hops.map((h) => h.byte).toList(), - ); + _hexController.text = _hops + .map((h) => PathHelper.formatHopHex(h.bytes)) + .join(','); _syncingHex = false; _hexError = null; } @@ -104,8 +111,13 @@ class _PathEditorSheetState extends State { .split(RegExp(r'[,\s]+')) .where((t) => t.isNotEmpty) .toList(); + final width = widget.pathHashByteWidth.clamp(1, pubKeySize).toInt(); + final expectedChars = width * 2; final invalid = tokens - .where((t) => t.length != 2 || int.tryParse(t, radix: 16) == null) + .where( + (t) => + t.length != expectedChars || int.tryParse(t, radix: 16) == null, + ) .toList(); setState(() { if (invalid.isNotEmpty) { @@ -120,15 +132,29 @@ class _PathEditorSheetState extends State { _hops ..clear() ..addAll( - tokens.map((t) => _Hop(_nextHopId++, int.parse(t, radix: 16))), + tokens.map((t) { + final bytes = []; + for (var i = 0; i < t.length; i += 2) { + bytes.add(int.parse(t.substring(i, i + 2), radix: 16)); + } + return _Hop(_nextHopId++, Uint8List.fromList(bytes)); + }), ); }); } void _addHop(Contact contact) { if (_hops.length >= _maxHops) return; + final width = widget.pathHashByteWidth + .clamp(1, contact.publicKey.length) + .toInt(); setState(() { - _hops.add(_Hop(_nextHopId++, contact.publicKey.first)); + _hops.add( + _Hop( + _nextHopId++, + Uint8List.fromList(contact.publicKey.sublist(0, width)), + ), + ); _syncHexFromHops(); }); } @@ -149,18 +175,31 @@ class _PathEditorSheetState extends State { } void _save() { - Navigator.pop( - context, - Uint8List.fromList(_hops.map((h) => h.byte).toList()), - ); + final bytes = []; + for (final hop in _hops) { + bytes.addAll(hop.bytes); + } + Navigator.pop(context, Uint8List.fromList(bytes)); } Widget _hopTile(BuildContext context, int index) { final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final hop = _hops[index]; - final hex = PathHelper.hopHex(hop.byte); - final name = PathHelper.hopName(hop.byte, widget.availableContacts); + final hex = PathHelper.formatHopHex(hop.bytes); + final matches = widget.availableContacts.where((contact) { + if (contact.publicKey.length < hop.bytes.length) return false; + return contact.publicKey + .sublist(0, hop.bytes.length) + .asMap() + .entries + .every((entry) => entry.value == hop.bytes[entry.key]); + }).toList(); + final name = matches.isEmpty + ? null + : matches.length == 1 + ? matches.first.name + : matches.map((c) => c.name).join(' | '); return ListTile( key: ValueKey(hop.id), @@ -224,7 +263,7 @@ class _PathEditorSheetState extends State { ), title: Text(contact.name, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text( - '${contact.typeLabel(l10n)} • ${PathHelper.hopHex(contact.publicKey.first)}', + '${contact.typeLabel(l10n)} • ${PathHelper.formatHopHex(contact.publicKey.sublist(0, widget.pathHashByteWidth.clamp(1, contact.publicKey.length).toInt()))}', ), trailing: const Icon(Icons.add_circle_outline), onTap: full ? null : () => _addHop(contact), diff --git a/lib/widgets/quick_switch_bar.dart b/lib/widgets/quick_switch_bar.dart index 90b90b40..917ceced 100644 --- a/lib/widgets/quick_switch_bar.dart +++ b/lib/widgets/quick_switch_bar.dart @@ -26,9 +26,16 @@ class QuickSwitchBar extends StatelessWidget { final colorScheme = theme.colorScheme; final labelStyle = theme.textTheme.labelMedium ?? const TextStyle(); final background = highContrast ? MapPalette.panelDark : Colors.transparent; - final selectedColor = highContrast + // The selected icon sits on the primary indicator pill, so it uses + // onPrimary. The label sits below on the bar background, so it must use a + // foreground color that contrasts with the surface (not onPrimary, which + // is white-on-white in the light theme). + final selectedIconColor = highContrast ? MapPalette.textPrimary : colorScheme.onPrimary; + final selectedLabelColor = highContrast + ? MapPalette.textPrimary + : colorScheme.onSurface; final unselectedColor = highContrast ? MapPalette.textSecondary : colorScheme.onSurfaceVariant; @@ -59,13 +66,13 @@ class QuickSwitchBar extends StatelessWidget { final isSelected = states.contains(WidgetState.selected); return labelStyle.copyWith( fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500, - color: isSelected ? selectedColor : unselectedColor, + color: isSelected ? selectedLabelColor : unselectedColor, ); }), iconTheme: WidgetStateProperty.resolveWith((states) { final isSelected = states.contains(WidgetState.selected); return IconThemeData( - color: isSelected ? selectedColor : unselectedColor, + color: isSelected ? selectedIconColor : unselectedColor, ); }), ), diff --git a/lib/widgets/received_image_message.dart b/lib/widgets/received_image_message.dart new file mode 100644 index 00000000..e3f56350 --- /dev/null +++ b/lib/widgets/received_image_message.dart @@ -0,0 +1,655 @@ +/// In-bubble renderer for AEIC images received over the mesh. +/// +/// Mirrors `lib/widgets/gif_message.dart`: a fixed-size box (so the reversed +/// `ListView` never jumps as chunks land), one widget per message, all state +/// pulled from [ReceivedImageStore]. +/// +/// ## RISK R6 — permanent synthesized-content label +/// +/// A 156-byte AEIC bitstream decoded by a one-step diffusion model is not a +/// photograph. On the measurement corpus this decoder turned a fox into a +/// sharp, natural, artefact-free sheep. Every decoded image therefore carries +/// TWO provenance elements that no caller can influence: +/// +/// * [_SyntheticBanner] — a band burnt into the bottom of the image itself, +/// inside the `ClipRRect`, inside the `Stack`. It is +/// part of the pixels the user sees and part of any +/// screenshot that contains the image at all. +/// * [_SyntheticCaption] — a line of text immediately under the image. +/// +/// Both are private to this file, are not parameterised, and are reused +/// verbatim by the full-screen viewer this widget opens on tap, so there is no +/// route in the app that can show the pixels without them. The only case in +/// which they are absent is [ReceivedImageEntry.isOutgoing], where the PNG is +/// the sender's own 512x512 crop and the label would be a falsehood — that is +/// read from the store's sidecar, never from a constructor argument. +/// +/// The widget deliberately exposes no share/save action: an exported raster +/// would have to have the caption composited into it first, and that belongs +/// with whoever implements export, not here. +library; + +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../services/received_image_store.dart'; +import 'image_send_codec_binding.dart' show ImageCodecAvailability; + +/// User-visible strings for the NON-decoded states. +/// +/// Exists so the wiring agent can hand in `AppLocalizations` values once the +/// `receivedImage_*` ARB keys land (they do not exist yet, so English defaults +/// ship inline). Deliberately contains no field for the R6 badge or caption: +/// those must not be overridable, shortenable or blankable. +@immutable +class ReceivedImageStrings { + final String Function(int received, int total) incoming; + final String queued; + final String tapToDecode; + + /// Headline of the awaiting-action placeholder: how big the bitstream is and + /// how many packets carried it, e.g. "156 bytes · 2 packets". + final String Function(int bytes, int packets) awaiting; + + /// The affordance on the awaiting-action placeholder. + final String tapToProcess; + final String decoding; + final String Function(int received, int total) incomplete; + final String corrupt; + final String decoderMissing; + final String evicted; + final String retry; + final String decodeAgain; + final String openSettings; + + const ReceivedImageStrings({ + required this.incoming, + required this.queued, + required this.tapToDecode, + // Optional on purpose: `channel_chat_screen.dart` builds this object and is + // owned by another workstream, so the two tap-to-process strings must not + // break that call site before the `receivedImage_*` ARB keys land. + this.awaiting = _defaultAwaiting, + this.tapToProcess = 'Tap to process', + required this.decoding, + required this.incomplete, + required this.corrupt, + required this.decoderMissing, + required this.evicted, + required this.retry, + required this.decodeAgain, + required this.openSettings, + }); + + // TODO(l10n): replace with context.l10n.receivedImage_* once app_en.arb has + // the keys listed in section 5(k) of the receive spec. + static ReceivedImageStrings english = ReceivedImageStrings( + incoming: (received, total) => '$received of $total packets', + queued: 'Waiting to decode', + tapToDecode: 'Tap to decode', + awaiting: _defaultAwaiting, + tapToProcess: 'Tap to process', + decoding: 'Reconstructing… about 1 s', + incomplete: (received, total) => + 'Image incomplete — $received of $total packets arrived', + corrupt: 'Image could not be reconstructed', + decoderMissing: 'Image received — image decoding is off', + evicted: 'Image no longer stored', + retry: 'Try again', + decodeAgain: 'Decode again', + openSettings: 'Set up', + ); +} + +/// English default for [ReceivedImageStrings.awaiting]. A top-level function so +/// it can be a `const` default value on the constructor. +String _defaultAwaiting(int bytes, int packets) => + '$bytes bytes · $packets packets'; + +/// Text of the R6 label. Private and const: not injectable, not localisable +/// yet, and never empty. +const String _kSyntheticBadge = 'AI-reconstructed'; + +/// The caption is built from the ACTUAL bitstream size, never a nominal one: +/// quoting a fixed "~156 bytes" under an image that took 209 is its own small +/// dishonesty, in a label whose whole job is honesty. +String _syntheticCaptionFor(int bytes) => + 'Reconstructed by an AI model from $bytes bytes. ' + 'Fine detail is generated, not transmitted.'; + +class ReceivedImageMessage extends StatefulWidget { + /// 14 hex chars, as parsed out of the message text by + /// [ReceivedImageRef.parse]. + final String streamId; + + /// True for the local user's own message. Not an R6 escape hatch: the label is + /// driven by [ReceivedImageEntry.synthesized], which is derived in the store. + final bool isOutgoing; + + /// Colour for the explanatory text inside a chat bubble. + final Color fallbackTextColor; + + final double maxSize; + + /// Test/preview override. Normally resolved from the widget tree. + final ReceivedImageStore? store; + + final ReceivedImageStrings? strings; + + /// Route to the image-messages settings page (offered only when the decoder + /// is missing because no weights are downloaded). + final VoidCallback? onOpenCodecSettings; + + const ReceivedImageMessage({ + super.key, + required this.streamId, + required this.isOutgoing, + required this.fallbackTextColor, + this.maxSize = 200, + this.store, + this.strings, + this.onOpenCodecSettings, + }); + + @override + State createState() => _ReceivedImageMessageState(); +} + +class _ReceivedImageMessageState extends State { + ReceivedImageStore? _store; + + /// Which stream we have already asked the store to page in. Keyed by id, not + /// a bare bool: a `ListView` recycles this State object across messages, and + /// a bool left over from the previous stream meant the new one's pixels were + /// never requested and the bubble sat on a spinner forever. + String? _pngRequestedFor; + + ReceivedImageStore? _resolveStore() { + final injected = widget.store; + if (injected != null) return injected; + try { + return Provider.of(context, listen: false); + } on ProviderNotFoundException { + // The receive service is not registered (e.g. a screen test); render the + // "no decoder" state rather than crashing the whole message list. + return null; + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _store = _resolveStore(); + _maybeLoadPng(); + } + + @override + void didUpdateWidget(covariant ReceivedImageMessage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.streamId != widget.streamId) { + _pngRequestedFor = null; + _store = _resolveStore(); + _maybeLoadPng(); + } + } + + void _maybeLoadPng() { + final store = _store; + if (store == null) return; + if (_pngRequestedFor == widget.streamId) return; + final entry = store.entryFor(widget.streamId); + if (entry == null) return; + if (entry.state != ReceivedImageState.decoded) return; + if (entry.pngBytes != null) return; + _pngRequestedFor = widget.streamId; + store.ensurePng(widget.streamId); + } + + @override + Widget build(BuildContext context) { + final store = _store; + if (store == null) { + return _box(context, _unavailableBody(context, null)); + } + return ValueListenableBuilder( + valueListenable: store.listenableFor(widget.streamId), + builder: (context, _, _) { + final entry = store.entryFor(widget.streamId); + _maybeLoadPng(); + if (entry == null) { + return _box(context, _unavailableBody(context, null)); + } + return _buildForEntry(context, store, entry); + }, + ); + } + + ReceivedImageStrings get _s => widget.strings ?? ReceivedImageStrings.english; + + Widget _buildForEntry( + BuildContext context, + ReceivedImageStore store, + ReceivedImageEntry entry, + ) { + switch (entry.state) { + case ReceivedImageState.decoded: + final png = entry.pngBytes; + if (png == null) { + return _box( + context, + _progressBody(context, progress: null, label: _s.decoding), + ); + } + return _decodedBody(context, entry, png); + + case ReceivedImageState.receiving: + final total = entry.totalChunks <= 0 ? 1 : entry.totalChunks; + return _box( + context, + _progressBody( + context, + progress: (entry.receivedChunks / total).clamp(0.0, 1.0), + label: _s.incoming(entry.receivedChunks, total), + ), + ); + + // "Bitstream complete, not decoded". Two shades of it, distinguished by + // queue membership rather than by a fourth enum value: + // needsManualDecode -> parked, waiting for a tap (the setting is off, + // or the burst cap trimmed it) + // !needsManualDecode -> already in the store's decode queue + // Both are tappable. The second one deliberately so: a sidecar restored + // by load() is never re-enqueued, so without a tap target a restored + // "Waiting to decode" card would be dead forever. + case ReceivedImageState.reassembled: + return _box( + context, + _iconBody( + context, + icon: entry.needsManualDecode + ? Icons.image_outlined + : Icons.hourglass_empty, + label: entry.needsManualDecode + ? _s.awaiting(entry.bitstreamByteCount, entry.totalChunks) + : _s.queued, + action: entry.needsManualDecode + ? _ActionSpec( + _s.tapToProcess, + () => _onProcessTap(store, entry), + ) + : null, + ), + onTap: () => _onProcessTap(store, entry), + ); + + case ReceivedImageState.decoding: + return _box( + context, + _progressBody(context, progress: null, label: _s.decoding), + ); + + case ReceivedImageState.failedIncomplete: + return _box( + context, + _iconBody( + context, + icon: Icons.broken_image_outlined, + label: _s.incomplete(entry.receivedChunks, entry.totalChunks), + isError: true, + ), + ); + + case ReceivedImageState.failedCorrupt: + return _box( + context, + _iconBody( + context, + icon: Icons.error_outline, + label: _s.corrupt, + isError: true, + action: entry.canRetryDecode + ? _ActionSpec( + _s.retry, + () => store.requestDecode(entry.streamId), + ) + : null, + ), + ); + + case ReceivedImageState.decoderUnavailable: + return _box(context, _unavailableBody(context, entry)); + + case ReceivedImageState.evicted: + return _box( + context, + _iconBody( + context, + icon: Icons.delete_outline, + label: _s.evicted, + action: entry.canRetryDecode + ? _ActionSpec( + _s.decodeAgain, + () => store.requestDecode(entry.streamId), + ) + : null, + ), + ); + } + } + + /// Availability of the store's decoder seam. + /// + /// Read through the store's public `decoder` field rather than importing + /// `ImageCodecService`: the bubble only needs to know whether a tap would + /// reach a working codec. + ImageCodecAvailability _availability(ReceivedImageStore store) => + store.decoder?.availability ?? ImageCodecAvailability.unavailable; + + /// The one tap handler for the awaiting-action card. + /// + /// With no model installed, going through [ReceivedImageStore.requestDecode] + /// would cost the user two taps: the entry would flip to + /// `decoderUnavailable`, and only *then* would the card offer a "Set up" + /// button. So when the codec is not ready and the host screen gave us a route + /// to the image-messages setting, go straight there. + void _onProcessTap(ReceivedImageStore store, ReceivedImageEntry entry) { + final openSettings = widget.onOpenCodecSettings; + if (_availability(store) != ImageCodecAvailability.ready && + openSettings != null) { + openSettings(); + return; + } + store.requestDecode(entry.streamId); + } + + // ---- bodies -------------------------------------------------------------- + + /// 4:3 placeholder box, same discipline as `GifMessage`, so a bubble does not + /// resize as an image progresses. + Widget _box(BuildContext context, Widget child, {VoidCallback? onTap}) { + final theme = Theme.of(context); + final box = Container( + width: widget.maxSize, + height: widget.maxSize * 0.75, + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(8), + ), + child: Center(child: child), + ); + if (onTap == null) return box; + return GestureDetector(onTap: onTap, child: box); + } + + Widget _progressBody( + BuildContext context, { + required double? progress, + required String label, + }) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2, value: progress), + ), + const SizedBox(height: 8), + _label(context, label), + ], + ); + } + + Widget _iconBody( + BuildContext context, { + required IconData icon, + required String label, + bool isError = false, + _ActionSpec? action, + }) { + final color = isError + ? Theme.of(context).colorScheme.error + : widget.fallbackTextColor; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 22, color: color), + const SizedBox(height: 6), + _label(context, label, color: color), + if (action != null) + TextButton( + onPressed: action.onPressed, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 28), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: Text(action.label, style: const TextStyle(fontSize: 12)), + ), + ], + ); + } + + Widget _unavailableBody(BuildContext context, ReceivedImageEntry? entry) { + final canSetUp = widget.onOpenCodecSettings != null; + return _iconBody( + context, + icon: Icons.visibility_off_outlined, + label: _s.decoderMissing, + action: canSetUp + ? _ActionSpec(_s.openSettings, widget.onOpenCodecSettings!) + : (entry != null && entry.canRetryDecode && _store != null + ? _ActionSpec( + _s.retry, + () => _store!.requestDecode(entry.streamId), + ) + : null), + ); + } + + Widget _label(BuildContext context, String text, {Color? color}) { + return Text( + text, + textAlign: TextAlign.center, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, color: color ?? widget.fallbackTextColor), + ); + } + + // ---- decoded (R6) -------------------------------------------------------- + + Widget _decodedBody( + BuildContext context, + ReceivedImageEntry entry, + Uint8List png, + ) { + final size = widget.maxSize; + return GestureDetector( + onTap: () => _openViewer(context, entry, png), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: SizedBox( + width: size, + // The codec always produces a 512x512 square because the sender + // stretched the whole frame into it. entry.displayAspectRatio is + // the shape it started as, so undo the stretch here rather than + // showing a widened photo. Null means square or unknown. + height: entry.displayAspectRatio == null + ? size + : size / entry.displayAspectRatio!, + child: Stack( + children: [ + Positioned.fill( + // fill, not contain: the pixels ARE the stretched square, + // so mapping them onto the original aspect box is exactly + // the inverse of what the sender did. + child: Image.memory(png, fit: BoxFit.fill), + ), + if (entry.synthesized) + const Positioned( + left: 0, + right: 0, + bottom: 0, + child: _SyntheticBanner(), + ), + ], + ), + ), + ), + if (entry.synthesized) + SizedBox( + width: size, + child: _SyntheticCaption(bytes: entry.bitstreamByteCount), + ), + ], + ), + ); + } + + void _openViewer( + BuildContext context, + ReceivedImageEntry entry, + Uint8List png, + ) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => _ReceivedImageViewer( + png: png, + synthesized: entry.synthesized, + bytes: entry.bitstreamByteCount, + ), + ), + ); + } +} + +class _ActionSpec { + final String label; + final VoidCallback onPressed; + + const _ActionSpec(this.label, this.onPressed); +} + +/// R6, part 1: a band composited over the bottom of the image. +class _SyntheticBanner extends StatelessWidget { + const _SyntheticBanner(); + + @override + Widget build(BuildContext context) { + return Container( + height: 18, + 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 SizedBox(width: 4), + Text( + _kSyntheticBadge, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10, color: Colors.white), + ), + ], + ), + ); + } +} + +/// R6, part 2: the full sentence, immediately under the image. +class _SyntheticCaption extends StatelessWidget { + /// Contrast variant only. The TEXT is the same const in both cases; there is + /// no parameter that can shorten, blank or restyle it away. + final bool onDark; + + /// Size of the bitstream this image was reconstructed from. + final int bytes; + + const _SyntheticCaption({required this.bytes, this.onDark = false}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + _syntheticCaptionFor(bytes), + // No maxLines: the bubble is narrow and the sentence must never be + // truncated. A label that reads "Details are invented. Not a" is worse + // than none — it clips exactly where the warning was going. + softWrap: true, + style: TextStyle( + fontSize: 10, + color: onDark + ? Colors.white70 + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); + } +} + +/// Full-screen view. Private to this file so no other widget can present the +/// pixels without the two R6 elements. +class _ReceivedImageViewer extends StatelessWidget { + final Uint8List png; + final bool synthesized; + + /// Bitstream size, so the full-screen caption quotes the same real number as + /// the one in the transcript. + final int bytes; + + const _ReceivedImageViewer({ + required this.png, + required this.synthesized, + required this.bytes, + }); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + ), + body: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Stack( + children: [ + InteractiveViewer(child: Image.memory(png)), + if (synthesized) + const Positioned( + left: 0, + right: 0, + bottom: 0, + child: _SyntheticBanner(), + ), + ], + ), + ), + if (synthesized) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _SyntheticCaption(bytes: bytes, onDark: true), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/repeater_login_dialog.dart b/lib/widgets/repeater_login_dialog.dart index 56834455..f3567742 100644 --- a/lib/widgets/repeater_login_dialog.dart +++ b/lib/widgets/repeater_login_dialog.dart @@ -7,11 +7,13 @@ import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; import '../services/storage_service.dart'; +import '../services/repeater_command_service.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import '../utils/app_logger.dart'; +import '../helpers/utf8_length_limiter.dart'; import 'routing_sheet.dart'; class RepeaterLoginDialog extends StatefulWidget { @@ -201,7 +203,10 @@ class _RepeaterLoginDialogState extends State { await _connector.sendFrame( buildSendCliCommandFrame( repeater.publicKey, - 'clock sync', + normalizeRepeaterClockSyncCommand( + 'clock sync', + nowSeconds: timestampSeconds, + ), timestampSeconds: timestampSeconds, ), ); @@ -276,6 +281,9 @@ class _RepeaterLoginDialogState extends State { final repeater = _resolveRepeater(connector); final isFloodMode = repeater.pathOverride == -1; return AlertDialog( + insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24), + titlePadding: const EdgeInsets.fromLTRB(16, 20, 16, 0), + contentPadding: const EdgeInsets.fromLTRB(16, 16, 16, 0), title: Row( children: [ AvatarCircle( @@ -347,6 +355,10 @@ class _RepeaterLoginDialogState extends State { TextField( controller: _passwordController, obscureText: _obscurePassword, + // Firmware stores at most 15 bytes (CommonCLI.h password[16]). + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(15), + ], decoration: InputDecoration( labelText: l10n.login_password, hintText: l10n.login_enterPassword, @@ -357,6 +369,9 @@ class _RepeaterLoginDialogState extends State { ? Icons.visibility : Icons.visibility_off, ), + tooltip: _obscurePassword + ? l10n.login_showPassword + : l10n.login_hidePassword, onPressed: () { setState(() { _obscurePassword = !_obscurePassword; @@ -393,98 +408,116 @@ class _RepeaterLoginDialogState extends State { controlAffinity: ListTileControlAffinity.leading, contentPadding: EdgeInsets.zero, ), - const Divider(), - Row( + ExpansionTile( + title: Text(l10n.login_advanced), + tilePadding: EdgeInsets.zero, + childrenPadding: EdgeInsets.zero, + expandedCrossAxisAlignment: CrossAxisAlignment.start, + shape: const Border(), + collapsedShape: const Border(), children: [ - Text( - l10n.login_routing, - style: MeshTheme.accentLabel( - color: scheme.onSurfaceVariant, - fontSize: 11, - ), - ), - const Spacer(), - PopupMenuButton( - icon: Icon(isFloodMode ? Icons.waves : Icons.route), - tooltip: l10n.login_routingMode, - onSelected: (mode) async { - if (mode == 'flood') { - await connector.setPathOverride( - repeater, - pathLen: -1, - ); - } else { - await connector.setPathOverride( - repeater, - pathLen: null, - ); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'auto', - child: Row( - children: [ - Icon( - Icons.auto_mode, - size: 20, - color: !isFloodMode ? scheme.primary : null, - ), - const SizedBox(width: 8), - Text( - l10n.login_autoUseSavedPath, - style: TextStyle( - fontWeight: !isFloodMode - ? FontWeight.bold - : FontWeight.normal, - ), - ), - ], + Row( + children: [ + Text( + l10n.login_routing, + style: MeshTheme.accentLabel( + color: scheme.onSurfaceVariant, + fontSize: 11, ), ), - PopupMenuItem( - value: 'flood', - child: Row( - children: [ - Icon( - Icons.waves, - size: 20, - color: isFloodMode ? scheme.primary : null, + const Spacer(), + PopupMenuButton( + icon: Icon(isFloodMode ? Icons.waves : Icons.route), + tooltip: l10n.login_routingMode, + onSelected: (mode) async { + if (mode == 'flood') { + await connector.setPathOverride( + repeater, + pathLen: -1, + ); + } else { + await connector.setPathOverride( + repeater, + pathLen: null, + ); + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'auto', + child: Row( + children: [ + Icon( + Icons.auto_mode, + size: 20, + color: !isFloodMode + ? scheme.primary + : null, + ), + const SizedBox(width: 8), + Text( + l10n.login_autoUseSavedPath, + style: TextStyle( + fontWeight: !isFloodMode + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], ), - const SizedBox(width: 8), - Text( - l10n.login_forceFloodMode, - style: TextStyle( - fontWeight: isFloodMode - ? FontWeight.bold - : FontWeight.normal, - ), + ), + PopupMenuItem( + value: 'flood', + child: Row( + children: [ + Icon( + Icons.waves, + size: 20, + color: isFloodMode + ? scheme.primary + : null, + ), + const SizedBox(width: 8), + Text( + l10n.login_forceFloodMode, + style: TextStyle( + fontWeight: isFloodMode + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], ), - ], - ), + ), + ], ), ], ), + const SizedBox(height: 4), + Text( + repeater.pathLabel( + context.l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: TextButton.icon( + onPressed: () => ContactRoutingSheet.show( + context, + contact: repeater, + ), + icon: const Icon(Icons.timeline, size: 18), + label: Text(l10n.login_managePaths), + ), + ), ], ), - const SizedBox(height: 4), - Text( - repeater.pathLabel(context.l10n), - style: TextStyle( - fontSize: 11, - color: scheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 8), - Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: () => - ContactRoutingSheet.show(context, contact: repeater), - icon: const Icon(Icons.timeline, size: 18), - label: Text(l10n.login_managePaths), - ), - ), ], ), ), diff --git a/lib/widgets/room_login_dialog.dart b/lib/widgets/room_login_dialog.dart index a5e2555b..1ed67d33 100644 --- a/lib/widgets/room_login_dialog.dart +++ b/lib/widgets/room_login_dialog.dart @@ -14,6 +14,7 @@ import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import '../utils/app_logger.dart'; import '../helpers/snack_bar_builder.dart'; +import '../helpers/utf8_length_limiter.dart'; import 'routing_sheet.dart'; class RoomLoginDialog extends StatefulWidget { @@ -233,6 +234,9 @@ class _RoomLoginDialogState extends State { final repeater = _resolveRepeater(connector); final isFloodMode = repeater.pathOverride == -1; return AlertDialog( + insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24), + titlePadding: const EdgeInsets.fromLTRB(16, 20, 16, 0), + contentPadding: const EdgeInsets.fromLTRB(16, 16, 16, 0), title: Row( children: [ AvatarCircle( @@ -288,6 +292,10 @@ class _RoomLoginDialogState extends State { TextField( controller: _passwordController, obscureText: _obscurePassword, + // Firmware stores at most 15 bytes (CommonCLI.h password[16]). + inputFormatters: const [ + Utf8LengthLimitingTextInputFormatter(15), + ], decoration: InputDecoration( labelText: l10n.login_password, hintText: l10n.login_enterPassword, @@ -298,6 +306,9 @@ class _RoomLoginDialogState extends State { ? Icons.visibility : Icons.visibility_off, ), + tooltip: _obscurePassword + ? l10n.login_showPassword + : l10n.login_hidePassword, onPressed: () { setState(() { _obscurePassword = !_obscurePassword; @@ -329,98 +340,116 @@ class _RoomLoginDialogState extends State { controlAffinity: ListTileControlAffinity.leading, contentPadding: EdgeInsets.zero, ), - const Divider(), - Row( + ExpansionTile( + title: Text(l10n.login_advanced), + tilePadding: EdgeInsets.zero, + childrenPadding: EdgeInsets.zero, + expandedCrossAxisAlignment: CrossAxisAlignment.start, + shape: const Border(), + collapsedShape: const Border(), children: [ - Text( - l10n.login_routing, - style: MeshTheme.accentLabel( - color: scheme.onSurfaceVariant, - fontSize: 11, - ), - ), - const Spacer(), - PopupMenuButton( - icon: Icon(isFloodMode ? Icons.waves : Icons.route), - tooltip: l10n.login_routingMode, - onSelected: (mode) async { - if (mode == 'flood') { - await connector.setPathOverride( - repeater, - pathLen: -1, - ); - } else { - await connector.setPathOverride( - repeater, - pathLen: null, - ); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'auto', - child: Row( - children: [ - Icon( - Icons.auto_mode, - size: 20, - color: !isFloodMode ? scheme.primary : null, - ), - const SizedBox(width: 8), - Text( - l10n.login_autoUseSavedPath, - style: TextStyle( - fontWeight: !isFloodMode - ? FontWeight.bold - : FontWeight.normal, - ), - ), - ], + Row( + children: [ + Text( + l10n.login_routing, + style: MeshTheme.accentLabel( + color: scheme.onSurfaceVariant, + fontSize: 11, ), ), - PopupMenuItem( - value: 'flood', - child: Row( - children: [ - Icon( - Icons.waves, - size: 20, - color: isFloodMode ? scheme.primary : null, + const Spacer(), + PopupMenuButton( + icon: Icon(isFloodMode ? Icons.waves : Icons.route), + tooltip: l10n.login_routingMode, + onSelected: (mode) async { + if (mode == 'flood') { + await connector.setPathOverride( + repeater, + pathLen: -1, + ); + } else { + await connector.setPathOverride( + repeater, + pathLen: null, + ); + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'auto', + child: Row( + children: [ + Icon( + Icons.auto_mode, + size: 20, + color: !isFloodMode + ? scheme.primary + : null, + ), + const SizedBox(width: 8), + Text( + l10n.login_autoUseSavedPath, + style: TextStyle( + fontWeight: !isFloodMode + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], ), - const SizedBox(width: 8), - Text( - l10n.login_forceFloodMode, - style: TextStyle( - fontWeight: isFloodMode - ? FontWeight.bold - : FontWeight.normal, - ), + ), + PopupMenuItem( + value: 'flood', + child: Row( + children: [ + Icon( + Icons.waves, + size: 20, + color: isFloodMode + ? scheme.primary + : null, + ), + const SizedBox(width: 8), + Text( + l10n.login_forceFloodMode, + style: TextStyle( + fontWeight: isFloodMode + ? FontWeight.bold + : FontWeight.normal, + ), + ), + ], ), - ], - ), + ), + ], ), ], ), + const SizedBox(height: 4), + Text( + repeater.pathLabel( + context.l10n, + pathHashByteWidth: connector.pathHashByteWidth, + ), + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: TextButton.icon( + onPressed: () => ContactRoutingSheet.show( + context, + contact: repeater, + ), + icon: const Icon(Icons.timeline, size: 18), + label: Text(l10n.login_managePaths), + ), + ), ], ), - const SizedBox(height: 4), - Text( - repeater.pathLabel(context.l10n), - style: TextStyle( - fontSize: 11, - color: scheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 8), - Align( - alignment: Alignment.centerLeft, - child: TextButton.icon( - onPressed: () => - ContactRoutingSheet.show(context, contact: repeater), - icon: const Icon(Icons.timeline, size: 18), - label: Text(l10n.login_managePaths), - ), - ), ], ), ), diff --git a/lib/widgets/routing_sheet.dart b/lib/widgets/routing_sheet.dart index 2cc55b8a..1b8e3e5d 100644 --- a/lib/widgets/routing_sheet.dart +++ b/lib/widgets/routing_sheet.dart @@ -99,7 +99,10 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { final override = contact.pathOverride; final initial = override != null && override > 0 ? (contact.pathOverrideBytes ?? Uint8List(0)) - : (contact.pathLength > 0 ? contact.path : Uint8List(0)); + : (contact.pathLength > 0 && + contact.pathHashWidth == connector.pathHashByteWidth + ? contact.path + : Uint8List(0)); final available = connector.allContacts .where((c) => c.publicKeyHex != contact.publicKeyHex) .toList(); @@ -107,11 +110,13 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { context, availableContacts: available, initialPath: initial, + pathHashByteWidth: connector.pathHashByteWidth, ); if (result == null || !mounted) return; + final hopCount = result.length ~/ connector.pathHashByteWidth; await connector.setPathOverride( contact, - pathLen: result.length, + pathLen: hopCount, pathBytes: result, ); await _verifyPath(connector, contact, result); @@ -123,9 +128,10 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { PathRecord record, ) async { final bytes = Uint8List.fromList(record.pathBytes); + final hopCount = bytes.length ~/ connector.pathHashByteWidth; await connector.setPathOverride( contact, - pathLen: bytes.length, + pathLen: hopCount, pathBytes: bytes, ); await _verifyPath(connector, contact, bytes); @@ -157,11 +163,17 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { setState(() => _syncStatus = context.l10n.chat_pathCleared); } - _PathQuality _qualityOf(PathRecord record, List ranked) { + _PathQuality _qualityOf( + MeshCoreConnector connector, + PathRecord record, + List ranked, + ) { if (record.pathBytes.isNotEmpty) { - final first = record.pathBytes.first; for (var i = 0; i < ranked.length && i < 3; i++) { - if (ranked[i].pubkeyFirstByte == first) { + if (ranked[i].matchesPathStart( + record.pathBytes, + _recordPathHashWidth(record), + )) { return switch (i) { 0 => _PathQuality.strong, 1 => _PathQuality.good, @@ -229,14 +241,22 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { case _RoutingMode.manual: final bytes = contact.pathOverrideBytes ?? Uint8List(0); if (bytes.isEmpty) return l10n.routing_directNoHops; - return PathHelper.resolvePathNames(bytes, connector.allContacts); + return PathHelper.resolvePathNames( + bytes, + connector.allContacts, + connector.pathHashByteWidth, + ); case _RoutingMode.auto: if (contact.pathLength < 0) return l10n.routing_noPathYet; if (contact.pathLength == 0) return l10n.routing_directNoHops; if (contact.path.isEmpty) { return l10n.chat_hopsCount(contact.pathLength); } - return PathHelper.resolvePathNames(contact.path, connector.allContacts); + return PathHelper.resolvePathNames( + contact.path, + connector.allContacts, + contact.pathHashWidth, + ); } } @@ -268,17 +288,26 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { ); } + int _recordPathHashWidth(PathRecord record) => + Contact.inferPathHashWidth(record.hopCount, record.pathBytes.length); + void _showPathDetail( BuildContext context, MeshCoreConnector connector, Contact contact, - List pathBytes, + PathRecord record, ) { final l10n = context.l10n; - final formattedPath = PathHelper.formatPathHex(pathBytes); + final pathBytes = record.pathBytes; + final width = _recordPathHashWidth(record); + final formattedPath = PathHelper.splitPathBytes( + pathBytes, + width, + ).map(PathHelper.formatHopHex).join(','); final resolvedNames = PathHelper.resolvePathNames( pathBytes, connector.allContacts, + width, ); showDialog( @@ -521,11 +550,21 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { listEquals(record.pathBytes, contact.path))); final title = hasBytes - ? PathHelper.resolvePathNames(record.pathBytes, connector.allContacts) + ? PathHelper.resolvePathNames( + record.pathBytes, + connector.allContacts, + _recordPathHashWidth(record), + ) : l10n.chat_hopsCount(record.hopCount); + final displayHopCount = hasBytes + ? PathHelper.splitPathBytes( + record.pathBytes, + _recordPathHashWidth(record), + ).length + : record.hopCount; final line1 = - '${l10n.chat_hopsCount(record.hopCount)} • ${_qualityLabel(context, quality)}'; + '${l10n.chat_hopsCount(displayHopCount)} • ${_qualityLabel(context, quality)}'; final line2Parts = [ record.timestamp != null ? l10n.routing_lastWorked(_relativeTime(context, record.timestamp!)) @@ -539,7 +578,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { behavior: HitTestBehavior.opaque, onSecondaryTapUp: PlatformInfo.isDesktop && hasBytes ? (_) => - _showPathDetail(context, connector, contact, record.pathBytes) + _showPathDetail(context, connector, contact, record) : null, child: Card( margin: const EdgeInsets.symmetric(vertical: 4), @@ -588,12 +627,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { ? () => _applyHistoryPath(connector, contact, record) : null, onLongPress: hasBytes - ? () => _showPathDetail( - context, - connector, - contact, - record.pathBytes, - ) + ? () => _showPathDetail(context, connector, contact, record) : null, ), ), @@ -621,7 +655,10 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { pathService .getRecentPaths(contact.publicKeyHex) .map( - (r) => (quality: _qualityOf(r, rankedRepeaters), record: r), + (r) => ( + quality: _qualityOf(connector, r, rankedRepeaters), + record: r, + ), ) .toList() ..sort((a, b) { diff --git a/lib/widgets/snr_indicator.dart b/lib/widgets/snr_indicator.dart index f57776de..f485e0c0 100644 --- a/lib/widgets/snr_indicator.dart +++ b/lib/widgets/snr_indicator.dart @@ -1,8 +1,10 @@ import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; import 'package:latlong2/latlong.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +import '../helpers/path_helper.dart'; import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../theme/mesh_theme.dart'; @@ -11,15 +13,27 @@ import 'signal_ui.dart'; Contact? _getRepeaterPrefixMatchNearLocation( List contacts, - int pubkeyFirstByte, { + List pubkeyPrefix, { + String? contactKeyHex, LatLng? searchPoint, bool preferFavorites = false, }) { + if (contactKeyHex != null) { + for (final c in contacts) { + if (c.publicKeyHex == contactKeyHex) { + return c; + } + } + } + final candidates = contacts .where( (c) => - c.publicKey.isNotEmpty && - c.publicKey.first == pubkeyFirstByte && + c.publicKey.length >= pubkeyPrefix.length && + listEquals( + c.publicKey.sublist(0, pubkeyPrefix.length), + pubkeyPrefix, + ) && (c.type == advTypeRepeater || c.type == advTypeRoom), ) .toList(); @@ -164,7 +178,7 @@ class _SNRIndicatorState extends State { ), if (directRepeater != null) Text( - '${directRepeaters.length}: ${directRepeater.pubkeyFirstByte.toRadixString(16).padLeft(2, '0')}: ${_formatLastUpdated(directRepeater.lastUpdated)}', + '${directRepeaters.length}: ${directRepeater.pubkeyPrefixHex}: ${_formatLastUpdated(directRepeater.lastUpdated)}', style: TextStyle( fontSize: 12, fontWeight: FontWeight.w500, @@ -212,78 +226,110 @@ class _SNRIndicatorState extends State { title: Text(l10n.snrIndicator_nearByRepeaters), content: SizedBox( width: double.maxFinite, - child: Scrollbar( - child: ListView.separated( - shrinkWrap: true, - padding: const EdgeInsets.symmetric(vertical: 4), - itemCount: directBestRepeaters.length, - separatorBuilder: (_, _) => const Divider(height: 1), - itemBuilder: (context, index) { - final repeater = directBestRepeaters[index]; - final allContacts = widget.connector.allContacts; + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.snrIndicator_nearByRepeatersDescription, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Flexible( + child: Scrollbar( + child: ListView.separated( + shrinkWrap: true, + padding: const EdgeInsets.symmetric(vertical: 4), + itemCount: directBestRepeaters.length, + separatorBuilder: (_, _) => const Divider(height: 1), + itemBuilder: (context, index) { + final repeater = directBestRepeaters[index]; + final allContacts = widget.connector.allContacts; - final selfLat = widget.connector.selfLatitude; - final selfLon = widget.connector.selfLongitude; + final selfLat = widget.connector.selfLatitude; + final selfLon = widget.connector.selfLongitude; - LatLng? selfPoint; - if (selfLat != null && - selfLon != null && - _isValidSelfLocation(selfLat, selfLon)) { - selfPoint = LatLng(selfLat, selfLon); - } + LatLng? selfPoint; + if (selfLat != null && + selfLon != null && + _isValidSelfLocation(selfLat, selfLon)) { + selfPoint = LatLng(selfLat, selfLon); + } - final contact = _getRepeaterPrefixMatchNearLocation( - allContacts, - repeater.pubkeyFirstByte, - searchPoint: selfPoint, - preferFavorites: true, - ); + final contact = _getRepeaterPrefixMatchNearLocation( + allContacts, + repeater.pubkeyPrefix, + contactKeyHex: repeater.contactKeyHex, + searchPoint: selfPoint, + preferFavorites: true, + ); - final name = contact?.name; - final hex = repeater.pubkeyFirstByte - .toRadixString(16) - .padLeft(2, '0'); - final snrColor = MeshTheme.snrColor( - repeater.snr, - blocked: false, - ); + final name = contact?.name; + final prefixLabel = PathHelper.formatHopHex( + repeater.pubkeyPrefix, + ); + final snrColor = MeshTheme.snrColor( + repeater.snr, + blocked: false, + ); + final colorScheme = Theme.of(context).colorScheme; - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 10, - ), - child: Row( - children: [ - AvatarCircle( - name: name ?? hex, - size: 36, - color: snrColor, - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + return Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + child: Row( children: [ - Text( - name ?? hex, - style: Theme.of(context).textTheme.bodyMedium, + AvatarCircle( + name: name ?? prefixLabel, + size: 36, + color: colorScheme.onSurfaceVariant, ), - Text( - '${repeater.snr.toStringAsFixed(1)} dB • ${_formatLastUpdated(repeater.lastUpdated)}', - style: MeshTheme.mono( - fontSize: 11, - color: snrColor, + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + name ?? prefixLabel, + style: Theme.of(context) + .textTheme + .bodyMedium + ?.copyWith( + color: colorScheme.onSurface, + ), + ), + Row( + children: [ + Icon( + Icons.circle, + size: 8, + color: snrColor, + ), + const SizedBox(width: 6), + Text( + '${repeater.snr.toStringAsFixed(1)} dB • ${_formatLastUpdated(repeater.lastUpdated)}', + style: MeshTheme.mono( + fontSize: 11, + color: colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ], ), ), ], ), - ), - ], + ); + }, ), - ); - }, - ), + ), + ), + ], ), ), actions: [ diff --git a/lib/widgets/telemetry_location_map.dart b/lib/widgets/telemetry_location_map.dart index f8983c04..537867c5 100644 --- a/lib/widgets/telemetry_location_map.dart +++ b/lib/widgets/telemetry_location_map.dart @@ -11,7 +11,6 @@ import '../models/app_settings.dart'; import '../models/contact.dart'; import '../services/app_settings_service.dart'; import '../services/map_tile_cache_service.dart'; -import 'themed_map_tile_layer.dart'; class TelemetryLocationMap extends StatefulWidget { final double latitude; @@ -115,7 +114,7 @@ class _TelemetryLocationMapState extends State { ), ), children: [ - ThemedMapTileLayer(tileCache: tileCache), + tileCache.buildTileLayer(context), MarkerLayer( markers: [ ...contacts.map(_buildContactMarker), diff --git a/lib/widgets/themed_map_tile_layer.dart b/lib/widgets/themed_map_tile_layer.dart deleted file mode 100644 index c6d2eaad..00000000 --- a/lib/widgets/themed_map_tile_layer.dart +++ /dev/null @@ -1,60 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_map/flutter_map.dart'; - -import '../services/map_tile_cache_service.dart'; - -/// Shared cached map tiles with an automatic dark-mode treatment. -/// -/// The dark style transforms the existing OpenStreetMap raster tiles, so light -/// and dark maps share the same offline cache and network requests. -class ThemedMapTileLayer extends StatelessWidget { - final MapTileCacheService tileCache; - final double opacity; - - const ThemedMapTileLayer({ - super.key, - required this.tileCache, - this.opacity = 1, - }); - - static const ColorFilter _darkMapFilter = ColorFilter.matrix([ - -0.0850, - -0.2861, - -0.0289, - 0, - 120, - -0.0957, - -0.3218, - -0.0325, - 0, - 140, - -0.1169, - -0.3934, - -0.0397, - 0, - 170, - 0, - 0, - 0, - 1, - 0, - ]); - - @override - Widget build(BuildContext context) { - Widget layer = TileLayer( - urlTemplate: kMapTileUrlTemplate, - tileProvider: tileCache.tileProvider, - userAgentPackageName: MapTileCacheService.userAgentPackageName, - maxZoom: 19, - ); - - if (Theme.of(context).brightness == Brightness.dark) { - layer = ColorFiltered(colorFilter: _darkMapFilter, child: layer); - } - if (opacity < 1) { - layer = Opacity(opacity: opacity, child: layer); - } - return layer; - } -} diff --git a/lib/widgets/unread_badge.dart b/lib/widgets/unread_badge.dart index 1cf5c1d6..dd2e2ab3 100644 --- a/lib/widgets/unread_badge.dart +++ b/lib/widgets/unread_badge.dart @@ -11,18 +11,19 @@ class UnreadBadge extends StatelessWidget { Widget build(BuildContext context) { final display = count > 9999 ? '9999+' : count.toString(); return Container( - padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2), + constraints: const BoxConstraints(minWidth: 20), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + alignment: Alignment.center, decoration: BoxDecoration( - color: MeshPalette.blue.withValues(alpha: 0.18), + color: MeshPalette.alert, borderRadius: BorderRadius.circular(MeshRadii.pill), - border: Border.all(color: MeshPalette.blue.withValues(alpha: 0.45)), ), child: Text( display, style: MeshTheme.mono( fontSize: 11, fontWeight: FontWeight.w700, - color: MeshPalette.blue, + color: Colors.white, ), ), ); diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index f6f23bfe..e30f8886 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,9 +6,17 @@ #include "generated_plugin_registrant.h" +#include +#include #include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) flutter_onnxruntime_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterOnnxruntimePlugin"); + flutter_onnxruntime_plugin_register_with_registrar(flutter_onnxruntime_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 379e36fa..9c7e2a7a 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,11 +3,14 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + flutter_onnxruntime url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST flserial + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index ffc8c590..9f7f4ab8 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,8 +5,11 @@ import FlutterMacOS import Foundation +import cryptography_flutter +import file_selector_macos import flutter_blue_plus_darwin import flutter_local_notifications +import flutter_onnxruntime import mobile_scanner import package_info_plus import share_plus @@ -15,8 +18,11 @@ import sqflite_darwin import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + CryptographyFlutterPlugin.register(with: registry.registrar(forPlugin: "CryptographyFlutterPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + FlutterOnnxruntimePlugin.register(with: registry.registrar(forPlugin: "FlutterOnnxruntimePlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) diff --git a/macos/Podfile b/macos/Podfile index ff5ddb3b..0d122438 100644 --- a/macos/Podfile +++ b/macos/Podfile @@ -1,4 +1,4 @@ -platform :osx, '10.15' +platform :osx, '14.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 0f1561a5..04f338b5 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -17,6 +17,6 @@ SPEC CHECKSUMS: flserial: 3c161e076dfc73458ec5803e7a9a9d2bb85fadf6 FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 -PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 +PODFILE CHECKSUM: d16f5e5d196d1ca9863d7a71d5885cad7ffa7d2d COCOAPODS: 1.16.2 diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index 10f8906b..ea27169d 100644 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -567,7 +567,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -649,7 +649,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -699,7 +699,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..cf855ad1 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "onnxruntime-swift-package-manager", + "kind" : "remoteSourceControl", + "location" : "https://github.com/masicai/onnxruntime-swift-package-manager", + "state" : { + "revision" : "57f28b1fdd6fe33585370b146a46c597d6750953", + "version" : "1.23.1" + } + } + ], + "version" : 2 +} diff --git a/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..cf855ad1 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "onnxruntime-swift-package-manager", + "kind" : "remoteSourceControl", + "location" : "https://github.com/masicai/onnxruntime-swift-package-manager", + "state" : { + "revision" : "57f28b1fdd6fe33585370b146a46c597d6750953", + "version" : "1.23.1" + } + } + ], + "version" : 2 +} diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements index 2fcad1b4..103ed4dc 100644 --- a/macos/Runner/DebugProfile.entitlements +++ b/macos/Runner/DebugProfile.entitlements @@ -22,5 +22,8 @@ com.apple.security.device.camera + + com.apple.security.files.user-selected.read-only + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist index c55e9d73..9560762d 100644 --- a/macos/Runner/Info.plist +++ b/macos/Runner/Info.plist @@ -32,5 +32,7 @@ MeshCore needs Bluetooth to communicate with LoRa mesh devices NSCameraUsageDescription This app uses the camera to scan QR codes for joining communities. + NSPhotoLibraryUsageDescription + This app lets you pick a photo to compress and send over the mesh. diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements index 2b1c6948..c97754d5 100644 --- a/macos/Runner/Release.entitlements +++ b/macos/Runner/Release.entitlements @@ -18,5 +18,8 @@ com.apple.security.device.camera + + com.apple.security.files.user-selected.read-only + diff --git a/pubspec.yaml b/pubspec.yaml index eaf46c9f..9115c3a7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 9.5.0+13 +version: 9.5.0+16 environment: sdk: ^3.9.2 @@ -42,7 +42,8 @@ dependencies: flserial: git: url: https://github.com/MeshEnvy/flserial.git - ref: 48216310061efc8d5d217cc18014fc2cb501646e + ref: e1864de9b65cda9656dba804329bdd2890dd5a92 + ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers provider: ^6.1.5+1 shared_preferences: ^2.2.2 uuid: ^4.3.3 @@ -58,11 +59,13 @@ dependencies: characters: ^1.4.0 package_info_plus: ^10.1.0 mobile_scanner: ^7.1.4 # QR/barcode scanning + image_picker: ^1.1.2 # Pick photos to send as compressed mesh images qr_flutter: ^4.1.0 # QR code generation url_launcher: ^6.3.0 # Launch URLs in system browser flutter_linkify: ^6.0.0 # Auto-detect and linkify URLs in text gpx: ^2.3.0 path_provider: ^2.1.5 + file_selector: ^1.0.3 # desktop save dialog for GPX export share_plus: ^13.1.0 build_pipe: ^0.3.1 material_symbols_icons: ^4.2928.1 @@ -73,6 +76,15 @@ dependencies: ml_dataframe: ^1.0.0 llamadart: ^0.8.0 flutter_langdetect: ^0.0.1 + cryptography: ^2.9.0 + cryptography_flutter: ^2.3.4 + convert: ^3.1.2 + # ONNX Runtime 1.23.0 via platform channels. Powers the AEIC-SE image codec + # decoder (lib/services/image_codec_backend.dart). arm64-only on Android — see + # the abiFilters note in android/app/build.gradle.kts; a universal APK pays + # ~56 MB for ORT instead of ~18 MB. + flutter_onnxruntime: ^1.8.3 + base32: ^2.2.0 hooks: user_defines: @@ -111,6 +123,17 @@ flutter: assets: - assets/images/ - assets/icons/ + - assets/fonts/ + + fonts: + - family: Inter + fonts: + - asset: assets/fonts/Inter.ttf + - asset: assets/fonts/InterItalic.ttf + style: italic + - family: JetBrains Mono + fonts: + - asset: assets/fonts/JetBrainsMono.ttf flutter_launcher_icons: android: true diff --git a/test/connector/build_update_contact_path_frame_test.dart b/test/connector/build_update_contact_path_frame_test.dart index da88f9aa..1ab5961d 100644 --- a/test/connector/build_update_contact_path_frame_test.dart +++ b/test/connector/build_update_contact_path_frame_test.dart @@ -6,7 +6,7 @@ import 'package:meshcore_open/connector/meshcore_protocol.dart'; void main() { // Frame layout per the doc comment on buildUpdateContactPathFrame: // [cmd][pub_key x32][type][flags][path_len][path x64][name x32] - // [timestamp x4][Lat? x4, Lon? x4][timestamp? x4] + // [last_advert x4][Lat? x4, Lon? x4][lastmod? x4] // // Base (mandatory) bytes: // 1 cmd + 32 pubKey + 1 type + 1 flags + 1 pathLen + 64 path @@ -101,5 +101,77 @@ void main() { expect(latBytes.getInt32(0, Endian.little), (49.123456 * 1e6).round()); expect(lonBytes.getInt32(0, Endian.little), (-123.123456 * 1e6).round()); }); + + int lastAdvertField(Uint8List frame) => ByteData.sublistView( + frame, + baseFrameLength - 4, + baseFrameLength, + ).getUint32(0, Endian.little); + + test('writes the contact advert timestamp, not the phone clock', () { + final advert = DateTime.utc(2025, 6, 1, 12); + final frame = buildUpdateContactPathFrame( + pubKey, + path, + path.length, + lastAdvert: advert, + lastModified: DateTime.utc(2026, 1, 2), + ); + + expect(lastAdvertField(frame), advert.millisecondsSinceEpoch ~/ 1000); + expect( + ByteData.sublistView( + frame, + baseFrameLength + 8, + ).getUint32(0, Endian.little), + DateTime.utc(2026, 1, 2).millisecondsSinceEpoch ~/ 1000, + ); + }); + + test('writes 0 for last advert when unknown', () { + final frame = buildUpdateContactPathFrame(pubKey, path, path.length); + expect(lastAdvertField(frame), 0); + }); + }); + + group('auto-add / repeat freq frames', () { + test('SET_AUTOADD_CONFIG appends max hops only when given', () { + final withoutHops = buildSetAutoAddConfigFrame( + autoAddChat: true, + autoAddRepeater: false, + autoAddRoomServer: false, + autoAddSensor: false, + overwriteOldest: true, + ); + expect(withoutHops, [ + cmdSetAutoAddConfig, + autoAddChatFlag | autoAddOverwriteOldestFlag, + ]); + + final withHops = buildSetAutoAddConfigFrame( + autoAddChat: false, + autoAddRepeater: false, + autoAddRoomServer: false, + autoAddSensor: false, + overwriteOldest: false, + maxHops: 3, + ); + expect(withHops, [cmdSetAutoAddConfig, 0, 3]); + }); + + test('parses RESP_ALLOWED_REPEAT_FREQ ranges', () { + final data = ByteData(1 + 16); + data.setUint8(0, respCodeAllowedRepeatFreq); + data.setUint32(1, 433000, Endian.little); + data.setUint32(5, 433000, Endian.little); + data.setUint32(9, 869495, Endian.little); + data.setUint32(13, 869600, Endian.little); + final ranges = parseAllowedRepeatFreqFrame(data.buffer.asUint8List()); + expect(ranges, [ + (lowKHz: 433000, highKHz: 433000), + (lowKHz: 869495, highKHz: 869600), + ]); + expect(buildGetAllowedRepeatFreqFrame(), [cmdGetAllowedRepeatFreq]); + }); }); } diff --git a/test/connector/contact_push_codes_test.dart b/test/connector/contact_push_codes_test.dart new file mode 100644 index 00000000..5392c3fc --- /dev/null +++ b/test/connector/contact_push_codes_test.dart @@ -0,0 +1,57 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _contactFrame(int code, Uint8List key, String name) { + final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12); + final bytes = data.buffer.asUint8List(); + bytes[0] = code; + bytes.setRange(1, 33, key); + bytes[33] = advTypeChat; + bytes[35] = 0xFF; // path unknown + bytes.setRange(100, 100 + name.length, name.codeUnits); + data.setUint32(132, 1700000000, Endian.little); + return bytes; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + final key = Uint8List.fromList(List.generate(32, (i) => i + 1)); + + test('NEW_ADVERT is discovered only, not a firmware contact', () { + final connector = MeshCoreConnector(); + connector.handleFrameForTest(_contactFrame(pushCodeNewAdvert, key, 'Bob')); + + expect(connector.contacts, isEmpty); + expect(connector.discoveredContacts.map((c) => c.name), contains('Bob')); + }); + + test('CONTACT_DELETED removes the firmware contact', () { + final connector = MeshCoreConnector(); + connector.handleFrameForTest(_contactFrame(respCodeContact, key, 'Bob')); + expect(connector.contacts.length, 1); + + connector.handleFrameForTest([pushCodeContactDeleted, ...key]); + expect(connector.contacts, isEmpty); + }); + + test('CONTACTS_FULL raises the storage-full signal', () async { + final connector = MeshCoreConnector(); + final events = connector.contactsFullEvents.first; + connector.handleFrameForTest([pushCodeContactsFull]); + + expect(connector.contactsStorageFull, isTrue); + await events; + }); +} diff --git a/test/connector/pending_command_replies_test.dart b/test/connector/pending_command_replies_test.dart new file mode 100644 index 00000000..0a8096a7 --- /dev/null +++ b/test/connector/pending_command_replies_test.dart @@ -0,0 +1,70 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/pending_command_replies.dart'; + +void main() { + Uint8List frame(List bytes) => Uint8List.fromList(bytes); + final keyA = Uint8List.fromList(List.generate(32, (i) => i + 1)); + final keyB = Uint8List.fromList(List.generate(32, (i) => i + 100)); + + PendingCommandReplies newQueue() => + PendingCommandReplies(staleAfter: const Duration(seconds: 10)); + + test('ERR goes to the oldest pending command (firmware order)', () { + final queue = newQueue(); + final time = queue.track(buildSetDeviceTimeFrame(1)); + queue.track(buildSetAdvertNameFrame('x')); + + final failed = queue.takeErr(6); + expect(failed, same(time)); + expect(queue.takeOk()?.commandCode, cmdSetAdvertName); + expect(queue.length, 0); + }); + + test('OK skips commands whose success is a specific RESP_CODE', () { + final queue = newQueue(); + queue.track(buildSendTextMsgFrame(keyA, 'hi')); + queue.track(buildRemoveContactFrame(keyA)); + + expect(queue.takeOk()?.commandCode, cmdRemoveContact); + expect(queue.completeReply(frame([respCodeSent, 0, 0, 0, 0, 0])), isTrue); + expect(queue.length, 0); + }); + + test('specific replies clear their entry so a later ERR is not misread', () { + final queue = newQueue(); + queue.track(buildGetChannelFrame(0)); + queue.track(buildSetChannelFrame(1, 'c', Uint8List(16))); + + expect(queue.completeReply(frame([respCodeChannelInfo, 0])), isTrue); + expect(queue.takeErr(2)?.commandCode, cmdSetChannel); + }); + + test('CONTACT only completes GET_CONTACT_BY_KEY for the same key', () { + final queue = newQueue(); + queue.track(buildGetContactByKeyFrame(keyA)); + + expect(queue.completeReply(frame([respCodeContact, ...keyB])), isFalse); + expect(queue.completeReply(frame([respCodeContact, ...keyA])), isTrue); + expect(queue.length, 0); + }); + + test('untracked commands are not enrolled', () { + final queue = newQueue(); + expect(queue.track(buildSyncNextMessageFrame()), isNull); + expect(queue.track(buildRebootFrame()), isNull); + expect(queue.takeErr(1), isNull); + }); + + test('awaited command completes with error on ERR', () async { + final queue = newQueue(); + final pending = queue.track( + buildSetRadioParamsFrame(869525, 250000, 11, 5), + waitForReply: true, + ); + queue.takeErr(6); + await expectLater(pending!.completer!.future, throwsException); + }); +} diff --git a/test/helpers/guessed_location_estimator_test.dart b/test/helpers/guessed_location_estimator_test.dart new file mode 100644 index 00000000..be9c0e6c --- /dev/null +++ b/test/helpers/guessed_location_estimator_test.dart @@ -0,0 +1,197 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:meshcore_open/helpers/guessed_location_estimator.dart'; + +const _phoenix = (33.45, -112.07); +const _casaGrande = (32.88, -111.76); +const _flagstaff = (35.20, -111.65); +const _london = (51.50, -0.12); + +Uint8List _key(List bytes) => + Uint8List.fromList([...bytes, ...List.filled(32 - bytes.length, 0)]); + +GuessInput _input({ + required List candidates, + required List<(Uint8List, double, double)> anchors, + (double, double)? self, +}) => ( + candidates: candidates, + anchors: anchors, + selfPosition: self, + maxRangeKm: null, +); + +GuessCandidate _node(List<(List, int)> paths) => + (publicKey: _key([0x99]), paths: paths); + +double _km((double, double) a, double lat, double lon) => const Distance().as( + LengthUnit.Kilometer, + LatLng(a.$1, a.$2), + LatLng(lat, lon), +); + +void main() { + test('places a node next to the repeater its path ends on', () { + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xA1, 0xB2], 1), + ]), + ], + anchors: [ + (_key([0xA1]), _phoenix.$1, _phoenix.$2), + (_key([0xB2]), _casaGrande.$1, _casaGrande.$2), + ], + self: _phoenix, + ), + ); + + expect(result, hasLength(1)); + final (index, lat, lon, highConfidence) = result.single; + expect(index, 0); + expect(_km(_casaGrande, lat, lon), lessThan(1)); + expect(highConfidence, isFalse); + }); + + test('resolves a colliding hop prefix to the repeater in range', () { + // Two repeaters share prefix 0xB2: one in Tucson, one in London. + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xA1, 0xB2], 1), + ]), + ], + anchors: [ + (_key([0xA1]), _phoenix.$1, _phoenix.$2), + (_key([0xB2]), _london.$1, _london.$2), + (_key([0xB2, 0x01]), _casaGrande.$1, _casaGrande.$2), + ], + self: _phoenix, + ), + ); + + final (_, lat, lon, _) = result.single; + expect(_km(_casaGrande, lat, lon), lessThan(1)); + }); + + test('skips an ambiguous prefix when there is no reference point', () { + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xB2], 1), + ]), + ], + anchors: [ + (_key([0xB2]), _london.$1, _london.$2), + (_key([0xB2, 0x01]), _casaGrande.$1, _casaGrande.$2), + ], + ), + ); + + expect(result, isEmpty); + }); + + test('weights repeaters by how many paths ended on them', () { + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xB2], 1), + ([0xB2], 1), + ([0xB2], 1), + ([0xC3], 1), + ]), + ], + anchors: [ + (_key([0xB2]), _phoenix.$1, _phoenix.$2), + (_key([0xC3]), _casaGrande.$1, _casaGrande.$2), + ], + ), + ); + + final (_, lat, lon, highConfidence) = result.single; + expect(highConfidence, isTrue); + // Three votes for Phoenix, one for Tucson: a quarter of the way. + expect( + lat, + closeTo(_phoenix.$1 + (_casaGrande.$1 - _phoenix.$1) / 4, 0.01), + ); + expect( + lon, + closeTo(_phoenix.$2 + (_casaGrande.$2 - _phoenix.$2) / 4, 0.01), + ); + }); + + test('result does not depend on path order', () { + List<(int, double, double, bool)> run(List<(List, int)> paths) => + estimateGuessedLocations( + _input( + candidates: [_node(paths)], + anchors: [ + (_key([0xB2]), _phoenix.$1, _phoenix.$2), + (_key([0xC3]), _flagstaff.$1, _flagstaff.$2), + ], + ), + ); + + expect( + run([ + ([0xB2], 1), + ([0xC3], 1), + ]), + run([ + ([0xC3], 1), + ([0xB2], 1), + ]), + ); + }); + + test('drops a repeater too far from the others to share one node', () { + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xB2], 1), + ([0xC3], 1), + ([0xD4], 1), + ]), + ], + anchors: [ + (_key([0xB2]), _phoenix.$1, _phoenix.$2), + (_key([0xC3]), _casaGrande.$1, _casaGrande.$2), + (_key([0xD4]), _london.$1, _london.$2), + ], + ), + ); + + final (_, lat, lon, _) = result.single; + expect(lat, closeTo((_phoenix.$1 + _casaGrande.$1) / 2, 0.01)); + expect(lon, closeTo((_phoenix.$2 + _casaGrande.$2) / 2, 0.01)); + }); + + test('handles 2-byte hop hashes', () { + final result = estimateGuessedLocations( + _input( + candidates: [ + _node([ + ([0xA1, 0x01, 0xB2, 0x02], 2), + ]), + ], + anchors: [ + (_key([0xA1, 0x01]), _phoenix.$1, _phoenix.$2), + (_key([0xB2, 0x02]), _casaGrande.$1, _casaGrande.$2), + (_key([0xB2, 0x03]), _flagstaff.$1, _flagstaff.$2), + ], + self: _phoenix, + ), + ); + + final (_, lat, lon, _) = result.single; + expect(_km(_casaGrande, lat, lon), lessThan(1)); + }); +} diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart new file mode 100644 index 00000000..11e1b022 --- /dev/null +++ b/test/helpers/message_url_image_helper_test.dart @@ -0,0 +1,108 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/helpers/message_url_image_helper.dart'; + +void main() { + group('MessageUrlImageHelper', () { + tearDown(() => MessageUrlImageHelper.httpClient = null); + + void mockPyxPage(String id) { + MessageUrlImageHelper.httpClient = MockClient((request) async { + expect(request.url.toString(), 'https://pyx.li/?i=$id'); + return http.Response( + '', + 200, + headers: {'content-type': 'text/html; charset=utf-8'}, + ); + }); + } + + test('parses short pyx ids', () async { + mockPyxPage('RzmdkTsE'); + final attachment = await MessageUrlImageHelper.parse( + 'my picture: https://pyx.li/?i=RzmdkTsE text', + ); + + expect(attachment, 'https://pyx.li/i/RzmdkTsE.jpg'); + }); + + test('parses direct pyx image urls', () async { + mockPyxPage('Cd1KFiwu'); + final attachment = await MessageUrlImageHelper.parse( + 'https://pyx.li/?i=Cd1KFiwu', + ); + + expect(attachment, 'https://pyx.li/i/Cd1KFiwu.jpg'); + }); + + test('parses provider-hosted ipfs links', () async { + final attachment = await MessageUrlImageHelper.parse( + 'my picture: https://uneven-plum-tarantula.myfilebase.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ); + + expect(attachment, isNotNull); + expect( + attachment, + 'https://uneven-plum-tarantula.myfilebase.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + }); + + test('parses direct ipfs cid urls', () async { + final attachment = await MessageUrlImageHelper.parse( + 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ); + + expect(attachment, isNotNull); + expect( + attachment, + 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + }); + + test('parses direct ipfs cid urls without double slashes', () async { + final attachment = await MessageUrlImageHelper.parse( + 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ); + + expect( + attachment, + 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + }); + + test('parses http image urls', () async { + final attachment = await MessageUrlImageHelper.parse( + 'see this image https://example.com/picture.png?size=large additional text', + ); + + expect(attachment, isNotNull); + expect(attachment, 'https://example.com/picture.png?size=large'); + }); + + test('returns null for plain text', () async { + expect(await MessageUrlImageHelper.parse('hello world'), isNull); + }); + + test('detects supported image URLs without resolving them', () { + expect( + MessageUrlImageHelper.hasPotentialImageUrl( + 'https://pyx.li/?i=RzmdkTsE', + ), + isTrue, + ); + expect( + MessageUrlImageHelper.hasPotentialImageUrl('hello world'), + isFalse, + ); + }); + + test('returns null for non-image ipfs gateway URL', () async { + final attachment = await MessageUrlImageHelper.parseVerified( + 'https://lime-famous-rat-748.mypinata.cloud/ipfs/bafybeih3jqv36rsxqx7yw3k3ixhganrevrk7xmcxgkr2zuzjegxdytb3nq', + ); + + expect(attachment, isNull); + }); + }); +} diff --git a/test/helpers/path_helper_test.dart b/test/helpers/path_helper_test.dart index 38abf2cd..67391c94 100644 --- a/test/helpers/path_helper_test.dart +++ b/test/helpers/path_helper_test.dart @@ -22,15 +22,64 @@ Contact _contact({ } void main() { - test('resolvePathNames ignores chat nodes and keeps repeater/room nodes', () { + test('splitPathBytes groups bytes by hash width', () { + final hops = PathHelper.splitPathBytes([0xA1, 0xA2, 0xC1, 0xC2], 2); + + expect(hops, hasLength(2)); + expect(hops.first, equals(Uint8List.fromList([0xA1, 0xA2]))); + expect(hops.last, equals(Uint8List.fromList([0xC1, 0xC2]))); + expect(PathHelper.formatHopHex(hops.first), equals('A1A2')); + }); + + test( + 'resolvePathNames ignores chat nodes and keeps repeater/room nodes with 1-byte paths', + () { + final contacts = [ + _contact(firstByte: 0xF2, name: 'MunTui', type: advTypeChat), + _contact(firstByte: 0x7E, name: 'zrepeater', type: advTypeRepeater), + _contact(firstByte: 0xBA, name: 'USS Ronald Reagan', type: advTypeRoom), + ]; + + final resolved = PathHelper.resolvePathNames( + [0xF2, 0x7E, 0xBA], + contacts, + 1, // 1-byte hash width + ); + + expect(resolved, equals('F2 → zrepeater → USS Ronald Reagan')); + }, + ); + + test('resolvePathNames supports multi-byte paths', () { final contacts = [ - _contact(firstByte: 0xF2, name: 'MunTui', type: advTypeChat), - _contact(firstByte: 0x7E, name: 'zrepeater', type: advTypeRepeater), - _contact(firstByte: 0xBA, name: 'USS Ronald Reagan', type: advTypeRoom), + _contact(firstByte: 0xA1, name: 'Repeater1', type: advTypeRepeater), + _contact(firstByte: 0xC1, name: 'Room42', type: advTypeRoom), ]; - final resolved = PathHelper.resolvePathNames([0xF2, 0x7E, 0xBA], contacts); + // Contacts with 2-byte public keys + contacts[0] = Contact( + publicKey: Uint8List.fromList([0xA1, 0xA2, ...List.filled(30, 0)]), + name: 'Repeater1', + type: advTypeRepeater, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.now(), + ); + contacts[1] = Contact( + publicKey: Uint8List.fromList([0xC1, 0xC2, ...List.filled(30, 0)]), + name: 'Room42', + type: advTypeRoom, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.now(), + ); - expect(resolved, equals('F2 → zrepeater → USS Ronald Reagan')); + final resolved = PathHelper.resolvePathNames( + [0xA1, 0xA2, 0xC1, 0xC2], + contacts, + 2, // 2-byte hash width + ); + + expect(resolved, equals('Repeater1 → Room42')); }); } diff --git a/test/helpers/utf8_length_limiter_test.dart b/test/helpers/utf8_length_limiter_test.dart new file mode 100644 index 00000000..6aa2a7ef --- /dev/null +++ b/test/helpers/utf8_length_limiter_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/utf8_length_limiter.dart'; + +TextEditingValue _value(String text, [int? cursor]) => TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: cursor ?? text.length), +); + +void main() { + const formatter = Utf8LengthLimitingTextInputFormatter(5); + + test('accepts edits within the limit', () { + final result = formatter.formatEditUpdate(_value('ab'), _value('abc')); + expect(result.text, 'abc'); + }); + + test('clips only the inserted text and keeps the end of the draft', () { + // Paste "XYZ" at the start of "abc" (limit 5 bytes). + final result = formatter.formatEditUpdate( + _value('abc', 0), + _value('XYZabc', 3), + ); + expect(result.text, 'XYabc'); + expect(result.selection.baseOffset, 2); + }); + + test('rejects an insertion in the middle when full', () { + final result = formatter.formatEditUpdate( + _value('abcde', 2), + _value('abXcde', 3), + ); + expect(result.text, 'abcde'); + expect(result.selection.baseOffset, 2); + }); + + test('does not split a multi-code-point grapheme', () { + // Family emoji is 18 UTF-8 bytes, so it cannot fit in the 4 bytes left. + final result = formatter.formatEditUpdate( + _value('a'), + _value('a\u{1F468}‍\u{1F469}‍\u{1F467}'), + ); + expect(result.text, 'a'); + }); + + test('keeps whole emoji that fit', () { + const limiter = Utf8LengthLimitingTextInputFormatter(9); + final result = limiter.formatEditUpdate( + _value('a'), + _value('a\u{1F600}\u{1F601}'), + ); + expect(result.text, 'a\u{1F600}\u{1F601}'); + final clipped = const Utf8LengthLimitingTextInputFormatter( + 8, + ).formatEditUpdate(_value('a'), _value('a\u{1F600}\u{1F601}')); + expect(clipped.text, 'a\u{1F600}'); + }); + + test('replacing one emoji with another sharing a surrogate stays valid', () { + const limiter = Utf8LengthLimitingTextInputFormatter(5); + final result = limiter.formatEditUpdate( + _value('a\u{1F600}'), + _value('a\u{1F601}\u{1F602}'), + ); + expect(result.text, 'a\u{1F601}'); + }); + + test('allows deletions even when the text is already over the limit', () { + final result = formatter.formatEditUpdate( + _value('abcdefg'), + _value('abcdef'), + ); + expect(result.text, 'abcdef'); + }); +} diff --git a/test/image_chunk_transport_test.dart b/test/image_chunk_transport_test.dart new file mode 100644 index 00000000..d5a2959b --- /dev/null +++ b/test/image_chunk_transport_test.dart @@ -0,0 +1,1257 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/image_chunk_transport.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; + +Uint8List payloadOf(int length, {int seed = 7}) => Uint8List.fromList( + List.generate(length, (i) => (i * 37 + seed * 11) & 0xFF), +); + +const ImageStreamMetadata stdMeta = ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, +); +const ImageStreamMetadata highMeta = ImageStreamMetadata( + rate: ImageCodecRatePoint.high, +); + +const int senderA = 0x1234; +const int senderB = 0xBEEF; + +/// A copy of [blob] with the byte at [offset] flipped by [mask]. +Uint8List flipByte(Uint8List blob, int offset, {int mask = 0x01}) { + final copy = Uint8List.fromList(blob); + copy[offset] ^= mask; + return copy; +} + +/// Feeds [blobs] to [r] in the given order and returns the completed image, if +/// any completed. +ImageReassemblyResult? feed( + ImageReassembler r, + List blobs, { + int channelIndex = 0, + DateTime? now, +}) { + ImageReassemblyResult? result; + for (final blob in blobs) { + final outcome = r.addChunk(blob, channelIndex: channelIndex, now: now); + result ??= outcome.result; + } + return result; +} + +void main() { + group('constants', () { + test('every blob fits the binding transport limit', () { + expect(kImageChunkBlobBytes, 163); + expect(kImageChunkHeaderBytes, 4); + expect(kImageChunkBodyBytes, 158); + // Chunk 0 spends 1 byte on metadata and nothing else: the CRC-16 that + // briefly lived here was removed once it turned out the LoRa PHY CRC and + // MeshCore's per-packet HMAC already cover a delivered chunk. + expect(kImageChunkMetadataBytes, 1); + expect(kImageChunkZeroMetadataBytes, 1); + expect(kImageChunkFirstCapacity, 157); + expect(kImageChunkCapacity, 158); + expect(kImageMaxPayloadBytes, 157 + 14 * 158); + }); + + test('measured codec worst cases hit the design chunk counts', () { + // ft32 (standard) max 209 B, ft16 (high) max 409 B. + expect(imageDataChunkCount(209), 2); + expect(imageDataChunkCount(409), 3); + // With chunk 0 back at 157 data bytes the measured ft32 MEAN fits in a + // single data chunk (2 packets with parity), which is the whole point of + // dropping the CRC. + expect(ImageCodecRateStats.standard.meanBytes, 156); + expect(imageDataChunkCount(ImageCodecRateStats.standard.meanBytes), 1); + expect(imageDataChunkCount(157), 1); + expect(imageDataChunkCount(158), 2); + expect(imageDataChunkCount(ImageCodecRateStats.standard.minBytes), 1); + expect(imageDataChunkCount(ImageCodecRateStats.high.meanBytes), 2); + }); + }); + + group('metadata byte', () { + test('round-trips both rate points', () { + for (final rate in ImageCodecRatePoint.values) { + final meta = ImageStreamMetadata(rate: rate); + expect(ImageStreamMetadata.decode(meta.encode()), meta); + } + }); + + test('rejects an unrepresentable resolution', () { + expect( + () => const ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, + squareSize: 999, + ).encode(), + throwsArgumentError, + ); + }); + + test('an unknown RATE code is what signals a format break', () { + // The byte is aspect(4) | resolution(2) | rate(2). Resolution is now a + // closed 2-bit field: all four codes are legal, so an unknown resolution + // is no longer expressible. Rate keeps two spare codes (2 and 3), and + // that is the channel a future incompatible format must use so older + // receivers reject it instead of guessing. + expect(ImageStreamMetadata.decode(0x02), isNull); // rate code 2 + expect(ImageStreamMetadata.decode(0x03), isNull); // rate code 3 + // 0xF0 is aspect 15 (unknown shape), resolution 0, rate 0 — all legal. + final legal = ImageStreamMetadata.decode(0xF0); + expect(legal, isNotNull); + expect(legal!.aspectCode, kImageAspectUnknown); + expect(legal.isSquare, isTrue); + }); + }); + + group('chunking', () { + test('one, two and three chunk payloads produce the right blob shapes', () { + final cases = { + 1: 1, + kImageChunkFirstCapacity: 1, + kImageChunkFirstCapacity + 1: 2, + kImageChunkFirstCapacity + kImageChunkCapacity: 2, + kImageChunkFirstCapacity + kImageChunkCapacity + 1: 3, + }; + cases.forEach((length, expectedChunks) { + final set = buildImageChunks( + payload: payloadOf(length), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 3, + ); + expect(set.dataChunkCount, expectedChunks, reason: 'len $length'); + expect(set.blobs.length, expectedChunks + 1); // + parity + for (final blob in set.blobs) { + expect(blob.length, lessThanOrEqualTo(kImageChunkBlobBytes)); + } + }); + }); + + test('header fields are on the wire where the spec says', () { + final set = buildImageChunks( + payload: payloadOf(400), + metadata: highMeta, + senderPrefix: senderA, + imgId: 0x5A, + ); + expect(set.dataChunkCount, 3); + for (var i = 0; i < set.blobs.length; i++) { + final blob = set.blobs[i]; + expect(blob[0], 0x12); + expect(blob[1], 0x34); + expect(blob[2], 0x5A); + expect((blob[3] >> 4) & 0x0F, i); + expect(blob[3] & 0x0F, 3); + } + expect(parseImageChunkHeader(set.blobs.last)!.isParity, isTrue); + expect(set.blobs[4 - 1].length, greaterThan(kImageChunkHeaderBytes)); + // Chunk 0 carries the metadata byte first. + expect(set.blobs[0][kImageChunkHeaderBytes], highMeta.encode()); + }); + + test('rejects a payload larger than the framing can address', () { + expect( + () => buildImageChunks( + payload: payloadOf(kImageMaxPayloadBytes + 1), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 1, + ), + throwsArgumentError, + ); + }); + }); + + group('round trip', () { + for (final length in [ + 100, // 1 chunk + 300, // 2 chunks + 460, // 3 chunks + ]) { + test('$length bytes round-trips in order', () { + final payload = payloadOf(length); + final set = buildImageChunks( + payload: payload, + metadata: highMeta, + senderPrefix: senderA, + imgId: 11, + ); + final r = ImageReassembler(selfPrefix: senderB); + final result = feed(r, set.blobs); + expect(result, isNotNull); + expect(result!.data, payload); + expect(result.metadata, highMeta); + expect(result.recoveredWithParity, isFalse); + expect(result.chunkCount, set.dataChunkCount); + expect(r.pendingCount, 0, reason: 'trailing parity must not linger'); + }); + } + + test('completion callback fires exactly once', () { + final payload = payloadOf(300); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 4, + ); + final results = []; + final r = ImageReassembler(onImage: results.add); + feed(r, set.blobs); + expect(results.length, 1); + expect(results.single.data, payload); + }); + + test('out-of-order arrival still reassembles', () { + final payload = payloadOf(460, seed: 3); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 9, + ); + // All three data chunks arrive out of order, parity last (so this + // exercises reordering, not parity recovery). + final shuffled = [ + set.blobs[2], + set.blobs[0], + set.blobs[1], + set.blobs[3], // parity + ]; + final r = ImageReassembler(); + final result = feed(r, shuffled); + expect(result, isNotNull); + expect(result!.data, payload); + expect(result.recoveredWithParity, isFalse); + }); + + test('duplicate chunks are ignored', () { + final payload = payloadOf(460); // 3 data chunks + parity + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 2, + ); + final r = ImageReassembler(); + expect(r.addChunk(set.blobs[0]).status, ImageChunkStatus.accepted); + expect(r.addChunk(set.blobs[0]).status, ImageChunkStatus.duplicate); + expect(r.addChunk(set.blobs[2]).status, ImageChunkStatus.accepted); + expect(r.addChunk(set.blobs[2]).status, ImageChunkStatus.duplicate); + final done = r.addChunk(set.blobs[1]); + expect(done.status, ImageChunkStatus.completed); + expect(done.result!.data, payload); + expect(done.result!.recoveredWithParity, isFalse); + // Trailing parity and late duplicates are ignored, not restarted. + expect(r.addChunk(set.blobs[3]).status, ImageChunkStatus.duplicate); + expect(r.addChunk(set.blobs[1]).status, ImageChunkStatus.duplicate); + expect(r.pendingCount, 0); + }); + + test('a duplicate parity chunk is ignored', () { + final set = buildImageChunks( + payload: payloadOf(460), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 15, + ); + final r = ImageReassembler(); + expect(r.addChunk(set.blobs[3]).status, ImageChunkStatus.accepted); + expect(r.addChunk(set.blobs[3]).status, ImageChunkStatus.duplicate); + expect(r.pendingCount, 1); + }); + + test('parity completes an image that is one chunk short', () { + final payload = payloadOf(300); // 2 data chunks + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 16, + ); + final r = ImageReassembler(); + expect(r.addChunk(set.blobs[0]).status, ImageChunkStatus.accepted); + final done = r.addChunk(set.blobs[2]); // parity rebuilds chunk 1 + expect(done.status, ImageChunkStatus.completed); + expect(done.result!.data, payload); + expect(done.result!.recoveredWithParity, isTrue); + }); + + test('two senders interleaved on one channel do not mix', () { + final a = payloadOf(300, seed: 1); + final b = payloadOf(300, seed: 2); + final setA = buildImageChunks( + payload: a, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 5, + ); + final setB = buildImageChunks( + payload: b, + metadata: highMeta, + senderPrefix: senderB, + imgId: 5, // same img_id on purpose + ); + final got = {}; + final r = ImageReassembler( + onImage: (res) => got[res.key.senderPrefix] = res.data, + ); + feed(r, [ + setA.blobs[0], + setB.blobs[1], + setA.blobs[1], + setB.blobs[0], + ]); + expect(got[senderA], a); + expect(got[senderB], b); + }); + + test('the same img_id on different channels stays separate', () { + final payload = payloadOf(300); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 8, + ); + final r = ImageReassembler(); + expect( + r.addChunk(set.blobs[0], channelIndex: 0).status, + ImageChunkStatus.accepted, + ); + expect( + r.addChunk(set.blobs[1], channelIndex: 1).status, + ImageChunkStatus.accepted, + ); + expect(r.pendingCount, 2); + }); + }); + + group('parity recovery', () { + test('recovers any single lost data chunk (2 and 3 chunk images)', () { + for (final length in [300, 460]) { + final payload = payloadOf(length, seed: length); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 6, + ); + for (var lost = 0; lost < set.dataChunkCount; lost++) { + final blobs = [ + for (var i = 0; i < set.blobs.length; i++) + if (i != lost) set.blobs[i], + ]; + final r = ImageReassembler(); + final result = feed(r, blobs); + expect(result, isNotNull, reason: 'len $length lost $lost'); + expect(result!.data, payload, reason: 'len $length lost $lost'); + expect(result.metadata, stdMeta); + expect(result.recoveredWithParity, isTrue); + } + } + }); + + test('recovers the short final chunk (length is carried by parity)', () { + // 158 + 1 => final chunk is a single byte long. + final payload = payloadOf(kImageChunkFirstCapacity + 1); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 12, + ); + expect(set.dataChunkCount, 2); + final r = ImageReassembler(); + final result = feed(r, [set.blobs[0], set.blobs[2]]); + expect(result, isNotNull); + expect(result!.data, payload); + expect(result.recoveredWithParity, isTrue); + }); + + test('total=1 with parity recovers the only data chunk', () { + final payload = payloadOf(100); + final set = buildImageChunks( + payload: payload, + metadata: highMeta, + senderPrefix: senderA, + imgId: 1, + ); + expect(set.dataChunkCount, 1); + expect(set.blobs.length, 2); + final r = ImageReassembler(); + final result = feed(r, [set.blobs[1]]); // parity only + expect(result, isNotNull); + expect(result!.data, payload); + expect(result.metadata, highMeta); + expect(result.recoveredWithParity, isTrue); + }); + + test('losing two chunks fails and never yields a wrong image', () { + final payload = payloadOf(460); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 7, + ); + final r = ImageReassembler(); + // Deliver only chunk 1 and parity: two data chunks are missing. + final result = feed(r, [set.blobs[1], set.blobs[3]]); + expect(result, isNull); + expect(r.pendingCount, 1); + }); + + test('parity is optional', () { + final payload = payloadOf(300); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 3, + parity: false, + ); + expect(set.hasParity, isFalse); + expect(set.blobs.length, 2); + final r = ImageReassembler(); + expect(feed(r, set.blobs)!.data, payload); + }); + }); + + group('TTL and eviction', () { + test('a stalled image expires and is reported as failed', () { + final set = buildImageChunks( + payload: payloadOf(460), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 21, + ); + final failures = []; + final start = DateTime(2026, 1, 1, 12); + final r = ImageReassembler( + ttl: const Duration(seconds: 60), + onFailed: failures.add, + ); + r.addChunk(set.blobs[0], now: start); + r.addChunk(set.blobs[1], now: start.add(const Duration(seconds: 30))); + expect(r.pendingCount, 1); + + expect( + r.evictExpired(now: start.add(const Duration(seconds: 59))), + isEmpty, + ); + expect(r.pendingCount, 1); + + final expired = r.evictExpired( + now: start.add(const Duration(minutes: 2)), + ); + expect(expired.length, 1); + expect(expired.single.total, 3); + expect(expired.single.receivedDataChunks, 2); + expect(expired.single.hadParity, isFalse); + expect(expired.single.missingChunks, 1); + expect(failures.length, 1); + expect(r.pendingCount, 0); + }); + + test('addChunk sweeps expired streams', () { + final setOld = buildImageChunks( + payload: payloadOf(460), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 30, + ); + final setNew = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderB, + imgId: 31, + ); + final failures = []; + final start = DateTime(2026, 1, 1); + final r = ImageReassembler(onFailed: failures.add); + r.addChunk(setOld.blobs[0], now: start); + r.addChunk(setNew.blobs[0], now: start.add(const Duration(minutes: 5))); + expect(failures.length, 1); + expect(failures.single.key.imgId, 30); + expect(r.pendingCount, 1); + }); + + test('an unrelated chunk after expiry does not resurrect the old data', () { + final set = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 40, + ); + final start = DateTime(2026, 5, 5); + final r = ImageReassembler(); + r.addChunk(set.blobs[0], now: start); + final late = r.addChunk( + set.blobs[1], + now: start.add(const Duration(minutes: 2)), + ); + // Chunk 0 expired, so chunk 1 alone cannot complete anything. + expect(late.status, ImageChunkStatus.accepted); + expect(late.result, isNull); + }); + + test('too many concurrent streams evicts the oldest', () { + final start = DateTime(2026, 2, 2); + final failures = []; + final r = ImageReassembler( + maxConcurrentStreams: 2, + onFailed: failures.add, + ); + for (var i = 0; i < 3; i++) { + final set = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 50 + i, + ); + r.addChunk(set.blobs[0], now: start.add(Duration(seconds: i))); + } + expect(r.pendingCount, 2); + expect(failures.length, 1); + expect(failures.single.key.imgId, 50); + }); + }); + + group('boundary cases', () { + test('empty payload round-trips as one chunk', () { + final set = buildImageChunks( + payload: Uint8List(0), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 0, + ); + expect(set.dataChunkCount, 1); + expect( + set.blobs[0].length, + kImageChunkHeaderBytes + kImageChunkZeroMetadataBytes, + ); + final r = ImageReassembler(); + final result = feed(r, set.blobs); + expect(result, isNotNull); + expect(result!.data, isEmpty); + expect(result.metadata, stdMeta); + }); + + test('empty payload recovers from parity alone', () { + final set = buildImageChunks( + payload: Uint8List(0), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 0, + ); + final r = ImageReassembler(); + final result = feed(r, [set.blobs[1]]); + expect(result, isNotNull); + expect(result!.data, isEmpty); + }); + + test('maximum addressable payload round-trips', () { + final payload = payloadOf(kImageMaxPayloadBytes); + final set = buildImageChunks( + payload: payload, + metadata: highMeta, + senderPrefix: senderA, + imgId: 255, + ); + expect(set.dataChunkCount, kImageMaxDataChunks); + expect(set.blobs.length, kImageMaxDataChunks + 1); + for (final blob in set.blobs) { + expect(blob.length, lessThanOrEqualTo(kImageChunkBlobBytes)); + } + final r = ImageReassembler(); + expect(feed(r, set.blobs.reversed.toList())!.data, payload); + }); + + test('maximum payload still recovers a single loss', () { + final payload = payloadOf(kImageMaxPayloadBytes, seed: 5); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 254, + ); + final blobs = [ + for (var i = 0; i < set.blobs.length; i++) + if (i != kImageMaxDataChunks - 1) set.blobs[i], + ]; + final r = ImageReassembler(); + final result = feed(r, blobs); + expect(result!.data, payload); + expect(result.recoveredWithParity, isTrue); + }); + + test('img_id wraps around 255 -> 0', () { + final alloc = ImageIdAllocator(seed: 254); + expect(alloc.next(), 254); + expect(alloc.next(), 255); + expect(alloc.next(), 0); + expect(alloc.next(), 1); + }); + + test('img_id wraparound reusing a key restarts the stream', () { + final first = buildImageChunks( + payload: payloadOf(460, seed: 1), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 77, + ); + final second = payloadOf(300, seed: 2); + final secondSet = buildImageChunks( + payload: second, + metadata: highMeta, + senderPrefix: senderA, + imgId: 77, // wrapped back onto the same id + ); + final r = ImageReassembler(); + // Partially deliver the first image (3 data chunks), then the second + // image (2 data chunks) arrives under the same key. + expect(r.addChunk(first.blobs[0]).status, ImageChunkStatus.accepted); + expect( + r.addChunk(secondSet.blobs[0]).status, + ImageChunkStatus.conflicting, + ); + final done = r.addChunk(secondSet.blobs[1]); + expect(done.status, ImageChunkStatus.completed); + expect(done.result!.data, second); + }); + + test('chunks bearing our own prefix are dropped as loopback', () { + final set = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 1, + ); + final r = ImageReassembler(selfPrefix: senderA); + expect(r.addChunk(set.blobs[0]).status, ImageChunkStatus.fromSelf); + expect(r.pendingCount, 0); + }); + + test('malformed blobs are rejected, not stored', () { + final r = ImageReassembler(); + expect( + r.addChunk(Uint8List.fromList([1, 2, 3])).status, + ImageChunkStatus.malformed, + ); + // total == 0 is illegal. + expect( + r.addChunk(Uint8List.fromList([0, 1, 2, 0x00, 9])).status, + ImageChunkStatus.malformed, + ); + // index > total is illegal. + expect( + r.addChunk(Uint8List.fromList([0, 1, 2, 0x32, 9])).status, + ImageChunkStatus.malformed, + ); + // Over-long blob cannot have come from this framing. + expect( + r.addChunk(Uint8List(kImageChunkBlobBytes + 1)).status, + ImageChunkStatus.malformed, + ); + expect(r.pendingCount, 0); + }); + + test('senderPrefixFromKey needs two bytes', () { + expect(senderPrefixFromKey(null), isNull); + expect(senderPrefixFromKey([0x12]), isNull); + expect(senderPrefixFromKey([0x12, 0x34, 0x56]), 0x1234); + }); + }); + + group('protocol glue', () { + test('CMD_SEND_CHANNEL_DATA flood frame matches the wire spec', () { + final frame = buildSendChannelDataFrame( + channelIndex: 0, + dataType: dataTypeAeicImage, + payload: Uint8List.fromList([0xAA, 0xBB]), + ); + expect(frame, [0x3E, 0x00, 0xFF, 0x1C, 0xAE, 0xAA, 0xBB]); + }); + + test('a direct-path frame inserts the path bytes before the data type', () { + final frame = buildSendChannelDataFrame( + channelIndex: 2, + dataType: dataTypeAeicImage, + payload: Uint8List.fromList([0x01]), + pathLen: 0x02, + path: Uint8List.fromList([0x11, 0x22]), + ); + expect(frame, [0x3E, 0x02, 0x02, 0x11, 0x22, 0x1C, 0xAE, 0x01]); + }); + + test('RESP_CODE_CHANNEL_DATA_RECV parses, snr is signed', () { + final frame = Uint8List.fromList([ + 0x1B, + 0xF8, + 0, + 0, + 3, + 0xFF, + 0x1C, + 0xAE, + 2, + 0x42, + 0x43, + ]); + final parsed = parseChannelDataFrame(frame)!; + expect(parsed.snrRaw, -8); + expect(parsed.snrDb, -2.0); + expect(parsed.channelIndex, 3); + expect(parsed.arrivedByFlood, isFalse); + expect(parsed.hopCount, isNull); + expect(parsed.dataType, dataTypeAeicImage); + expect(parsed.payload, [0x42, 0x43]); + }); + + test('a flooded frame exposes hop count and hash width', () { + final frame = Uint8List.fromList([ + 0x1B, + 0x04, + 0, + 0, + 0, + 0x43, + 0x1C, + 0xAE, + 0, + ]); + final parsed = parseChannelDataFrame(frame)!; + expect(parsed.arrivedByFlood, isTrue); + expect(parsed.hopCount, 3); + expect(parsed.pathHashWidth, 2); + expect(parsed.payload, isEmpty); + }); + + test('truncated or foreign frames parse as null', () { + expect(parseChannelDataFrame(Uint8List(4)), isNull); + expect( + parseChannelDataFrame( + Uint8List.fromList([0x1B, 0, 0, 0, 0, 0xFF, 0x1C, 0xAE, 5, 1]), + ), + isNull, + ); + expect( + parseChannelDataFrame( + Uint8List.fromList([0x10, 0, 0, 0, 0, 0xFF, 0x1C, 0xAE, 0]), + ), + isNull, + ); + }); + + test( + 'transport sends chunks strictly sequentially and reassembles', + () async { + final sent = []; + var inFlight = 0; + var maxInFlight = 0; + final received = []; + final rxWithCallback = ImageReassembler( + selfPrefix: senderB, + onImage: received.add, + ); + + final tx = ImageChunkTransport( + senderPrefix: senderA, + reassembler: rxWithCallback, + idAllocator: ImageIdAllocator(seed: 60), + send: (blob, channelIndex) async { + inFlight++; + maxInFlight = maxInFlight > inFlight ? maxInFlight : inFlight; + await Future.delayed(const Duration(milliseconds: 1)); + sent.add(blob); + inFlight--; + }, + ); + + final payload = payloadOf(460, seed: 9); + final set = await tx.sendImage( + payload: payload, + metadata: highMeta, + channelIndex: 1, + ); + expect(set.imgId, 60); + expect(sent.length, 4); + expect(maxInFlight, 1); + + // Loop the blobs back through the receive path as real frames. + for (final blob in sent) { + final frame = BytesBuilder() + ..add([0x1B, 0x10, 0, 0, 1, 0xFF, 0x1C, 0xAE, blob.length]) + ..add(blob); + tx.handleFrame(frame.toBytes()); + } + expect(received.length, 1); + expect(received.single.data, payload); + expect(received.single.key.channelIndex, 1); + }, + ); + + test('handleFrame ignores other data types and other frames', () { + final rx = ImageReassembler(); + final tx = ImageChunkTransport( + senderPrefix: senderA, + reassembler: rx, + send: (_, _) async {}, + ); + expect( + tx.handleFrame( + Uint8List.fromList([0x1B, 0, 0, 0, 0, 0xFF, 0x01, 0x00, 0]), + ), + isNull, + ); + expect(tx.handleFrame(Uint8List.fromList([0x00])), isNull); + expect(rx.pendingCount, 0); + }); + + test('concurrent sendImage calls do not interleave on the wire', () async { + final order = []; + final tx = ImageChunkTransport( + senderPrefix: senderA, + reassembler: ImageReassembler(), + idAllocator: ImageIdAllocator(seed: 100), + send: (blob, _) async { + await Future.delayed(const Duration(milliseconds: 1)); + order.add('${blob[2]}:${(blob[3] >> 4) & 0x0F}'); + }, + ); + final a = tx.sendImage(payload: payloadOf(300), metadata: stdMeta); + final b = tx.sendImage(payload: payloadOf(300), metadata: stdMeta); + await Future.wait(>[a, b]); + expect(order, [ + '100:0', + '100:1', + '100:2', + '101:0', + '101:1', + '101:2', + ]); + }); + }); + + group('regressions confirmed by adversarial review', () { + // PROBE A: an image completes; a DIFFERENT image reusing the same img_id + // arrives within the TTL. The recently-completed shortcut used to report + // every chunk of it as `duplicate`, so onImage never fired, onFailed never + // fired, and the image was lost with no diagnostic. ImageIdAllocator seeds + // from Random().nextInt(256), so a restart really can re-roll a live id. + test('a new image reusing a just-completed img_id is not swallowed', () { + final delivered = []; + final failed = []; + final r = ImageReassembler(onImage: delivered.add, onFailed: failed.add); + + final first = buildImageChunks( + payload: payloadOf(200, seed: 1), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 42, + ); + feed(r, first.blobs); + expect(delivered, hasLength(1), reason: 'first image should complete'); + + // Same sender, same img_id, different content and a different length. + final second = buildImageChunks( + payload: payloadOf(300, seed: 99), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 42, + ); + feed(r, second.blobs); + + expect(delivered, hasLength(2), reason: 'second image must not be lost'); + expect(delivered.last.data, equals(payloadOf(300, seed: 99))); + expect(failed, isEmpty); + }); + + test('a genuine re-send of a delivered chunk is still a duplicate', () { + final delivered = []; + final r = ImageReassembler(onImage: delivered.add); + final set = buildImageChunks( + payload: payloadOf(200, seed: 1), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 42, + ); + feed(r, set.blobs); + expect(delivered, hasLength(1)); + + // Replay every blob verbatim: none may open a new stream. + for (final blob in set.blobs) { + final outcome = r.addChunk(blob, channelIndex: 0); + expect(outcome.status, ImageChunkStatus.duplicate); + } + expect(delivered, hasLength(1)); + expect(r.pendingCount, 0); + }); + + // PROBE B/C: a flipped bit in the parity length byte used to yield a + // silently TRUNCATED image reported as `completed`. Only the last data + // chunk may be short. + test( + 'corrupt parity length is rejected rather than silently truncating', + () { + for (final payloadLen in [300, 400]) { + final set = buildImageChunks( + payload: payloadOf(payloadLen, seed: 3), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 7, + ); + final data = set.blobs.sublist(0, set.dataChunkCount); + final parity = Uint8List.fromList(set.blobs.last); + // Corrupt the len_xor byte (first body byte, just after the header). + parity[kImageChunkHeaderBytes] ^= 0x02; + + final delivered = []; + final r = ImageReassembler(onImage: delivered.add); + // Drop a NON-FINAL chunk (index 1 of >=3, else index 0) and supply + // the corrupted parity. + final dropIndex = data.length >= 3 ? 1 : 0; + final kept = [ + for (var i = 0; i < data.length; i++) + if (i != dropIndex) data[i], + parity, + ]; + feed(r, kept); + expect( + delivered, + isEmpty, + reason: 'payload $payloadLen: truncated recovery must not complete', + ); + } + }, + ); + + test('parity still recovers a genuinely lost non-final chunk', () { + final payload = payloadOf(400, seed: 5); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 8, + ); + final data = set.blobs.sublist(0, set.dataChunkCount); + expect(data.length, greaterThanOrEqualTo(3)); + + final delivered = []; + final r = ImageReassembler(onImage: delivered.add); + feed(r, [ + for (var i = 0; i < data.length; i++) + if (i != 1) data[i], + set.blobs.last, + ]); + expect(delivered, hasLength(1)); + expect(delivered.single.data, equals(payload)); + expect(delivered.single.recoveredWithParity, isTrue); + }); + }); + + group('oversized data body', () { + test('a 159-byte data body is rejected and parity cannot overrun', () { + final failed = []; + final r = ImageReassembler(onFailed: failed.add); + // Header: sender 0x1234, img 5, idx 0 of 2; body one byte past the cap. + final oversized = Uint8List.fromList([ + 0x12, + 0x34, + 5, + (0 << 4) | 2, + ...List.filled(kImageChunkBodyBytes + 1, 0xAA), + ]); + expect(oversized.length, kImageChunkBlobBytes); + expect(r.addChunk(oversized).status, ImageChunkStatus.malformed); + expect(r.pendingCount, 0); + + // A parity chunk for the same stream must not throw. + final parity = Uint8List.fromList([ + 0x12, + 0x34, + 5, + (2 << 4) | 2, + ...List.filled(kImageChunkBodyBytes + 1, 0x55), + ]); + expect(() => r.addChunk(parity), returnsNormally); + }); + }); + + group('clear()', () { + test('reports in-progress streams as failed (disconnected)', () { + final failed = []; + final r = ImageReassembler(onFailed: failed.add); + final set = buildImageChunks( + payload: payloadOf(400, seed: 3), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 8, + ); + r.addChunk(set.blobs[0]); + expect(r.pendingCount, 1); + r.clear(); + expect(r.pendingCount, 0); + expect(failed, hasLength(1)); + expect(failed.single.reason, ImageReassemblyFailureReason.disconnected); + expect(failed.single.isCorrupt, isFalse); + expect(r.evictExpired(now: DateTime(2100)), isEmpty); + }); + }); + + group('completed-image map is capped', () { + /// A lone parity chunk of a `total == 1` image completes that image by + /// itself — one packet, one remembered entry. That is the amplification the + /// cap exists to bound. + List loneParity(int imgId) => buildImageChunks( + payload: payloadOf(20, seed: imgId), + metadata: stdMeta, + senderPrefix: senderA, + imgId: imgId, + ).blobs; + + test('one packet per img_id can complete an image (the attack)', () { + final r = ImageReassembler(); + final done = r.addChunk(loneParity(1)[1]); + expect(done.status, ImageChunkStatus.completed); + expect(r.completedCount, 1); + expect(r.pendingCount, 0); + }); + + test( + 'the map never exceeds maxCompletedStreams and evicts oldest first', + () { + final start = DateTime(2026, 3, 3); + final r = ImageReassembler(maxCompletedStreams: 3); + for (var i = 0; i < 20; i++) { + r.addChunk( + loneParity(100 + i)[1], + now: start.add(Duration(seconds: i)), + ); + expect(r.completedCount, lessThanOrEqualTo(3)); + } + expect(r.completedCount, 3); + expect(r.completedKeys.map((k) => k.imgId).toList()..sort(), [ + 117, + 118, + 119, + ]); + }, + ); + + test('default cap matches the pending cap', () { + final start = DateTime(2026, 3, 4); + final r = ImageReassembler(); + expect(r.maxCompletedStreams, 8); + expect(r.maxConcurrentStreams, 8); + for (var i = 0; i < 30; i++) { + r.addChunk(loneParity(i)[1], now: start.add(Duration(seconds: i))); + } + expect(r.completedCount, 8); + }); + + test('capping does not break straggler suppression for recent images', () { + final start = DateTime(2026, 3, 5); + final r = ImageReassembler(maxCompletedStreams: 2); + final set = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 200, + ); + feed(r, set.blobs.sublist(0, 2), now: start); + // Trailing parity of the newest image is still recognised as a duplicate. + expect( + r.addChunk(set.blobs[2], now: start).status, + ImageChunkStatus.duplicate, + ); + expect(r.pendingCount, 0); + }); + + test('clear() empties the completed map too', () { + final r = ImageReassembler(); + r.addChunk(loneParity(9)[1]); + expect(r.completedCount, 1); + r.clear(); + expect(r.completedCount, 0); + }); + }); + + group('rate point wire codes', () { + test('the chunk-0 nibble is not the AeicRatePoint ordinal', () { + // The trap: AeicRatePoint.wireValue is 0..4 and selects a MODEL; ft32 is 4 + // there but 0 in the chunk-0 metadata nibble. If the two were ever + // conflated, ft32 would go on air as 4. + expect(AeicRatePoint.values.length, 5); + expect(AeicRatePoint.ft32.wireValue, 4); + expect( + aeicRatePointForUi(ImageCodecRatePoint.standard), + AeicRatePoint.ft32, + ); + expect( + imageRateWireCode(ImageCodecRatePoint.standard), + kImageRateWireStandard, + ); + expect(kImageRateWireStandard, 0); + expect(kImageRateWireHigh, 1); + expect( + const ImageStreamMetadata(rate: ImageCodecRatePoint.standard).encode() & + 0x0F, + 0, + ); + // ...and an AeicRatePoint ordinal on the wire is refused outright. + expect(imageRatePointFromWireCode(AeicRatePoint.ft32.wireValue), isNull); + expect(imageRatePointFromWireCode(AeicRatePoint.ft8.wireValue), isNull); + }); + + test('every wire code round-trips and unknown codes are null', () { + for (final rate in ImageCodecRatePoint.values) { + final code = imageRateWireCode(rate); + expect(code, lessThan(kImageRateWireCodeCount)); + expect(imageRatePointFromWireCode(code), rate); + } + expect( + ImageCodecRatePoint.values.map(imageRateWireCode).toSet(), + hasLength(ImageCodecRatePoint.values.length), + ); + for (var code = kImageRateWireCodeCount; code < 16; code++) { + expect(imageRatePointFromWireCode(code), isNull, reason: 'code $code'); + } + }); + + test('an unknown rate code fails cleanly instead of decoding wrong', () { + final payload = payloadOf(300); + final set = buildImageChunks( + payload: payload, + metadata: stdMeta, + senderPrefix: senderA, + imgId: 80, + ); + // Overwrite the 2-bit rate field with 2 — a code no shipping build + // emits. Without an explicit rate table this would have decoded as a + // valid rate point and fed the wrong model. + final bad = Uint8List.fromList(set.blobs[0]); + bad[kImageChunkHeaderBytes] = (bad[kImageChunkHeaderBytes] & 0xFC) | 0x02; + + final delivered = []; + final failures = []; + final r = ImageReassembler( + onImage: delivered.add, + onFailed: failures.add, + ); + expect(r.addChunk(bad).status, ImageChunkStatus.accepted); + final done = r.addChunk(set.blobs[1]); + expect(done.status, ImageChunkStatus.unsupportedFormat); + expect(done.result, isNull); + expect(delivered, isEmpty); + expect(failures, hasLength(1)); + expect( + failures.single.reason, + ImageReassemblyFailureReason.unsupportedFormat, + ); + expect(failures.single.isCorrupt, isTrue); + expect(r.pendingCount, 0); + }); + + test('a reserved rate code fails the same way through reassembly', () { + // Resolution is a closed 2-bit field now, so it cannot carry an unknown + // value; the reserved RATE codes are what a future format must use to be + // rejected rather than misread. This asserts the rejection survives the + // whole reassembly path, not just ImageStreamMetadata.decode. + final set = buildImageChunks( + payload: payloadOf(300), + metadata: stdMeta, + senderPrefix: senderA, + imgId: 81, + ); + final bad = Uint8List.fromList(set.blobs[0]); + bad[kImageChunkHeaderBytes] = + (bad[kImageChunkHeaderBytes] & 0xFC) | 0x03; // reserved rate code 3 + final r = ImageReassembler(); + r.addChunk(bad); + expect( + r.addChunk(set.blobs[1]).status, + ImageChunkStatus.unsupportedFormat, + ); + }); + }); + + group('metadata byte: aspect ratio', () { + // The codec stretches the WHOLE frame into 512x512 rather than cropping, so + // nothing outside the frame is lost — but the stretch is not invertible + // from pixels alone. The sender names the source shape in spare bits of the + // metadata byte and the receiver letterboxes back. + test('round-trips every aspect code with rate and resolution intact', () { + for (var code = 0; code < kImageAspectCodes.length; code++) { + final m = ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, + squareSize: 512, + aspectCode: code, + ); + final decoded = ImageStreamMetadata.decode(m.encode()); + expect(decoded, isNotNull, reason: 'aspect code $code'); + expect(decoded!.aspectCode, code); + expect(decoded.rate, ImageCodecRatePoint.standard); + expect(decoded.squareSize, 512); + } + }); + + test('the whole byte still fits in 8 bits for every legal combination', () { + for (final size in kImageResolutionCodes) { + for (final rate in ImageCodecRatePoint.values) { + for (var code = 0; code < kImageAspectCodes.length; code++) { + final byte = ImageStreamMetadata( + rate: rate, + squareSize: size, + aspectCode: code, + ).encode(); + expect(byte, inInclusiveRange(0, 255)); + final back = ImageStreamMetadata.decode(byte)!; + expect(back.squareSize, size); + expect(back.rate, rate); + expect(back.aspectCode, code); + } + } + } + }); + + test('common phone shapes snap exactly, not approximately', () { + expect(imageAspectCodeFor(4032, 3024), 2); // 4:3 + expect(imageAspectCodeFor(3024, 4032), 9); // 3:4 + expect(imageAspectCodeFor(1920, 1080), 5); // 16:9 + expect(imageAspectCodeFor(1080, 1920), 12); // 9:16 + expect(imageAspectCodeFor(1000, 1000), 0); // 1:1 + // A ratio between table entries still picks the nearest. + expect(kImageAspectCodes[imageAspectCodeFor(1500, 1000)], [3, 2]); + }); + + test('extremes and nonsense degrade to unknown, not a wrong shape', () { + expect(imageAspectCodeFor(4000, 500), kImageAspectUnknown); // 8:1 pano + expect(imageAspectCodeFor(500, 4000), kImageAspectUnknown); + expect(imageAspectCodeFor(0, 100), kImageAspectUnknown); + expect(imageAspectCodeFor(100, 0), kImageAspectUnknown); + expect(imageAspectCodeFor(-4, 3), kImageAspectUnknown); + final m = ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, + aspectCode: kImageAspectUnknown, + ); + expect(m.isSquare, isTrue); + expect(m.aspectRatio, 1.0); + }); + + test('aspectRatio reconstructs the source shape', () { + final m = ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, + aspectCode: imageAspectCodeFor(1920, 1080), + ); + expect(m.aspectRatio, closeTo(16 / 9, 1e-9)); + expect(m.isSquare, isFalse); + }); + }); +} diff --git a/test/image_wiring_test.dart b/test/image_wiring_test.dart new file mode 100644 index 00000000..dbcfa90c --- /dev/null +++ b/test/image_wiring_test.dart @@ -0,0 +1,120 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/main.dart'; +import 'package:meshcore_open/services/image_chunk_transport.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; + +void main() { + test( + 'ImageStreamReassembler.selfPrefix override suppresses our own echo', + () { + final store = ReceivedImageStore(); + final r = ImageStreamReassembler(store: store); + final set = buildImageChunks( + payload: Uint8List.fromList(List.generate(120, (i) => i)), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: 0xABCD, + imgId: 7, + ); + // Before SELF_INFO the prefix is unknown, so nothing is suppressed. + expect( + r.addChunk(set.blobs[0], channelIndex: 1).status, + ImageChunkStatus.completed, + ); + r.clear(); + // After SELF_INFO the superclass must see the overridden getter. + r.selfPrefix = 0xABCD; + expect( + r.addChunk(set.blobs[0], channelIndex: 1).status, + ImageChunkStatus.fromSelf, + ); + }, + ); + + test( + 'addChunk forwards outcomes to the store with the channel index', + () async { + final store = ReceivedImageStore(); + final r = ImageStreamReassembler(store: store); + final set = buildImageChunks( + payload: Uint8List.fromList(List.generate(400, (i) => i & 0xFF)), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: 0x1234, + imgId: 3, + ); + r.addChunk(set.blobs[0], channelIndex: 5); + await store.settle(); + final entry = store.entries.single; + expect(entry.channelIndex, 5); + expect(entry.senderPrefix, 0x1234); + expect(entry.state, ReceivedImageState.receiving); + }, + ); + + group('AppSettings image codec block', () { + test( + 'round-trips through toJson/fromJson on the ImageCodecPreferences keys', + () { + final settings = AppSettings( + imageCodecEnabled: true, + imageCodecSelectedModelId: 'qdq_conv_pct_novae', + imageCodecModelSourceUrl: 'https://example.invalid/model.onnx', + imageCodecRatePoint: 4, + imageCodecDownloadedModels: [ + ImageCodecModelRecord( + id: 'qdq_conv_pct_novae', + name: 'AEIC ft32 (int8)', + sourceUrl: 'https://example.invalid/model.onnx', + localPath: '/tmp/model.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1000), + fileSizeBytes: 872 * 1024 * 1024, + ), + ], + ); + final json = settings.toJson(); + // The keys must be the ones ImageCodecPreferences already used, so a + // build that wrote them through the old standalone store still reads. + expect(json['image_codec_enabled'], isTrue); + expect(json['image_codec_selected_model_id'], 'qdq_conv_pct_novae'); + expect(json['image_codec_rate_point'], 4); + + final restored = AppSettings.fromJson(json); + expect(restored.imageCodecEnabled, isTrue); + expect(restored.imageCodecSelectedModelId, 'qdq_conv_pct_novae'); + expect( + restored.imageCodecModelSourceUrl, + 'https://example.invalid/model.onnx', + ); + expect(restored.imageCodecRatePoint, 4); + expect( + restored.imageCodecDownloadedModels.single.localPath, + '/tmp/model.onnx', + ); + }, + ); + + test('defaults are off, ft32, and empty', () { + const prefs = ImageCodecPreferences(); + final settings = AppSettings(); + expect(settings.imageCodecEnabled, prefs.enabled); + expect(settings.imageCodecRatePoint, prefs.ratePoint); + expect(settings.imageCodecDownloadedModels, isEmpty); + expect(settings.imageCodec.aeicRatePoint, AeicRatePoint.ft32); + }); + + test('the assembled view matches the five fields', () { + final settings = AppSettings( + imageCodecEnabled: true, + imageCodecSelectedModelId: 'x', + imageCodecRatePoint: 4, + ); + expect(settings.imageCodec.enabled, isTrue); + expect(settings.imageCodec.selectedModelId, 'x'); + expect(settings.imageCodec.ratePoint, 4); + }); + }); +} diff --git a/test/lora_airtime_test.dart b/test/lora_airtime_test.dart new file mode 100644 index 00000000..e40d3e1d --- /dev/null +++ b/test/lora_airtime_test.dart @@ -0,0 +1,599 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/image_chunk_transport.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; +import 'package:meshcore_open/models/radio_settings.dart'; +import 'package:meshcore_open/utils/lora_airtime.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart' as protocol; + +double _ms(Duration d) => d.inMicroseconds / 1000.0; + +RadioSettings _radio({ + LoRaSpreadingFactor sf = LoRaSpreadingFactor.sf10, + LoRaBandwidth bw = LoRaBandwidth.bw250, + LoRaCodingRate cr = LoRaCodingRate.cr4_5, +}) => RadioSettings( + frequencyMHz: 869.525, + bandwidth: bw, + spreadingFactor: sf, + codingRate: cr, + txPowerDbm: 22, +); + +void main() { + group('loraTimeOnAir reference values (255-byte packet)', () { + test('SF9, CR 4/8, BW 250 kHz -> 992 ms', () { + final toa = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 8, + ); + expect(_ms(toa), closeTo(991.744, 1)); + }); + + test('SF10, CR 4/5, BW 250 kHz -> 1181 ms', () { + final toa = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 5, + ); + expect(_ms(toa), closeTo(1180.672, 1)); + }); + }); + + group('low data rate optimize', () { + test('SF12 / BW 125 kHz engages LDRO (Tsym = 32.768 ms > 16 ms)', () { + final toa = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 12, + bandwidthHz: 125000, + codingRate: 5, + ); + // DE = 1 -> denominator 4*(12-2) = 40 -> 51 * 5 = 255 payload symbols + // ToA = (20.25 + 263) * 32.768 ms + expect(_ms(toa), closeTo(9281.536, 1)); + }); + + test('SF12 / BW 500 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () { + final toa = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 12, + bandwidthHz: 500000, + codingRate: 5, + ); + // DE = 0 -> denominator 48 -> 43 * 5 = 215 payload symbols + // ToA = (20.25 + 223) * 8.192 ms + expect(_ms(toa), closeTo(1992.704, 1)); + }); + + test('SF11 / BW 250 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () { + // Guards against the common `sf >= 11` shortcut, which is wrong here. + final withSf11 = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 11, + bandwidthHz: 250000, + codingRate: 5, + ); + // DE = 0 -> denominator 44 -> 47 * 5 = 235 payload symbols + // ToA = (20.25 + 243) * 8.192 ms + expect(_ms(withSf11), closeTo(2156.544, 1)); + }); + + test('calculateLoRaAirtime derives LDRO off for SF11 / BW 250 kHz', () { + // cr is in the 1..4 domain here; 16-symbol preamble at SF11. + expect( + protocol.calculateLoRaAirtime( + payloadBytes: 255, + spreadingFactor: 11, + bandwidthHz: 250000, + codingRate: 1, + ), + 2157, + ); + }); + }); + + group('preamble matches firmware (32 symbols <= SF8, 16 above)', () { + test('meshCorePreambleSymbols', () { + expect(meshCorePreambleSymbols(7), 32); + expect(meshCorePreambleSymbols(8), 32); + expect(meshCorePreambleSymbols(9), 16); + expect(meshCorePreambleSymbols(12), 16); + }); + + for (final sf in [7, 8, 9, 12]) { + test('SF$sf default preamble equals explicit firmware length', () { + final preamble = sf <= 8 ? 32 : 16; + Duration toa({int? preambleSymbols}) => loraTimeOnAir( + payloadBytes: 100, + spreadingFactor: sf, + bandwidthHz: 125000, + codingRate: 5, + preambleSymbols: preambleSymbols, + ); + expect(toa(), toa(preambleSymbols: preamble)); + expect( + protocol.calculateLoRaAirtime( + payloadBytes: 100, + spreadingFactor: sf, + bandwidthHz: 125000, + codingRate: 1, + ), + protocol.calculateLoRaAirtime( + payloadBytes: 100, + spreadingFactor: sf, + bandwidthHz: 125000, + codingRate: 1, + preambleSymbols: preamble, + ), + ); + }); + } + }); + + group('airtime monotonicity / sanity', () { + test('longer payload never takes less airtime', () { + Duration at(int pl) => loraTimeOnAir( + payloadBytes: pl, + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 5, + ); + var previous = at(0); + for (var pl = 1; pl <= 255; pl++) { + final current = at(pl); + expect( + current.inMicroseconds, + greaterThanOrEqualTo(previous.inMicroseconds), + ); + previous = current; + } + }); + + test('zero and one byte payloads do not crash and are positive', () { + for (final pl in [0, 1]) { + final toa = loraTimeOnAir( + payloadBytes: pl, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 5, + ); + expect(toa.inMicroseconds, greaterThan(0)); + } + }); + }); + + group('normalizeCodingRate', () { + test('maps both firmware encodings to 5..8', () { + expect(normalizeCodingRate(1), 5); + expect(normalizeCodingRate(4), 8); + expect(normalizeCodingRate(5), 5); + expect(normalizeCodingRate(8), 8); + }); + + test('raw 1..4 and 5..8 produce identical airtime after normalisation', () { + final a = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: normalizeCodingRate(4), + ); + final b = loraTimeOnAir( + payloadBytes: 255, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: normalizeCodingRate(8), + ); + expect(a, b); + expect(_ms(a), closeTo(991.744, 1)); + }); + }); + + group('chunk counts for measured codec payload sizes', () { + test('ft32 "standard" (110 / 155.8 / 209 bytes) -> 1-2 chunks', () { + // Derived from kImageChunkFirstCapacity, never hardcoded: that constant + // has already moved twice (2->4 byte header, then a 2-byte CRC added to + // chunk 0), and each time a hardcoded expectation here would have hidden + // the estimator drifting away from the chunker. + expect(imageChunkCount(110), 1); + expect(imageChunkCount(209), 2); + expect(imageChunkCount(156), 156 <= kImageChunkFirstCapacity ? 1 : 2); + for (final pl in [110, 156, 209]) { + expect(imageChunkCount(pl), inInclusiveRange(1, 2)); + } + }); + + test('ft16 "high" (176 / 288 / 409 bytes) -> 2-3 chunks', () { + expect(imageChunkCount(176), 2); + expect(imageChunkCount(288), 2); + expect(imageChunkCount(409), 3); + for (final pl in [176, 288, 409]) { + expect(imageChunkCount(pl), inInclusiveRange(2, 3)); + } + }); + + test('chunk 0 carries one fewer payload byte (boundary handling)', () { + // Derived from the transport's constants, never hardcoded: these numbers + // moved once already when the header grew from 2 to 4 bytes to carry the + // sender prefix, and a hardcoded test hid the estimator disagreeing with + // the chunker. + const first = kImageChunkFirstCapacity; + const rest = kImageChunkCapacity; + expect(first, rest - kImageChunkZeroMetadataBytes); + expect(imageChunkCount(first), 1); + expect(imageChunkCount(first + 1), 2); + expect(imageChunkCount(first + rest), 2); + expect(imageChunkCount(first + rest + 1), 3); + expect(imageChunkCount(0), 0); + expect(imageChunkCount(1), 1); + }); + + test('chunk payload sizes sum to the payload', () { + for (final pl in [0, 1, 110, 162, 163, 209, 288, 409, 1000]) { + expect(imageChunkPayloadSizes(pl).fold(0, (a, b) => a + b), pl); + } + }); + }); + + group('estimateSend', () { + test('parity adds exactly one packet', () { + final radio = _radio(); + for (final pl in [110, 209, 288, 409]) { + final without = estimateSend( + payloadBytes: pl, + radio: radio, + parity: false, + ); + final with_ = estimateSend(payloadBytes: pl, radio: radio); + expect(with_.chunkCount, without.chunkCount + 1); + expect(without.includesParity, isFalse); + expect(with_.includesParity, isTrue); + expect( + with_.totalAirtime!.inMicroseconds, + greaterThan(without.totalAirtime!.inMicroseconds), + ); + } + }); + + test('unknown radio settings -> packet count kept, airtime null', () { + final est = estimateSend(payloadBytes: 288, radio: null); + expect(est.chunkCount, 3); // 2 data chunks + parity + expect(est.totalBytes, greaterThan(288)); + expect(est.perPacketAirtime, isNull); + expect(est.totalAirtime, isNull); + expect(est.hasAirtime, isFalse); + }); + + test('partially unknown radio params also yield a null airtime', () { + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 10, + bandwidthHz: null, + codingRate: 5, + ); + expect(est.chunkCount, 3); + expect(est.hasAirtime, isFalse); + }); + + test('raw firmware coding rate 1..4 is normalised', () { + final a = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 4, // firmware 1..4 encoding for 4/8 + ); + final b = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 8, // 5..8 encoding for 4/8 + ); + expect(a, b); + }); + + test('zero-byte payload does not crash and adds no parity', () { + final est = estimateSend(payloadBytes: 0, radio: _radio()); + expect(est.chunkCount, 0); + expect(est.totalBytes, 0); + expect(est.includesParity, isFalse); + expect(est.totalAirtime, Duration.zero); + }); + + test('one-byte payload is a single chunk plus parity', () { + final est = estimateSend(payloadBytes: 1, radio: _radio()); + expect(est.chunkCount, 2); + expect(est.totalAirtime!.inMicroseconds, greaterThan(0)); + }); + + test('total bytes account for chunk headers and metadata', () { + final est = estimateSend( + payloadBytes: 209, + radio: _radio(), + parity: false, + ); + // A data blob is header + body (chunk 0's body opens with the metadata + // byte). Only the PARITY blob carries the length byte, and it is always a + // full kImageChunkBlobBytes because the XOR body is zero-padded. + final sizes = imageChunkPayloadSizes(209); + var expected = 0; + for (var i = 0; i < sizes.length; i++) { + expected += + kImageChunkHeaderBytes + + (i == 0 ? kImageChunkZeroMetadataBytes : 0) + + sizes[i]; + } + expect(est.chunkCount, 2); + expect(est.totalBytes, expected); + // Sanity: payload + per-chunk header + the one metadata byte. + expect( + expected, + 209 + 2 * kImageChunkHeaderBytes + kImageChunkZeroMetadataBytes, + ); + }); + + test('total airtime equals the sum of the per-chunk airtimes', () { + final est = estimateSend( + payloadBytes: 409, + radio: _radio(sf: LoRaSpreadingFactor.sf9, cr: LoRaCodingRate.cr4_8), + parity: false, + ); + final sizes = imageChunkPayloadSizes(409); + var expected = 0; + for (var i = 0; i < sizes.length; i++) { + expected += loraTimeOnAir( + payloadBytes: + kImageChunkHeaderBytes + + (i == 0 ? kImageChunkZeroMetadataBytes : 0) + + sizes[i], + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 8, + ).inMicroseconds; + } + expect(est.totalAirtime!.inMicroseconds, expected); + }); + + test('per-packet airtime is the airtime of a full chunk packet', () { + final est = estimateSend( + payloadBytes: 409, + radio: _radio(sf: LoRaSpreadingFactor.sf10, cr: LoRaCodingRate.cr4_5), + ); + final full = loraTimeOnAir( + payloadBytes: kImageChunkBlobBytes, + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 5, + ); + expect(est.perPacketAirtime, full); + }); + + test('a realistic ft16 image on SF10/BW250/CR4-5 stays under ~5 s', () { + final est = estimateSend(payloadBytes: 288, radio: _radio()); + expect(est.chunkCount, 3); + expect(est.totalAirtime!.inMilliseconds, greaterThan(1000)); + expect(est.totalAirtime!.inMilliseconds, lessThan(5000)); + }); + }); + + group('paced wall clock', () { + test('single-packet send has no pacing gap', () { + final est = estimateSend( + payloadBytes: 110, + radio: _radio(), + parity: false, + ); + expect(est.chunkCount, 1); + expect(est.pacedWallClock, est.totalAirtime); + }); + + test('multi-packet send adds one gap per inter-packet boundary', () { + final est = estimateSend(payloadBytes: 209, radio: _radio()); + expect(est.chunkCount, 3); // 2 data + parity + final sizes = imageChunkPayloadSizes(209); + const framing = kImageChunkHeaderBytes + kImageParityLengthBytes; + final packetBytes = [ + framing + kImageChunkZeroMetadataBytes + sizes[0], + framing + sizes[1], + // parity body is as large as the largest data body + framing + + (sizes[0] + kImageChunkZeroMetadataBytes > sizes[1] + ? sizes[0] + kImageChunkZeroMetadataBytes + : sizes[1]), + ]; + var airtime = 0; + var wall = 0; + for (var i = 0; i < packetBytes.length; i++) { + final toa = loraTimeOnAir( + payloadBytes: packetBytes[i], + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 5, + ); + airtime += toa.inMicroseconds; + wall += toa.inMicroseconds; + if (i != packetBytes.length - 1) { + wall += imageSendChunkGap(toa).inMicroseconds; + } + } + expect(est.totalAirtime!.inMicroseconds, airtime); + expect(est.pacedWallClock!.inMicroseconds, wall); + // Two boundaries, so at least two base delays of extra wall clock. + expect( + wall - airtime, + greaterThanOrEqualTo(2 * kImageSendChunkGapBase.inMicroseconds), + ); + }); + + test('the gap is the documented base plus airtime factor', () { + const toa = Duration(milliseconds: 300); + expect( + imageSendChunkGap(toa), + Duration( + microseconds: + kImageSendChunkGapBase.inMicroseconds + + (toa.inMicroseconds * kImageSendChunkGapAirtimeFactor).round(), + ), + ); + }); + + test('unknown radio settings leave the wall clock null too', () { + final est = estimateSend(payloadBytes: 156, radio: null); + expect(est.pacedWallClock, isNull); + expect(est.totalAirtime, isNull); + expect(est.chunkCount, imageChunkCount(156) + 1); // + parity + }); + + test('a realistic ft32 image on SF10/BW250/CR4-5 is a few seconds', () { + // 110-209 B measured => 1-2 data chunks + parity. The paced figure is + // what the compose sheet shows, so it must stay plausible. + for (final pl in [110, 156, 209]) { + final est = estimateSend(payloadBytes: pl, radio: _radio()); + expect(est.chunkCount, inInclusiveRange(2, 3)); + expect(est.pacedWallClock!.inMilliseconds, greaterThan(1000)); + expect(est.pacedWallClock!.inMilliseconds, lessThan(10000)); + expect( + est.pacedWallClock!.inMicroseconds, + greaterThan(est.totalAirtime!.inMicroseconds), + ); + } + }); + }); + + group('malformed radio parameters from the wire', () { + // currentSf/currentBwHz/currentCr are raw bytes off the device. A + // disconnected or half-initialised radio reports zeroes, which used to + // reach the ToA maths and throw "Unsupported operation: Infinity or NaN + // toInt" in release builds. Packet counts must survive; airtime must go + // null rather than be invented. + test('zero spreading factor yields packet counts but no airtime', () { + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 0, + bandwidthHz: 250000, + codingRate: 5, + ); + expect(est.chunkCount, greaterThan(0)); + expect(est.totalBytes, greaterThan(0)); + expect(est.totalAirtime, isNull); + expect(est.perPacketAirtime, isNull); + }); + + test('zero bandwidth yields no airtime', () { + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 9, + bandwidthHz: 0, + codingRate: 8, + ); + expect(est.totalAirtime, isNull); + }); + + test('zero coding rate yields no airtime', () { + // normalizeCodingRate(0) == 4, which is still outside the legal 5..8. + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 0, + ); + expect(est.totalAirtime, isNull); + }); + + test('out-of-range spreading factors are rejected at both ends', () { + for (final sf in [4, 13, 255]) { + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: sf, + bandwidthHz: 250000, + codingRate: 5, + ); + expect( + est.totalAirtime, + isNull, + reason: 'sf=$sf must not produce airtime', + ); + } + }); + + test('valid params still produce airtime after the guard', () { + final est = estimateSendFromRadioParams( + payloadBytes: 288, + spreadingFactor: 9, + bandwidthHz: 250000, + codingRate: 4, // 1..4 firmware encoding -> normalises to 4/8 + ); + expect(est.totalAirtime, isNotNull); + expect(est.totalAirtime!.inMilliseconds, greaterThan(0)); + }); + + test('areLoRaParamsValid accepts the boundary values', () { + expect( + areLoRaParamsValid( + spreadingFactor: 5, + bandwidthHz: 7800, + codingRate: 5, + ), + isTrue, + ); + expect( + areLoRaParamsValid( + spreadingFactor: 12, + bandwidthHz: 500000, + codingRate: 8, + ), + isTrue, + ); + expect( + areLoRaParamsValid( + spreadingFactor: null, + bandwidthHz: 250000, + codingRate: 5, + ), + isFalse, + ); + }); + }); + + group('estimator agrees with the real chunker', () { + // The estimator used to charge the parity-length byte to every data chunk + // and size the parity blob from the largest data body. Both were wrong: + // only parity carries that byte, and its XOR body is always zero-padded to + // full. A 110-byte payload was reported as 232 on-air bytes against a real + // 278 — a 17% understatement of airtime on the smallest, most common image. + // Compare against buildImageChunks() rather than restating the arithmetic. + for (final payload in [1, 110, 156, 157, 158, 209, 288, 409]) { + test('$payload-byte payload matches buildImageChunks byte for byte', () { + for (final parity in [false, true]) { + final set = buildImageChunks( + payload: Uint8List(payload), + metadata: const ImageStreamMetadata( + rate: ImageCodecRatePoint.standard, + ), + senderPrefix: 0x1234, + imgId: 7, + parity: parity, + ); + final actual = set.blobs.fold(0, (a, b) => a + b.length); + final est = estimateSend( + payloadBytes: payload, + radio: _radio(), + parity: parity, + ); + expect( + est.totalBytes, + actual, + reason: 'payload $payload, parity $parity', + ); + expect( + est.chunkCount, + set.blobs.length, + reason: 'payload $payload, parity $parity', + ); + } + }); + } + }); +} diff --git a/test/models/channel_message_reply_test.dart b/test/models/channel_message_reply_test.dart new file mode 100644 index 00000000..1f350aa0 --- /dev/null +++ b/test/models/channel_message_reply_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; + +void main() { + test('outgoing reply keeps the selected target, not the latest post', () { + final older = ChannelMessage.outgoing('first post', 'Alice', 0); + ChannelMessage.outgoing('second post', 'Alice', 0); + + final reply = ChannelMessage.outgoing( + '@[Alice] answer', + 'Me', + 0, + replyTo: older, + ); + + expect(reply.replyToMessageId, older.messageId); + expect(reply.replyToSenderName, 'Alice'); + expect(reply.replyToText, 'first post'); + expect( + ChannelMessage.parseReplyMention(reply.text)?.actualMessage, + 'answer', + ); + }); + + test('outgoing message without reply has no reply target', () { + final message = ChannelMessage.outgoing('hello', 'Me', 0); + expect(message.replyToMessageId, isNull); + }); +} diff --git a/test/models/contact_path_width_test.dart b/test/models/contact_path_width_test.dart new file mode 100644 index 00000000..a8b3004c --- /dev/null +++ b/test/models/contact_path_width_test.dart @@ -0,0 +1,203 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/path_helper.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_discovery_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _contactFrame(int pathLen, List path) { + final writer = BytesBuilder(); + writer.addByte(respCodeContact); + writer.add(List.generate(32, (i) => i + 1)); + writer.addByte(advTypeRepeater); + writer.addByte(0); + writer.addByte(pathLen); + writer.add(Uint8List(64)..setRange(0, path.length, path)); + writer.add(Uint8List(32)..setRange(0, 4, 'Node'.codeUnits)); + writer.add([0x01, 0x00, 0x00, 0x00]); + writer.add(Uint8List(12)); + return writer.toBytes(); +} + +Contact _contact({required int pathHashWidth}) => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + name: 'Node', + type: advTypeRepeater, + pathLength: 2, + path: Uint8List.fromList([0xA1, 0xA2, 0xB1, 0xB2]), + pathHashWidth: pathHashWidth, + lastSeen: DateTime.fromMillisecondsSinceEpoch(1000), +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + group('Contact.fromFrame keeps the path hash width', () { + test('2-byte hops', () { + final contact = Contact.fromFrame( + _contactFrame((1 << 6) | 2, [0xA1, 0xA2, 0xB1, 0xB2]), + )!; + expect(contact.pathLength, 2); + expect(contact.pathHashWidth, 2); + expect(contact.path, [0xA1, 0xA2, 0xB1, 0xB2]); + expect(PathHelper.splitPathBytes(contact.path, contact.pathHashWidth), [ + [0xA1, 0xA2], + [0xB1, 0xB2], + ]); + }); + + test('3-byte hops', () { + final contact = Contact.fromFrame( + _contactFrame((2 << 6) | 1, [0xA1, 0xA2, 0xA3]), + )!; + expect(contact.pathLength, 1); + expect(contact.pathHashWidth, 3); + expect(contact.path, [0xA1, 0xA2, 0xA3]); + }); + + test('flood defaults to width 1', () { + final contact = Contact.fromFrame(_contactFrame(0xFF, const []))!; + expect(contact.pathLength, -1); + expect(contact.pathHashWidth, 1); + }); + + test('copyWith preserves width', () { + final contact = _contact(pathHashWidth: 2).copyWith(name: 'Renamed'); + expect(contact.pathHashWidth, 2); + }); + }); + + group('Contact.inferPathHashWidth', () { + test('divides bytes by hops', () { + expect(Contact.inferPathHashWidth(2, 4), 2); + expect(Contact.inferPathHashWidth(1, 3), 3); + }); + + test('falls back to 1', () { + expect(Contact.inferPathHashWidth(0, 0), 1); + expect(Contact.inferPathHashWidth(-1, 0), 1); + expect(Contact.inferPathHashWidth(2, 3), 1); + expect(Contact.inferPathHashWidth(1, 4), 1); + }); + }); + + group('Contact stores persist the path hash width', () { + test('ContactStore round-trip', () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + await store.saveContacts([_contact(pathHashWidth: 2)]); + final loaded = await store.loadContacts(); + expect(loaded.single.pathHashWidth, 2); + expect(loaded.single.path, [0xA1, 0xA2, 0xB1, 0xB2]); + }); + + test('ContactDiscoveryStore round-trip', () async { + final store = ContactDiscoveryStore()..setPublicKeyHex = 'AABBCCDDEEFF00'; + await store.saveContacts([_contact(pathHashWidth: 2)]); + final loaded = await store.loadContacts(); + expect(loaded.single.pathHashWidth, 2); + }); + + test('legacy data without width is inferred from hops', () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + final json = { + 'publicKey': base64Encode(List.generate(32, (i) => i + 1)), + 'name': 'Legacy', + 'type': advTypeRepeater, + 'pathLength': 2, + 'path': base64Encode([0xA1, 0xA2, 0xB1, 0xB2]), + 'lastSeen': 1000, + }; + await PrefsManager.instance.setString(store.keyFor, jsonEncode([json])); + final loaded = await store.loadContacts(); + expect(loaded.single.pathHashWidth, 2); + }); + + test('legacy flood data without width falls back to 1', () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + final json = { + 'publicKey': base64Encode(List.generate(32, (i) => i + 1)), + 'name': 'Legacy', + 'type': advTypeRepeater, + 'pathLength': -1, + 'path': base64Encode(const []), + 'lastSeen': 1000, + }; + await PrefsManager.instance.setString(store.keyFor, jsonEncode([json])); + final loaded = await store.loadContacts(); + expect(loaded.single.pathHashWidth, 1); + }); + + test('legacy mode-encoded pathLength yields its width', () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + final json = { + 'publicKey': base64Encode(List.generate(32, (i) => i + 1)), + 'name': 'Legacy', + 'type': advTypeRepeater, + 'pathLength': (2 << 6) | 1, + 'path': base64Encode([0xA1, 0xA2, 0xA3]), + 'lastSeen': 1000, + }; + await PrefsManager.instance.setString(store.keyFor, jsonEncode([json])); + final loaded = await store.loadContacts(); + expect(loaded.single.pathLength, 1); + expect(loaded.single.pathHashWidth, 3); + }); + }); + + group('ChannelMessage.fromFrame path_len 0xFF (direct)', () { + Uint8List frame({required bool v3}) { + final writer = BytesBuilder(); + if (v3) { + writer.add([respCodeChannelMsgRecvV3, 0x10, 0x01, 0x00]); + } else { + writer.addByte(respCodeChannelMsgRecv); + } + writer.addByte(3); // channel index + writer.addByte(0xFF); + writer.addByte(txtTypePlain); + writer.add([0x01, 0x00, 0x00, 0x00]); + writer.add(utf8.encode('Alice: hi')); + writer.addByte(0); + return writer.toBytes(); + } + + test('V3 does not read 63 x 4-byte hops', () { + final message = ChannelMessage.fromFrame(frame(v3: true))!; + expect(message.text, 'hi'); + expect(message.senderName, 'Alice'); + expect(message.pathLength, isNull); + expect(message.pathBytes, isEmpty); + expect(message.pathHashWidth, isNull); + expect(message.channelIndex, 3); + }); + + test('non-V3 reads path_len unsigned', () { + final message = ChannelMessage.fromFrame(frame(v3: false))!; + expect(message.text, 'hi'); + expect(message.pathLength, isNull); + }); + }); + + test('PathHelper treats width 4 as invalid and clamps to 3', () { + expect(PathHelper.splitPathBytes([1, 2, 3, 4], 4), [ + [1, 2, 3], + [4], + ]); + }); + + test('buildSetPathHashModeFrame rejects reserved mode 3', () { + expect(buildSetPathHashModeFrame(3), [cmdSetPathHashMode, 0, 2]); + }); +} diff --git a/test/models/image_codec_support_test.dart b/test/models/image_codec_support_test.dart new file mode 100644 index 00000000..5a9d7cf0 --- /dev/null +++ b/test/models/image_codec_support_test.dart @@ -0,0 +1,509 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; + +void main() { + group('ImageCodecModelRecord', () { + test('round-trips through JSON', () { + final record = ImageCodecModelRecord( + id: 'aeic-se-512-int8', + name: 'aeic_se_512_int8.onnx', + sourceUrl: 'https://example.invalid/model.onnx', + localPath: '/tmp/aeic_se_512_int8.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1730000000000), + fileSizeBytes: 873463808, + assetFileNames: ['a.onnx', 'a.onnx.data', 'e.onnx', 't.bin'], + bundleVersion: kImageCodecBundleVersion, + ); + + final restored = ImageCodecModelRecord.fromJson(record.toJson()); + + expect(restored.id, record.id); + expect(restored.name, record.name); + expect(restored.sourceUrl, record.sourceUrl); + expect(restored.localPath, record.localPath); + expect(restored.downloadedAt, record.downloadedAt); + expect(restored.fileSizeBytes, record.fileSizeBytes); + expect(restored.assetFileNames, record.assetFileNames); + expect(restored.bundleVersion, kImageCodecBundleVersion); + }); + + test('tolerates a missing/garbage payload', () { + final restored = ImageCodecModelRecord.fromJson({}); + expect(restored.id, ''); + expect(restored.fileSizeBytes, 0); + expect(restored.downloadedAt.millisecondsSinceEpoch, 0); + expect(restored.assetFileNames, isEmpty); + expect(restored.bundleVersion, 0); + }); + + test('a record written by a pre-bundle build reads as version 0', () { + // The exact JSON the decoder-only build wrote. It must still load, and it + // must be recognisable as needing an upgrade rather than silently + // claiming to be a full bundle. + final restored = ImageCodecModelRecord.fromJson({ + 'id': 'aeic-se-decoder-qdq-conv-pct-novae', + 'name': 'aeic_decoder_qdq_conv_pct_novae.onnx', + 'source_url': 'https://example.invalid/x.onnx', + 'local_path': '/tmp/aeic_decoder_qdq_conv_pct_novae.onnx', + 'downloaded_at': 1730000000000, + 'file_size_bytes': 2909610, + }); + expect(restored.bundleVersion, 0); + expect(restored.bundleVersion, lessThan(kImageCodecBundleVersion)); + expect(restored.assetFileNames, isEmpty); + expect(restored.localPath, isNotEmpty); + expect(restored.assetRoles, isEmpty); + }); + + test('asset roles survive JSON and tell the two entropy graphs apart', () { + // The whole point of the field: `e_send.onnx` and `e_decode.onnx` are + // indistinguishable by name, extension or position, and swapping them is + // the silent-corruption failure mode. + final record = ImageCodecModelRecord( + id: 'bundle', + name: 'd.onnx', + sourceUrl: 'https://example.invalid/d.onnx', + localPath: '/tmp/d.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1730000000000), + fileSizeBytes: 1, + assetFileNames: const [ + 'd.onnx', + 'd.onnx.data', + 'e_send.onnx', + 'e_decode.onnx', + 't.bin', + ], + assetRoles: const { + 'd.onnx': ImageCodecAssetRole.decoderGraph, + 'd.onnx.data': ImageCodecAssetRole.decoderWeights, + 'e_send.onnx': ImageCodecAssetRole.entropyGraph, + 'e_decode.onnx': ImageCodecAssetRole.entropyDecodeGraph, + 't.bin': ImageCodecAssetRole.cdfTables, + }, + bundleVersion: kImageCodecBundleVersion, + ); + + // Serialised by NAME, so appending an enum member cannot re-label a file + // that is already installed. + expect(record.toJson()['asset_roles'], { + 'd.onnx': 'decoderGraph', + 'd.onnx.data': 'decoderWeights', + 'e_send.onnx': 'entropyGraph', + 'e_decode.onnx': 'entropyDecodeGraph', + 't.bin': 'cdfTables', + }); + + final restored = ImageCodecModelRecord.fromJson(record.toJson()); + expect( + restored.fileNameForRole(ImageCodecAssetRole.entropyGraph), + 'e_send.onnx', + ); + expect( + restored.fileNameForRole(ImageCodecAssetRole.entropyDecodeGraph), + 'e_decode.onnx', + ); + expect( + restored.fileNameForRole(ImageCodecAssetRole.entropyWeights), + isNull, + ); + }); + + test('an unknown role name is dropped, not coerced to a real role', () { + // A record written by a newer build. Filing its unknown file under some + // existing role would hand ORT the wrong graph. + final restored = ImageCodecModelRecord.fromJson({ + 'asset_file_names': ['a.onnx', 'b.bin'], + 'asset_roles': { + 'a.onnx': 'somethingFromTheFuture', + 'b.bin': 'cdfTables', + }, + }); + expect(restored.assetRoles.keys, ['b.bin']); + expect(restored.fileNameForRole(ImageCodecAssetRole.cdfTables), 'b.bin'); + expect(parseImageCodecAssetRole('somethingFromTheFuture'), isNull); + expect( + parseImageCodecAssetRole('entropyDecodeGraph'), + ImageCodecAssetRole.entropyDecodeGraph, + ); + }); + + test('a role naming a file that is not installed does not resolve', () { + // assetRoles and assetFileNames can disagree if a file was reaped; the + // list of what is actually on disk wins. + final record = ImageCodecModelRecord( + id: 'x', + name: 'd.onnx', + sourceUrl: '', + localPath: '/tmp/d.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(0), + fileSizeBytes: 0, + assetFileNames: const ['d.onnx'], + assetRoles: const { + 'd.onnx': ImageCodecAssetRole.decoderGraph, + 'gone.onnx': ImageCodecAssetRole.entropyDecodeGraph, + }, + ); + expect( + record.fileNameForRole(ImageCodecAssetRole.entropyDecodeGraph), + isNull, + ); + }); + }); + + group('ImageCodecBundle', () { + test('is complete only with both entropy graph and tables', () { + const decoderOnly = ImageCodecBundle(decoderGraphPath: '/m/d.onnx'); + expect(decoderOnly.isComplete, isFalse); + const noTables = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + ); + expect(noTables.isComplete, isFalse); + const noEntropy = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + tablesPath: '/m/t.bin', + ); + expect(noEntropy.isComplete, isFalse); + const full = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/t.bin', + ); + expect(full.isComplete, isTrue); + }); + + test('supportsDecode additionally requires the decode-side graph', () { + // Bundle version 1: the send-side entropy graph only. It can encode -- + // that graph emits every stage at once, which is all an encoder needs -- + // but decoding is sequential and needs the If-branched export. + const sendOnly = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/t.bin', + ); + expect(sendOnly.isComplete, isTrue); + expect(sendOnly.supportsDecode, isFalse); + + const both = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + entropyDecodeGraphPath: '/m/e_dec.onnx', + tablesPath: '/m/t.bin', + ); + expect(both.supportsDecode, isTrue); + + // A decode-side graph without the tables is still useless. + const noTables = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + entropyDecodeGraphPath: '/m/e_dec.onnx', + ); + expect(noTables.supportsDecode, isFalse); + }); + + test('the decode-side graph participates in equality', () { + // The service keys its cached session on the bundle. If this field were + // left out of ==, upgrading a v1 install in place would reuse an isolate + // that never learned about the new graph. + const sendOnly = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/t.bin', + ); + const both = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + entropyDecodeGraphPath: '/m/e_dec.onnx', + tablesPath: '/m/t.bin', + ); + expect(both, isNot(sendOnly)); + expect(both.hashCode, isNot(sendOnly.hashCode)); + expect(both.toString(), contains('/m/e_dec.onnx')); + }); + + test('defaults to the shipping rate point and compares by value', () { + const a = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/t.bin', + ); + const b = ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/t.bin', + ); + expect(a.ratePoint, kShippingAeicRatePoint); + // The service keys its cached session on the bundle; value equality is + // what stops an identical bundle from respawning the isolate. + expect(a, b); + expect(a.hashCode, b.hashCode); + expect( + a, + isNot( + const ImageCodecBundle( + decoderGraphPath: '/m/d.onnx', + entropyGraphPath: '/m/e.onnx', + tablesPath: '/m/other.bin', + ), + ), + ); + }); + }); + + group('AeicRatePoint', () { + test('ordinals are the persisted/isolate wire values', () { + expect(AeicRatePoint.ft2.wireValue, 0); + expect(AeicRatePoint.ft32.wireValue, 4); + expect(parseAeicRatePoint(4), AeicRatePoint.ft32); + }); + + test('parse falls back to ft32 for out-of-range values', () { + expect(parseAeicRatePoint(-1), AeicRatePoint.ft32); + expect(parseAeicRatePoint(99), AeicRatePoint.ft32); + }); + + test('label carries the measured mean size where one exists', () { + expect(AeicRatePoint.ft32.label, 'ft32 (~156 B)'); + expect(AeicRatePoint.ft2.label, 'ft2'); + }); + + test('ft32 is the only shipping rate point', () { + expect(kShippingAeicRatePoint, AeicRatePoint.ft32); + // ft16 was dropped: 2-3 data chunks with 79 B of headroom. The UI mapping + // is constant now, so no selector value can reach another checkpoint. + for (final rate in ImageCodecRatePoint.values) { + expect(aeicRatePointForUi(rate), AeicRatePoint.ft32); + } + for (final rate in AeicRatePoint.values) { + expect(uiRatePointForAeic(rate), ImageCodecRatePoint.standard); + } + }); + + test('ft32 measurements are the real corpus numbers', () { + expect(AeicRatePoint.ft32.meanBytes, 156); // 155.8 B over 26 images + expect(AeicRatePoint.ft32.maxBytes, 209); + }); + + test('UI index and model ordinal are NOT interchangeable', () { + // Guards the trap documented on AeicRatePoint: the on-air nibble is + // ImageCodecRatePoint.index, the settings/isolate value is this ordinal. + expect( + ImageCodecRatePoint.standard.index, + isNot(AeicRatePoint.ft32.wireValue), + ); + }); + }); + + group('ImageCodecPreferences', () { + test('defaults to disabled at ft32 with no models', () { + const prefs = ImageCodecPreferences(); + expect(prefs.enabled, isFalse); + expect(prefs.aeicRatePoint, AeicRatePoint.ft32); + expect(prefs.downloadedModels, isEmpty); + }); + + test('round-trips through JSON including nested models', () { + final preset = imageCodecPresetModels.first; + final prefs = ImageCodecPreferences( + enabled: true, + selectedModelId: preset.id, + modelSourceUrl: preset.graph.sourceUrl, + ratePoint: AeicRatePoint.ft32.wireValue, + downloadedModels: [ + ImageCodecModelRecord( + id: preset.id, + name: preset.fileName, + sourceUrl: preset.graph.sourceUrl, + localPath: '/tmp/${preset.fileName}', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1730000000000), + fileSizeBytes: preset.graph.sizeBytes, + ), + ], + ); + + final restored = ImageCodecPreferences.fromJson(prefs.toJson()); + + expect(restored.enabled, isTrue); + expect(restored.selectedModelId, preset.id); + expect(restored.modelSourceUrl, prefs.modelSourceUrl); + expect(restored.aeicRatePoint, AeicRatePoint.ft32); + expect(restored.downloadedModels, hasLength(1)); + expect(restored.downloadedModels.first.id, preset.id); + }); + + test('copyWith can clear nullable strings via the sentinel', () { + const prefs = ImageCodecPreferences(selectedModelId: 'x'); + expect(prefs.copyWith().selectedModelId, 'x'); + expect(prefs.copyWith(selectedModelId: null).selectedModelId, isNull); + }); + }); + + group('imageCodecPresetModels', () { + test('ships exactly one model: one ft32 bundle, not two downloads', () { + expect(imageCodecPresetModels, hasLength(1)); + final preset = imageCodecPresetModels.single; + expect(preset.id, 'aeic-se-ft32-bundle-v1'); + expect(preset.ratePoint, AeicRatePoint.ft32); + expect(preset.isComplete, isTrue); + expect(preset.totalSizeBytes, kImageCodecBundleTotalBytes); + // 958.0 MiB across the five files, measured with stat on the local + // exports. See the upload manifest in image_codec_support.dart. + expect(preset.totalSizeBytes, 1004548432); + }); + + test('ships qdq_conv_pct, NOT the novae variant', () { + // The novae variant leaves the VAE in fp32: +38 MB on disk and +0.83 GiB + // peak RSS for 0.17 dB. RAM is the binding constraint on a phone. + final preset = imageCodecPresetModels.single; + expect(preset.fileName, 'aeic_decoder_qdq_conv_pct.onnx'); + for (final asset in preset.assets) { + expect(asset.fileName, isNot(contains('novae'))); + } + expect( + preset.assetFor(ImageCodecAssetRole.decoderWeights).sizeBytes, + 872896480, + ); + }); + + test('carries all five roles exactly once', () { + final preset = imageCodecPresetModels.single; + expect(preset.assets, hasLength(5)); + for (final role in const [ + ImageCodecAssetRole.decoderGraph, + ImageCodecAssetRole.decoderWeights, + ImageCodecAssetRole.entropyGraph, + ImageCodecAssetRole.entropyDecodeGraph, + ImageCodecAssetRole.cdfTables, + ]) { + expect( + preset.assets.where((a) => a.role == role), + hasLength(1), + reason: 'exactly one asset per role: $role', + ); + } + // Reserved and deliberately absent: the fp32 entropy export is + // self-contained. + expect(preset.maybeAssetFor(ImageCodecAssetRole.entropyWeights), isNull); + }); + + test('resolves the graph by role, not by list position', () { + final preset = imageCodecPresetModels.single; + expect(preset.graph, preset.assetFor(ImageCodecAssetRole.decoderGraph)); + expect(preset.graph.fileName, endsWith('.onnx')); + expect( + preset.assetFor(ImageCodecAssetRole.decoderWeights).fileName, + '${preset.graph.fileName}.data', + reason: 'ORT resolves external data by the exact filename in the graph', + ); + // A reordered list must not change which file ORT is handed. + final reordered = ImageCodecModelSpec( + id: preset.id, + label: preset.label, + assets: preset.assets.reversed.toList(), + ); + expect(reordered.fileName, preset.fileName); + }); + + test('the entropy graph and the tables are the ones that were validated', () { + final preset = imageCodecPresetModels.single; + final entropy = preset.assetFor(ImageCodecAssetRole.entropyGraph); + // op17 fp32: byte-identical bitstreams on 26/26 images. Not op20, not int8. + expect(entropy.fileName, 'aeic_entropy_side_fp32_op17.onnx'); + expect(entropy.sizeBytes, 67262167); + // The decode-side export of the same weights. fp32 as well: int8 there + // breaks the bit-exactness the rANS decoder depends on. + final decode = preset.assetFor(ImageCodecAssetRole.entropyDecodeGraph); + expect(decode.fileName, 'aeic_entropy_decode_fp32_op17.onnx'); + expect(decode.sizeBytes, 60509540); + expect(decode.fileName, isNot(entropy.fileName)); + final tables = preset.assetFor(ImageCodecAssetRole.cdfTables); + expect(tables.fileName, 'aeic_cdf_ft32.bin'); + expect(tables.sizeBytes, 813648); + }); + + test('an incomplete spec is detectable', () { + final preset = imageCodecPresetModels.single; + final decoderOnly = ImageCodecModelSpec( + id: 'legacy', + label: 'Legacy', + assets: [ + preset.assetFor(ImageCodecAssetRole.decoderGraph), + preset.assetFor(ImageCodecAssetRole.decoderWeights), + ], + ); + expect(decoderOnly.isComplete, isFalse); + expect(decoderOnly.maybeAssetFor(ImageCodecAssetRole.cdfTables), isNull); + expect( + () => decoderOnly.assetFor(ImageCodecAssetRole.cdfTables), + throwsStateError, + ); + + // A version-1 spec: everything except the decode-side graph. It would + // install a codec that can send and never receive, so downloadPresetModel + // must refuse it too. + final sendOnly = ImageCodecModelSpec( + id: 'v1', + label: 'Send-only', + assets: [ + for (final asset in preset.assets) + if (asset.role != ImageCodecAssetRole.entropyDecodeGraph) asset, + ], + ); + expect(sendOnly.assets, hasLength(4)); + expect(sendOnly.isComplete, isFalse); + }); + + test('uses the HuggingFace resolve/main URL shape', () { + for (final asset in imageCodecPresetModels.single.assets) { + expect(asset.sourceUrl, startsWith('https://huggingface.co/')); + expect(asset.sourceUrl, contains('/resolve/main/')); + expect(asset.sourceUrl, endsWith('?download=true')); + expect(asset.sourceUrl, contains(asset.fileName)); + } + }); + + test('friendly name resolves through the registry', () { + final preset = imageCodecPresetModels.single; + final record = ImageCodecModelRecord( + id: preset.id, + name: preset.fileName, + sourceUrl: '', + localPath: '/tmp/x', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(0), + fileSizeBytes: 0, + ); + expect(imageCodecModelFriendlyName(record), preset.label); + }); + + test('latent contract matches the export', () { + expect(kImageCodecLatentShape, [1, 256, 16, 16]); + expect(kImageCodecLatentElements, 65536); + expect(kImageCodecDecoderInputName, 'y_hat'); + }); + }); + + group('exceptions', () { + test( + 'an incomplete install is NOT the same failure as a missing build', + () { + // Both are ImageCodecUnimplemented, but only one has a remedy the user + // can act on, and the UI branches on exactly that difference. + const incomplete = ImageCodecBundleIncomplete(); + const missing = ImageCodecEntropyPathMissing(); + expect(incomplete, isA()); + expect(missing, isA()); + expect(incomplete, isNot(isA())); + expect(incomplete.toString(), contains('re-download')); + }, + ); + }); + + group('parseImageCodecStatus', () { + test('maps known values and defaults to none', () { + expect(parseImageCodecStatus('completed'), ImageCodecStatus.completed); + expect(parseImageCodecStatus('nonsense'), ImageCodecStatus.none); + expect(parseImageCodecStatus(42), ImageCodecStatus.none); + }); + }); +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index a80c7944..fa834a4f 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -1,10 +1,19 @@ +import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel_message.dart'; import 'package:meshcore_open/models/contact.dart'; import 'package:meshcore_open/models/path_history.dart'; import 'package:meshcore_open/models/app_settings.dart'; -import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/contact_discovery_store.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; // Builds a valid contact frame with the given pathLen and optional overrides. // Frame layout: [respCode(1)][pubKey(32)][type(1)][flags(1)][pathLen(1)][path(64)][name(32)][timestamp(4)][lat(4)][lon(4)] @@ -37,7 +46,108 @@ Uint8List _buildContactFrame({ return Uint8List.fromList(writer.toBytes()); } +Uint8List _buildChannelMessageFrameV3({ + required int pathHashWidth, + required int hopCount, + required bool hasPath, + int channelIndex = 7, + String senderName = 'Alice', + + String text = 'Hello world', + int txtType = txtTypePlain, +}) { + final writer = BytesBuilder(); + writer.addByte(respCodeChannelMsgRecvV3); + writer.addByte(0x10); + writer.addByte(hasPath ? 0x01 : 0x00); + writer.addByte(0x00); + writer.addByte(channelIndex); + writer.addByte(((pathHashWidth - 1) << 6) | hopCount); + + if (hasPath && hopCount > 0) { + writer.add( + Uint8List.fromList(List.generate(hopCount * pathHashWidth, (i) => i + 1)), + ); + } + + writer.addByte(txtType); + writer.add(Uint8List.fromList([0x01, 0x00, 0x00, 0x00])); + writer.add(utf8.encode('$senderName: $text')); + writer.addByte(0x00); + + return Uint8List.fromList(writer.toBytes()); +} + void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + group('ChannelMessage.fromFrame — V3 packed path decoding', () { + test( + 'hasPath reads width, hop count, path bytes, and txtType correctly', + () { + final frame = _buildChannelMessageFrameV3( + pathHashWidth: 2, + hopCount: 3, + hasPath: true, + ); + + final message = ChannelMessage.fromFrame(frame); + + expect(message, isNotNull); + expect(message!.pathHashWidth, equals(2)); + expect(message.pathLength, equals(3)); + expect(message.pathBytes.length, equals(6)); + expect(message.senderName, equals('Alice')); + expect(message.text, equals('Hello world')); + }, + ); + + test('no path still reads width, hop count, and txtType correctly', () { + final frame = _buildChannelMessageFrameV3( + pathHashWidth: 4, + hopCount: 5, + hasPath: false, + ); + + final message = ChannelMessage.fromFrame(frame); + + expect(message, isNotNull); + expect(message!.pathHashWidth, equals(4)); + expect(message.pathLength, equals(5)); + expect(message.pathBytes, isEmpty); + expect(message.senderName, equals('Alice')); + expect(message.text, equals('Hello world')); + }); + + test('non-plain txtType with path -> returns null', () { + final frame = _buildChannelMessageFrameV3( + pathHashWidth: 2, + hopCount: 2, + hasPath: true, + txtType: txtTypeCliData, + ); + final message = ChannelMessage.fromFrame(frame); + expect(message, isNull); + }); + + test('non-plain txtType without path -> returns null', () { + final frame = _buildChannelMessageFrameV3( + pathHashWidth: 2, + hopCount: 2, + hasPath: false, + txtType: txtTypeCliData, + ); + final message = ChannelMessage.fromFrame(frame); + expect(message, isNull); + }); + }); + group('Contact.fromFrame — pathLen mapping', () { test('pathLen == 0 → pathLength == 0 (direct, NOT flood)', () { final frame = _buildContactFrame(pathLen: 0); @@ -53,11 +163,11 @@ void main() { expect(contact!.pathLength, equals(1)); }); - test('pathLen == 64 (maxPathSize) → pathLength == 64', () { - final frame = _buildContactFrame(pathLen: maxPathSize); + test('pathLen == 64 (mode 1, 0 hops) → pathLength == 0', () { + final frame = _buildContactFrame(pathLen: 64); final contact = Contact.fromFrame(frame); expect(contact, isNotNull); - expect(contact!.pathLength, equals(maxPathSize)); + expect(contact!.pathLength, equals(0)); }); test('pathLen == 0xFF → pathLength == -1 (flood)', () { @@ -67,11 +177,18 @@ void main() { expect(contact!.pathLength, equals(-1)); }); - test('pathLen == 65 (over maxPathSize) → pathLength == -1 (flood)', () { + test('pathLen == 65 (mode 1, 1 hop) → pathLength == 1', () { final frame = _buildContactFrame(pathLen: 65); final contact = Contact.fromFrame(frame); expect(contact, isNotNull); - expect(contact!.pathLength, equals(-1)); + expect(contact!.pathLength, equals(1)); + }); + + test('pathLen == 129 (mode 2, 1 hop) → pathLength == 1', () { + final frame = _buildContactFrame(pathLen: 129); + final contact = Contact.fromFrame(frame); + expect(contact, isNotNull); + expect(contact!.pathLength, equals(1)); }); }); @@ -358,4 +475,216 @@ void main() { expect(updated.maxRouteWeight, equals(settings.maxRouteWeight)); }); }); + + group('Storage migration — multi-byte paths compatibility', () { + test( + 'ContactStore decodes and migrates legacy mode-encoded paths', + () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + + // Let's create a contact with legacy 64 path length (mode 1, 0 hops) + final rawPath = Uint8List(64); // 64 bytes of zeroes + final contactJson = [ + { + 'publicKey': base64Encode(Uint8List(32)..[0] = 0xAA), + 'name': 'LegacyNode', + 'type': 2, + 'flags': 0, + 'pathLength': 64, // encoded pathLength (mode 1, 0 hops) + 'path': base64Encode(rawPath), + 'lastSeen': DateTime.now().millisecondsSinceEpoch, + 'lastMessageAt': DateTime.now().millisecondsSinceEpoch, + 'isActive': true, + }, + ]; + + final prefs = PrefsManager.instance; + await prefs.setString(store.keyFor, jsonEncode(contactJson)); + + final contacts = await store.loadContacts(); + expect(contacts, hasLength(1)); + expect(contacts.first.pathLength, equals(0)); + expect(contacts.first.path, isEmpty); + }, + ); + + test( + 'ContactStore decodes and migrates legacy mode-1 paths with hops', + () async { + final store = ContactStore()..publicKeyHex = '1234567890'; + + // Contact with legacy 65 path length (mode 1, 1 hop) + final rawPath = Uint8List(64) + ..[0] = 0xBB + ..[1] = 0xCC; + final contactJson = [ + { + 'publicKey': base64Encode(Uint8List(32)..[0] = 0xAA), + 'name': 'LegacyNode2', + 'type': 2, + 'flags': 0, + 'pathLength': 65, // encoded pathLength (mode 1, 1 hop) + 'path': base64Encode(rawPath), + 'lastSeen': DateTime.now().millisecondsSinceEpoch, + 'lastMessageAt': DateTime.now().millisecondsSinceEpoch, + 'isActive': true, + }, + ]; + + final prefs = PrefsManager.instance; + await prefs.setString(store.keyFor, jsonEncode(contactJson)); + + final contacts = await store.loadContacts(); + expect(contacts, hasLength(1)); + expect(contacts.first.pathLength, equals(1)); + expect(contacts.first.path, equals(Uint8List.fromList([0xBB, 0xCC]))); + }, + ); + + test( + 'MessageStore decodes and migrates legacy mode-encoded message paths', + () async { + final store = MessageStore()..publicKeyHex = '1234567890'; + final contactKeyHex = pubKeyToHex(Uint8List(32)..[0] = 0xAA); + + final rawPath = Uint8List(64); + final messageJson = [ + { + 'senderKey': base64Encode(Uint8List(32)..[0] = 0xAA), + 'text': 'Hello', + 'timestamp': DateTime.now().millisecondsSinceEpoch, + 'isOutgoing': false, + 'status': 2, // delivered + 'messageId': 'msg_1', + 'pathLength': 64, // encoded pathLength (mode 1, 0 hops) + 'pathBytes': base64Encode(rawPath), + }, + ]; + + final prefs = PrefsManager.instance; + await prefs.setString( + '${store.keyFor}$contactKeyHex', + jsonEncode(messageJson), + ); + + final messages = await store.loadMessages(contactKeyHex); + expect(messages, hasLength(1)); + expect(messages.first.pathLength, equals(0)); + expect(messages.first.pathBytes, isEmpty); + }, + ); + + test( + 'ChannelMessageStore decodes and migrates legacy mode-encoded paths', + () async { + final store = ChannelMessageStore()..publicKeyHex = '1234567890'; + final channelIndex = 1; + + final rawPath = Uint8List(64) + ..[0] = 0xBB + ..[1] = 0xCC; + final messageJson = [ + { + 'senderName': 'Alice', + 'text': 'Hello', + 'timestamp': DateTime.now().millisecondsSinceEpoch, + 'isOutgoing': false, + 'status': 2, + 'channelIndex': channelIndex, + 'pathLength': 65, // encoded pathLength (mode 1, 1 hop) + 'pathBytes': base64Encode(rawPath), + }, + ]; + + final prefs = PrefsManager.instance; + await prefs.setString( + '${store.keyFor}$channelIndex', + jsonEncode(messageJson), + ); + + final messages = await store.loadChannelMessages(channelIndex); + expect(messages, hasLength(1)); + expect(messages.first.pathLength, equals(1)); + expect( + messages.first.pathBytes, + equals(Uint8List.fromList([0xBB, 0xCC])), + ); + expect(messages.first.pathHashWidth, equals(2)); + }, + ); + + test( + 'ContactDiscoveryStore decodes and migrates legacy mode-encoded paths', + () async { + final store = ContactDiscoveryStore() + ..setPublicKeyHex = 'AABBCCDDEEFF00112233'; + + final rawPath = Uint8List(64) + ..[0] = 0x11 + ..[1] = 0x22; + final contactJson = [ + { + 'publicKey': base64Encode(Uint8List(32)..[0] = 0xBB), + 'name': 'DiscoveredNode', + 'type': 1, + 'flags': 0, + 'pathLength': 65, // encoded pathLength (mode 1, 1 hop) + 'path': base64Encode(rawPath), + 'lastSeen': DateTime.now().millisecondsSinceEpoch, + 'lastMessageAt': DateTime.now().millisecondsSinceEpoch, + }, + ]; + + final prefs = PrefsManager.instance; + await prefs.setString('discovered_contacts', jsonEncode(contactJson)); + + final contacts = await store.loadContacts(); + expect(contacts, hasLength(1)); + expect(contacts.first.pathLength, equals(1)); + expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22]))); + expect(prefs.getString('discovered_contacts'), isNull); + expect(prefs.getString(store.keyFor), isNotNull); + }, + ); + }); + + group('AppSettingsService — gps interval fallback', () { + test('resolvedGpsIntervalSeconds prefers device custom var', () { + final service = AppSettingsService(); + + expect( + service.resolvedGpsIntervalSeconds(const {'gps_interval': '120'}), + equals(120), + ); + }); + + test('resolvedGpsIntervalSeconds falls back to stored value', () async { + final service = AppSettingsService(); + await service.updateSettings(AppSettings(gpsIntervalSeconds: 900)); + + expect(service.resolvedGpsIntervalSeconds(null), equals(900)); + expect( + service.resolvedGpsIntervalSeconds(const {'gps_interval': 'bad'}), + equals(900), + ); + }); + + test('resolvedGpsIntervalSeconds keeps an explicit device zero', () async { + final service = AppSettingsService(); + await service.updateSettings(AppSettings(gpsIntervalSeconds: 900)); + + expect( + service.resolvedGpsIntervalSeconds(const {'gps_interval': '0'}), + equals(0), + ); + }); + + test('toJson/fromJson preserves gpsIntervalSeconds', () { + final settings = AppSettings(gpsIntervalSeconds: 321); + + final restored = AppSettings.fromJson(settings.toJson()); + + expect(restored.gpsIntervalSeconds, equals(321)); + }); + }); } diff --git a/test/models/remote_node_stats_test.dart b/test/models/remote_node_stats_test.dart new file mode 100644 index 00000000..92546472 --- /dev/null +++ b/test/models/remote_node_stats_test.dart @@ -0,0 +1,66 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/remote_node_stats.dart'; + +Uint8List _frame(int statsSize, void Function(ByteData stats) fill) { + final frame = Uint8List(RemoteNodeStats.payloadOffset + statsSize); + fill(ByteData.sublistView(frame, RemoteNodeStats.payloadOffset)); + return frame; +} + +void _fillCommon(ByteData d) { + d.setUint16(0, 4100, Endian.little); + d.setInt16(4, -110, Endian.little); + d.setUint32(16, 300, Endian.little); + d.setUint32(20, 3600, Endian.little); + d.setInt16(42, -22, Endian.little); + d.setUint16(46, 9, Endian.little); +} + +void main() { + test('decodes repeater stats with rx airtime and recv errors', () { + final frame = _frame(56, (d) { + _fillCommon(d); + d.setUint32(48, 120, Endian.little); + d.setUint32(52, 7, Endian.little); + }); + final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!; + expect(stats.batteryMv, 4100); + expect(stats.noiseFloor, -110); + expect(stats.txAirSecs, 300); + expect(stats.uptimeSecs, 3600); + expect(stats.lastSnr, -5.5); + expect(stats.floodDups, 9); + expect(stats.rxAirSecs, 120); + expect(stats.recvErrors, 7); + expect(stats.posted, isNull); + }); + + test('older repeater frame without recv errors', () { + final frame = _frame(52, (d) { + _fillCommon(d); + d.setUint32(48, 120, Endian.little); + }); + final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!; + expect(stats.rxAirSecs, 120); + expect(stats.recvErrors, isNull); + }); + + test('decodes room server posted / pushed counters', () { + final frame = _frame(52, (d) { + _fillCommon(d); + d.setUint16(48, 42, Endian.little); + d.setUint16(50, 17, Endian.little); + }); + final stats = RemoteNodeStats.tryParse(frame, isRoom: true)!; + expect(stats.posted, 42); + expect(stats.postPushes, 17); + expect(stats.rxAirSecs, isNull); + expect(stats.recvErrors, isNull); + }); + + test('rejects frames shorter than the common layout', () { + expect(RemoteNodeStats.tryParse(Uint8List(50), isRoom: false), isNull); + }); +} diff --git a/test/reaction_helper_test.dart b/test/reaction_helper_test.dart index 2f4502e5..d3a952d8 100644 --- a/test/reaction_helper_test.dart +++ b/test/reaction_helper_test.dart @@ -1,3 +1,4 @@ +import 'package:characters/characters.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/helpers/reaction_helper.dart'; import 'package:meshcore_open/widgets/emoji_picker.dart'; @@ -340,6 +341,162 @@ void main() { }); }); + group('MeshCoreOne Reactions', () { + test('emoji validation sanity checks', () { + // This is more a test of expectations than of app code, but it was + // a good place to get this sorted out cleanly, and I leave it for + // anyone interested in understanding the emoji validation and tests. + expect('🥳'.length, equals(2)); + expect('\u{1f44c}\u{1f3ff}'.length, equals(4)); + final oneChar = RegExp(r'^(.)$'); + final twoChar = RegExp(r'^(..)$'); + expect(oneChar.firstMatch('🥳'), isNull); + expect(oneChar.firstMatch('\u{1F642}'), isNull); + expect(oneChar.firstMatch('\u{1f44c}\u{1f3ff}'), isNull); + expect(twoChar.firstMatch('\u{1f44c}\u{1f3ff}'), isNull); + + final regex = RegExp(r'^(.{1,4})$'); + expect(regex.firstMatch('🥳'), isNotNull); + expect(regex.firstMatch('😀'), isNotNull); + expect(regex.firstMatch('\u{1F642}'), isNotNull); + expect(regex.firstMatch('\u{1f44c}\u{1f3ff}'), isNotNull); + + expect(Characters('🥳').length, equals(1)); + expect(Characters('\u{1F642}').length, equals(1)); + expect(Characters('\u{1F642}').length, equals(1)); + expect(Characters('\u{1f44c}\u{1f3ff}').length, equals(1)); + expect(Characters('🧑‍🧑‍🧒‍🧒').length, equals(1)); + }); + + test('parse MeshCoreOne reaction', () { + final emoji = '🥳'; + final senderName = 'entropy 📓'; + final hash = 'b3je6qf7'; + final info = ReactionHelper.parseReactionMC1( + '@[$senderName]$emoji\n$hash', + ); + expect(info, isNotNull); + expect(info!.targetHash, equals('$hash:$senderName')); + expect(info.emoji, equals(emoji)); + + List messages = [ + '🥳\n01234567', + '@[entropy]🥳\n01234567', + '\u{1f44c}\u{1f3ff}\n01234567', + '@[entropy]\u{1f44c}\u{1f3ff}\n01234567', + '@[entropy]🧑‍🧑‍🧒\n01234567', // long composite emoji - 21 bytes + '🧑‍🧑‍🧒‍🧒\n01234567', // long composite emoji - 25 bytes + ]; + for (String txt in messages) { + final info = ReactionHelper.parseReactionMC1(txt); + expect(info, isNotNull, reason: "$txt did not parse"); + } + }); + + test('parse MeshCoreOne reaction - avoid false positives', () { + List messages = [ + 'test\nabcdefgh', + '🥳\nhashistoolong', + '🥳\nshort', + '🥳🥳\n01234567', // two emojis not composed into one grapheme + 'X\n01234567', + '🥳\nabcuuxyz', // u is not valid as we don't support checksums + ]; + for (String txt in messages) { + final info = ReactionHelper.parseReactionMC1(txt); + expect(info, isNull, reason: "$txt should not have parsed"); + } + }); + + test('parse MeshCoreOne reaction - Legacy format', () { + final emoji = '🥳'; + final senderName = 'entropy 📓'; + final hash = 'b3je6qf7'; + final info = ReactionHelper.parseReactionMC1Legacy( + '$emoji@[$senderName]\n$hash', + ); + expect(info, isNotNull); + expect(info!.targetHash, equals('$hash:$senderName')); + expect(info.emoji, equals(emoji)); + + List messages = [ + '🥳\n01234567', + '🥳@[entropy]\n01234567', + '\u{1f44c}\u{1f3ff}\n01234567', + '\u{1f44c}\u{1f3ff}@[entropy]\n01234567', + '🧑‍🧑‍🧒@[entropy]\n01234567', // long composite emoji - 21 bytes + '🧑‍🧑‍🧒‍🧒\n01234567', // long composite emoji - 25 bytes + ]; + for (String txt in messages) { + final info = ReactionHelper.parseReactionMC1Legacy(txt); + expect(info, isNotNull, reason: "$txt did not parse"); + } + }); + + test( + 'parse MeshCoreOne reaction - Legacy format - avoid false positives', + () { + List messages = [ + 'test\nabcdefgh', + '🥳\nhashistoolong', + '🥳\nshort', + '🥳🥳\n01234567', // two emojis not composed into one grapheme + 'X\n01234567', + '🥳\nabcuuxyz', // u is not valid as we don't support checksums + ]; + for (String txt in messages) { + final info = ReactionHelper.parseReactionMC1Legacy(txt); + expect(info, isNull, reason: "$txt should not have parsed"); + } + }, + ); + + test('parse MeshCoreOne reaction - main entry', () { + final emoji = '🥳'; + final senderName = 'entropy 📓'; + final hash = 'b3je6qf7'; + final info = ReactionHelper.parseReaction( + '@[$senderName]$emoji\n$hash', + ); + expect(info, isNotNull); + expect(info!.targetHash, equals('$hash:$senderName')); + expect(info.emoji, equals(emoji)); + }); + + test('parse MeshCoreOne reaction Legacy format - main entry', () { + final emoji = '🥳'; + final senderName = 'entropy 📓'; + final hash = 'b3je6qf7'; + final info = ReactionHelper.parseReaction( + '$emoji@[$senderName]\n$hash', + ); + expect(info, isNotNull); + expect(info!.targetHash, equals('$hash:$senderName')); + expect(info.emoji, equals(emoji)); + }); + + test('parse MeshCoreOne reaction for DM chats', () { + final emoji = '🥳'; + final hash = 'b3je6qf7'; + final info = ReactionHelper.parseReaction('$emoji\n$hash'); + expect(info, isNotNull); + expect(info!.targetHash, equals('$hash:')); + expect(info.emoji, equals(emoji)); + }); + + test('computeq MeshCoreOne reaction hash', () { + const timestamp = 1234567890; + const senderName = 'Alice'; + const messageText = 'Hello world!'; + final hash = ReactionHelper.computeReactionHashMC1( + timestamp, + senderName, + messageText, + ); + expect(hash, equals('tyvbkb33')); + }); + }); + group('full reaction flow', () { test('should encode and decode reaction correctly', () { // Simulate sending a reaction diff --git a/test/screens/map_marker_parse_test.dart b/test/screens/map_marker_parse_test.dart new file mode 100644 index 00000000..53b846c2 --- /dev/null +++ b/test/screens/map_marker_parse_test.dart @@ -0,0 +1,19 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/screens/map_screen.dart'; + +void main() { + test('parseMarkerText accepts in-range coordinates', () { + final payload = parseMarkerText('m:45.5,-122.6|Camp|x'); + expect(payload, isNotNull); + expect(payload!.position.latitude, 45.5); + expect(payload.position.longitude, -122.6); + expect(payload.label, 'Camp'); + }); + + test('parseMarkerText rejects out-of-range coordinates', () { + expect(parseMarkerText('m:999,999|x|'), isNull); + expect(parseMarkerText('m:90.1,0|x|'), isNull); + expect(parseMarkerText('m:0,-180.5|x|'), isNull); + expect(parseMarkerText('m:-90,180|edge|'), isNotNull); + }); +} diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart new file mode 100644 index 00000000..74b2b37a --- /dev/null +++ b/test/screens/path_trace_test.dart @@ -0,0 +1,403 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'dart:typed_data'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/screens/path_trace_map.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/models/path_history.dart'; + +class _FakeStorageService extends StorageService { + @override + Future savePathHistory( + String contactPubKeyHex, + ContactPathHistory history, + ) async {} + @override + Future loadPathHistory(String contactPubKeyHex) async => + null; + @override + Future clearPathHistory(String contactPubKeyHex) async {} +} + +class _FakeMeshCoreConnector extends MeshCoreConnector { + final StreamController _receivedFramesController = + StreamController.broadcast(); + + @override + Stream get receivedFrames => _receivedFramesController.stream; + + @override + Uint8List? get selfPublicKey => + Uint8List.fromList(List.generate(32, (i) => i)); + + @override + double? get selfLatitude => 48.8566; + + @override + double? get selfLongitude => 2.3522; + + @override + List get allContactsUnfiltered => []; + + @override + List get contacts => []; + + void emitFrame(Uint8List frame) { + _receivedFramesController.add(frame); + } + + final List sentFrames = []; + + @override + Future sendFrame( + Uint8List frame, { + String? channelSendQueueId, + bool expectsGenericAck = false, + bool waitForGenericAck = false, + }) async { + sentFrames.add(frame); + } +} + +Widget _buildTestApp({ + required MeshCoreConnector connector, + required Widget child, +}) { + final appSettingsService = AppSettingsService(); + + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value( + value: appSettingsService, + ), + ChangeNotifierProvider( + create: (_) => + MapTileCacheService(appSettingsService: appSettingsService), + ), + ChangeNotifierProvider( + create: (_) => PathHistoryService(_FakeStorageService()), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: child, + ), + ); +} + +void main() { + testWidgets('PathTraceMapScreen parses response frames correctly', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector(); + + final screen = PathTraceMapScreen( + title: 'Test Trace', + path: Uint8List.fromList([0x12, 0x34]), + pathHashByteWidth: 1, + ); + + await tester.pumpWidget(_buildTestApp(connector: connector, child: screen)); + await tester.pump(); + + // Verify a send request was made + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + + // Extract the tag sent in the request (bytes 2-5) + final tag = sentFrame.sublist(2, 6); + + // Emit respCodeSent (6) + final respCodeSentFrame = Uint8List(10); + respCodeSentFrame[0] = respCodeSent; + respCodeSentFrame[1] = 0; // reserved / is_flood + respCodeSentFrame.setRange(2, 6, tag); + // timeout milliseconds = 5000 (0x1388) + respCodeSentFrame[6] = 0x88; + respCodeSentFrame[7] = 0x13; + respCodeSentFrame[8] = 0x00; + respCodeSentFrame[9] = 0x00; + + connector.emitFrame(respCodeSentFrame); + await tester.pump(); + + // Now emit PUSH_CODE_TRACE_DATA (0x89) + // Structure: + // Offset 0: pushCodeTraceData (0x89) + // Offset 1: reserved (0) + // Offset 2: pathLength (2) + // Offset 3: flag (0) + // Offset 4..7: tag + // Offset 8..11: auth (0) + // Offset 12..13: pathBytes [0x12, 0x34] + // Offset 14..16: SNR bytes [12, 16, 20] -> to be mapped to signed 8 bit Snr/4 + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; // reserved + pushTraceFrame[2] = 2; // pathLength + pushTraceFrame[3] = 0; // flag + pushTraceFrame.setRange(4, 8, tag); + // auth bytes (8..11) = 0 + pushTraceFrame.setRange(12, 14, [0x12, 0x34]); // pathBytes + pushTraceFrame.setRange(14, 17, [12, 16, 20]); // SNR bytes + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + // Verify it doesn't show "Path trace not available" or similar + expect(find.text('Path trace not available.'), findsNothing); + }); + + testWidgets( + 'PathTraceMapScreen parses multi-byte encoded path trace response correctly', + (tester) async { + final connector = _FakeMeshCoreConnector(); + + final screen = PathTraceMapScreen( + title: 'Test Trace Multi-byte', + path: Uint8List.fromList([0x12, 0x34]), + pathHashByteWidth: 2, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + // Verify a send request was made + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + + // Extract the tag sent in the request (bytes 2-5) + final tag = sentFrame.sublist(2, 6); + + // Emit respCodeSent (6) + final respCodeSentFrame = Uint8List(10); + respCodeSentFrame[0] = respCodeSent; + respCodeSentFrame[1] = 0; + respCodeSentFrame.setRange(2, 6, tag); + respCodeSentFrame[6] = 0x88; + respCodeSentFrame[7] = 0x13; + respCodeSentFrame[8] = 0x00; + respCodeSentFrame[9] = 0x00; + + connector.emitFrame(respCodeSentFrame); + await tester.pump(); + + // Now emit PUSH_CODE_TRACE_DATA (0x89) + // Structure: + // Offset 0: pushCodeTraceData (0x89) + // Offset 1: reserved (0) + // Offset 2: pathLength (65) -> mode 1 (width 2), 1 hop + // Offset 3: flag (0) + // Offset 4..7: tag + // Offset 8..11: auth (0) + // Offset 12..13: pathBytes [0x12, 0x34] + // Offset 14..15: SNR bytes [12, 16] + final pushTraceFrame = Uint8List(16); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; // reserved + pushTraceFrame[2] = 65; // pathLength encoded (mode 1, 1 hop -> 2 bytes) + pushTraceFrame[3] = 0; // flag + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x12, 0x34]); // pathBytes + pushTraceFrame.setRange(14, 16, [12, 16]); // SNR bytes + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + // Verify it parsed correctly (should not show the unavailable message) + expect(find.text('Path trace not available.'), findsNothing); + }, + ); + + testWidgets('PathTraceMapScreen buildPath: Direct repeater ping (0-hop)', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector(); + final target = Contact( + publicKey: Uint8List.fromList([0xAA, 0xBB, 0xCC]), + name: 'Repeater Node', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + lastSeen: DateTime.now(), + ); + + final screen = PathTraceMapScreen( + title: 'Direct Repeater Ping', + path: Uint8List.fromList([0xAA]), + targetContact: target, + flipPathAround: true, + pathHashByteWidth: 1, + ); + + await tester.pumpWidget(_buildTestApp(connector: connector, child: screen)); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + final payload = sentFrame.sublist(10); + expect(payload, Uint8List.fromList([0xAA])); + }); + + testWidgets('PathTraceMapScreen buildPath: 1-hop chat contact trace', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector(); + final target = Contact( + publicKey: Uint8List.fromList([0xCC, 0xDD, 0xEE]), + name: 'Chat User', + type: advTypeChat, + path: Uint8List.fromList([0xBB]), + pathLength: 1, + lastSeen: DateTime.now(), + ); + + final screen = PathTraceMapScreen( + title: '1-Hop Chat Trace', + path: Uint8List.fromList([0xBB]), + targetContact: target, + flipPathAround: true, + pathHashByteWidth: 1, + ); + + await tester.pumpWidget(_buildTestApp(connector: connector, child: screen)); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + final payload = sentFrame.sublist(10); + expect(payload, Uint8List.fromList([0xBB, 0xCC, 0xBB])); + }); + + testWidgets('PathTraceMapScreen buildPath: Multi-hop chat contact trace', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector(); + final target = Contact( + publicKey: Uint8List.fromList([0x33, 0x44, 0x55]), + name: 'Chat User Multi-hop', + type: advTypeChat, + path: Uint8List.fromList([0x11, 0x22]), + pathLength: 2, + lastSeen: DateTime.now(), + ); + + final screen = PathTraceMapScreen( + title: 'Multi-Hop Chat Trace', + path: Uint8List.fromList([0x11, 0x22]), + targetContact: target, + flipPathAround: true, + pathHashByteWidth: 1, + ); + + await tester.pumpWidget(_buildTestApp(connector: connector, child: screen)); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + final payload = sentFrame.sublist(10); + expect(payload, Uint8List.fromList([0x11, 0x22, 0x33, 0x22, 0x11])); + }); + + testWidgets( + 'PathTraceMapScreen buildPath: Map trace with null target contact', + (tester) async { + final connector = _FakeMeshCoreConnector(); + + final screen = PathTraceMapScreen( + title: 'Map Trace No Target', + path: Uint8List.fromList([0x11, 0x22]), + targetContact: null, + flipPathAround: true, + pathHashByteWidth: 1, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + expect(sentFrame[0], cmdSendTracePath); + final payload = sentFrame.sublist(10); + expect(payload, Uint8List.fromList([0x11, 0x22, 0x11])); + }, + ); + + testWidgets('PathTraceMapScreen parses raw byte length fallback correctly', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector(); + + final screen = PathTraceMapScreen( + title: 'Test Raw Fallback', + path: Uint8List.fromList([0x12, 0x34]), + pathHashByteWidth: 2, + ); + + await tester.pumpWidget(_buildTestApp(connector: connector, child: screen)); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final sentFrame = connector.sentFrames.first; + // Extract the tag sent in the request (bytes 2-5) + final tag = sentFrame.sublist(2, 6); + + // Emit respCodeSent (6) + final respCodeSentFrame = Uint8List(10); + respCodeSentFrame[0] = respCodeSent; + respCodeSentFrame[1] = 0; + respCodeSentFrame.setRange(2, 6, tag); + respCodeSentFrame[6] = 0x88; + respCodeSentFrame[7] = 0x13; + respCodeSentFrame[8] = 0x00; + respCodeSentFrame[9] = 0x00; + + connector.emitFrame(respCodeSentFrame); + await tester.pump(); + + // Now emit PUSH_CODE_TRACE_DATA (0x89) + // Structure: + // Offset 2: pathLength (1) -> mode 0, hop count 1. + // Offset 12..13: pathBytes [0x12, 0x34] (1 hop * 2 bytes/hop) + final pushTraceFrame = Uint8List(16); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; // reserved + pushTraceFrame[2] = 1; // pathLength encoded (mode 0, 1 hop) + pushTraceFrame[3] = 0; // flag + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x12, 0x34]); // pathBytes + pushTraceFrame.setRange(14, 16, [12, 16]); // SNR bytes + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + // Verify it parsed correctly (should not show the unavailable message) + expect(find.text('Path trace not available.'), findsNothing); + }); +} diff --git a/test/services/entropy_tables_test.dart b/test/services/entropy_tables_test.dart new file mode 100644 index 00000000..a5633a45 --- /dev/null +++ b/test/services/entropy_tables_test.dart @@ -0,0 +1,138 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/entropy_tables.dart'; + +/// Structural checks on the shipped CDF table file. The invariants here are the +/// ones the rANS coder relies on; if any of them breaks, encoding silently +/// produces garbage rather than failing loudly. +void main() { + final Directory goldenDir = _resolveGoldenDir(); + final Uint8List raw = File( + '${goldenDir.path}/aeic_cdf_ft32.bin', + ).readAsBytesSync(); + final Map manifest = + jsonDecode(File('${goldenDir.path}/manifest.json').readAsStringSync()) + as Map; + final EntropyTables tables = EntropyTables.parse(raw); + + test('header matches the manifest', () { + expect(raw.length, manifest['table_bytes']); + expect(tables.version, 1); + expect(tables.precision, manifest['precision']); + expect(tables.bypassPrecision, manifest['bypass_precision']); + expect(tables.streamParts, manifest['stream_parts']); + expect(tables.groups.length, 2); + }); + + test('group shapes match the manifest', () { + final List> meta = + (manifest['table_groups'] as List) + .cast>(); + for (var g = 0; g < 2; g++) { + final CdfGroup group = tables.groups[g]; + expect(group.numCdfs, meta[g]['rows'], reason: 'group $g rows'); + expect(group.cdfWidth, meta[g]['width'], reason: 'group $g width'); + expect(group.quantizedCdf.length, group.numCdfs * group.cdfWidth); + + var lenMin = 1 << 30, lenMax = -(1 << 30); + var offMin = 1 << 30, offMax = -(1 << 30); + for (var r = 0; r < group.numCdfs; r++) { + lenMin = group.cdfLength[r] < lenMin ? group.cdfLength[r] : lenMin; + lenMax = group.cdfLength[r] > lenMax ? group.cdfLength[r] : lenMax; + offMin = group.offset[r] < offMin ? group.offset[r] : offMin; + offMax = group.offset[r] > offMax ? group.offset[r] : offMax; + } + expect(lenMin, meta[g]['cdf_length_min']); + expect(lenMax, meta[g]['cdf_length_max']); + expect(offMin, meta[g]['offset_min']); + expect(offMax, meta[g]['offset_max']); + } + expect(tables.zGroup.numCdfs, 128); + expect(tables.zGroup.cdfWidth, 19); + expect(tables.yGroup.numCdfs, 64); + expect(tables.yGroup.cdfWidth, 3133); + }); + + test('every CDF row is a valid, gap-free distribution', () { + for (var g = 0; g < tables.groups.length; g++) { + final CdfGroup group = tables.groups[g]; + for (var r = 0; r < group.numCdfs; r++) { + final int n = group.cdfLength[r]; + expect(n, greaterThanOrEqualTo(2), reason: 'group $g row $r length'); + expect(n, lessThanOrEqualTo(group.cdfWidth)); + expect(group.cdfAt(r, 0), 0, reason: 'group $g row $r first'); + expect( + group.cdfAt(r, n - 1), + 1 << 16, + reason: 'group $g row $r terminal', + ); + for (var c = 0; c + 1 < n; c++) { + final int gap = group.cdfAt(r, c + 1) - group.cdfAt(r, c); + expect( + gap, + greaterThanOrEqualTo(1), + reason: 'group $g row $r has a zero-frequency symbol at $c', + ); + } + for (var c = n; c < group.cdfWidth; c++) { + expect(group.cdfAt(r, c), 0, reason: 'group $g row $r padding at $c'); + } + } + } + }); + + test('index-quantizer block parses', () { + final IndexQuantizerParams p = tables.indexQuantizer; + expect(p.scalesLevels, 64); + expect(p.scaleTable.length, 64); + expect(p.logScaleMin, closeTo(-2.2072749131897207, 1e-15)); + expect(p.logScaleStep, closeTo(0.12305479932808384, 1e-15)); + expect(p.scaleThreshold, closeTo(0.08, 1e-7)); + expect(p.scaleFloor, closeTo(1e-5, 1e-11)); + expect(p.scaleTable.first, closeTo(0.11, 1e-5)); + expect(p.scaleTable.last, closeTo(256.0, 1e-3)); + for (var i = 1; i < p.scaleTable.length; i++) { + expect(p.scaleTable[i], greaterThan(p.scaleTable[i - 1])); + } + }); + + test('rejects a corrupt magic', () { + final Uint8List bad = Uint8List.fromList(raw.sublist(0, 4096)); + bad[3] ^= 0xFF; + expect( + () => EntropyTables.parse(bad), + throwsA(isA()), + ); + }); + + test('rejects a truncated file', () { + expect( + () => EntropyTables.parse(Uint8List.fromList(raw.sublist(0, 1024))), + throwsA(isA()), + ); + }); + + test('rejects trailing garbage', () { + final Uint8List extra = Uint8List(raw.length + 1) + ..setRange(0, raw.length, raw); + expect( + () => EntropyTables.parse(extra), + throwsA(isA()), + ); + }); +} + +Directory _resolveGoldenDir() { + for (final String candidate in [ + 'test/services/golden', + '../test/services/golden', + 'golden', + ]) { + final Directory d = Directory(candidate); + if (d.existsSync()) return d; + } + return Directory('test/services/golden'); +} diff --git a/test/services/golden/aeic_cdf_ft32.bin b/test/services/golden/aeic_cdf_ft32.bin new file mode 100644 index 00000000..e3b669dd Binary files /dev/null and b/test/services/golden/aeic_cdf_ft32.bin differ diff --git a/test/services/golden/e2e/image2.aeicrec b/test/services/golden/e2e/image2.aeicrec new file mode 100644 index 00000000..806bc1ec Binary files /dev/null and b/test/services/golden/e2e/image2.aeicrec differ diff --git a/test/services/golden/e2e/images.aeicrec b/test/services/golden/e2e/images.aeicrec new file mode 100644 index 00000000..e276c963 Binary files /dev/null and b/test/services/golden/e2e/images.aeicrec differ diff --git a/test/services/golden/e2e/kodim01.aeicrec b/test/services/golden/e2e/kodim01.aeicrec new file mode 100644 index 00000000..5b7c22bd Binary files /dev/null and b/test/services/golden/e2e/kodim01.aeicrec differ diff --git a/test/services/golden/e2e/kodim02.aeicrec b/test/services/golden/e2e/kodim02.aeicrec new file mode 100644 index 00000000..15190568 Binary files /dev/null and b/test/services/golden/e2e/kodim02.aeicrec differ diff --git a/test/services/golden/e2e/kodim05.aeicrec b/test/services/golden/e2e/kodim05.aeicrec new file mode 100644 index 00000000..af6cf927 Binary files /dev/null and b/test/services/golden/e2e/kodim05.aeicrec differ diff --git a/test/services/golden/e2e/manifest.json b/test/services/golden/e2e/manifest.json new file mode 100644 index 00000000..d7069acf --- /dev/null +++ b/test/services/golden/e2e/manifest.json @@ -0,0 +1,33 @@ +{ + "format": "aeic-entropy-e2e-recording", + "version": 1, + "checkpoint": "AEIC_SE_ft32.pkl", + "size": 512, + "files": [ + { + "file": "kodim01.aeicrec", + "bytes": 7378887, + "sha256": "dd4278523e2a51d031e11b3d71e90f9ffe863d1244bf3de3896525ff0da9c049" + }, + { + "file": "kodim02.aeicrec", + "bytes": 7378887, + "sha256": "8cc3043664c7c6d993baf6fd37db04f0e22954af114c1463b2000a5e230c2e20" + }, + { + "file": "kodim05.aeicrec", + "bytes": 7378927, + "sha256": "535eef3213b0fdb0238bebad7e3baa041fe62aae1623fd9ec2deebd06c11ce1c" + }, + { + "file": "image2.aeicrec", + "bytes": 7378902, + "sha256": "2779478763c22955bc0e61c22fb555dd0f016f3a5d3629a2272a66d1000d485e" + }, + { + "file": "images.aeicrec", + "bytes": 7378878, + "sha256": "d7153bfd8bb9a1f7bd764eb7fcb43b1932205ac1b43be5b2c6ef6c8a5c57edb1" + } + ] +} \ No newline at end of file diff --git a/test/services/golden/manifest.json b/test/services/golden/manifest.json new file mode 100644 index 00000000..3ce558d0 --- /dev/null +++ b/test/services/golden/manifest.json @@ -0,0 +1,486 @@ +{ + "checkpoint": "AEIC_SE_ft32.pkl", + "size": 512, + "precision": 16, + "bypass_precision": 2, + "stream_parts": 2, + "table_file": "aeic_cdf_ft32.bin", + "table_bytes": 813648, + "table_sha256": "4089fde2af16c340642a5c857be42f6d0f21caf71dd5b4f32d62efcd41c77bd5", + "table_groups": [ + { + "group": "z", + "rows": 128, + "width": 19, + "cdf_length_min": 19, + "cdf_length_max": 19, + "offset_min": -8, + "offset_max": -8, + "cdf_max": 65536 + }, + { + "group": "y", + "rows": 64, + "width": 3133, + "cdf_length_min": 5, + "cdf_length_max": 3133, + "offset_min": -1565, + "offset_max": -1, + "cdf_max": 65536 + } + ], + "z_cdf_group_index": 0, + "y_cdf_group_index": 1, + "images": [ + { + "image": "kodim01.png", + "stem": "kodim01", + "bitstream_file": "kodim01.bin", + "bitstream_bytes_stat": 136, + "bitstream_sha256": "771be01642e69c277e6dd6a1b5fe926d45990883e0a2d56a2fca67f5e29b385d", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 81, + 52 + ], + "substream_sha256": [ + "7803b0726155984d86876d260c72c7376fd1e24b49fa31e279e6c88b0b0b3e73", + "8b7e01993f42cd08cb08f3f75d2f94e186ea03e772d47a09a58796bf7db33b0b" + ], + "vector_file": "kodim01.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 13, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim02.png", + "stem": "kodim02", + "bitstream_file": "kodim02.bin", + "bitstream_bytes_stat": 135, + "bitstream_sha256": "6d158062f4e940a09098fdae516eba541cf1c6c3c4aee39d95031add3bf33d7a", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 90, + 42 + ], + "substream_sha256": [ + "a9ab7f345e0733c799da943ac065a21bd407a00e946fab48ec1e1dd8b7bee468", + "7f765eebbaf5dfde47e1d1f70eb8a1407d55f59e0edf5839b378b9c3d7a39dd3" + ], + "vector_file": "kodim02.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 13, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim05.png", + "stem": "kodim05", + "bitstream_file": "kodim05.bin", + "bitstream_bytes_stat": 173, + "bitstream_sha256": "65ba06f964e1f726f7a72f2c4e634282d60ed16232747bb4a84c1d73ed8411bc", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 119, + 51 + ], + "substream_sha256": [ + "12a97d8cd41b03930fa735d867f31756ba499e2d7220ea10f9b5ea96d1f15de3", + "c30c0be1d858848fcd6833a66bc6c3fae8b3dedcac463a598621794cef4ff894" + ], + "vector_file": "kodim05.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 14, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim08.png", + "stem": "kodim08", + "bitstream_file": "kodim08.bin", + "bitstream_bytes_stat": 209, + "bitstream_sha256": "9e1747db3ec84a993e28b52923140948afbf93df483b4f20be93a0f79206ebc4", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 136, + 70 + ], + "substream_sha256": [ + "965f5fd268c6f367b998c827f95f090ba2d945d7e4ebe4003fb604c48711cd03", + "19fd4a704675ad1cd3f97aaf2670e7818d465d3fc800a03621dd11e167a77a9f" + ], + "vector_file": "kodim08.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 14, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim13.png", + "stem": "kodim13", + "bitstream_file": "kodim13.bin", + "bitstream_bytes_stat": 118, + "bitstream_sha256": "75e13bfca9c13400c62aaab08648fa408a4e4cdb13d02ce3e64767f08728cc64", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 64, + 51 + ], + "substream_sha256": [ + "5b1b045e0c850df548bfdc3cf5777bcc1050d226365a5a3ab3dc1cdfd76cd077", + "81b80624237a8796034d94281be0aa3088eebf8124218d7f4a02257473d2fbcb" + ], + "vector_file": "kodim13.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 14, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim19.png", + "stem": "kodim19", + "bitstream_file": "kodim19.bin", + "bitstream_bytes_stat": 170, + "bitstream_sha256": "0ac1e2f5981c7afb8c3efd5cc2c14acf4b53d949e4dd2f2701cf377068d62e0e", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 104, + 63 + ], + "substream_sha256": [ + "d9f566fbde8f3da32f738004a7e88764cf52d8df04c7905f53c0018057899e6f", + "790c717eb572cb07ac17c4324424293559a127de8299ffd4eaeb02f2d2e4f200" + ], + "vector_file": "kodim19.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 13, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "kodim23.png", + "stem": "kodim23", + "bitstream_file": "kodim23.bin", + "bitstream_bytes_stat": 206, + "bitstream_sha256": "1728c415e5a35f9fd501a35369166db8435e3fcfa2fabe99dcd38f21782f6ed7", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 135, + 68 + ], + "substream_sha256": [ + "b169be22ee0554ce83b47118534a25066c4dbb21b3c11e16e69c36eb905d485c", + "c3dd848ad555641febdbad1d5cfe7516965362e735eb36172fed096c1f8fa69e" + ], + "vector_file": "kodim23.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -2, + "z_q_max": 1, + "y_q_min": -2, + "y_q_max": 2, + "y_index_min": -1, + "y_index_max": 14, + "n_skipped_y_indexes": 1, + "roundtrip_bitexact": true + }, + { + "image": "kodim24.png", + "stem": "kodim24", + "bitstream_file": "kodim24.bin", + "bitstream_bytes_stat": 154, + "bitstream_sha256": "9c397ca0212cc6aeaea687c2fc8dc3b88a95a6c153108a056e4fc7254a21b371", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 91, + 60 + ], + "substream_sha256": [ + "4d83ea0c3d9f58795068962f02a9eea9d7ad91afaebe0e330c20e95f695e22c1", + "65c7cdc5f581934b21ea8a16aff1a67dd36118c58933997fc776b99c7f317525" + ], + "vector_file": "kodim24.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 2, + "y_index_min": 0, + "y_index_max": 14, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + }, + { + "image": "image2.webp", + "stem": "image2", + "bitstream_file": "image2.bin", + "bitstream_bytes_stat": 147, + "bitstream_sha256": "258fe68ff7bb9ad41e1b3c7f885c56d051b3d55d313e5e5cc04b4faaf3b181e0", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 88, + 56 + ], + "substream_sha256": [ + "60c3ec394f474c060bfe51f4a086ab40d6f409ab4694ff8b02b68f15029116be", + "d874295cab097586ca1da2026a89a694051baf832fe3e4cd52f03fafbdf896c8" + ], + "vector_file": "image2.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -3, + "z_q_max": 2, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": -1, + "y_index_max": 16, + "n_skipped_y_indexes": 1, + "roundtrip_bitexact": true + }, + { + "image": "images.jpeg", + "stem": "images", + "bitstream_file": "images.bin", + "bitstream_bytes_stat": 128, + "bitstream_sha256": "2ad2224c85c25c394daf0c6e35d0c8fba194b689863f42ebe85a0d67dd632869", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 75, + 50 + ], + "substream_sha256": [ + "706a74709539f2d63f0b9b58d78920c9dfe995a804a4af19ded31b0c51f9adde", + "d35ab3320032adaad85343918c5e118fcb3aea20168024e433b608acc6d918ab" + ], + "vector_file": "images.gv", + "vector_bytes_stat": 270592, + "n_z_symbols": 2048, + "n_y_symbols_each": 16384, + "z_q_min": -1, + "z_q_max": 1, + "y_q_min": -1, + "y_q_max": 1, + "y_index_min": 0, + "y_index_max": 13, + "n_skipped_y_indexes": 0, + "roundtrip_bitexact": true + } + ], + "synthetic": [ + { + "name": "z_escape_exact", + "cdf_group": 0, + "n": 640, + "n_filler_each_end": 256, + "bitstream_file": "synth_z_escape_exact.bin", + "bitstream_bytes_stat": 307, + "bitstream_sha256": "43918b9fc2cd685ce619632b83cb00d99b763e7476e2ea08367e1a88d1040c44", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 152, + 152 + ], + "vector_file": "synth_z_escape_exact.gv", + "vector_bytes_stat": 2624, + "expected_decode_sha256": "230e5130f0690bc31122a475f2d04495244ea1c2dcc663c74e9d4182425d9255", + "sym_min": 0, + "sym_max": 9, + "n_skipped": 0, + "roundtrip_exact": true + }, + { + "name": "z_escape_mixed", + "cdf_group": 0, + "n": 256, + "n_filler_each_end": 64, + "bitstream_file": "synth_z_escape_mixed.bin", + "bitstream_bytes_stat": 443, + "bitstream_sha256": "fc3088f9608c0c8e56876d0034d1c8ab45ec34c83dd6491c26981836b4f8075f", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 211, + 229 + ], + "vector_file": "synth_z_escape_mixed.gv", + "vector_bytes_stat": 1088, + "expected_decode_sha256": "a428f456dc7f31ecae1c1fc5fed8517bcd585783f03f3e3423fbf3649745501a", + "sym_min": -72, + "sym_max": 138, + "n_skipped": 0, + "roundtrip_exact": true + }, + { + "name": "z_dense_normal", + "cdf_group": 0, + "n": 10240, + "n_filler_each_end": 4096, + "bitstream_file": "synth_z_dense_normal.bin", + "bitstream_bytes_stat": 3841, + "bitstream_sha256": "0d2c604369c89081df11ac39a2c3218f3e4bcfe208b32fb9a716ea2ea292be8a", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 1891, + 1947 + ], + "vector_file": "synth_z_dense_normal.gv", + "vector_bytes_stat": 41024, + "expected_decode_sha256": "a293328cba494459297083a0e7c465af5f8ee339c701e5d84bef749ace2d9786", + "sym_min": -8, + "sym_max": 7, + "n_skipped": 0, + "roundtrip_exact": true + }, + { + "name": "y_bypass_long", + "cdf_group": 1, + "n": 640, + "n_filler_each_end": 64, + "bitstream_file": "synth_y_bypass_long.bin", + "bitstream_bytes_stat": 2251, + "bitstream_sha256": "faa8b40f9ce682dc10c1cbb6471c684182ed4fa32023ce915513598147f24c99", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 1163, + 1085 + ], + "vector_file": "synth_y_bypass_long.gv", + "vector_bytes_stat": 2624, + "expected_decode_sha256": "f842f136f187644884733ffd83db78647ead2faeec29d2be3d53322159e2589c", + "sym_min": -32000, + "sym_max": 32000, + "n_skipped": 0, + "roundtrip_exact": true + }, + { + "name": "y_skip_indexes", + "cdf_group": 1, + "n": 384, + "n_filler_each_end": 128, + "bitstream_file": "synth_y_skip_indexes.bin", + "bitstream_bytes_stat": 160, + "bitstream_sha256": "4144dd2271f54d7ceab9001dbb43601839a08176d576cad15a3fe02502361be7", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 78, + 79 + ], + "vector_file": "synth_y_skip_indexes.gv", + "vector_bytes_stat": 1600, + "expected_decode_sha256": "8e17e97e31d0e687efec4ae1f6bd3d7ddd80d73f6a3bbf1bcf72072062069ae3", + "sym_min": -1564, + "sym_max": 12345, + "n_skipped": 43, + "roundtrip_exact": true + }, + { + "name": "y_edges_normal", + "cdf_group": 1, + "n": 1280, + "n_filler_each_end": 512, + "bitstream_file": "synth_y_edges_normal.bin", + "bitstream_bytes_stat": 470, + "bitstream_sha256": "ae336f2000c2f6548e897078cf429e85fa1efd6df7973a6257b6495072e5f8ec", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 207, + 260 + ], + "vector_file": "synth_y_edges_normal.gv", + "vector_bytes_stat": 5184, + "expected_decode_sha256": "ff25d3624640925c557155e83d02fd2fec0b25de8f4b3320fcc6c1db2590c6ac", + "sym_min": -1565, + "sym_max": 1564, + "n_skipped": 0, + "roundtrip_exact": true + }, + { + "name": "y_tiny", + "cdf_group": 1, + "n": 130, + "n_filler_each_end": 64, + "bitstream_file": "synth_y_tiny.bin", + "bitstream_bytes_stat": 13, + "bitstream_sha256": "b5df63c5644dc0b7c599a2009de025721c3ff439eed06b427deee1439dc5a84c", + "container_flag": 17, + "container_header_bytes": 2, + "substream_sizes": [ + 6, + 4 + ], + "vector_file": "synth_y_tiny.gv", + "vector_bytes_stat": 584, + "expected_decode_sha256": "e851be60ef0e9dc7488caaf7ba6e35ecccb933ce6775829d0fbd9dc3010d1d49", + "sym_min": -1, + "sym_max": 0, + "n_skipped": 0, + "roundtrip_exact": true + } + ], + "reference_port_selfcheck": { + "ok": 17, + "total": 17 + } +} \ No newline at end of file diff --git a/test/services/golden/vectors/image2.bin b/test/services/golden/vectors/image2.bin new file mode 100644 index 00000000..3506099e Binary files /dev/null and b/test/services/golden/vectors/image2.bin differ diff --git a/test/services/golden/vectors/image2.gv b/test/services/golden/vectors/image2.gv new file mode 100644 index 00000000..a1bac962 Binary files /dev/null and b/test/services/golden/vectors/image2.gv differ diff --git a/test/services/golden/vectors/images.bin b/test/services/golden/vectors/images.bin new file mode 100644 index 00000000..326e1540 Binary files /dev/null and b/test/services/golden/vectors/images.bin differ diff --git a/test/services/golden/vectors/images.gv b/test/services/golden/vectors/images.gv new file mode 100644 index 00000000..e5a5a27b Binary files /dev/null and b/test/services/golden/vectors/images.gv differ diff --git a/test/services/golden/vectors/kodim01.bin b/test/services/golden/vectors/kodim01.bin new file mode 100644 index 00000000..4299cdb4 Binary files /dev/null and b/test/services/golden/vectors/kodim01.bin differ diff --git a/test/services/golden/vectors/kodim01.gv b/test/services/golden/vectors/kodim01.gv new file mode 100644 index 00000000..982d5328 Binary files /dev/null and b/test/services/golden/vectors/kodim01.gv differ diff --git a/test/services/golden/vectors/kodim02.bin b/test/services/golden/vectors/kodim02.bin new file mode 100644 index 00000000..65227408 Binary files /dev/null and b/test/services/golden/vectors/kodim02.bin differ diff --git a/test/services/golden/vectors/kodim02.gv b/test/services/golden/vectors/kodim02.gv new file mode 100644 index 00000000..59fb957f Binary files /dev/null and b/test/services/golden/vectors/kodim02.gv differ diff --git a/test/services/golden/vectors/kodim05.bin b/test/services/golden/vectors/kodim05.bin new file mode 100644 index 00000000..cedccce4 Binary files /dev/null and b/test/services/golden/vectors/kodim05.bin differ diff --git a/test/services/golden/vectors/kodim05.gv b/test/services/golden/vectors/kodim05.gv new file mode 100644 index 00000000..c808964e Binary files /dev/null and b/test/services/golden/vectors/kodim05.gv differ diff --git a/test/services/golden/vectors/kodim08.bin b/test/services/golden/vectors/kodim08.bin new file mode 100644 index 00000000..67a2f493 Binary files /dev/null and b/test/services/golden/vectors/kodim08.bin differ diff --git a/test/services/golden/vectors/kodim08.gv b/test/services/golden/vectors/kodim08.gv new file mode 100644 index 00000000..1f820ad6 Binary files /dev/null and b/test/services/golden/vectors/kodim08.gv differ diff --git a/test/services/golden/vectors/kodim13.bin b/test/services/golden/vectors/kodim13.bin new file mode 100644 index 00000000..732d785f Binary files /dev/null and b/test/services/golden/vectors/kodim13.bin differ diff --git a/test/services/golden/vectors/kodim13.gv b/test/services/golden/vectors/kodim13.gv new file mode 100644 index 00000000..b5fa10c9 Binary files /dev/null and b/test/services/golden/vectors/kodim13.gv differ diff --git a/test/services/golden/vectors/kodim19.bin b/test/services/golden/vectors/kodim19.bin new file mode 100644 index 00000000..2eb725c5 Binary files /dev/null and b/test/services/golden/vectors/kodim19.bin differ diff --git a/test/services/golden/vectors/kodim19.gv b/test/services/golden/vectors/kodim19.gv new file mode 100644 index 00000000..0f0604a1 Binary files /dev/null and b/test/services/golden/vectors/kodim19.gv differ diff --git a/test/services/golden/vectors/kodim23.bin b/test/services/golden/vectors/kodim23.bin new file mode 100644 index 00000000..cd305d98 Binary files /dev/null and b/test/services/golden/vectors/kodim23.bin differ diff --git a/test/services/golden/vectors/kodim23.gv b/test/services/golden/vectors/kodim23.gv new file mode 100644 index 00000000..f68b6464 Binary files /dev/null and b/test/services/golden/vectors/kodim23.gv differ diff --git a/test/services/golden/vectors/kodim24.bin b/test/services/golden/vectors/kodim24.bin new file mode 100644 index 00000000..9c9beb05 Binary files /dev/null and b/test/services/golden/vectors/kodim24.bin differ diff --git a/test/services/golden/vectors/kodim24.gv b/test/services/golden/vectors/kodim24.gv new file mode 100644 index 00000000..49b43683 Binary files /dev/null and b/test/services/golden/vectors/kodim24.gv differ diff --git a/test/services/golden/vectors/synth_y_bypass_long.bin b/test/services/golden/vectors/synth_y_bypass_long.bin new file mode 100644 index 00000000..f955f8d3 --- /dev/null +++ b/test/services/golden/vectors/synth_y_bypass_long.bin @@ -0,0 +1,3 @@ +‹Æ;Éaÿ/þÿÿ۟ÿÿÿòpþÿï=œÿÿÿ÷ÿÿõÿÿöÿÿÕaÿÿ/þÿÿ۟ÿÿÿòpþÿï=œÿÿÿ÷ÿÿõÿÿöÿÿÕaÿÿ/þÿÿ۟ÿÿÿòpþÿï=œÿÿÿ÷ÿÿõÿÿöÿÿÕaÿÿ/þÿÿ۟ÿÿÿòpþÿï=œÿÿÿ÷ÿÿõÿÿöÿÿÕaÿÿ¯~þÿÿ»Ÿÿÿÿêpþÿï;œÿÿŸþ÷ÿÿíÿÿŸöÿÿÍaÿÿ¯~þÿÿ»Ÿÿÿÿêpþÿï;œÿÿŸþ÷ÿÿíÿÿŸöÿÿÍaÿÿ¯~þÿÿ»Ÿÿÿÿêpþÿï;œÿÿŸþ÷ÿÿíÿÿŸöÿÿÍaÿÿ¯~þÿÿ»Ÿÿÿÿêpþÿï;œÿÿŸþ÷ÿÿíÿÿŸöÿÿÍaÿÿ¯~þÿÿ»Ÿÿÿÿêpþÿï;œÿÿŸþ÷ÿÿíÿÿŸöÿÿÍaÿÿ/~þÿÿ›Ÿÿÿÿâpþÿï9œÿÿþ÷ÿÿåÿÿöÿÿÅaÿÿ/~þÿÿ›Ÿÿÿÿâpþÿï9œÿÿþ÷ÿÿåÿÿöÿÿÅaÿÿ‹Ÿÿÿÿæçÿÿ/çÿÿ›Ãùÿßøßÿÿ—ÿýÿöÿÿÅaÿÿ/~þÿÿ›Ÿÿÿÿâpþÿï9œÿÿþ÷ÿÿåÿÿöÿÿÅaÿÿ¯}þÿÿ{ŸÿÿÿÚpþÿï7œÿÿŸý÷ÿÿÝÿÿŸöÿÿ½aÿÿ¯}þÿÿ{ŸÿÿÿÚpþÿï7œÿÿŸý÷ÿÿÝÿÿŸöÿÿ½aÿÿ/}þÿÿ[ŸÿÿÿÒpþÿï5œÿÿý÷ÿÿÕÿÿöÿÿµaÿÿ/}þ?ÿ[ŸÿÿÿÒpþÿï5œÿÿý÷ÿÿÕÿÿöÏÿµaþÿ+Ÿßÿï|¾ÿÊpöþï ç?ÿÉûÿ7ÿùÿŸ¶ÿßöÿÿÂçÿÿïñùÿÿ/ çÿÿÃùÿÿÁÿÿ_ü÷ÿÿ¡aÿÿ_öÿÿÂçÿÿïñùÿÿ/ çÿÃùÿÿÁÿÿ_ü÷ÿÿ¡aÿÿ_¶ÿïîùÿÿûžï¿ï.œýÿ¾pîÿŸû÷ÿßïßÿßf/ÿ�aþÿ²ççþo{>¿ï,œþÿ¶pÖÿÇþåÿ_û‡ÿæÿ_öÿÿ¢çÿÿïéùÿÿ/ +çÿÿ›Âùÿÿ¡ÿÿ_ú÷ÿÿ�aÿÿ_öÿÿšçÿÿïçùÿÿ¯ çÿÿ{Âùÿÿ™ÿÿßù÷ÿÿyaÿÿßöÿÿ’çÿÿïåùÿÿ/ çÿÿ[Âùÿÿ‘ÿÿ_ù÷ÿÿqaÿÿ_öÿÿ‚çÿÿïáùÿÿ/çÿÿÂùÿÿ�ÿÿ_ø÷ÿÿaaÿþ_öÿ/w>¿ïÝùýÿrpîÿvp®ÿÇýõÿ×ý­ÿG…­ÿUaÿÿ/vþÿÿ›�ÿÿÿbpþÿïœÿÿö÷ÿÿeÿÿö?ÿEaçÿJç¿û;�ÿ+Á9ÿïgÿŸô·þßôWÿ§„ýÿ·„ýÿïÎùÿÿïsþÿÿëÀùÿÿ>pþÿßÎßÿÿ÷üýÿßFØÿÿw„ýÿïÈùÿÿorþÿÿ‹Àùÿÿ&pþÿßÈßÿÿ—üýÿß@Ø?ÿ„}ÿç¿ÿçŸÿ Àù÷Àùÿü½ÿü}ÿá`à9ÿÿoÿÿâæÿÿï¹ùÿÿ/þæÿÿ›¿ùÿÿá~ÿÿ_î÷ÿÿÁ`ÿÿ_ öÿÿÂæÿÿï±ùÿÿ/üæÿÿ¿ùÿÿÁ~ÿÿ_ì÷ÿÿ¡`ÿÿ_ +öÿÿ’æÿÿï¥ùÿÿ/ùæÿÿ[¾ùÿÿ‘~ÿÿ_é÷ÿÿq`ÿÿ_öÿÿjæÿÿï›ùÿÿ¯öæÿÿ»½ùÿÿi~ÿÿßæ÷ÿÿI`ÿÿßöÿÿ2æÿÿï�ùÿÿ/óæÿۼùÿÿ1~ÿÿ_ã÷ÿÿ`ÿý_öûë—ÿóû—ÿûë»ù÷û»ùÿç÷yßßüŸýõÿwýï²åÿïmùÿ﬛ßﭛûßlßÿ×öýÿ‘_ÿßå×ÿÿ«•ÿÿÿnåÿÿÿÿïææÿÿ§õýÿß[ßÿÿ'}ýÿßÓ×ÿÿK”ÿÿÿåÿÿÿÿoáæÿÿGôýÿßEßÿÿÇ{ýúŸ½ã˒ÿےÏï²mRÿ¶mjß,ßû_Ëÿ‘^ˆ_éuß ‘ïFä_ïBmïQ›‡ÄwÿñA_ˆ×ÿ—xÕþ¯<þïóøùÿÊlêþïÌæÿŸò^ÿ_óÞÿ_j—ÿÿ­]ÿÿBãÿÿ�ÿÿ/Äæÿï›ÿÿA{ÿÿE{ÿÿ!]ÿÿ%]ÿÿ/*þÿÿ›Šÿÿÿ¢kþÿïéšÿÿª÷ÿÿ¥zÿÿÈõÿÿ…\ÿÿ¯þÿ»‡ÿÿÿêjþÿﻚÿÿŸž÷ÿÿíyÿÿŸ¼õÿÍ[ùÿ"áóÿ›„�ÿ/¢¦ÿÿ&jÞÿ‡äõÿ—äåÿ°Uÿ_°õÿÿBàÿÿïøÿÿ/”æÿÿ¥ùÿÿAxÿÿ_„÷ÿÿ!Zÿÿ_¢õÿ¯óýÿïÏ÷ÿÿ:hþÿû ùÿŸs÷ÿßs÷ÿŸ‘õÿߑõÿ¯áýÿï‡÷ÿÿgþÿ{œùÿŸa÷ÿßa÷ÿŸõÿßõÿÿÊÜÿÿï3÷ÿÿ¯\æÿ;—ùÿÿÉtÿÿßL÷ÿÿ©VÿþßjÕÿ¯µ=ÿï×öûï™òÿ^dÒÿgÍùÿwÍÕÿçTÙÿ÷TýÿËfÿÿo›½ÿ﬘ÿÿ¶bþÿÇÆýÿׯýÿGNýÿWNñÿK_¿þo}ý¿ï4˜øÿÖ`úÿývÿ_ý–ÿuÿ_ú/[½þo[=?ﬗôÿ¶^ÆÿǶýÿµmõÿ‘Oñÿ•O÷ïÔôéÿVÓßÿR\Æÿ[q™ÿG­½ÿW­åÿ1Mñÿ5Mýï&ô÷ÿžÐßÿkfyüï™åÿ_&Zÿ'Zÿ_žÒþŸŸ’ÿïbóÿïcóúÿŠVîÿ;Z©ÿ'–ñÿ7–¡ÿ§¥ÿmGíÿÊÓÿ[(_ÿKLÉýo1åÿ_„ÿ_!6þ?„ÿ_?ôþ¯b¼ï‹ñûÿ«<¹ÿïòäÿŸŠ¿ÿ-^÷ÿ @ùÿ @ÿÿÂÁßÿÆÁ{ÿ +)ÿ+þœÿg‰ÿƒîý�éþû ó>ûó^ó Ù÷9þLµÿS•O vÿOjoÿ·ÿ·Oÿ@~ÿ@ÆÿOݟÅSÿ�ô0 \ No newline at end of file diff --git a/test/services/golden/vectors/synth_y_bypass_long.gv b/test/services/golden/vectors/synth_y_bypass_long.gv new file mode 100644 index 00000000..1043185c Binary files /dev/null and b/test/services/golden/vectors/synth_y_bypass_long.gv differ diff --git a/test/services/golden/vectors/synth_y_edges_normal.bin b/test/services/golden/vectors/synth_y_edges_normal.bin new file mode 100644 index 00000000..4e89c6fe Binary files /dev/null and b/test/services/golden/vectors/synth_y_edges_normal.bin differ diff --git a/test/services/golden/vectors/synth_y_edges_normal.gv b/test/services/golden/vectors/synth_y_edges_normal.gv new file mode 100644 index 00000000..03aa5085 Binary files /dev/null and b/test/services/golden/vectors/synth_y_edges_normal.gv differ diff --git a/test/services/golden/vectors/synth_y_skip_indexes.bin b/test/services/golden/vectors/synth_y_skip_indexes.bin new file mode 100644 index 00000000..6870de8c Binary files /dev/null and b/test/services/golden/vectors/synth_y_skip_indexes.bin differ diff --git a/test/services/golden/vectors/synth_y_skip_indexes.gv b/test/services/golden/vectors/synth_y_skip_indexes.gv new file mode 100644 index 00000000..b378c92d Binary files /dev/null and b/test/services/golden/vectors/synth_y_skip_indexes.gv differ diff --git a/test/services/golden/vectors/synth_y_tiny.bin b/test/services/golden/vectors/synth_y_tiny.bin new file mode 100644 index 00000000..363e394d Binary files /dev/null and b/test/services/golden/vectors/synth_y_tiny.bin differ diff --git a/test/services/golden/vectors/synth_y_tiny.gv b/test/services/golden/vectors/synth_y_tiny.gv new file mode 100644 index 00000000..6f732429 Binary files /dev/null and b/test/services/golden/vectors/synth_y_tiny.gv differ diff --git a/test/services/golden/vectors/synth_z_dense_normal.bin b/test/services/golden/vectors/synth_z_dense_normal.bin new file mode 100644 index 00000000..328fa5b2 Binary files /dev/null and b/test/services/golden/vectors/synth_z_dense_normal.bin differ diff --git a/test/services/golden/vectors/synth_z_dense_normal.gv b/test/services/golden/vectors/synth_z_dense_normal.gv new file mode 100644 index 00000000..c44ecd0b Binary files /dev/null and b/test/services/golden/vectors/synth_z_dense_normal.gv differ diff --git a/test/services/golden/vectors/synth_z_escape_exact.bin b/test/services/golden/vectors/synth_z_escape_exact.bin new file mode 100644 index 00000000..7edd0f6d Binary files /dev/null and b/test/services/golden/vectors/synth_z_escape_exact.bin differ diff --git a/test/services/golden/vectors/synth_z_escape_exact.gv b/test/services/golden/vectors/synth_z_escape_exact.gv new file mode 100644 index 00000000..e0f6db32 Binary files /dev/null and b/test/services/golden/vectors/synth_z_escape_exact.gv differ diff --git a/test/services/golden/vectors/synth_z_escape_mixed.bin b/test/services/golden/vectors/synth_z_escape_mixed.bin new file mode 100644 index 00000000..54fbf5c4 Binary files /dev/null and b/test/services/golden/vectors/synth_z_escape_mixed.bin differ diff --git a/test/services/golden/vectors/synth_z_escape_mixed.gv b/test/services/golden/vectors/synth_z_escape_mixed.gv new file mode 100644 index 00000000..0b0ba509 Binary files /dev/null and b/test/services/golden/vectors/synth_z_escape_mixed.gv differ diff --git a/test/services/image_codec_boot_payload_test.dart b/test/services/image_codec_boot_payload_test.dart new file mode 100644 index 00000000..68f77d4b --- /dev/null +++ b/test/services/image_codec_boot_payload_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/image_codec_session_io.dart'; + +/// Connection tests for the codec worker's boot payload. +/// +/// Two bugs in this feature had the same shape and both survived a green suite: +/// `imageCodecRansCoderBuilder` was declared, documented and consumed but never +/// assigned; and `entropyDecodeGraphPath` was resolved on the main isolate but +/// never put in the list handed to the worker, so every decode threw +/// [ImageCodecBundleIncomplete] while `canDecode` cheerfully reported true. +/// +/// Neither was a broken component. Both were missing *connections*, and unit +/// tests that exercise each side in isolation cannot see them. These tests +/// assert the payload itself: what spawn() sends is exactly what the worker +/// needs to rebuild a bundle that can decode. +void main() { + ImageCodecBundle fiveAssetBundle() => const ImageCodecBundle( + decoderGraphPath: '/models/aeic_decoder_qdq_conv_pct.onnx', + entropyGraphPath: '/models/aeic_entropy_side_fp32_op17.onnx', + entropyDecodeGraphPath: '/models/aeic_entropy_decode_fp32_op17.onnx', + tablesPath: '/models/aeic_cdf_ft32.bin', + ratePoint: AeicRatePoint.ft32, + ); + + group('codec worker boot payload', () { + test('a five-asset bundle survives the round trip and can still decode', () { + final sent = fiveAssetBundle(); + expect(sent.supportsDecode, isTrue, reason: 'precondition'); + + final rebuilt = debugBundleFromBootPayload(debugBootPayloadFor(sent)); + + expect(rebuilt.decoderGraphPath, sent.decoderGraphPath); + expect(rebuilt.entropyGraphPath, sent.entropyGraphPath); + expect(rebuilt.tablesPath, sent.tablesPath); + expect(rebuilt.ratePoint, sent.ratePoint); + // The one that was missing. Without it the worker builds a bundle whose + // supportsDecode is false and every decode throws, on a correct install. + expect(rebuilt.entropyDecodeGraphPath, sent.entropyDecodeGraphPath); + expect(rebuilt.supportsDecode, isTrue); + }); + + test('no field is silently reindexed by the positional layout', () { + // The payload is a positional List. Inserting a slot anywhere but the end + // shifts every field after it, and the casts are permissive enough that + // tablesPath could arrive as the rate point without throwing. Pin each + // slot to its meaning so a future insert fails here rather than in the + // field, where it would read as a mysterious wrong-model error. + final payload = debugBootPayloadFor(fiveAssetBundle()); + expect(payload[1], '/models/aeic_decoder_qdq_conv_pct.onnx'); + expect(payload[2], '/models/aeic_entropy_side_fp32_op17.onnx'); + expect(payload[3], '/models/aeic_cdf_ft32.bin'); + expect(payload[4], AeicRatePoint.ft32.wireValue); + expect(payload[6], '/models/aeic_entropy_decode_fp32_op17.onnx'); + }); + + test( + 'a send-only bundle rebuilds as send-only rather than half-decoding', + () { + const sendOnly = ImageCodecBundle( + decoderGraphPath: '/models/decoder.onnx', + entropyGraphPath: '/models/entropy.onnx', + tablesPath: '/models/tables.bin', + ratePoint: AeicRatePoint.ft32, + ); + final rebuilt = debugBundleFromBootPayload( + debugBootPayloadFor(sendOnly), + ); + expect(rebuilt.entropyDecodeGraphPath, isNull); + expect(rebuilt.supportsDecode, isFalse); + }, + ); + + test('a short payload does not crash the worker', () { + // An older sender, or a truncated message, must degrade to "cannot + // decode" rather than throwing a RangeError inside the isolate where the + // failure would surface as an opaque spawn error. + final short = debugBootPayloadFor(fiveAssetBundle()).sublist(0, 6); + final rebuilt = debugBundleFromBootPayload(short); + expect(rebuilt.entropyDecodeGraphPath, isNull); + expect(rebuilt.supportsDecode, isFalse); + }); + }); +} diff --git a/test/services/image_codec_download_test.dart b/test/services/image_codec_download_test.dart new file mode 100644 index 00000000..babe08e3 --- /dev/null +++ b/test/services/image_codec_download_test.dart @@ -0,0 +1,720 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/image_codec_file_store.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/image_codec_settings_store.dart'; + +/// Real file store, redirected at a temp directory. +/// +/// Subclassed rather than faked on purpose: the resume logic's whole premise is +/// that a partial file's *length on disk* is its progress marker, so a test that +/// mocked the filesystem would be testing the mock. Only the one method that +/// needs `path_provider` (unavailable in a unit test) is overridden. +class _TempFileStore extends ImageCodecFileStore { + final String root; + + _TempFileStore(this.root); + + @override + Future modelDirectoryPath() async => root; +} + +/// Deterministic pseudo-random bytes, so a sliced Range response can be checked +/// byte-for-byte against the source. +Uint8List _body(int length, [int seed = 7]) { + final bytes = Uint8List(length); + var state = seed | 1; + for (var i = 0; i < length; i++) { + state = (state * 1103515245 + 12345) & 0x7FFFFFFF; + bytes[i] = (state >> 16) & 0xFF; + } + return bytes; +} + +String _sha256(List bytes) => crypto.sha256.convert(bytes).toString(); + +/// A record of every range the client asked for, as `'start-end'`. +class _Log { + final List ranges = []; + int headCount = 0; +} + +/// Serves [assets] (by last path segment) over Range requests. +/// +/// [failAtOffset] makes exactly one range request die half-way through its body, +/// which is what an interrupted 872 MB transfer looks like from Dart's side. +http.Client Function() _server( + Map assets, + _Log log, { + int? failAtOffset, + bool acceptRanges = true, +}) { + return () => MockClient.streaming((request, _) async { + final name = request.url.pathSegments.last; + final data = assets[name]; + if (data == null) { + return http.StreamedResponse(const Stream>.empty(), 404); + } + if (request.method == 'HEAD') { + log.headCount++; + return http.StreamedResponse( + const Stream>.empty(), + 200, + contentLength: data.length, + headers: acceptRanges ? {'accept-ranges': 'bytes'} : const {}, + ); + } + final range = request.headers['Range']; + if (range == null) { + return http.StreamedResponse( + Stream>.value(data), + 200, + contentLength: data.length, + ); + } + final match = RegExp(r'bytes=(\d+)-(\d+)').firstMatch(range)!; + final start = int.parse(match.group(1)!); + final end = int.parse(match.group(2)!); + log.ranges.add('$start-$end'); + final slice = data.sublist(start, end + 1); + + Stream> stream() async* { + if (failAtOffset == start) { + yield slice.sublist(0, slice.length ~/ 2); + throw const SocketException('connection reset by peer'); + } + // Several chunks, so a mid-stream failure is a realistic partial write. + const pieces = 4; + final step = (slice.length / pieces).ceil(); + for (var i = 0; i < slice.length; i += step) { + yield slice.sublist(i, (i + step).clamp(0, slice.length)); + } + } + + return http.StreamedResponse( + stream(), + 206, + contentLength: slice.length, + headers: {'content-range': 'bytes $start-$end/${data.length}'}, + ); + }); +} + +void main() { + late Directory tempDir; + late _TempFileStore store; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('image_codec_dl'); + store = _TempFileStore(tempDir.path); + }); + + tearDown(() async { + if (tempDir.existsSync()) { + await tempDir.delete(recursive: true); + } + }); + + ImageCodecService serviceWith(http.Client Function() clientFactory) { + return ImageCodecService( + AppSettingsService(), + fileStore: store, + settingsStore: InMemoryImageCodecSettingsStore(), + clientFactory: clientFactory, + ); + } + + // 12 MiB clears the 10 MB threshold, so this asset takes the 8-way ranged + // path; the three small ones take the plain GET path. Both are exercised. + // The shape mirrors the real bundle: a small decoder graph, a huge weights + // sibling, a mid-size entropy graph and a tiny table file. + final large = _body(12 * 1024 * 1024, 3); + final small = _body(4096, 11); + final entropy = _body(65536, 23); + final entropyDecode = _body(32768, 31); + final tables = _body(2048, 29); + + /// The five-role spec. Digests default to empty (verification skipped), which + /// is the shipping state until the weights are published. + ImageCodecModelSpec spec({ + String? largeDigest, + String? smallDigest, + String? entropyDigest, + String? entropyDecodeDigest, + String? tablesDigest, + }) { + return ImageCodecModelSpec( + id: 'test-model', + label: 'Test model', + ratePoint: AeicRatePoint.ft32, + assets: [ + ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderGraph, + fileName: 'model.onnx', + sourceUrl: 'https://example.invalid/repo/model.onnx', + sizeBytes: small.length, + sha256: smallDigest ?? '', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderWeights, + fileName: 'model.onnx.data', + sourceUrl: 'https://example.invalid/repo/model.onnx.data', + sizeBytes: large.length, + sha256: largeDigest ?? '', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.entropyGraph, + fileName: 'entropy.onnx', + sourceUrl: 'https://example.invalid/repo/entropy.onnx', + sizeBytes: entropy.length, + sha256: entropyDigest ?? '', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.entropyDecodeGraph, + fileName: 'entropy_decode.onnx', + sourceUrl: 'https://example.invalid/repo/entropy_decode.onnx', + sizeBytes: entropyDecode.length, + sha256: entropyDecodeDigest ?? '', + ), + ImageCodecModelAsset( + role: ImageCodecAssetRole.cdfTables, + fileName: 'cdf.bin', + sourceUrl: 'https://example.invalid/repo/cdf.bin', + sizeBytes: tables.length, + sha256: tablesDigest ?? '', + ), + ], + ); + } + + ImageCodecModelSpec verifiedSpec() => spec( + smallDigest: _sha256(small), + largeDigest: _sha256(large), + entropyDigest: _sha256(entropy), + entropyDecodeDigest: _sha256(entropyDecode), + tablesDigest: _sha256(tables), + ); + + final serverAssets = { + 'model.onnx': small, + 'model.onnx.data': large, + 'entropy.onnx': entropy, + 'entropy_decode.onnx': entropyDecode, + 'cdf.bin': tables, + }; + + group('downloadPresetModel', () { + test('fetches all five assets of the bundle and verifies each', () async { + final log = _Log(); + final service = serviceWith(_server(serverAssets, log)); + addTearDown(service.dispose); + + final record = await service.downloadPresetModel(verifiedSpec()); + + // The record points at the DECODER GRAPH, not the weights and not + // whichever asset happened to be first: that is the path ONNX Runtime is + // handed. + expect(record.name, 'model.onnx'); + expect(record.localPath, '${tempDir.path}/model.onnx'); + // ...but the recorded size is the whole bundle, because that is what the + // user gave up on their device. + expect( + record.fileSizeBytes, + small.length + + large.length + + entropy.length + + entropyDecode.length + + tables.length, + ); + expect(record.assetFileNames, [ + 'model.onnx', + 'model.onnx.data', + 'entropy.onnx', + 'entropy_decode.onnx', + 'cdf.bin', + ]); + expect(record.bundleVersion, kImageCodecBundleVersion); + + final graph = File('${tempDir.path}/model.onnx'); + final weights = File('${tempDir.path}/model.onnx.data'); + expect(graph.existsSync(), isTrue); + expect(weights.existsSync(), isTrue); + expect(await graph.readAsBytes(), small); + expect(await weights.length(), large.length); + expect(_sha256(await weights.readAsBytes()), _sha256(large)); + expect(await File('${tempDir.path}/entropy.onnx').readAsBytes(), entropy); + // Two different entropy exports land side by side; neither may overwrite + // or be mistaken for the other. + expect( + await File('${tempDir.path}/entropy_decode.onnx').readAsBytes(), + entropyDecode, + ); + expect(entropyDecode, isNot(entropy)); + expect(await File('${tempDir.path}/cdf.bin').readAsBytes(), tables); + + // The external-weights sibling MUST keep its exact name or the graph's + // relative reference will not resolve. + expect(weights.uri.pathSegments.last, 'model.onnx.data'); + + // Resume state is swept once an asset verifies. + final leftovers = tempDir + .listSync() + .whereType() + .map((f) => f.uri.pathSegments.last) + .where((n) => n.startsWith('.')) + .toList(); + expect(leftovers, isEmpty); + + expect(service.selectedModel?.id, 'test-model'); + }); + + test('progress is one bar across the set, not four', () async { + final log = _Log(); + final service = serviceWith(_server(serverAssets, log)); + addTearDown(service.dispose); + + final progress = []; + final names = {}; + service.addListener(() { + final value = service.downloadProgress; + if (value != null) progress.add(value); + final name = service.downloadFileName; + if (name != null) names.add(name); + }); + + await service.downloadPresetModel(verifiedSpec()); + + expect(progress, isNotEmpty); + // Monotonic: a per-file bar would snap back to 0 three times. + for (var i = 1; i < progress.length; i++) { + expect( + progress[i], + greaterThanOrEqualTo(progress[i - 1]), + reason: 'progress went backwards at $i', + ); + } + expect(progress.last, closeTo(1.0, 0.001)); + // Every asset was named while it was in flight, so the UI can say which + // of the four files a 900 MB transfer is on. + expect( + names, + containsAll(['model.onnx', 'model.onnx.data', 'cdf.bin']), + ); + }); + + test('refuses a spec that is missing a bundle role', () async { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + + // Decoder-only: it would install a codec that can render a latent and + // nothing else, which is exactly the state this work removes. + final full = spec(); + await expectLater( + service.downloadPresetModel( + ImageCodecModelSpec( + id: 'decoder-only', + label: 'Decoder only', + assets: full.assets.take(2).toList(), + ), + ), + throwsA(isA()), + ); + expect(tempDir.listSync(), isEmpty); + }); + + test('discardPartialDownload sweeps every asset of the bundle', () async { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + final target = spec(); + for (final asset in target.assets) { + await File( + await store.chunkFilePath('${asset.fileName}.99', 0), + ).writeAsBytes(const [1, 2, 3]); + } + final other = File(await store.chunkFilePath('unrelated.onnx.99', 0)); + await other.writeAsBytes(const [1]); + + await service.discardPartialDownload(target); + + final leftovers = tempDir + .listSync() + .whereType() + .map((f) => f.uri.pathSegments.last) + .toList(); + expect(leftovers, ['.unrelated.onnx.99_chunk_0']); + }); + + test('refuses a spec whose URLs are placeholders', () async { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + + await expectLater( + service.downloadPresetModel( + ImageCodecModelSpec( + id: 'placeholder', + label: 'Placeholder', + urlsArePlaceholders: true, + assets: spec().assets, + ), + ), + throwsA(isA()), + ); + expect(tempDir.listSync(), isEmpty); + }); + + test('the shipped preset points at published, verifiable assets', () { + // The weights are published, so the old "still a placeholder" guard is + // inverted: what matters now is that nothing ships half-wired. A real URL + // with an empty digest is worse than a placeholder, because the download + // succeeds and the integrity check silently passes. + expect(imageCodecPresetModels, hasLength(1)); + for (final preset in imageCodecPresetModels) { + expect(preset.urlsArePlaceholders, isFalse); + expect(preset.assets, isNotEmpty); + for (final asset in preset.assets) { + expect( + asset.sourceUrl, + startsWith('https://huggingface.co/'), + reason: asset.fileName, + ); + expect( + asset.sourceUrl, + contains(asset.fileName), + reason: '${asset.fileName} url must name its own file', + ); + expect(asset.sizeBytes, greaterThan(0), reason: asset.fileName); + expect( + asset.sha256, + matches(RegExp(r'^[0-9a-f]{64}$')), + reason: '${asset.fileName} needs a real digest', + ); + } + // Five assets, one bundle: decoder graph + weights, both entropy + // graphs, and the CDF tables. + expect(preset.assets, hasLength(5)); + } + }); + }); + + group('resume', () { + test('a broken transfer resumes from the bytes already on disk', () async { + final chunkSize = (large.length / 8).ceil(); + final victimStart = chunkSize * 3; + + final firstLog = _Log(); + final first = serviceWith( + _server(serverAssets, firstLog, failAtOffset: victimStart), + ); + addTearDown(first.dispose); + + await expectLater( + first.downloadPresetModel(spec()), + throwsA(isA()), + ); + + // Seven chunks landed whole, one is half-written, and none were deleted. + final partials = tempDir + .listSync() + .whereType() + .where((f) => f.uri.pathSegments.last.startsWith('.')) + .toList(); + expect(partials, hasLength(8)); + final victimPath = partials.firstWhere( + (f) => f.uri.pathSegments.last.endsWith('_chunk_3'), + ); + final resumeFrom = await victimPath.length(); + expect(resumeFrom, greaterThan(0)); + expect(resumeFrom, lessThan(chunkSize)); + expect(File('${tempDir.path}/model.onnx.data').existsSync(), isFalse); + + final secondLog = _Log(); + final second = serviceWith(_server(serverAssets, secondLog)); + addTearDown(second.dispose); + await second.downloadPresetModel(verifiedSpec()); + + // Exactly one range was re-requested, and it started where the partial + // file ended rather than at the chunk boundary. + expect(secondLog.ranges, hasLength(1)); + expect( + secondLog.ranges.single, + startsWith('${victimStart + resumeFrom}-'), + ); + + final weights = File('${tempDir.path}/model.onnx.data'); + expect(await weights.length(), large.length); + expect(_sha256(await weights.readAsBytes()), _sha256(large)); + }); + + test('an already-complete verified asset is not re-fetched', () async { + final log = _Log(); + final service = serviceWith(_server(serverAssets, log)); + addTearDown(service.dispose); + final digested = verifiedSpec(); + + await service.downloadPresetModel(digested); + final rangesAfterFirst = log.ranges.length; + expect(rangesAfterFirst, greaterThan(0)); + + await service.downloadPresetModel(digested); + expect(log.ranges.length, rangesAfterFirst, reason: 'no re-download'); + }); + + test('resume state does not survive a change in upstream length', () async { + // Chunk keys embed the total size, so offsets computed for one length can + // never be spliced onto a file of another length. + final a = await store.chunkFilePath('model.onnx.data.1000', 3); + final b = await store.chunkFilePath('model.onnx.data.2000', 3); + expect(a, isNot(b)); + }); + }); + + group('integrity', () { + test('a wrong digest fails loudly and removes the file', () async { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + + await expectLater( + service.downloadPresetModel( + spec(smallDigest: _sha256(utf8.encode('not the model'))), + ), + throwsA(isA()), + ); + expect(File('${tempDir.path}/model.onnx').existsSync(), isFalse); + expect(service.selectedModel, isNull); + }); + + test('sha256OfFile streams the same digest as an in-memory hash', () async { + final path = '${tempDir.path}/blob.bin'; + await File(path).writeAsBytes(large); + expect(await store.sha256OfFile(path), _sha256(large)); + }); + + test('a missing digest is skipped rather than treated as a match', () { + const withDigest = ImageCodecModelAsset( + role: ImageCodecAssetRole.decoderGraph, + fileName: 'a', + sourceUrl: 'https://example.invalid/a', + sizeBytes: 1, + sha256: + '0000000000000000000000000000000000000000000000000000000000000000', + ); + const without = ImageCodecModelAsset( + role: ImageCodecAssetRole.cdfTables, + fileName: 'b', + sourceUrl: 'https://example.invalid/b', + sizeBytes: 1, + ); + expect(withDigest.hasChecksum, isTrue); + expect(without.hasChecksum, isFalse); + }); + }); + + group('scanDownloadedModels', () { + test('preserves chunk files but reaps other hidden junk', () async { + final chunk = File(await store.chunkFilePath('model.onnx.data.99', 2)); + await chunk.writeAsBytes(const [1, 2, 3]); + final junk = File('${tempDir.path}/.DS_Store'); + await junk.writeAsBytes(const [0]); + await File('${tempDir.path}/model.onnx').writeAsBytes(small); + + final found = await store.scanDownloadedModels(); + + expect(found.map((m) => m.name), ['model.onnx']); + expect(chunk.existsSync(), isTrue, reason: 'resume state must survive'); + expect(junk.existsSync(), isFalse); + }); + + test('deletePartialDownloads sweeps only the named model', () async { + final mine = File(await store.chunkFilePath('model.onnx.data.99', 0)); + final other = File(await store.chunkFilePath('other.onnx.99', 0)); + await mine.writeAsBytes(const [1]); + await other.writeAsBytes(const [1]); + + await store.deletePartialDownloads('model.onnx.data'); + + expect(mine.existsSync(), isFalse); + expect(other.existsSync(), isTrue); + }); + }); + + group('non-ranged servers', () { + test('fall back to a single GET', () async { + final log = _Log(); + final service = serviceWith( + _server(serverAssets, log, acceptRanges: false), + ); + addTearDown(service.dispose); + + await service.downloadPresetModel(verifiedSpec()); + + expect(log.ranges, isEmpty); + expect( + await File('${tempDir.path}/model.onnx.data').length(), + large.length, + ); + }); + }); + + group('installedBundle', () { + test( + 'a fresh install resolves the decoder, entropy and table paths', + () async { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + + await service.downloadPresetModel(verifiedSpec()); + + final bundle = service.installedBundle; + expect(bundle, isNotNull); + expect(bundle!.decoderGraphPath, '${tempDir.path}/model.onnx'); + expect(bundle.entropyGraphPath, '${tempDir.path}/entropy.onnx'); + // Resolved by ROLE. Both entropy files end in `.onnx`, so a + // position- or extension-based guess would be a coin flip, and handing + // the decode-side graph to the encoder fails at the first run. + expect( + bundle.entropyDecodeGraphPath, + '${tempDir.path}/entropy_decode.onnx', + ); + expect(bundle.tablesPath, '${tempDir.path}/cdf.bin'); + expect(bundle.isComplete, isTrue); + expect(bundle.supportsDecode, isTrue); + expect(service.needsModelUpgrade, isFalse); + expect(service.needsModelDownload, isFalse); + }, + ); + + test('a bundle-version-1 install can send but not receive', () async { + // The record the previous release wrote: four assets, no decode-side + // graph. Encoding still works, decoding does not, and the remedy is a + // re-download rather than "your device cannot do this". + final v1 = ImageCodecModelRecord( + id: 'test-model', + name: 'model.onnx', + sourceUrl: 'https://example.invalid/repo/model.onnx', + localPath: '${tempDir.path}/model.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1730000000000), + fileSizeBytes: 1, + assetFileNames: const [ + 'model.onnx', + 'model.onnx.data', + 'entropy.onnx', + 'cdf.bin', + ], + bundleVersion: 1, + ); + final service = ImageCodecService( + AppSettingsService(), + fileStore: store, + settingsStore: InMemoryImageCodecSettingsStore( + ImageCodecPreferences( + enabled: true, + selectedModelId: v1.id, + downloadedModels: [v1], + ), + ), + clientFactory: _server(serverAssets, _Log()), + ); + addTearDown(service.dispose); + + final bundle = service.installedBundle; + expect(bundle, isNotNull); + expect(bundle!.entropyGraphPath, '${tempDir.path}/entropy.onnx'); + // No spec asset name is present in the record, and the heuristic must NOT + // invent one: a filename that was never downloaded resolves to an opaque + // ORT failure instead of a download prompt. + expect(bundle.entropyDecodeGraphPath, isNull); + expect(bundle.isComplete, isTrue); + expect(bundle.supportsDecode, isFalse); + expect(service.needsModelUpgrade, isTrue); + expect(service.needsModelDownload, isFalse); + expect(service.canDecode, isFalse); + expect(service.statusReason, isNotNull); + }); + + test('a pre-bundle install is an upgrade, not a broken build', () { + // The decoder-only record the shipped build wrote: no asset list, no + // bundle version. It must stay loadable, report an incomplete bundle, + // and ask for a download rather than declaring the device incapable. + final legacy = ImageCodecModelRecord( + id: 'aeic-se-decoder-qdq-conv-pct-novae', + name: 'aeic_decoder_qdq_conv_pct_novae.onnx', + sourceUrl: 'https://example.invalid/x.onnx', + localPath: '${tempDir.path}/aeic_decoder_qdq_conv_pct_novae.onnx', + downloadedAt: DateTime.fromMillisecondsSinceEpoch(1730000000000), + fileSizeBytes: 2909610, + ); + final service = ImageCodecService( + AppSettingsService(), + fileStore: store, + settingsStore: InMemoryImageCodecSettingsStore( + ImageCodecPreferences( + enabled: true, + selectedModelId: legacy.id, + downloadedModels: [legacy], + ), + ), + clientFactory: _server(serverAssets, _Log()), + ); + addTearDown(service.dispose); + + expect(service.needsModelDownload, isFalse, reason: 'a model IS present'); + expect(service.needsModelUpgrade, isTrue); + final bundle = service.installedBundle; + expect(bundle, isNotNull); + expect(bundle!.decoderGraphPath, legacy.localPath); + expect(bundle.entropyGraphPath, isNull); + expect(bundle.entropyDecodeGraphPath, isNull); + expect(bundle.tablesPath, isNull); + expect(bundle.isComplete, isFalse); + expect(bundle.supportsDecode, isFalse); + expect(service.canEncode, isFalse); + expect(service.canDecode, isFalse); + // An incomplete install is a download away, so the user always gets a + // sentence explaining what to do. + expect(service.statusReason, isNotNull); + }); + + test('nothing installed means no bundle and a download prompt', () { + final service = ImageCodecService( + AppSettingsService(), + fileStore: store, + settingsStore: InMemoryImageCodecSettingsStore( + const ImageCodecPreferences(enabled: true), + ), + clientFactory: _server(serverAssets, _Log()), + ); + addTearDown(service.dispose); + + expect(service.installedBundle, isNull); + expect(service.needsModelDownload, isTrue); + expect(service.needsModelUpgrade, isFalse); + expect(service.canEncode, isFalse); + }); + + test('statusReason is a superset of unavailableReason', () { + final service = serviceWith(_server(serverAssets, _Log())); + addTearDown(service.dispose); + + // While kImageCodecBitstreamPathAvailable is false this is the build + // sentence; when the gate flips, the remaining branches (switched off, + // not downloaded, needs upgrade) take over. Either way it is non-empty + // whenever the codec is not ready, which is the contract the compose + // sheet's banner depends on. + final status = service.statusReason; + expect(status, isNotNull); + expect(status!.trim(), isNotEmpty); + final permanent = service.unavailableReason; + if (permanent != null) { + expect(status, permanent); + } + }); + }); +} diff --git a/test/services/image_codec_e2e_test.dart b/test/services/image_codec_e2e_test.dart new file mode 100644 index 00000000..54252e24 --- /dev/null +++ b/test/services/image_codec_e2e_test.dart @@ -0,0 +1,414 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' show sha256; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/entropy_tables.dart'; +import 'package:meshcore_open/services/image_codec_backend.dart'; +import 'package:meshcore_open/services/image_codec_entropy.dart'; + +/// End-to-end cross-language conformance for the AEIC entropy path. +/// +/// This is deliberately **not** a Dart-encodes-then-Dart-decodes round trip. +/// That shape passes happily with a completely wrong wire format — a swapped +/// mask permutation, a reversed squeeze, an off-by-one in `my_build_indexes` — +/// because both halves make the same mistake. Every assertion here compares +/// Dart against bytes and tensors that Python/ORT/C++ produced: +/// +/// ENCODE: recorded encode-graph outputs -> real Dart four-stage loop -> +/// real Dart rANS ==> byte-identical to the recorded C++ bitstream. +/// DECODE: recorded C++ bitstream -> real Dart rANS -> real Dart four-stage +/// loop (replaying the recorded decode-side network calls) +/// ==> y_hat exactly equal, element for element, to the recorded one. +/// +/// The only thing faked is [AeicEntropyNetwork]: the neural half is replayed +/// from `.aeicrec` recordings made by `aic/exp/record_entropy_io.py`. The fake +/// asserts on its *inputs* as well as returning outputs — in particular the +/// `base` tensor handed to each decode stage must match the recorded one bit +/// for bit, which is what localises a wrong mask / mergeContext / squeeze to +/// the stage that broke instead of to a garbled final image. +void main() { + final Directory goldenDir = _resolveGoldenDir(); + final Directory e2eDir = Directory('${goldenDir.path}/e2e'); + final EntropyTables tables = EntropyTables.parse( + File('${goldenDir.path}/aeic_cdf_ft32.bin').readAsBytesSync(), + ); + final AeicRansCoderFactory coders = AeicRansCoders(tables); + final Map manifest = + jsonDecode(File('${e2eDir.path}/manifest.json').readAsStringSync()) + as Map; + final List> files = (manifest['files'] as List) + .cast>(); + + test('recording corpus is present and unmodified', () { + expect(manifest['format'], 'aeic-entropy-e2e-recording'); + expect(manifest['version'], 1); + expect(manifest['checkpoint'], 'AEIC_SE_ft32.pkl'); + expect(manifest['size'], 512); + expect(files.length, 5); + for (final Map rec in files) { + final File f = File('${e2eDir.path}/${rec['file']}'); + expect(f.existsSync(), isTrue, reason: '${rec['file']} missing'); + final Uint8List raw = f.readAsBytesSync(); + expect(raw.length, rec['bytes'], reason: '${rec['file']} size'); + expect( + sha256.convert(raw).toString(), + rec['sha256'], + reason: '${rec['file']} sha256', + ); + } + }); + + for (final Map rec in files) { + final String name = rec['file'] as String; + group(name, () { + late _Recording r; + late AeicEntropyGeometry geometry; + late AeicMaskSet masks; + + setUpAll(() { + r = _Recording.load('${e2eDir.path}/$name'); + geometry = AeicEntropyGeometry.forResolution( + r.meta['size'] as int, + yChannels: (r.meta['y_shape'] as List)[1] as int, + ); + masks = AeicMaskSet(geometry); + }); + + test('recording shape matches the geometry the codec derives', () { + expect(r.meta['checkpoint'], 'AEIC_SE_ft32.pkl'); + expect(r.meta['z_cdf_group'], kAeicZCdfGroup); + expect(r.meta['y_cdf_group'], kAeicYCdfGroup); + expect(r.meta['byte_order'], 'little'); + expect(r.f32('enc/z_q').length, geometry.zElements); + expect(r.f32('enc/y_hat').length, geometry.yElements); + expect(r.f32('dec/y_hat').length, geometry.yElements); + expect(r.u8('enc/bitstream').length, r.meta['bitstream_bytes']); + expect(r.calls.length, 5); + expect(r.calls[0]['kind'], 'hyper_synthesis'); + for (var i = 0; i < 4; i++) { + expect(r.calls[i + 1]['kind'], 'stage'); + expect(r.calls[i + 1]['stage'], i); + } + }); + + // The pieces the Dart entropy layer computes on its own between the + // graph and the coder. Checked against Python directly so a divergence + // here is attributed to squeeze / my_build_indexes rather than to rANS. + test('symbols and indexes match the recorded integer arrays', () { + _expectSameInts( + aeicToSymbols(r.f32('enc/z_q')), + r.i16('enc/z_symbols'), + 'z symbols', + ); + _expectSameInts( + aeicZIndexes(geometry), + r.i16('enc/z_indexes'), + 'z indexes', + ); + for (var s = 0; s < 4; s++) { + _expectSameInts( + aeicToSymbols(masks.squeeze(r.f32('enc/yq$s'))), + r.i16('enc/symbols$s'), + 'stage $s symbols', + ); + _expectSameInts( + aeicBuildIndexes(masks.squeeze(r.f32('enc/sc$s'))), + r.i16('enc/indexes$s'), + 'stage $s indexes', + ); + } + }); + + test( + 'ENCODE: Dart bitstream is byte-identical to the C++ bitstream', + () async { + final _ReplayNetwork network = _ReplayNetwork(r); + final AeicEntropyCodec codec = AeicEntropyCodec( + geometry: geometry, + network: network, + coders: coders, + ); + final Uint8List got = await codec.encode( + Uint8List(geometry.resolution * geometry.resolution * 3), + ); + expect(network.encodeCalls, 1); + _expectSameBytes(got, r.u8('enc/bitstream'), name); + expect( + sha256.convert(got).toString(), + r.meta['bitstream_sha256'], + reason: '$name: bitstream sha256', + ); + }, + ); + + test( + 'DECODE: y_hat from the C++ bitstream is exactly the recorded y_hat', + () async { + final _ReplayNetwork network = _ReplayNetwork(r); + final AeicEntropyCodec codec = AeicEntropyCodec( + geometry: geometry, + network: network, + coders: coders, + ); + final Float32List got = await codec.decodeToLatent( + r.u8('enc/bitstream'), + ); + expect(network.hyperCalls, 1); + expect(network.stageCalls, [0, 1, 2, 3]); + _expectSameFloats(got, r.f32('dec/y_hat'), '$name: y_hat'); + // The recording asserts the decoder's latent equals the encoder's; if + // that holds in Python it must hold here too. + expect(r.meta['decoded_y_hat_equals_encoder_y_hat'], isTrue); + _expectSameFloats(got, r.f32('enc/y_hat'), '$name: y_hat vs encoder'); + }, + ); + + test('a single flipped bitstream byte does not still pass', () async { + // Byte 3 is the first payload byte of sub-stream 0 (1-byte flag + + // 2-byte size header), which the decoder loads straight into the rANS + // state, so flipping it must change the output. The *last* byte is a + // poor choice: renormalisation does not always consume the tail, and + // on two of these five recordings flipping it is genuinely a no-op. + final Uint8List mutated = Uint8List.fromList(r.u8('enc/bitstream')); + expect(mutated.length, greaterThan(4)); + mutated[3] ^= 0x01; + final AeicEntropyCodec codec = AeicEntropyCodec( + geometry: geometry, + network: _networkForMutation(r), + coders: coders, + ); + Float32List? got; + try { + got = await codec.decodeToLatent(mutated); + } catch (_) { + // Desync raising is an acceptable outcome; silently matching is not. + return; + } + expect( + _sameFloats(got, r.f32('dec/y_hat')), + isFalse, + reason: + '$name: corrupting the stream changed nothing — the ' + 'comparison is vacuous', + ); + }); + }); + } +} + +/// A replay network for the mutated-stream test: it must NOT assert on its +/// inputs, because a desynchronised decode legitimately feeds it a different +/// `base`. It returns the recorded outputs regardless. +AeicEntropyNetwork _networkForMutation(_Recording r) => + _ReplayNetwork(r, strict: false); + +/// [AeicEntropyNetwork] that replays one `.aeicrec` recording. +/// +/// Returns the ORT tensors Python captured, and — when [strict] — asserts that +/// the tensors the Dart loop hands it are bit-for-bit the ones Python's own +/// decode loop handed the real graph. +class _ReplayNetwork implements AeicEntropyNetwork { + _ReplayNetwork(this.r, {this.strict = true}); + + final _Recording r; + final bool strict; + + int encodeCalls = 0; + int hyperCalls = 0; + final List stageCalls = []; + + @override + bool get supportsDecodeSide => true; + + @override + Future runEncodeSide(Float32List imageChw) async { + encodeCalls++; + return AeicEncodeSideTensors( + zQ: r.f32('enc/z_q'), + yQ: [for (var i = 0; i < 4; i++) r.f32('enc/yq$i')], + scales: [for (var i = 0; i < 4; i++) r.f32('enc/sc$i')], + ); + } + + @override + Future runHyperSynthesis(Float32List zQ) async { + hyperCalls++; + final Map call = r.calls[0]; + if (strict) { + _expectSameFloats( + zQ, + r.f32((call['inputs'] as Map)['z_q'] as String), + 'hyper_synthesis input z_q', + ); + } + return r.f32((call['outputs'] as Map)['base0'] as String); + } + + @override + Future runStage(int stage, Float32List base) async { + stageCalls.add(stage); + final Map call = r.calls[stage + 1]; + expect(call['stage'], stage, reason: 'call table is positional'); + if (strict) { + _expectSameFloats( + base, + r.f32((call['inputs'] as Map)['base'] as String), + 'stage $stage input base', + ); + } + final Map outputs = + call['outputs'] as Map; + return AeicStageParams( + meansSupp: r.f32(outputs['means'] as String), + scalesSupp: r.f32(outputs['scales'] as String), + ); + } +} + +/// Reader for the `.aeicrec` container (magic "AEICREC1", little-endian): +/// 32-byte header, an 8-byte-aligned tensor blob, then a UTF-8 JSON index. +class _Recording { + _Recording(this.index, this.bytes) + : _entries = >{ + for (final Map e + in (index['entries'] as List).cast>()) + e['name'] as String: e, + }; + + final Map index; + final Uint8List bytes; + final Map> _entries; + + static _Recording load(String path) { + final Uint8List bytes = File(path).readAsBytesSync(); + final ByteData bd = ByteData.sublistView(bytes); + final String magic = ascii.decode(bytes.sublist(0, 8)); + if (magic != 'AEICREC1') { + throw FormatException('bad .aeicrec magic "$magic" in $path'); + } + final int version = bd.getUint32(8, Endian.little); + if (version != 1) { + throw FormatException('.aeicrec version $version in $path'); + } + final int indexOffset = bd.getUint64(16, Endian.little); + final int indexLength = bd.getUint32(24, Endian.little); + final Map index = + jsonDecode( + utf8.decode( + bytes.sublist(indexOffset, indexOffset + indexLength), + ), + ) + as Map; + return _Recording(index, bytes); + } + + Map get meta => index['meta'] as Map; + + List> get calls => + (index['calls'] as List).cast>(); + + Map _entry(String name, String dtype) { + final Map? e = _entries[name]; + if (e == null) { + throw StateError('no entry "$name" in recording'); + } + if (e['dtype'] != dtype) { + throw StateError('entry "$name" is ${e['dtype']}, wanted $dtype'); + } + return e; + } + + Float32List f32(String name) { + final Map e = _entry(name, 'f32'); + return Float32List.sublistView( + bytes, + e['offset'] as int, + (e['offset'] as int) + (e['length'] as int), + ); + } + + Int16List i16(String name) { + final Map e = _entry(name, 'i16'); + return Int16List.sublistView( + bytes, + e['offset'] as int, + (e['offset'] as int) + (e['length'] as int), + ); + } + + Uint8List u8(String name) { + final Map e = _entry(name, 'u8'); + return Uint8List.sublistView( + bytes, + e['offset'] as int, + (e['offset'] as int) + (e['length'] as int), + ); + } +} + +void _expectSameBytes(Uint8List got, Uint8List want, String label) { + final int n = got.length < want.length ? got.length : want.length; + for (var i = 0; i < n; i++) { + if (got[i] != want[i]) { + fail( + '$label: first byte divergence at offset $i of ${want.length} ' + '(got 0x${got[i].toRadixString(16)}, ' + 'want 0x${want[i].toRadixString(16)})', + ); + } + } + expect( + got.length, + want.length, + reason: '$label: length differs (prefix matched)', + ); +} + +void _expectSameInts(List got, List want, String label) { + expect(got.length, want.length, reason: '$label: length'); + for (var i = 0; i < got.length; i++) { + if (got[i] != want[i]) { + fail( + '$label: first divergence at index $i of ${want.length} ' + '(got ${got[i]}, want ${want[i]})', + ); + } + } +} + +/// Exact equality, element for element — no tolerance. These are integers +/// carried in float32 (symbols + means), so "close" is not the bar. +void _expectSameFloats(Float32List got, Float32List want, String label) { + expect(got.length, want.length, reason: '$label: length'); + for (var i = 0; i < got.length; i++) { + if (got[i] != want[i]) { + fail( + '$label: first divergence at index $i of ${want.length} ' + '(got ${got[i]}, want ${want[i]}, ' + 'diff ${(got[i] - want[i]).abs()})', + ); + } + } +} + +bool _sameFloats(Float32List a, Float32List 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; +} + +Directory _resolveGoldenDir() { + for (final String candidate in [ + 'test/services/golden', + '../test/services/golden', + 'golden', + ]) { + final Directory d = Directory(candidate); + if (d.existsSync()) return d; + } + return Directory('test/services/golden'); +} diff --git a/test/services/image_codec_entropy_test.dart b/test/services/image_codec_entropy_test.dart new file mode 100644 index 00000000..2038f9ff --- /dev/null +++ b/test/services/image_codec_entropy_test.dart @@ -0,0 +1,1025 @@ +import 'dart:io'; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/entropy_tables.dart'; +import 'package:meshcore_open/services/image_codec_backend.dart' + show AeicRansCoders; +import 'package:meshcore_open/services/image_codec_entropy.dart'; + +/// Golden vectors for the entropy layer — the arithmetic between the ONNX +/// tensors and the rANS coder. +/// +/// GENERATED BY: `aic/exp/export_entropy_layer_golden.py`, which runs the real +/// `torch` ops from `aic/aeic/src/codec/codec_practical.py` +/// (`get_mask_four_parts`, `sequeeze`, `torch.round`, `my_build_indexes`) on +/// inputs built from a closed-form integer recipe. Every constant in that +/// recipe is a power-of-two fraction or a plain float64 division, so Dart and +/// numpy reproduce the float32 inputs bit-for-bit and the comparison is real +/// rather than a re-implementation checking itself. +/// +/// Regenerate with: +/// cd /Users/Zach/Documents/mycode/aic +/// AEIC_DEVICE=cpu .venv/bin/python exp/export_entropy_layer_golden.py +/// +/// WHY THIS MATTERS: none of these failures are loud. A wrong mask permutation, +/// a `sequeeze` that folds the wrong channels, or a rounding tie resolved away +/// from zero instead of to even does not throw — it desynchronises rANS and +/// produces a sharp, plausible, wrong image. +class _Golden { + // --- small case: C = 8, H = 4, W = 4, squeezed length 32 --- + + /// `mask_i` flattened over `[1, 8, 4, 4]`, '1' where live. Straight from + /// `get_mask_four_parts(1, 8, 4, 4)`. + static const List masks = [ + '10100000101000001010000010100000010100000101000001010000010100000000101000001010000010100000101000000101000001010000010100000101', + '00000101000001010000010100000101000010100000101000001010000010100101000001010000010100000101000010100000101000001010000010100000', + '00001010000010100000101000001010000001010000010100000101000001011010000010100000101000001010000001010000010100000101000001010000', + '01010000010100000101000001010000101000001010000010100000101000000000010100000101000001010000010100001010000010100000101000001010', + ]; + + static const List> symbols = >[ + [ + -1, + -1, + -2, + 4, + 0, + 0, + 6, + -3, + 2, + 1, + 1, + -1, + -5, + 1, + 0, + 0, + -1, + -1, + -2, + 4, + 0, + 0, + 5, + -3, + 2, + 1, + 1, + -1, + -5, + 1, + 0, + 0, + ], + [ + -1, + -1, + 4, + 4, + 0, + 0, + 0, + 5, + 2, + 1, + -1, + -1, + 3, + -5, + 1, + 0, + -1, + -2, + 4, + 4, + 0, + 0, + 0, + 5, + 1, + 1, + -1, + -1, + 3, + -5, + 1, + 0, + ], + [ + -1, + -2, + -2, + 4, + 1, + 0, + 0, + 5, + 2, + 0, + -1, + -1, + 3, + -5, + 1, + 0, + -1, + -2, + -2, + 4, + 0, + 0, + 0, + 5, + 2, + -1, + -1, + -1, + 3, + -5, + 1, + 0, + ], + [ + -1, + -1, + -2, + -2, + 0, + 0, + 5, + -3, + 2, + 1, + -1, + -1, + -5, + -5, + 0, + 0, + -1, + -1, + -2, + -2, + 0, + 0, + 5, + -3, + 2, + 1, + -1, + -1, + -5, + 1, + 0, + 0, + ], + ]; + + static const List> indexes = >[ + [ + -1, + 6, + -1, + 8, + 12, + 15, + 13, + 16, + 0, + 9, + 3, + 10, + 13, + 16, + 14, + 17, + 0, + 9, + 3, + 10, + 13, + 16, + 14, + 17, + 5, + 11, + 7, + 12, + 15, + 17, + 15, + 18, + ], + [ + 14, + 11, + 15, + 12, + 7, + 0, + 8, + 2, + 15, + 13, + 16, + 14, + 9, + 4, + 11, + 6, + 15, + 13, + 16, + 14, + 10, + 4, + 11, + 6, + 16, + 14, + 17, + 15, + 11, + 7, + 12, + 9, + ], + [ + 11, + 14, + 12, + 15, + -1, + 8, + 0, + 9, + 12, + 16, + 13, + 16, + 2, + 10, + 5, + 11, + 13, + 16, + 13, + 16, + 3, + 10, + 5, + 11, + 14, + 17, + 15, + 17, + 7, + 12, + 8, + 13, + ], + [ + 5, + -1, + 7, + 0, + 15, + 12, + 15, + 13, + 8, + 1, + 10, + 4, + 16, + 14, + 16, + 14, + 8, + 2, + 10, + 4, + 16, + 14, + 16, + 14, + 11, + 6, + 12, + 8, + 17, + 15, + 17, + 16, + ], + ]; + + // --- full case: C = 256, H = W = 16 (the shipping geometry) --- + // + // 16,384 symbols per stage is too much to embed, so the golden is a + // fingerprint: total, extremes, and the first and last twelve values. Any + // permutation error moves the head or the tail; any arithmetic error moves + // the sum. + static const List fullSymbolSum = [-17, 40, -10, 29]; + static const List fullIndexSum = [412240, 412285, 412231, 412219]; + static const List> fullSymbolHead = >[ + [-1, -4, -2, 1, 4, -1, -5, -2, 0, 3, -1, -5], + [-3, 0, 3, 5, 0, -4, -1, 2, 4, 1, -4, -2], + [0, 3, -1, 2, -3, 0, 2, -1, 1, -4, -1, 2], + [-3, -1, 2, -2, 1, 3, -2, 1, 4, 0, 3, 5], + ]; + static const List> fullSymbolTail = >[ + [-4, -2, 1, 4, -2, 1, -3, 0, 3, -2, -6, -3], + [-2, 0, -3, -1, 2, 5, 0, -4, -1, 1, 4, 6], + [-5, -2, 0, 3, -1, -6, -3, 0, 2, 5, 1, -4], + [-1, 1, 4, 0, -4, -2, 1, 3, 6, 2, -2, 0], + ]; + static const List> fullIndexHead = >[ + [-1, -1, -1, 1, 0, 4, 4, 6, 6, 8, 8, 9], + [0, 0, 4, 3, 6, 6, 8, 7, 9, 9, 10, 10], + [0, 2, 2, 5, 4, 7, 7, 8, 8, 10, 10, 11], + [-1, -1, 0, 0, 3, 2, 5, 5, 7, 7, 9, 8], + ]; + static const List> fullIndexTail = >[ + [16, 17, 17, 18, 17, 18, 18, 18, 18, 19, 19, 19], + [16, 16, 17, 16, 17, 17, 18, 18, 18, 18, 19, 18], + [16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19], + [17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19], + ]; + + /// `my_build_indexes` on a spread of scales, isolated from everything else. + static const List probeScales = [ + 0.0, + 9.999999974752427e-07, + 0.05000000074505806, + 0.07989999651908875, + 0.07999999821186066, + 0.10999999940395355, + 0.11000010371208191, + 0.5, + 1.0, + 2.0, + 7.5, + 63.900001525878906, + 255.89999389648438, + 256.0, + 10000.0, + ]; + static const List probeIndexes = [ + -1, + -1, + -1, + -1, + 0, + 0, + 0, + 12, + 17, + 23, + 34, + 51, + 62, + 63, + 63, + ]; +} + +/// The same closed-form recipe the generator uses, in Dart. +/// +/// `y`, `means_supp` and `scales_supp` for a `[1, C, H, W]` tensor. Kept +/// byte-identical to `recipe()` in `export_entropy_layer_golden.py`. +({Float32List y, Float32List means, Float32List scales}) _recipe( + int channels, + int height, + int width, +) { + final n = channels * height * width; + final y = Float32List(n); + final means = Float32List(n); + final scales = Float32List(n); + var i = 0; + for (var c = 0; c < channels; c++) { + for (var h = 0; h < height; h++) { + for (var w = 0; w < width; w++, i++) { + y[i] = ((c * 3 + h * 17 + w * 11) % 61 - 30) * 0.125; + means[i] = ((c * 7 + h * 13 + w * 29) % 97 - 48) * 0.0625; + scales[i] = ((c * 11 + h * 5 + w * 3) % 700) * 0.01 + 0.001; + } + } + } + return (y: y, means: means, scales: scales); +} + +/// One stage of `compress()`: mask, quantize, fold, index. +({Int16List symbols, Int16List indexes}) _runStage( + AeicMaskSet masks, + Float32List y, + Float32List meansSupp, + Float32List scalesSupp, + int stage, +) { + final means = masks.applyMask(meansSupp, stage); + final scales = masks.applyMask(scalesSupp, stage); + final maskedY = masks.applyMask(y, stage); + final yq = Float32List(y.length); + for (var i = 0; i < y.length; i++) { + yq[i] = roundHalfToEven(f32(maskedY[i] - means[i])); + } + return ( + symbols: aeicToSymbols(masks.squeeze(yq)), + indexes: aeicBuildIndexes(masks.squeeze(scales)), + ); +} + +void main() { + group('AeicEntropyGeometry', () { + test('512x512 ft32 matches the shapes the bitstream format assumes', () { + final g = AeicEntropyGeometry.forResolution(512); + expect(g.yShape, [1, 256, 16, 16]); + expect(g.zShape, [1, 128, 4, 4]); + expect(g.squeezedChannels, 64); + // From aic/results/rans_port_spec.md §1. + expect(g.zElements, 2048); + expect(g.symbolsPerStage, 16384); + expect(g.totalEntries, 67584); + }); + + test('z is ceil(y/4), not floor', () { + // 320/32 = 10 -> z must be 3, matching compress()'s reflect padding. + final g = AeicEntropyGeometry.forResolution(320); + expect(g.yHeight, 10); + expect(g.zHeight, 3); + }); + + test('rejects a resolution g_a cannot downsample by 32', () { + expect(() => AeicEntropyGeometry.forResolution(500), throwsArgumentError); + expect(() => AeicEntropyGeometry.forResolution(0), throwsArgumentError); + }); + }); + + group('AeicMaskSet', () { + test('the four masks are get_mask_four_parts, element for element', () { + final masks = AeicMaskSet( + AeicEntropyGeometry.forResolution(128, yChannels: 8), + ); + // 128/32 = 4, so this is exactly the C=8 H=W=4 case in the golden. + for (var stage = 0; stage < 4; stage++) { + final tensor = masks.maskTensor(stage); + final actual = tensor.map((v) => v == 1.0 ? '1' : '0').join(); + expect(actual, _Golden.masks[stage], reason: 'mask_$stage'); + } + }); + + test('every position is claimed by exactly one stage, per channel', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + final counts = Uint8List(geometry.yElements); + for (var stage = 0; stage < 4; stage++) { + final tensor = masks.maskTensor(stage); + for (var i = 0; i < tensor.length; i++) { + counts[i] += tensor[i].toInt(); + } + } + expect(counts.every((c) => c == 1), isTrue); + }); + + test('each mask carries exactly a quarter of the tensor', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + for (var stage = 0; stage < 4; stage++) { + final live = masks.maskTensor(stage).where((v) => v == 1.0).length; + expect(live, geometry.symbolsPerStage); + } + }); + + test('squeeze then unsqueeze is the identity on a masked tensor', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + final recipe = _recipe(256, 16, 16); + for (var stage = 0; stage < 4; stage++) { + final masked = masks.applyMask(recipe.y, stage); + final restored = masks.unsqueeze(masks.squeeze(masked), stage); + expect(restored, masked, reason: 'stage $stage'); + } + }); + + test('mergeContext replaces exactly the stage mask', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + final base = _recipe(256, 16, 16).y; + final stageLatent = masks.applyMask(_recipe(256, 16, 16).means, 2); + final merged = masks.mergeContext(base, stageLatent, 2); + final mask = masks.maskTensor(2); + for (var i = 0; i < merged.length; i++) { + expect(merged[i], mask[i] == 1.0 ? stageLatent[i] : base[i]); + } + }); + }); + + group('roundHalfToEven', () { + test('ties go to even, unlike Dart round()', () { + expect(roundHalfToEven(0.5), 0.0); + expect(roundHalfToEven(1.5), 2.0); + expect(roundHalfToEven(2.5), 2.0); + expect(roundHalfToEven(-0.5), 0.0); + expect(roundHalfToEven(-1.5), -2.0); + expect(roundHalfToEven(-2.5), -2.0); + // Dart disagrees on every one of those ties. + expect((-0.5).roundToDouble(), -1.0); + }); + + test('non-ties are ordinary rounding', () { + expect(roundHalfToEven(0.49), 0.0); + expect(roundHalfToEven(0.51), 1.0); + expect(roundHalfToEven(-1.51), -2.0); + expect(roundHalfToEven(-1.49), -1.0); + expect(roundHalfToEven(7.0), 7.0); + }); + }); + + group('aeicBuildIndexes', () { + test('matches my_build_indexes on the probe scales', () { + final scales = Float32List.fromList(_Golden.probeScales); + expect(aeicBuildIndexes(scales), _Golden.probeIndexes); + }); + + test('the 0.08 threshold is strict, and clamps do not leak', () { + // 0.08 itself is NOT skipped; it clamps to row 0 because ln(0.08) is + // below ln(0.11). + expect(aeicBuildIndexes(Float32List.fromList([0.08])).first, 0); + expect( + aeicBuildIndexes(Float32List.fromList([0.0799])).first, + -1, + ); + expect( + aeicBuildIndexes(Float32List.fromList([1e9])).first, + kAeicScalesLevels - 1, + ); + }); + }); + + group('aeicZIndexes', () { + test('is the channel arange broadcast over H*W', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final indexes = aeicZIndexes(geometry); + expect(indexes.length, 2048); + expect(indexes.first, 0); + expect(indexes[15], 0); + expect(indexes[16], 1); + expect(indexes.last, 127); + // Verified against results/golden/vectors/kodim01.gv, which stores the + // exact int16 array the C++ coder was given. + for (var i = 0; i < indexes.length; i++) { + expect(indexes[i], i ~/ 16); + } + }); + }); + + group('aeicToSymbols', () { + test('rejects a value the int16 wire format cannot carry', () { + expect( + () => aeicToSymbols(Float32List.fromList([40000.0])), + throwsStateError, + ); + expect( + () => aeicToSymbols(Float32List.fromList([1.5])), + throwsStateError, + ); + expect(aeicToSymbols(Float32List.fromList([-3.0])), [-3]); + }); + }); + + group('aeicRgbToChw', () { + test('reproduces ToTensor + Normalize([0.5], [0.5])', () { + final chw = aeicRgbToChw(Uint8List.fromList([0, 128, 255]), 1); + expect(chw.length, 3); + expect(chw[0], -1.0); + expect(chw[1], closeTo(0.00392, 1e-4)); + expect(chw[2], 1.0); + }); + + test('is channel-planar, not interleaved', () { + final rgb = Uint8List(4 * 3); + for (var i = 0; i < 4; i++) { + rgb[i * 3] = 255; // R + rgb[i * 3 + 1] = 0; // G + rgb[i * 3 + 2] = 0; // B + } + final chw = aeicRgbToChw(rgb, 2); + expect(chw.sublist(0, 4), [1.0, 1.0, 1.0, 1.0]); + expect(chw.sublist(4, 8), [-1.0, -1.0, -1.0, -1.0]); + }); + + test('rejects a byte count that is not the stated square', () { + expect(() => aeicRgbToChw(Uint8List(11), 2), throwsArgumentError); + }); + }); + + group('four-stage symbol packing (golden)', () { + test('C=8 H=4 W=4: symbols and indexes match torch exactly', () { + final geometry = AeicEntropyGeometry.forResolution(128, yChannels: 8); + final masks = AeicMaskSet(geometry); + final recipe = _recipe(8, 4, 4); + for (var stage = 0; stage < 4; stage++) { + final out = _runStage( + masks, + recipe.y, + recipe.means, + recipe.scales, + stage, + ); + expect(out.symbols, _Golden.symbols[stage], reason: 'symbols $stage'); + expect(out.indexes, _Golden.indexes[stage], reason: 'indexes $stage'); + } + }); + + test('C=256 H=W=16 (shipping geometry): fingerprint matches torch', () { + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + final recipe = _recipe(256, 16, 16); + for (var stage = 0; stage < 4; stage++) { + final out = _runStage( + masks, + recipe.y, + recipe.means, + recipe.scales, + stage, + ); + expect(out.symbols.length, 16384); + expect( + out.symbols.fold(0, (a, b) => a + b), + _Golden.fullSymbolSum[stage], + reason: 'symbol sum $stage', + ); + expect(out.symbols.sublist(0, 12), _Golden.fullSymbolHead[stage]); + expect(out.symbols.sublist(16372), _Golden.fullSymbolTail[stage]); + expect( + out.indexes.fold(0, (a, b) => a + b), + _Golden.fullIndexSum[stage], + reason: 'index sum $stage', + ); + expect(out.indexes.sublist(0, 12), _Golden.fullIndexHead[stage]); + expect(out.indexes.sublist(16372), _Golden.fullIndexTail[stage]); + } + }); + }); + + group('AeicEntropyCodec', () { + test( + 'encode pushes z, y0, y1, y2, y3 in that order and no other', + () async { + final geometry = AeicEntropyGeometry.forResolution(512); + final network = _FakeNetwork(geometry); + final coders = _RecordingCoders(); + final codec = AeicEntropyCodec( + geometry: geometry, + network: network, + coders: coders, + ); + final progress = []; + final stream = await codec.encode( + Uint8List(512 * 512 * 3), + onProgress: progress.add, + ); + + expect(coders.encoder.groups, [ + kAeicZCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + ]); + expect(coders.encoder.lengths, [2048, 16384, 16384, 16384, 16384]); + expect(stream, isNotEmpty); + expect(progress.last, 1.0); + // The image really was normalized before the graph saw it: 0 -> -1. + expect(network.lastInput!.first, -1.0); + }, + ); + + test('encode refuses a graph that returns the wrong z size', () async { + final geometry = AeicEntropyGeometry.forResolution(512); + final codec = AeicEntropyCodec( + geometry: geometry, + network: _FakeNetwork(geometry, zElements: 7), + coders: _RecordingCoders(), + ); + await expectLater( + codec.encode(Uint8List(512 * 512 * 3)), + throwsStateError, + ); + }); + + test('encode honours shouldCancel between stages', () async { + final geometry = AeicEntropyGeometry.forResolution(512); + final codec = AeicEntropyCodec( + geometry: geometry, + network: _FakeNetwork(geometry), + coders: _RecordingCoders(), + ); + await expectLater( + codec.encode(Uint8List(512 * 512 * 3), shouldCancel: () => true), + throwsA(isA()), + ); + }); + + test('decode reports a send-side-only graph instead of guessing', () async { + final geometry = AeicEntropyGeometry.forResolution(512); + final codec = AeicEntropyCodec( + geometry: geometry, + network: _FakeNetwork(geometry, decodeSide: false), + coders: _RecordingCoders(), + ); + await expectLater( + codec.decodeToLatent(Uint8List(16)), + throwsA(isA()), + ); + }); + + test('decode walks the stages in order and rebuilds y_hat', () async { + final geometry = AeicEntropyGeometry.forResolution(512); + final network = _FakeNetwork(geometry); + final coders = _RecordingCoders(); + final codec = AeicEntropyCodec( + geometry: geometry, + network: network, + coders: coders, + ); + final yHat = await codec.decodeToLatent(Uint8List(16)); + + expect(network.stageCalls, [0, 1, 2, 3]); + expect(coders.decoder.groups, [ + kAeicZCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + kAeicYCdfGroup, + ]); + expect(yHat.length, geometry.yElements); + // The fake decoder returns symbol 1 everywhere and the fake network + // returns means 0, so every position of y_hat must be exactly 1 — which + // only holds if the four masks tile the tensor and each stage's squeezed + // symbols were unsqueezed back into the right channel group. + expect(yHat.every((v) => v == 1.0), isTrue); + }); + }); + // The end-to-end proof: the entropy layer plus the pure-Dart range coder + // reproduce, byte for byte, the bitstreams the C++ coder produced for real + // images — and decode them back to the same symbols. + group('bitstream round trip against the C++ golden vectors', () { + final Directory goldenDir = _resolveGoldenDir(); + final EntropyTables tables = EntropyTables.parse( + File('${goldenDir.path}/aeic_cdf_ft32.bin').readAsBytesSync(), + ); + final geometry = AeicEntropyGeometry.forResolution(512); + final masks = AeicMaskSet(geometry); + + // kodim01 is the plain case; kodim23 and image2 both carry index -1 + // (scales below 0.08), which the coder must skip on encode and read back as + // a literal 0. + for (final name in ['kodim01', 'kodim23', 'image2']) { + test('$name: symbols -> bitstream -> symbols', () async { + final vector = _readGoldenVector( + File('${goldenDir.path}/vectors/$name.gv').readAsBytesSync(), + ); + final expectedStream = File( + '${goldenDir.path}/vectors/$name.bin', + ).readAsBytesSync(); + + // Rebuild the pre-fold tensors the graph would have produced. `squeeze` + // is a bijection on masked tensors, so unsqueezing the golden arrays + // recovers a legitimate input and the loop's own fold has to invert it. + final yQ = []; + final scales = []; + for (var stage = 0; stage < 4; stage++) { + final symbols = vector['y_q$stage']!; + final indexes = vector['y_indexes$stage']!; + final squeezedY = Float32List(symbols.length); + final squeezedS = Float32List(indexes.length); + for (var i = 0; i < symbols.length; i++) { + squeezedY[i] = symbols[i].toDouble(); + squeezedS[i] = _scaleForIndex(indexes[i]); + } + // Self-check: the synthesized scales must land back on the exact + // golden indexes, or this test is measuring the wrong thing. + expect(aeicBuildIndexes(squeezedS), indexes, reason: 'stage $stage'); + yQ.add(masks.unsqueeze(squeezedY, stage)); + scales.add(masks.unsqueeze(squeezedS, stage)); + } + final zQ = Float32List(vector['z_q']!.length); + for (var i = 0; i < zQ.length; i++) { + zQ[i] = vector['z_q']![i].toDouble(); + } + + final network = _ReplayNetwork( + geometry: geometry, + tensors: AeicEncodeSideTensors(zQ: zQ, yQ: yQ, scales: scales), + ); + final codec = AeicEntropyCodec( + geometry: geometry, + network: network, + coders: AeicRansCoders(tables), + ); + + // ENCODE: byte-for-byte against the C++ coder's output. + final stream = await codec.encode(Uint8List(512 * 512 * 3)); + expect(stream, expectedStream, reason: 'bitstream for $name'); + + // DECODE: the same bytes back to the same symbols. means are zero, so + // y_hat is exactly the four stages' symbols tiled back into place — + // which only holds if every mask, fold and unfold agrees with encode. + final yHat = await codec.decodeToLatent(stream); + var expected = Float32List(geometry.yElements); + for (var stage = 0; stage < 4; stage++) { + expected = masks.mergeContext(expected, yQ[stage], stage); + } + expect(yHat, expected, reason: 'y_hat for $name'); + expect(network.stageCalls, [0, 1, 2, 3]); + }); + } + }); +} + +Directory _resolveGoldenDir() { + for (final candidate in [ + 'test/services/golden', + '../test/services/golden', + 'golden', + ]) { + final dir = Directory(candidate); + if (dir.existsSync()) { + return dir; + } + } + throw StateError( + 'golden vectors not found; expected test/services/golden relative to the ' + 'package root', + ); +} + +/// Parses the `.gv` container documented in `aic/results/rans_port_spec.md` §10. +Map _readGoldenVector(Uint8List bytes) { + final data = ByteData.sublistView(bytes); + const magic = [0x41, 0x45, 0x49, 0x43, 0x47, 0x56, 0x00, 0x01]; + for (var i = 0; i < magic.length; i++) { + if (bytes[i] != magic[i]) { + throw StateError('not a .gv container'); + } + } + final count = data.getUint32(12, Endian.little); + final names = []; + final counts = []; + final dtypes = []; + var off = 16; + for (var i = 0; i < count; i++) { + final raw = bytes.sublist(off, off + 16); + final end = raw.indexOf(0); + names.add(String.fromCharCodes(raw.sublist(0, end < 0 ? 16 : end))); + dtypes.add(data.getUint32(off + 16, Endian.little)); + counts.add(data.getUint32(off + 20, Endian.little)); + off += 24; + } + final out = {}; + for (var i = 0; i < count; i++) { + if (dtypes[i] != 0) { + throw StateError('${names[i]} is not int16'); + } + final values = Int16List(counts[i]); + for (var j = 0; j < counts[i]; j++) { + values[j] = data.getInt16(off + j * 2, Endian.little); + } + off += counts[i] * 2; + out[names[i]] = values; + } + return out; +} + +/// A scale that `my_build_indexes` maps back to exactly [index]. +/// +/// Row centres, so float32 rounding cannot push one over a boundary; index -1 +/// means "skipped", which any scale below 0.08 produces. +double _scaleForIndex(int index) { + if (index < 0) { + return 0.0; + } + return f32(math.exp(kAeicLogScaleMin + (index + 0.5) * kAeicLogScaleStep)); +} + +/// Replays fixed tensors as if they came from the graph, for both directions. +class _ReplayNetwork implements AeicEntropyNetwork { + final AeicEntropyGeometry geometry; + final AeicEncodeSideTensors tensors; + final List stageCalls = []; + + _ReplayNetwork({required this.geometry, required this.tensors}); + + @override + bool get supportsDecodeSide => true; + + @override + Future runEncodeSide(Float32List imageChw) async => + tensors; + + @override + Future runHyperSynthesis(Float32List zQ) async { + // The real h_s consumes z_hat; here the only thing under test is that the + // decoded z symbols reach it. Assert that and hand back a zero context. + expect(zQ.length, geometry.zElements); + for (var i = 0; i < zQ.length; i++) { + expect(zQ[i], tensors.zQ[i], reason: 'z symbol $i'); + } + return Float32List(geometry.yElements); + } + + @override + Future runStage(int stage, Float32List base) async { + stageCalls.add(stage); + return AeicStageParams( + meansSupp: Float32List(geometry.yElements), + scalesSupp: tensors.scales[stage], + ); + } +} + +/// A stand-in for the ONNX graph: shapes and call order, no arithmetic. +class _FakeNetwork implements AeicEntropyNetwork { + final AeicEntropyGeometry geometry; + final int? zElements; + final bool decodeSide; + final List stageCalls = []; + Float32List? lastInput; + + _FakeNetwork(this.geometry, {this.zElements, this.decodeSide = true}); + + @override + bool get supportsDecodeSide => decodeSide; + + @override + Future runEncodeSide(Float32List imageChw) async { + lastInput = imageChw; + return AeicEncodeSideTensors( + zQ: Float32List(zElements ?? geometry.zElements), + yQ: [ + for (var i = 0; i < 4; i++) Float32List(geometry.yElements), + ], + scales: [ + for (var i = 0; i < 4; i++) + Float32List(geometry.yElements) + ..fillRange(0, geometry.yElements, 1.0), + ], + ); + } + + @override + Future runHyperSynthesis(Float32List zQ) async => + Float32List(geometry.yElements); + + @override + Future runStage(int stage, Float32List base) async { + stageCalls.add(stage); + return AeicStageParams( + meansSupp: Float32List(geometry.yElements), + scalesSupp: Float32List(geometry.yElements) + ..fillRange(0, geometry.yElements, 1.0), + ); + } +} + +class _RecordingEncoder implements AeicRansEncoder { + final List groups = []; + final List lengths = []; + + @override + void pushSymbols(Int16List symbols, Int16List indexes, int cdfGroup) { + expect(symbols.length, indexes.length); + groups.add(cdfGroup); + lengths.add(symbols.length); + } + + @override + Uint8List finish() => Uint8List.fromList([0x11, 4, 0]); +} + +class _RecordingDecoder implements AeicRansDecoder { + final List groups = []; + + @override + Int16List decodeStream(Int16List indexes, int cdfGroup) { + groups.add(cdfGroup); + return Int16List(indexes.length)..fillRange(0, indexes.length, 1); + } +} + +class _RecordingCoders implements AeicRansCoderFactory { + final _RecordingEncoder encoder = _RecordingEncoder(); + final _RecordingDecoder decoder = _RecordingDecoder(); + + @override + AeicRansEncoder createEncoder() => encoder; + + @override + AeicRansDecoder createDecoder(Uint8List bitstream) => decoder; +} diff --git a/test/services/image_codec_png_test.dart b/test/services/image_codec_png_test.dart new file mode 100644 index 00000000..f95c7bbf --- /dev/null +++ b/test/services/image_codec_png_test.dart @@ -0,0 +1,47 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; + +/// Covers the one piece of the decode path that can be executed without a model +/// file, a device or ONNX Runtime: turning the backend's packed RGB output into +/// PNG bytes a widget can render. +/// +/// It needs the engine's image codecs, hence the binding. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('ImageCodecService.rgbToPng', () { + test('encodes a PNG with the right magic bytes and dimensions', () async { + const side = 8; + final rgb = Uint8List(side * side * 3); + for (var i = 0; i < rgb.length; i++) { + rgb[i] = i & 0xFF; + } + + final png = await ImageCodecService.rgbToPng(rgb, side); + + expect(png.sublist(0, 8), [ + 0x89, + 0x50, + 0x4E, + 0x47, + 0x0D, + 0x0A, + 0x1A, + 0x0A, + ]); + // IHDR width/height, big-endian at offsets 16 and 20. + final header = ByteData.sublistView(png); + expect(header.getUint32(16), side); + expect(header.getUint32(20), side); + }); + + test('rejects a buffer that is not RGB at the stated size', () async { + await expectLater( + ImageCodecService.rgbToPng(Uint8List(10), 8), + throwsA(isA()), + ); + }); + }); +} diff --git a/test/services/map_tile_cache_key_test.dart b/test/services/map_tile_cache_key_test.dart new file mode 100644 index 00000000..e734869b --- /dev/null +++ b/test/services/map_tile_cache_key_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; + +void main() { + test('tile cache key drops api_key and keeps everything else', () { + expect( + MapTileCacheService.tileCacheKey( + 'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png?api_key=k1', + ), + 'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png', + ); + expect( + MapTileCacheService.tileCacheKey('https://x/t/1/2/3.png?a=1&api_key=k2'), + 'https://x/t/1/2/3.png?a=1', + ); + expect( + MapTileCacheService.tileCacheKey( + 'https://tile.openstreetmap.org/1/2/3.png', + ), + 'https://tile.openstreetmap.org/1/2/3.png', + ); + }); +} diff --git a/test/services/message_retry_failure_test.dart b/test/services/message_retry_failure_test.dart new file mode 100644 index 00000000..b0c9e0d3 --- /dev/null +++ b/test/services/message_retry_failure_test.dart @@ -0,0 +1,85 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; + +Contact _contact() => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => 0xAA + i)), + name: 'Test', + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.now(), +); + +void main() { + late MessageRetryService service; + late Map latest; + late List sentTexts; + late bool failSends; + Uint8List? selfKey; + + setUp(() { + service = MessageRetryService(); + latest = {}; + sentTexts = []; + failSends = false; + selfKey = Uint8List(32); + service.initialize( + RetryServiceConfig( + sendMessage: (_, text, _, _) async { + if (failSends) throw StateError('Not connected'); + sentTexts.add(text); + }, + addMessage: (_, m) => latest[m.messageId] = m, + updateMessage: (m) => latest[m.messageId] = m, + getSelfPublicKey: () => selfKey, + ), + ); + }); + + tearDown(() => service.dispose()); + + Message byText(String text) => + latest.values.firstWhere((m) => m.text == text); + + test('failed send fails the message and frees the contact slot', () async { + failSends = true; + final contact = _contact(); + await service.sendMessageWithRetry(contact: contact, text: 'a'); + await pumpEventQueue(); + expect(byText('a').status, MessageStatus.failed); + + failSends = false; + await service.sendMessageWithRetry(contact: contact, text: 'b'); + await pumpEventQueue(); + expect(sentTexts, ['b']); + }); + + test('unknown self key fails instead of waiting forever', () async { + selfKey = null; + await service.sendMessageWithRetry(contact: _contact(), text: 'a'); + await pumpEventQueue(); + expect(byText('a').status, MessageStatus.failed); + expect(sentTexts, isEmpty); + expect(service.hasPendingMessages, isFalse); + }); + + test('failAllPending fails in-flight and queued messages', () async { + final contact = _contact(); + await service.sendMessageWithRetry(contact: contact, text: 'a'); + await service.sendMessageWithRetry(contact: contact, text: 'b'); + await pumpEventQueue(); + expect(sentTexts, ['a']); + + service.failAllPending(); + await pumpEventQueue(); + + expect(byText('a').status, MessageStatus.failed); + expect(byText('b').status, MessageStatus.failed); + expect(service.hasPendingMessages, isFalse); + expect(sentTexts, ['a']); + }); +} diff --git a/test/services/path_history_service_test.dart b/test/services/path_history_service_test.dart index 87ae729d..a5403b5f 100644 --- a/test/services/path_history_service_test.dart +++ b/test/services/path_history_service_test.dart @@ -549,12 +549,15 @@ void main() { final pubKey = _hex('w004'); await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1, weight: 0.3); - svc.recordPathResult( - pubKey, - const PathSelection(pathBytes: [0x01], hopCount: 1, useFlood: false), - success: false, - failureDecrement: 0.5, // 0.3 - 0.5 = -0.2 → remove - ); + // The service requires failureCount >= 3 to remove a path + for (int i = 0; i < 3; i++) { + svc.recordPathResult( + pubKey, + const PathSelection(pathBytes: [0x01], hopCount: 1, useFlood: false), + success: false, + failureDecrement: 0.5, // 0.3 - 0.5 = -0.2 → remove + ); + } await _flush(); final paths = svc.getRecentPaths(pubKey); @@ -820,4 +823,70 @@ void main() { expect(paths.first.routeWeight, closeTo(1.5, 0.001)); }); }); + + group('learned state is preserved', () { + const sel = PathSelection(pathBytes: [0x01], hopCount: 1, useFlood: false); + + test('recordPathAttempt keeps the learned route weight', () async { + final pubKey = _hex('k001'); + await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0); + svc.recordPathResult(pubKey, sel, success: true, successIncrement: 1.0); + await _flush(); + + svc.recordPathAttempt(pubKey, sel); + await _flush(); + + expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(2.0, 1e-9)); + }); + + test('handlePathUpdated keeps the learned route weight', () async { + final pubKey = _hex('k002'); + await _seed(svc, pubKey, pathBytes: [0x01], weight: 3.0); + + svc.handlePathUpdated( + _makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x01]), + ); + await _flush(); + + expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(3.0, 1e-9)); + }); + + test('recordPathResult after eviction merges with stored counts', () async { + final pubKey = _hex('k003'); + await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0); + for (var i = 0; i < 3; i++) { + svc.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5); + } + await _flush(); + + final fresh = PathHistoryService(storage); + fresh.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5); + await _flush(); + + final record = fresh.getRecentPaths(pubKey).first; + expect(record.successCount, equals(4)); + expect(record.routeWeight, closeTo(3.0, 1e-9)); + }); + + test('getRecentPaths load does not drop a concurrent add', () async { + final pubKey = _hex('k004'); + await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0); + + final fresh = PathHistoryService(storage); + fresh.getRecentPaths(pubKey); + fresh.handlePathUpdated( + _makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x02]), + ); + await _flush(); + + final paths = fresh.getRecentPaths(pubKey).map((p) => p.pathBytes); + expect( + paths, + containsAll([ + [0x01], + [0x02], + ]), + ); + }); + }); } diff --git a/test/services/rans_coder_test.dart b/test/services/rans_coder_test.dart new file mode 100644 index 00000000..3f921d00 --- /dev/null +++ b/test/services/rans_coder_test.dart @@ -0,0 +1,263 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/entropy_tables.dart'; +import 'package:meshcore_open/services/rans_coder.dart'; + +/// Golden-vector conformance for the pure-Dart rANS port. +/// +/// The bar is byte-identical: encoding the golden symbol/index arrays must +/// reproduce the exact bitstream the C++ coder produced, and decoding that +/// bitstream must reproduce the exact symbols. A single differing byte +/// desynchronises rANS and silently corrupts most of an image. +void main() { + final Directory goldenDir = _resolveGoldenDir(); + final EntropyTables tables = EntropyTables.parse( + File('${goldenDir.path}/aeic_cdf_ft32.bin').readAsBytesSync(), + ); + final Map manifest = + jsonDecode(File('${goldenDir.path}/manifest.json').readAsStringSync()) + as Map; + final List> images = + (manifest['images'] as List).cast>(); + final List> synthetic = + (manifest['synthetic'] as List).cast>(); + + test('golden corpus is complete', () { + expect(images.length, 10); + expect(synthetic.length, 7); + expect(manifest['stream_parts'], 2); + expect(manifest['reference_port_selfcheck'], { + 'ok': 17, + 'total': 17, + }); + }); + + group('image vectors', () { + for (final Map rec in images) { + final String stem = rec['stem'] as String; + test('$stem encodes and decodes byte-identically', () { + final Map> arrays = _readGoldenVector( + File( + '${goldenDir.path}/vectors/${rec['vector_file']}', + ).readAsBytesSync(), + ); + final Uint8List want = File( + '${goldenDir.path}/vectors/${rec['bitstream_file']}', + ).readAsBytesSync(); + + // Call order is part of the format: z, then y0..y3. + final List<_Call> calls = <_Call>[ + _Call(arrays['z_q']!, arrays['z_indexes']!, 0), + for (var i = 0; i < 4; i++) + _Call(arrays['y_q$i']!, arrays['y_indexes$i']!, 1), + ]; + + final RansEncoder encoder = RansEncoder(tables); + for (final _Call c in calls) { + encoder.encodeWithIndexes(c.symbols, c.indexes, c.group); + } + _expectSameBytes(encoder.finish(), want, stem); + + // One decoder, five incremental calls sharing the sub-stream states. + final RansDecoder decoder = RansDecoder(tables, want); + for (final _Call c in calls) { + _expectSameSymbols(decoder.decodeStream(c.indexes, c.group), c, stem); + } + + final List parts = parseRansContainer(want); + expect( + parts.map((Uint8List p) => p.length).toList(), + (rec['substream_sizes'] as List).cast(), + ); + expect(want[0], rec['container_flag']); + }); + } + }); + + group('synthetic vectors', () { + for (final Map rec in synthetic) { + final String name = rec['name'] as String; + test('$name encodes and decodes byte-identically', () { + final int group = rec['cdf_group'] as int; + final Map> arrays = _readGoldenVector( + File( + '${goldenDir.path}/vectors/${rec['vector_file']}', + ).readAsBytesSync(), + ); + final Uint8List want = File( + '${goldenDir.path}/vectors/${rec['bitstream_file']}', + ).readAsBytesSync(); + final _Call call = _Call(arrays['symbols']!, arrays['indexes']!, group); + + final RansEncoder encoder = RansEncoder(tables); + encoder.encodeWithIndexes(call.symbols, call.indexes, call.group); + _expectSameBytes(encoder.finish(), want, name); + + final RansDecoder decoder = RansDecoder(tables, want); + _expectSameSymbols( + decoder.decodeStream(call.indexes, call.group), + call, + name, + ); + + final List parts = parseRansContainer(want); + expect( + parts.map((Uint8List p) => p.length).toList(), + (rec['substream_sizes'] as List).cast(), + ); + expect(want[0], rec['container_flag']); + }); + } + }); + + test('container round-trips through build/parse', () { + final List parts = [ + Uint8List.fromList([1, 2, 3, 4, 5]), + Uint8List.fromList([9, 8, 7]), + ]; + final Uint8List packed = buildRansContainer(parts); + expect(packed[0], 0x11); + final List back = parseRansContainer(packed); + expect(back.length, 2); + expect(back[0], parts[0]); + expect(back[1], parts[1]); + }); + + test('a flipped bitstream byte would be caught', () { + // Guards the comparison itself against being vacuous. + final Map> arrays = _readGoldenVector( + File('${goldenDir.path}/vectors/synth_y_tiny.gv').readAsBytesSync(), + ); + final Uint8List want = File( + '${goldenDir.path}/vectors/synth_y_tiny.bin', + ).readAsBytesSync(); + final Uint8List mutated = Uint8List.fromList(want); + mutated[mutated.length - 1] ^= 0x01; + final RansEncoder encoder = RansEncoder(tables); + encoder.encodeWithIndexes(arrays['symbols']!, arrays['indexes']!, 1); + final Uint8List got = encoder.finish(); + expect(got, equals(want)); + expect(got, isNot(equals(mutated))); + }); + + test('encoder rejects a second finish()', () { + final RansEncoder encoder = RansEncoder(tables); + encoder.finish(); + expect(encoder.finish, throwsStateError); + }); +} + +class _Call { + _Call(this.symbols, this.indexes, this.group); + + final List symbols; + final List indexes; + final int group; +} + +void _expectSameBytes(Uint8List got, Uint8List want, String label) { + final int n = got.length < want.length ? got.length : want.length; + for (var i = 0; i < n; i++) { + if (got[i] != want[i]) { + fail( + '$label: first byte divergence at offset $i of ${want.length} ' + '(got 0x${got[i].toRadixString(16)}, ' + 'want 0x${want[i].toRadixString(16)})', + ); + } + } + expect( + got.length, + want.length, + reason: '$label: length differs (prefix matched)', + ); +} + +void _expectSameSymbols(Int16List got, _Call call, String label) { + expect(got.length, call.symbols.length, reason: '$label: length'); + for (var i = 0; i < got.length; i++) { + // idx < 0 is asymmetric: it emits nothing on encode, decodes as literal 0. + final int want = call.indexes[i] < 0 ? 0 : call.symbols[i]; + if (got[i] != want) { + fail( + '$label: first symbol divergence at $i ' + '(got ${got[i]}, want $want, index ${call.indexes[i]})', + ); + } + } +} + +Directory _resolveGoldenDir() { + for (final String candidate in [ + 'test/services/golden', + '../test/services/golden', + 'golden', + ]) { + final Directory d = Directory(candidate); + if (d.existsSync()) return d; + } + return Directory('test/services/golden'); +} + +/// Reads a `.gv` golden-vector container. +/// +/// char[8] magic "AEICGV\0\x01", u32 version, u32 nArrays, +/// nArrays x { char[16] name, u32 dtype (0=int16, 1=int32), u32 count }, +/// then the payloads back to back, little-endian. +Map> _readGoldenVector(Uint8List raw) { + const List magic = [0x41, 0x45, 0x49, 0x43, 0x47, 0x56, 0x00, 0x01]; + for (var i = 0; i < magic.length; i++) { + if (raw[i] != magic[i]) { + throw FormatException('bad .gv magic at byte $i'); + } + } + final ByteData bd = ByteData.view( + raw.buffer, + raw.offsetInBytes, + raw.lengthInBytes, + ); + final int version = bd.getUint32(8, Endian.little); + if (version != 1) { + throw FormatException('unsupported .gv version $version'); + } + final int n = bd.getUint32(12, Endian.little); + var off = 16; + final List names = []; + final List dtypes = []; + final List counts = []; + for (var i = 0; i < n; i++) { + final List nameBytes = raw.sublist(off, off + 16); + var end = nameBytes.indexOf(0); + if (end < 0) end = nameBytes.length; + names.add(ascii.decode(nameBytes.sublist(0, end))); + dtypes.add(bd.getUint32(off + 16, Endian.little)); + counts.add(bd.getUint32(off + 20, Endian.little)); + off += 24; + } + final Map> out = >{}; + for (var k = 0; k < n; k++) { + final int count = counts[k]; + if (dtypes[k] == 0) { + final Int16List a = Int16List(count); + for (var i = 0; i < count; i++) { + a[i] = bd.getInt16(off + i * 2, Endian.little); + } + off += count * 2; + out[names[k]] = a; + } else { + final Int32List a = Int32List(count); + for (var i = 0; i < count; i++) { + a[i] = bd.getInt32(off + i * 4, Endian.little); + } + off += count * 4; + out[names[k]] = a; + } + } + if (off != raw.length) { + throw FormatException('.gv trailing data: $off of ${raw.length}'); + } + return out; +} diff --git a/test/services/received_image_store_test.dart b/test/services/received_image_store_test.dart new file mode 100644 index 00000000..feaa9982 --- /dev/null +++ b/test/services/received_image_store_test.dart @@ -0,0 +1,1307 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/image_chunk_transport.dart'; +import 'package:meshcore_open/services/received_image_blob_store_io.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; + +/// Deterministic stand-in for `ImageCodecService`. +class _FakeDecoder implements ReceivedImageDecoder { + @override + ImageCodecAvailability availability; + + @override + bool isBusy; + + /// null -> `decodeBitstream` returns null (codec cannot decode at all) + /// 'fail'-> returns a result with status failed + /// 'throw'-> throws + /// 'ok' -> returns a PNG + String mode; + + Uint8List png; + int calls = 0; + int cancels = 0; + + /// Concurrency witness: a decode peaks at ~2.16 GiB, so `maxConcurrent > 1` + /// is an out-of-memory kill on a phone, not a performance note. + int _inFlight = 0; + int maxConcurrent = 0; + + /// Forces a real suspension inside the decode so a second caller has a + /// chance to overlap. + Duration delay = Duration.zero; + + _FakeDecoder({ + this.availability = ImageCodecAvailability.ready, + this.isBusy = false, + this.mode = 'ok', + Uint8List? png, + }) : png = png ?? Uint8List.fromList(List.filled(4096, 7)); + + @override + Future decodeBitstream({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + }) async { + calls++; + _inFlight++; + if (_inFlight > maxConcurrent) maxConcurrent = _inFlight; + try { + return await _run(ratePoint, resolution); + } finally { + _inFlight--; + } + } + + Future _run( + AeicRatePoint ratePoint, + int resolution, + ) async { + if (delay > Duration.zero) await Future.delayed(delay); + switch (mode) { + case 'null': + return null; + case 'throw': + throw StateError('decoder exploded'); + case 'fail': + return ImageCodecResult( + ratePoint: ratePoint, + resolution: resolution, + durationMs: 5, + status: ImageCodecStatus.failed, + ); + default: + return ImageCodecResult( + ratePoint: ratePoint, + resolution: resolution, + durationMs: 11, + status: ImageCodecStatus.completed, + pngBytes: png, + ); + } + } + + @override + void cancelCodecJob() => cancels++; +} + +const int kSender = 0x1a2b; +const int kSelf = 0xbeef; + +Uint8List _payload(int length, [int seed = 0]) { + return Uint8List.fromList( + List.generate(length, (i) => (i * 31 + seed) & 0xFF), + ); +} + +typedef _Rig = ({ + ReceivedImageStore store, + _FakeDecoder decoder, + InMemoryReceivedImageBlobStore blobs, + ImageReassembler reassembler, + DateTime Function() clock, + void Function(Duration) advance, +}); + +/// Builds a store wired to a fake decoder, an in-memory blob store and a +/// reassembler that all share one injected clock. +_Rig _build({ + int burstCap = 3, + int maxImages = 200, + int maxBytes = 64 * 1024 * 1024, + Duration maxAge = const Duration(days: 30), + _FakeDecoder? decoder, + InMemoryReceivedImageBlobStore? blobs, + bool processAutomatically = true, +}) { + var now = DateTime.utc(2026, 1, 1); + final dec = decoder ?? _FakeDecoder(); + final blobStore = blobs ?? InMemoryReceivedImageBlobStore(); + final reassembler = ImageReassembler(selfPrefix: kSelf, clock: () => now); + final store = ReceivedImageStore( + blobs: blobStore, + decoder: dec, + processAutomatically: processAutomatically, + burstCap: burstCap, + maxImages: maxImages, + maxBytes: maxBytes, + maxAge: maxAge, + clock: () => now, + ); + return ( + store: store, + decoder: dec, + blobs: blobStore, + reassembler: reassembler, + clock: () => now, + advance: (Duration d) => now = now.add(d), + ); +} + +void main() { + group('ReceivedImageRef', () { + test('round-trips a stream id', () { + final id = ReceivedImageRef.streamIdFor( + senderPrefix: 0x1a2b, + imgId: 7, + firstSeen: DateTime.fromMillisecondsSinceEpoch(0x693F21 * 1000), + ); + expect( + id, + '1a2b07' + '00693f21', + ); + expect(id.length, 14); + expect(ReceivedImageRef.parse(ReceivedImageRef.encode(id)), id); + }); + + test('rejects everything that is not an image sentinel', () { + expect(ReceivedImageRef.parse('g:abc123'), isNull); + expect(ReceivedImageRef.parse('hello world'), isNull); + expect(ReceivedImageRef.parse('aeic:1:short'), isNull); + expect(ReceivedImageRef.parse('aeic:1:1A2B0700693F21'), isNull); + expect(ReceivedImageRef.parse('aeic:2:1a2b0700693f21'), isNull); + expect(ReceivedImageRef.parse('@[Bob] hi'), isNull); + expect( + ReceivedImageRef.parse(' aeic:1:1a2b0700693f21 '), + '1a2b0700693f21', + ); + }); + }); + + group('intake and state machine', () { + test('one-chunk image goes receiving -> reassembled -> decoded', () async { + final h = _build(); + final payload = _payload(140); + final set = buildImageChunks( + payload: payload, + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 9, + ); + expect(set.dataChunkCount, 1); + + final outcome = h.reassembler.addChunk(set.blobs[0], channelIndex: 3); + final entry = await h.store.handleOutcome(outcome, channelIndex: 3); + expect(entry, isNotNull); + expect(entry!.state, ReceivedImageState.reassembled); + expect(entry.rate, AeicRatePoint.ft32); + expect(entry.metadataAssumed, isFalse); + expect( + h.blobs.hasBitstream(entry.streamId), + isTrue, + reason: 'bitstream must be written before the state changes', + ); + + await h.store.settle(); + final decoded = h.store.entryFor(entry.streamId)!; + expect(decoded.state, ReceivedImageState.decoded); + expect(decoded.synthesized, isTrue); + expect(decoded.decodeMs, 11); + expect(await h.store.ensurePng(entry.streamId), isNotNull); + expect(h.decoder.calls, 1); + }); + + test('two-chunk image reports 1 of 2 while incomplete', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + expect(set.dataChunkCount, 2); + + final first = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + expect(first!.state, ReceivedImageState.receiving); + expect(first.receivedChunks, 1); + expect(first.totalChunks, 2); + + final second = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[1], channelIndex: 3), + channelIndex: 3, + ); + expect( + second!.streamId, + first.streamId, + reason: 'the sentinel must not change as chunks arrive', + ); + expect(second.state, ReceivedImageState.reassembled); + await h.store.settle(); + expect( + h.store.entryFor(first.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('duplicate delivery does not double-count chunks', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + final first = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + // Same blob three more times (repeaters flood). + for (var i = 0; i < 3; i++) { + await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + } + final entry = h.store.entryFor(first!.streamId)!; + expect(entry.receivedChunks, 1); + expect(entry.state, ReceivedImageState.receiving); + expect(h.store.entries.length, 1); + }); + + test('parity chunks never count towards progress', () async { + final h = _build(); + // Three data chunks: chunk 0 + parity leaves one hole, so the image + // cannot complete and we can observe the progress count. + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + kImageChunkCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + expect(set.dataChunkCount, 3); + expect(set.hasParity, isTrue); + // Parity first, then chunk 0: 1 data chunk received, not 2. + await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs.last, channelIndex: 3), + channelIndex: 3, + ); + final entry = h.store.entries.single; + expect(entry.receivedChunks, 0); + final after = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + expect(after!.receivedChunks, 1); + expect(after.state, ReceivedImageState.receiving); + }); + + test('parity recovery still lands on decoded', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + // Drop chunk 1, deliver 0 + parity. + await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs.last, channelIndex: 3), + channelIndex: 3, + ); + expect(entry!.state, ReceivedImageState.reassembled); + expect(entry.recoveredWithParity, isTrue); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('loopback and malformed blobs create nothing', () async { + final h = _build(); + final own = buildImageChunks( + payload: _payload(120), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSelf, + imgId: 1, + ); + await h.store.handleOutcome( + h.reassembler.addChunk(own.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + await h.store.handleOutcome( + h.reassembler.addChunk(Uint8List.fromList([1, 2]), channelIndex: 3), + channelIndex: 3, + ); + expect(h.store.entries, isEmpty); + }); + + test('TTL expiry moves a partial image to failedIncomplete', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + h.advance(kImageReassemblyTtl + const Duration(seconds: 1)); + final failures = []; + final expiring = ImageReassembler( + selfPrefix: kSelf, + onFailed: failures.add, + ); + // Rebuild the failure the transport would emit for this stream. + failures.add( + ImageReassemblyFailure( + key: entry!.key, + total: 2, + receivedDataChunks: 1, + hadParity: false, + firstSeen: entry.firstSeen, + expiredAt: h.clock(), + ), + ); + expiring.clear(); + await h.store.handleFailure(failures.single); + final failed = h.store.entryFor(entry.streamId)!; + expect(failed.state, ReceivedImageState.failedIncomplete); + expect(failed.receivedChunks, 1); + expect(failed.totalChunks, 2); + expect(failed.canRetryDecode, isFalse); + }); + + test('a corrupt-payload failure reports corrupt, not incomplete', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + await h.store.handleFailure( + ImageReassemblyFailure( + key: entry!.key, + total: 2, + receivedDataChunks: 2, + hadParity: true, + firstSeen: entry.firstSeen, + expiredAt: h.clock(), + reason: ImageReassemblyFailureReason.unsupportedFormat, + ), + ); + final failed = h.store.entryFor(entry.streamId)!; + expect(failed.state, ReceivedImageState.failedCorrupt); + expect(failed.pngStored, isFalse); + expect(await h.store.ensurePng(entry.streamId), isNull); + }); + }); + + group('decode outcomes never present as decoded', () { + test('decoder failure -> failedCorrupt and no pixels', () async { + final h = _build(decoder: _FakeDecoder(mode: 'fail')); + final entry = await _completeOne(h); + await h.store.settle(); + final after = h.store.entryFor(entry.streamId)!; + expect(after.state, ReceivedImageState.failedCorrupt); + expect(after.pngStored, isFalse); + expect(after.pngBytes, isNull); + expect(await h.store.ensurePng(entry.streamId), isNull); + // Retryable, because the bitstream survived. + expect(after.canRetryDecode, isTrue); + }); + + test('decoder throw -> failedCorrupt', () async { + final h = _build(decoder: _FakeDecoder(mode: 'throw')); + final entry = await _completeOne(h); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.failedCorrupt, + ); + }); + + test('decodeBitstream null -> decoderUnavailable', () async { + final h = _build(decoder: _FakeDecoder(mode: 'null')); + final entry = await _completeOne(h); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoderUnavailable, + ); + }); + + test('availability != ready at dequeue -> decoderUnavailable, and the ' + 'image decodes once the codec comes back', () async { + final decoder = _FakeDecoder( + availability: ImageCodecAvailability.disabled, + ); + final h = _build(decoder: decoder); + final entry = await _completeOne(h); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoderUnavailable, + ); + expect(decoder.calls, 0); + + decoder.availability = ImageCodecAvailability.ready; + h.store.notifyDecoderChanged(); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('a busy codec parks the queue instead of failing it', () async { + final decoder = _FakeDecoder(isBusy: true); + final h = _build(decoder: decoder); + final entry = await _completeOne(h); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.reassembled, + ); + expect(h.store.decodeQueue, [entry.streamId]); + expect(decoder.calls, 0); + + decoder.isBusy = false; + h.store.notifyDecoderChanged(); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('retry after failure re-runs the decoder', () async { + final decoder = _FakeDecoder(mode: 'fail'); + final h = _build(decoder: decoder); + final entry = await _completeOne(h); + await h.store.settle(); + decoder.mode = 'ok'; + await h.store.requestDecode(entry.streamId); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + expect(decoder.calls, 2); + }); + + test('failedIncomplete is never retryable', () async { + final h = _build(); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 4, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + await h.store.handleFailure( + ImageReassemblyFailure( + key: entry!.key, + total: 2, + receivedDataChunks: 1, + hadParity: false, + firstSeen: entry.firstSeen, + expiredAt: h.clock(), + ), + ); + await h.store.requestDecode(entry.streamId); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.failedIncomplete, + ); + expect(h.decoder.calls, 0); + }); + }); + + group('decode gates', () { + test('backgrounded: nothing decodes until the app resumes', () async { + final h = _build(); + h.store.setForeground(false); + final entry = await _completeOne(h); + await h.store.settle(); + expect(h.decoder.calls, 0); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.reassembled, + ); + h.store.setForeground(true); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('burst cap parks all but the newest few behind a tap', () async { + final h = _build(burstCap: 3); + h.store.setForeground(false); + final ids = []; + for (var i = 0; i < 5; i++) { + ids.add((await _completeOne(h, imgId: 20 + i, seed: i)).streamId); + h.advance(const Duration(seconds: 2)); + } + expect(h.store.decodeQueue.length, 3); + expect(h.store.entryFor(ids[0])!.needsManualDecode, isTrue); + expect(h.store.entryFor(ids[1])!.needsManualDecode, isTrue); + expect(h.store.entryFor(ids[4])!.needsManualDecode, isFalse); + + h.store.setForeground(true); + await h.store.settle(); + expect(h.decoder.calls, 3); + expect(h.store.entryFor(ids[0])!.state, ReceivedImageState.reassembled); + expect(h.store.entryFor(ids[4])!.state, ReceivedImageState.decoded); + + // A tap on a parked image decodes it. + await h.store.requestDecode(ids[0]); + await h.store.settle(); + expect(h.store.entryFor(ids[0])!.state, ReceivedImageState.decoded); + }); + + test('memory pressure cancels and parks, never fails', () async { + final h = _build(); + h.store.setForeground(false); + final entry = await _completeOne(h); + await h.store.handleMemoryPressure(); + expect(h.decoder.cancels, greaterThanOrEqualTo(1)); + expect(h.store.decodeQueue, isEmpty); + final after = h.store.entryFor(entry.streamId)!; + expect(after.state, ReceivedImageState.reassembled); + expect(after.needsManualDecode, isTrue); + }); + }); + + group('eviction', () { + test( + 'byte budget drops the oldest PNG first and keeps the bitstream', + () async { + final decoder = _FakeDecoder( + png: Uint8List.fromList(List.filled(1000, 3)), + ); + final h = _build(decoder: decoder, maxBytes: 2500); + final ids = []; + for (var i = 0; i < 3; i++) { + final entry = await _completeOne(h, imgId: 40 + i, seed: i); + await h.store.settle(); + ids.add(entry.streamId); + h.advance(const Duration(seconds: 5)); + } + // 3 x 1000 B PNG > 2500 B, so the oldest PNG must have gone. + expect(h.store.entryFor(ids[0])!.state, ReceivedImageState.evicted); + expect(h.store.entryFor(ids[0])!.pngStored, isFalse); + expect(h.blobs.hasPng(ids[0]), isFalse); + expect( + h.blobs.hasBitstream(ids[0]), + isTrue, + reason: 'a ~156 B bitstream is cheap; keep it so we can re-decode', + ); + expect(h.store.entryFor(ids[0])!.canRetryDecode, isTrue); + expect(h.store.entryFor(ids[2])!.state, ReceivedImageState.decoded); + expect(h.store.totalBytes, lessThanOrEqualTo(2500)); + + // "Decode again" works off the surviving bitstream, and the image we just + // decoded is never the budget's own victim (that would thrash forever). + await h.store.requestDecode(ids[0]); + await h.store.settle(); + expect(h.store.entryFor(ids[0])!.state, ReceivedImageState.decoded); + expect(h.store.entryFor(ids[1])!.state, ReceivedImageState.evicted); + expect(h.store.totalBytes, lessThanOrEqualTo(2500)); + }, + ); + + test('image-count budget evicts oldest first', () async { + final h = _build(maxImages: 2); + final ids = []; + for (var i = 0; i < 4; i++) { + final entry = await _completeOne(h, imgId: 60 + i, seed: i); + await h.store.settle(); + ids.add(entry.streamId); + h.advance(const Duration(seconds: 5)); + } + expect(h.store.storedImageCount, lessThanOrEqualTo(2)); + expect(h.store.entryFor(ids[0])!.state, ReceivedImageState.evicted); + expect(h.store.entryFor(ids[1])!.state, ReceivedImageState.evicted); + expect(h.store.entryFor(ids[3])!.state, ReceivedImageState.decoded); + }); + + test('age budget removes both files', () async { + final h = _build(maxAge: const Duration(minutes: 10)); + final entry = await _completeOne(h); + await h.store.settle(); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoded, + ); + h.advance(const Duration(minutes: 11)); + final evicted = await h.store.evictToBudget(); + expect(evicted, contains(entry.streamId)); + final after = h.store.entryFor(entry.streamId)!; + expect(after.state, ReceivedImageState.evicted); + expect(after.canRetryDecode, isFalse); + expect(h.blobs.hasBitstream(entry.streamId), isFalse); + expect(h.blobs.hasPng(entry.streamId), isFalse); + }); + + test('deleteImage reaps all three files', () async { + final h = _build(); + final entry = await _completeOne(h); + await h.store.settle(); + expect(h.blobs.hasSidecar(entry.streamId), isTrue); + await h.store.deleteImage(entry.streamId); + expect(h.store.entryFor(entry.streamId), isNull); + expect(h.blobs.hasSidecar(entry.streamId), isFalse); + expect(h.blobs.hasPng(entry.streamId), isFalse); + expect(h.blobs.hasBitstream(entry.streamId), isFalse); + }); + }); + + group('persistence and startup repair', () { + test('sidecars survive a restart and decoded images reload', () async { + final blobs = InMemoryReceivedImageBlobStore(); + final h = _build(blobs: blobs); + final entry = await _completeOne(h); + await h.store.settle(); + + final reborn = ReceivedImageStore( + blobs: blobs, + decoder: _FakeDecoder(), + clock: h.clock, + ); + await reborn.load(); + final loaded = reborn.entryFor(entry.streamId)!; + expect(loaded.state, ReceivedImageState.decoded); + expect(loaded.pngBytes, isNull, reason: 'pixels are read lazily'); + expect(await reborn.ensurePng(entry.streamId), isNotNull); + reborn.dispose(); + }); + + test('receiving and decoding are repaired on load', () async { + final blobs = InMemoryReceivedImageBlobStore(); + const receivingId = 'aaaa010000000001'; + await blobs.writeSidecar( + 'partial', + jsonEncode({ + 'streamId': 'partial00000001', + 'senderPrefix': 1, + 'imgId': 1, + 'channelIndex': 0, + 'firstSeenMs': DateTime.utc(2026, 1, 1).millisecondsSinceEpoch, + 'state': 'receiving', + 'receivedChunks': 1, + 'totalChunks': 2, + }), + ); + await blobs.writeSidecar( + 'midDecode', + jsonEncode({ + 'streamId': 'midDecode', + 'senderPrefix': 2, + 'imgId': 2, + 'channelIndex': 0, + 'firstSeenMs': DateTime.utc(2026, 1, 1).millisecondsSinceEpoch, + 'state': 'decoding', + 'receivedChunks': 1, + 'totalChunks': 1, + }), + ); + await blobs.writeBitstream('midDecode', _payload(150)); + await blobs.writeSidecar( + 'lostPng', + jsonEncode({ + 'streamId': 'lostPng', + 'senderPrefix': 3, + 'imgId': 3, + 'channelIndex': 0, + 'firstSeenMs': DateTime.utc(2026, 1, 1).millisecondsSinceEpoch, + 'state': 'decoded', + 'receivedChunks': 1, + 'totalChunks': 1, + }), + ); + expect(receivingId.length, 16); // sanity: not a valid sentinel id + + final store = ReceivedImageStore( + blobs: blobs, + decoder: _FakeDecoder(availability: ImageCodecAvailability.disabled), + clock: () => DateTime.utc(2026, 1, 1, 1), + ); + await store.load(); + expect( + store.entryFor('partial00000001')!.state, + ReceivedImageState.failedIncomplete, + ); + expect( + store.entryFor('midDecode')!.state, + ReceivedImageState.reassembled, + ); + expect(store.entryFor('lostPng')!.state, ReceivedImageState.evicted); + store.dispose(); + }); + }); + + group('outgoing', () { + test('registerOutgoing is decoded, not synthesized', () async { + final h = _build(); + final entry = await h.store.registerOutgoing( + channelIndex: 1, + senderPrefix: kSelf, + imgId: 3, + previewPng: Uint8List.fromList(List.filled(64, 1)), + rate: AeicRatePoint.ft32, + chunkCount: 2, + ); + expect(entry.state, ReceivedImageState.decoded); + expect(entry.isOutgoing, isTrue); + expect(entry.synthesized, isFalse); + expect(await h.store.ensurePng(entry.streamId), isNotNull); + expect(h.decoder.calls, 0); + }); + }); + + group('processAutomatically (tap to process)', () { + test('an arrival is parked, not decoded, and a tap still works', () async { + final h = _build(processAutomatically: false); + final entry = await _completeOne(h); + await h.store.settle(); + + expect(entry.state, ReceivedImageState.reassembled); + expect(entry.needsManualDecode, isTrue); + expect(h.store.decodeQueue, isEmpty); + expect( + h.decoder.calls, + 0, + reason: 'a radio packet must never start a 2.16 GiB decode by itself', + ); + // Everything the placeholder card needs is already on the entry. + expect(entry.senderPrefix, kSender); + expect(entry.bitstreamByteCount, greaterThan(0)); + expect(entry.receivedChunks, 1); + expect(entry.totalChunks, 1); + expect(h.blobs.hasBitstream(entry.streamId), isTrue); + + await h.store.requestDecode(entry.streamId); + await h.store.settle(); + final after = h.store.entryFor(entry.streamId)!; + expect(after.state, ReceivedImageState.decoded); + expect(after.needsManualDecode, isFalse); + expect(h.decoder.calls, 1); + }); + + test( + 'a finished model download does not decode the whole backlog', + () async { + final decoder = _FakeDecoder( + availability: ImageCodecAvailability.disabled, + ); + final h = _build(decoder: decoder, processAutomatically: false); + final ids = []; + for (var i = 0; i < 4; i++) { + ids.add((await _completeOne(h, imgId: 80 + i, seed: i)).streamId); + h.advance(const Duration(seconds: 2)); + } + // The model lands. + decoder.availability = ImageCodecAvailability.ready; + h.store.notifyDecoderChanged(); + await h.store.settle(); + expect(decoder.calls, 0); + expect(h.store.decodeQueue, isEmpty); + for (final id in ids) { + expect(h.store.entryFor(id)!.state, ReceivedImageState.reassembled); + expect(h.store.entryFor(id)!.needsManualDecode, isTrue); + } + }, + ); + + test('turning the setting on affects future arrivals only', () async { + final h = _build(processAutomatically: false); + final parked = await _completeOne(h, imgId: 90); + h.advance(const Duration(seconds: 2)); + + h.store.processAutomatically = true; + await h.store.settle(); + expect(h.decoder.calls, 0, reason: 'no retro-decode of the backlog'); + expect( + h.store.entryFor(parked.streamId)!.state, + ReceivedImageState.reassembled, + ); + + final fresh = await _completeOne(h, imgId: 91, seed: 5); + await h.store.settle(); + expect( + h.store.entryFor(fresh.streamId)!.state, + ReceivedImageState.decoded, + ); + expect( + h.store.entryFor(parked.streamId)!.state, + ReceivedImageState.reassembled, + ); + }); + + test('a reassembled entry restored from disk is always tappable', () async { + final blobs = InMemoryReceivedImageBlobStore(); + // Written by a session that had auto-processing ON. + final h = _build(blobs: blobs); + h.store.setForeground(false); + final entry = await _completeOne(h); + expect(entry.needsManualDecode, isFalse); + + final reborn = ReceivedImageStore( + blobs: blobs, + decoder: _FakeDecoder(), + processAutomatically: false, + clock: h.clock, + ); + await reborn.load(); + final loaded = reborn.entryFor(entry.streamId)!; + expect(loaded.state, ReceivedImageState.reassembled); + expect(loaded.needsManualDecode, isTrue); + expect(reborn.decodeQueue, isEmpty); + reborn.dispose(); + }); + + test('decoderAvailability is exposed for the tap target', () async { + final h = _build(); + expect(h.store.decoderAvailability, ImageCodecAvailability.ready); + h.decoder.availability = ImageCodecAvailability.disabled; + expect(h.store.decoderAvailability, ImageCodecAvailability.disabled); + final noDecoder = ReceivedImageStore(decoder: null); + expect(noDecoder.decoderAvailability, ImageCodecAvailability.unavailable); + noDecoder.dispose(); + }); + }); + + group('decode concurrency', () { + test('ten taps run ten decodes strictly one at a time', () async { + final decoder = _FakeDecoder()..delay = const Duration(milliseconds: 5); + final h = _build(decoder: decoder, processAutomatically: false); + final ids = []; + for (var i = 0; i < 10; i++) { + ids.add((await _completeOne(h, imgId: 100 + i, seed: i)).streamId); + h.advance(const Duration(seconds: 2)); + } + // Fire every tap without awaiting: this is a user hammering the list. + final taps = >[ + for (final id in ids) h.store.requestDecode(id), + ]; + await Future.wait(taps); + await h.store.settle(); + + expect(decoder.calls, 10); + expect( + decoder.maxConcurrent, + 1, + reason: 'two concurrent decodes is ~4.3 GiB and an OOM kill', + ); + for (final id in ids) { + expect(h.store.entryFor(id)!.state, ReceivedImageState.decoded); + } + }); + + test('an arrival during a decode does not start a second one', () async { + final decoder = _FakeDecoder()..delay = const Duration(milliseconds: 5); + final h = _build(decoder: decoder); + await _completeOne(h, imgId: 120); + h.advance(const Duration(seconds: 2)); + // Do NOT settle: the first decode is still in flight. + await _completeOne(h, imgId: 121, seed: 1); + await h.store.settle(); + expect(decoder.calls, 2); + expect(decoder.maxConcurrent, 1); + }); + }); + + group('deletion hooks', () { + test( + 'deleteImagesForChannel reclaims every image of one conversation', + () async { + final h = _build(); + final a = await _completeOne(h, imgId: 130); + h.advance(const Duration(seconds: 2)); + final b = await _completeOne(h, imgId: 131, seed: 1); + await h.store.settle(); + // A third image on another channel must survive. + final other = await h.store.registerOutgoing( + channelIndex: 9, + senderPrefix: kSelf, + imgId: 5, + previewPng: Uint8List.fromList(List.filled(32, 2)), + rate: AeicRatePoint.ft32, + chunkCount: 1, + ); + + final removed = await h.store.deleteImagesForChannel(3); + expect(removed, containsAll([a.streamId, b.streamId])); + expect(h.store.entryFor(a.streamId), isNull); + expect(h.store.entryFor(b.streamId), isNull); + expect(h.blobs.hasPng(a.streamId), isFalse); + expect(h.blobs.hasBitstream(a.streamId), isFalse); + expect(h.blobs.hasSidecar(a.streamId), isFalse); + expect(h.store.entryFor(other.streamId), isNotNull); + expect(h.store.totalBytes, other.storedBytes); + }, + ); + + test('deleteImageForSentinel takes the message text', () async { + final h = _build(); + final entry = await _completeOne(h); + await h.store.settle(); + await h.store.deleteImageForSentinel('not an image'); + expect(h.store.entryFor(entry.streamId), isNotNull); + await h.store.deleteImageForSentinel( + ReceivedImageRef.encode(entry.streamId), + ); + expect(h.store.entryFor(entry.streamId), isNull); + expect(h.blobs.hasPng(entry.streamId), isFalse); + }); + }); + + group('FileReceivedImageBlobStore', () { + late Directory tempDir; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('aeic_blobs_test'); + }); + + tearDown(() async { + if (tempDir.existsSync()) { + await tempDir.delete(recursive: true); + } + }); + + FileReceivedImageBlobStore newStore() => + FileReceivedImageBlobStore(baseDirectory: () async => tempDir); + + test('concurrent sidecar writes for one id land the last one', () async { + final blobs = newStore(); + await Future.wait([ + for (var i = 0; i < 20; i++) + blobs.writeSidecar('1a2b0700693f21', '{"n":$i}'), + ]); + final sidecars = await blobs.readSidecars(); + expect(sidecars['1a2b0700693f21'], '{"n":19}'); + }); + + test('round-trips bytes and sidecars through real files', () async { + final blobs = newStore(); + await blobs.writeBitstream('1a2b0700693f21', _payload(155)); + await blobs.writePng('1a2b0700693f21', _payload(4096, 3)); + await blobs.writeSidecar('1a2b0700693f21', '{"streamId":"x"}'); + + expect(await blobs.readBitstream('1a2b0700693f21'), _payload(155)); + expect(await blobs.readPng('1a2b0700693f21'), _payload(4096, 3)); + expect(await blobs.bitstreamSize('1a2b0700693f21'), 155); + expect(await blobs.pngSize('1a2b0700693f21'), 4096); + expect(await blobs.readSidecars(), { + '1a2b0700693f21': '{"streamId":"x"}', + }); + expect(blobs.pngPath('1a2b0700693f21'), endsWith('1a2b0700693f21.png')); + expect(File(blobs.pngPath('1a2b0700693f21')!).existsSync(), isTrue); + + // A fresh instance over the same directory sees the same bytes: this is + // the whole point of the class. + final second = newStore(); + expect(await second.readBitstream('1a2b0700693f21'), _payload(155)); + expect((await second.readSidecars()).keys, ['1a2b0700693f21']); + + await blobs.deletePng('1a2b0700693f21'); + await blobs.deleteBitstream('1a2b0700693f21'); + await blobs.deleteSidecar('1a2b0700693f21'); + expect(await blobs.readPng('1a2b0700693f21'), isNull); + expect(await blobs.pngSize('1a2b0700693f21'), isNull); + expect(await blobs.readSidecars(), isEmpty); + // Deletes are idempotent. + await blobs.deletePng('1a2b0700693f21'); + }); + + test('missing files read as null and unsafe ids are refused', () async { + final blobs = newStore(); + expect(await blobs.readPng('deadbeefdeadbe'), isNull); + expect(await blobs.bitstreamSize('deadbeefdeadbe'), isNull); + await blobs.writePng('../../escape', _payload(8)); + expect(blobs.pngPath('../../escape'), isNull); + await blobs.ensureReady(); + expect( + Directory(tempDir.path).listSync(recursive: true).length, + 1, + reason: 'only the received_images directory itself', + ); + }); + + test('readSidecars reaps orphaned bytes and stale tmp files', () async { + final blobs = newStore(); + final dir = await blobs.ensureReady(); + // A crash between "write bitstream" and "write sidecar". + await blobs.writeBitstream('orphan00000001', _payload(150)); + await blobs.writePng('orphan00000001', _payload(64)); + // A crash mid sidecar write. + await File('$dir/halfwrit0000001.json.tmp').writeAsString('{"a":'); + await blobs.writeSidecar('keeper000000001', '{"streamId":"keeper"}'); + await blobs.writeBitstream('keeper000000001', _payload(150)); + + final sidecars = await blobs.readSidecars(); + expect(sidecars.keys, ['keeper000000001']); + expect(await blobs.readBitstream('orphan00000001'), isNull); + expect(await blobs.readPng('orphan00000001'), isNull); + expect(File('$dir/halfwrit0000001.json.tmp').existsSync(), isFalse); + expect(await blobs.readBitstream('keeper000000001'), isNotNull); + }); + + test('a truncated sidecar is skipped, not surfaced as an entry', () async { + final blobs = newStore(); + final dir = await blobs.ensureReady(); + await File('$dir/broken000000001.json').writeAsString('{"streamId":'); + expect(await blobs.readSidecars(), isEmpty); + }); + + test('a received image survives a restart end to end', () async { + var now = DateTime.utc(2026, 1, 1); + final reassembler = ImageReassembler(selfPrefix: kSelf, clock: () => now); + final store = ReceivedImageStore( + blobs: newStore(), + decoder: _FakeDecoder(), + clock: () => now, + ); + final set = buildImageChunks( + payload: _payload(140), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 12, + ); + final entry = await store.handleOutcome( + reassembler.addChunk(set.blobs[0], channelIndex: 3, now: now), + channelIndex: 3, + at: now, + ); + await store.settle(); + expect( + store.entryFor(entry!.streamId)!.state, + ReceivedImageState.decoded, + ); + store.dispose(); + + final reborn = ReceivedImageStore( + blobs: newStore(), + decoder: _FakeDecoder(), + clock: () => now, + ); + await reborn.load(); + final loaded = reborn.entryFor(entry.streamId); + expect( + loaded, + isNotNull, + reason: 'the whole point: images outlive the process', + ); + expect(loaded!.state, ReceivedImageState.decoded); + expect(loaded.pngStored, isTrue); + expect(loaded.pngBytes, isNull, reason: 'pixels are read lazily'); + expect(loaded.bitstreamByteCount, greaterThan(0)); + expect(await reborn.ensurePng(entry.streamId), isNotNull); + expect(reborn.pngPath(entry.streamId), isNotNull); + reborn.dispose(); + }); + + test('the age budget deletes the real files', () async { + var now = DateTime.utc(2026, 1, 1); + final blobs = newStore(); + final reassembler = ImageReassembler(selfPrefix: kSelf, clock: () => now); + final store = ReceivedImageStore( + blobs: blobs, + decoder: _FakeDecoder(), + maxAge: const Duration(minutes: 10), + clock: () => now, + ); + final set = buildImageChunks( + payload: _payload(140), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 13, + ); + final entry = await store.handleOutcome( + reassembler.addChunk(set.blobs[0], channelIndex: 3, now: now), + channelIndex: 3, + at: now, + ); + await store.settle(); + final png = blobs.pngPath(entry!.streamId)!; + expect(File(png).existsSync(), isTrue); + now = now.add(const Duration(minutes: 11)); + await store.evictToBudget(); + expect(File(png).existsSync(), isFalse); + expect(await blobs.readBitstream(entry.streamId), isNull); + store.dispose(); + }); + }); + + test( + 'listeners fire for the message list and for the single bubble', + () async { + final h = _build(); + var storeNotifications = 0; + h.store.addListener(() => storeNotifications++); + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: 77, + ); + final first = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3), + channelIndex: 3, + ); + final listenable = h.store.listenableFor(first!.streamId); + var bubbleNotifications = 0; + listenable.addListener(() => bubbleNotifications++); + await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[1], channelIndex: 3), + channelIndex: 3, + ); + await h.store.settle(); + expect(storeNotifications, greaterThan(1)); + expect(bubbleNotifications, greaterThan(1)); + expect(listenable.value!.state, ReceivedImageState.decoded); + }, + ); + + group('review fixes 2026-09-24', () { + Future startTwoChunk(_Rig h, int imgId) async { + final set = buildImageChunks( + payload: _payload(kImageChunkFirstCapacity + 20, imgId), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: imgId, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()), + channelIndex: 3, + at: h.clock(), + ); + return entry!; + } + + Future failIt(_Rig h, ReceivedImageEntry entry) async { + await h.store.handleFailure( + ImageReassemblyFailure( + key: entry.key, + total: 2, + receivedDataChunks: 1, + hadParity: false, + firstSeen: entry.firstSeen, + expiredAt: h.clock(), + ), + ); + } + + test('a reused img_id does not overwrite a decoded image', () async { + final h = _build(); + final first = await _completeOne(h, imgId: 11, seed: 1); + await h.store.settle(); + expect( + h.store.entryFor(first.streamId)!.state, + ReceivedImageState.decoded, + ); + + h.advance(const Duration(minutes: 1)); + final second = await startTwoChunk(h, 11); + expect(second.streamId, isNot(first.streamId)); + expect(second.state, ReceivedImageState.receiving); + expect( + h.store.entryFor(first.streamId)!.state, + ReceivedImageState.decoded, + ); + + h.advance(const Duration(minutes: 10)); + h.reassembler.clear(); + final third = await _completeOne(h, imgId: 11, seed: 9); + expect(third.streamId, isNot(first.streamId)); + expect( + h.store.entryFor(first.streamId)!.state, + ReceivedImageState.decoded, + ); + }); + + test('failed entries are capped by count, oldest first', () async { + final h = _build(maxImages: 2); + final ids = []; + for (var i = 0; i < 4; i++) { + final entry = await startTwoChunk(h, 70 + i); + await failIt(h, entry); + ids.add(entry.streamId); + h.advance(const Duration(seconds: 5)); + } + expect(h.store.entries.length, 2); + expect(h.store.entryFor(ids[0]), isNull); + expect(h.blobs.hasSidecar(ids[0]), isFalse); + expect( + h.store.entryFor(ids[3])!.state, + ReceivedImageState.failedIncomplete, + ); + }); + + test('failed entries past maxAge are deleted outright', () async { + final h = _build(maxAge: const Duration(days: 1)); + final entry = await startTwoChunk(h, 80); + await failIt(h, entry); + h.advance(const Duration(days: 2)); + await h.store.evictToBudget(); + expect(h.store.entryFor(entry.streamId), isNull); + expect(h.blobs.hasSidecar(entry.streamId), isFalse); + }); + + test('foreground memory pressure mid-decode parks, not corrupt', () async { + final decoder = _FakeDecoder(mode: 'fail') + ..delay = const Duration(milliseconds: 50); + final h = _build(decoder: decoder); + final entry = await _completeOne(h); + await Future.delayed(const Duration(milliseconds: 10)); + expect( + h.store.entryFor(entry.streamId)!.state, + ReceivedImageState.decoding, + ); + await h.store.handleMemoryPressure(); + await h.store.settle(); + final after = h.store.entryFor(entry.streamId)!; + expect(after.state, ReceivedImageState.reassembled); + expect(after.needsManualDecode, isTrue); + }); + }); +} + +/// Delivers a whole single-chunk image and returns its entry (state +/// `reassembled`; the caller decides whether to `settle()`). +Future _completeOne( + _Rig h, { + int imgId = 11, + int seed = 0, +}) async { + final set = buildImageChunks( + payload: _payload(140, seed), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: kSender, + imgId: imgId, + ); + final entry = await h.store.handleOutcome( + h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()), + channelIndex: 3, + at: h.clock(), + ); + return entry!; +} diff --git a/test/services/repeater_command_service_test.dart b/test/services/repeater_command_service_test.dart new file mode 100644 index 00000000..ee7ee06a --- /dev/null +++ b/test/services/repeater_command_service_test.dart @@ -0,0 +1,121 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/path_selection.dart'; +import 'package:meshcore_open/services/repeater_command_service.dart'; + +class _FakeConnector extends MeshCoreConnector { + @override + Future preparePathForContactSend(Contact contact) async => + const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); + + @override + Future sendFrame( + Uint8List data, { + String? channelSendQueueId, + bool expectsGenericAck = false, + bool waitForGenericAck = false, + }) async {} +} + +Contact _repeater(int seed) => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => seed + i)), + name: 'R$seed', + type: 2, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.now(), +); + +void main() { + group('normalizeRepeaterClockSyncCommand', () { + test('translates "clock sync" to explicit time command', () { + final result = normalizeRepeaterClockSyncCommand( + 'clock sync', + nowSeconds: 1787900000, + ); + expect(result, 'time 1787900000'); + }); + + test('is case-insensitive and tolerates surrounding whitespace', () { + expect( + normalizeRepeaterClockSyncCommand(' Clock Sync ', nowSeconds: 1), + 'time 1', + ); + }); + + test('passes other commands through unchanged', () { + expect( + normalizeRepeaterClockSyncCommand('clock', nowSeconds: 1), + 'clock', + ); + expect( + normalizeRepeaterClockSyncCommand('get radio', nowSeconds: 1), + 'get radio', + ); + expect( + normalizeRepeaterClockSyncCommand('time 123', nowSeconds: 1), + 'time 123', + ); + }); + + test('uses current time when nowSeconds is omitted', () { + final before = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final result = normalizeRepeaterClockSyncCommand('clock sync'); + final after = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + expect(result, startsWith('time ')); + final epoch = int.parse(result.substring('time '.length)); + expect(epoch, inInclusiveRange(before, after)); + }); + }); + + group('RepeaterCommandService.handleResponse', () { + late RepeaterCommandService service; + + setUp(() => service = RepeaterCommandService(_FakeConnector())); + tearDown(() => service.dispose()); + + test('unknown prefix does not complete the pending command', () async { + final repeater = _repeater(1); + String? result; + unawaited( + service + .sendCommand(repeater, 'ver', retries: 1) + .then((r) => result = r, onError: (_) {}), + ); + await pumpEventQueue(); + + service.handleResponse(repeater, 'FE|late reply'); + await pumpEventQueue(); + expect(result, isNull); + + service.handleResponse(repeater, '00|v1.0'); + await pumpEventQueue(); + expect(result, 'v1.0'); + }); + + test('prefix owned by another repeater is ignored', () async { + final a = _repeater(1); + final b = _repeater(100); + String? result; + unawaited( + service + .sendCommand(a, 'ver', retries: 1) + .then((r) => result = r, onError: (_) {}), + ); + await pumpEventQueue(); + + service.handleResponse(b, '00|wrong'); + await pumpEventQueue(); + expect(result, isNull); + + service.handleResponse(a, 'unprefixed'); + await pumpEventQueue(); + expect(result, 'unprefixed'); + }); + }); +} diff --git a/test/storage/store_tolerant_parsing_test.dart b/test/storage/store_tolerant_parsing_test.dart new file mode 100644 index 00000000..d74d00d6 --- /dev/null +++ b/test/storage/store_tolerant_parsing_test.dart @@ -0,0 +1,93 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/community.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/community_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _device = 'abcdef012345'; + +Future _init(Map values) async { + SharedPreferences.setMockInitialValues(values); + PrefsManager.reset(); + await PrefsManager.initialize(); +} + +void main() { + test( + 'message store skips a malformed record instead of dropping all', + () async { + final good = { + 'senderKey': base64Encode([1, 2, 3]), + 'text': 'hello', + 'timestamp': 1000, + 'status': 1, + }; + await _init({ + 'messages_${_device.substring(0, 10)}c1': jsonEncode([ + good, + {'text': 'no timestamp'}, + ]), + }); + final store = MessageStore()..setPublicKeyHex = _device; + final messages = await store.loadMessages('c1'); + expect(messages.map((m) => m.text), ['hello']); + expect(messages.single.isOutgoing, isFalse); + }, + ); + + test('channel message store skips a malformed record', () async { + await _init({ + 'channel_messages_${_device.substring(0, 10)}0': jsonEncode([ + {'text': 'hi', 'timestamp': 1000, 'status': 1}, + 'garbage', + ]), + }); + final store = ChannelMessageStore()..setPublicKeyHex = _device; + final messages = await store.loadChannelMessages(0); + expect(messages.map((m) => m.text), ['hi']); + }); + + test('community store keeps valid communities next to a bad one', () async { + final community = Community.create(id: 'c1', name: 'Ops'); + await _init({ + 'communities_v1${_device.substring(0, 10)}': jsonEncode([ + community.toJson(), + {'id': 'broken'}, + ]), + }); + final store = CommunityStore()..setPublicKeyHex = _device; + final communities = await store.loadCommunities(); + expect(communities.map((c) => c.id), ['c1']); + }); + + test('delivery observations skip malformed entries', () async { + await _init({ + 'delivery_observations': jsonEncode([ + { + 'contact_key': 'k', + 'path_length': 1, + 'message_bytes': 10, + 'delivery_ms': 500, + 'timestamp': DateTime(2026).toIso8601String(), + }, + {'contact_key': 'bad'}, + ]), + }); + final observations = await StorageService().loadDeliveryObservations(); + expect(observations, hasLength(1)); + expect(observations.single.isFlood, isFalse); + }); + + test('community hashtag normalization trims before stripping #', () { + final community = Community.create(id: 'c1', name: 'Ops'); + expect( + community.deriveCommunityHashtagPsk(' #ops'), + community.deriveCommunityHashtagPsk('#ops'), + ); + }); +} diff --git a/test/utils/contact_qr_frame_test.dart b/test/utils/contact_qr_frame_test.dart new file mode 100644 index 00000000..13af81ee --- /dev/null +++ b/test/utils/contact_qr_frame_test.dart @@ -0,0 +1,207 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/utils/contact_qr.dart'; +import 'package:meshcore_open/utils/contact_qr_frame.dart'; + +void main() { + final publicKey = Uint8List.fromList(List.filled(32, 0xAB)); + + Contact contactWith({required String name, required int flags}) { + return Contact( + publicKey: publicKey, + name: name, + type: advTypeChat, + flags: flags, + pathLength: 2, + path: Uint8List.fromList([1, 2]), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + } + + group('buildContactQrFrame advert packet', () { + test('replays the advert with CMD_IMPORT_CONTACT', () { + final advert = Uint8List.fromList(List.filled(98, 7)); + final frame = buildContactQrFrame( + ScannedContact(advertPacket: advert), + existing: contactWith(name: 'Old', flags: 0x03), + ); + + expect(frame[0], cmdImportContact); + expect(frame.sublist(1), advert); + }); + }); + + group('buildContactQrFrame contact card', () { + test('writes an add/update frame with the unknown-path sentinel', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice', type: 2), + ); + + expect(frame[0], cmdAddUpdateContact); + expect(frame.sublist(1, 33), publicKey); + expect(frame[33], 2); + expect(frame[34], 0); + expect(frame[35], 0xFF, reason: 'path is unknown, not zero-hop'); + + final nameStart = 36 + maxPathSize; + final name = String.fromCharCodes( + frame + .sublist(nameStart, nameStart + maxNameSize) + .takeWhile((b) => b != 0), + ); + expect(name, 'Alice'); + }); + + test('defaults a new contact without a type to Companion', () { + final frame = buildContactQrFrame(ScannedContact(publicKey: publicKey)); + + expect(frame[33], advTypeChat); + }); + + test('keeps the type of an existing contact when the card has none', () { + final existing = Contact( + publicKey: publicKey, + name: 'Hilltop', + type: advTypeRepeater, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey), + existing: existing, + ); + + expect(frame[33], advTypeRepeater); + }); + + test('writes a zero advert timestamp for a new contact', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + ); + + final tsStart = 36 + maxPathSize + maxNameSize; + expect(frame.sublist(tsStart, tsStart + 4), [0, 0, 0, 0]); + }); + + test('keeps the advert timestamp of an existing contact', () { + final existing = Contact( + publicKey: publicKey, + name: 'Alice', + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000 * 1000), + ); + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: existing, + ); + + final tsStart = 36 + maxPathSize + maxNameSize; + final ts = ByteData.sublistView( + frame, + tsStart, + tsStart + 4, + ).getUint32(0, Endian.little); + expect(ts, 1700000000); + }); + + test('preserves the flags of an existing contact', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: contactWith(name: 'Alice', flags: 0x05), + ); + + expect(frame[34], 0x05); + }); + + test('falls back to the existing name when the card has none', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey), + existing: contactWith(name: 'Existing', flags: 0), + ); + + final nameStart = 36 + maxPathSize; + final name = String.fromCharCodes( + frame + .sublist(nameStart, nameStart + maxNameSize) + .takeWhile((b) => b != 0), + ); + expect(name, 'Existing'); + }); + + test('drops whole characters when the name exceeds 31 bytes', () { + // 16 three-byte characters = 48 encoded bytes; only 10 fit in 31. + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: '☂' * 16), + ); + + final nameStart = 36 + maxPathSize; + final bytes = frame + .sublist(nameStart, nameStart + maxNameSize) + .takeWhile((b) => b != 0) + .toList(); + expect(bytes.length, 30); + expect(utf8.decode(bytes), '☂' * 10); + }); + }); + + group('buildContactQrFrame route preservation', () { + Contact contactWithPath(int pathLength, List path) { + return Contact( + publicKey: publicKey, + name: 'Alice', + type: advTypeChat, + pathLength: pathLength, + path: Uint8List.fromList(path), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + } + + test('keeps the route of a contact the device already knows', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: contactWithPath(2, [0x11, 0x22]), + ); + + expect(frame[35], 0x02, reason: 'two hops, 1-byte hash mode'); + expect(frame.sublist(36, 38), [0x11, 0x22]); + }); + + test('encodes the hash mode in bits 6-7 for wider path hashes', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: contactWithPath(2, [0x11, 0x22, 0x33, 0x44]), + pathHashByteWidth: 2, + ); + + expect(frame[35], 0x42); + expect(frame.sublist(36, 40), [0x11, 0x22, 0x33, 0x44]); + }); + + test('uses the unknown sentinel for a flood-only contact', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: contactWithPath(-1, const []), + ); + + expect(frame[35], 0xFF); + expect(frame.sublist(36, 36 + maxPathSize).every((b) => b == 0), isTrue); + }); + + test('uses the unknown sentinel when the path does not fit the mode', () { + final frame = buildContactQrFrame( + ScannedContact(publicKey: publicKey, name: 'Alice'), + existing: contactWithPath(2, [0x11, 0x22]), + pathHashByteWidth: 2, + ); + + expect(frame[35], 0xFF); + }); + }); +} diff --git a/test/utils/contact_qr_test.dart b/test/utils/contact_qr_test.dart new file mode 100644 index 00000000..c900207c --- /dev/null +++ b/test/utils/contact_qr_test.dart @@ -0,0 +1,156 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/utils/contact_qr.dart'; + +void main() { + group('parseContactQr official contact card', () { + test('parses name with + and percent-encoding, key, explicit type', () { + final key = List.generate( + 32, + (i) => i.toRadixString(16).padLeft(2, '0'), + ).join(); + final result = parseContactQr( + 'meshcore://contact/add?name=Jane+D%C3%B6e&public_key=$key&type=2', + ); + + expect(result, isNotNull); + expect(result!.isAdvertPacket, isFalse); + expect(result.name, 'Jane Döe'); + expect(result.publicKey!.length, 32); + expect(result.publicKey![0], 0x00); + expect(result.publicKey![31], 0x1f); + expect(result.type, 2); + }); + + test('missing type is left unset', () { + final key = 'ab' * 32; + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=$key', + ); + + expect(result, isNotNull); + expect(result!.type, isNull); + }); + + test('garbage type is left unset', () { + final key = 'ab' * 32; + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=$key&type=nope', + ); + + expect(result, isNotNull); + expect(result!.type, isNull); + }); + + test('uppercase hex public key is accepted', () { + final key = 'AB' * 32; + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=$key', + ); + + expect(result, isNotNull); + expect(result!.publicKey!.length, 32); + expect(result.publicKey![0], 0xAB); + }); + + test('63-char public key is rejected', () { + final key = '${'ab' * 31}a'; + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=$key', + ); + + expect(result, isNull); + }); + + test('non-hex public key is rejected', () { + final key = ('zz' * 32); + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=$key', + ); + + expect(result, isNull); + }); + + test('signed public key digits are rejected', () { + final result = parseContactQr( + 'meshcore://contact/add?name=Bob&public_key=${'+1' * 32}', + ); + + expect(result, isNull); + }); + + test('missing name defaults to empty string', () { + final key = 'ab' * 32; + final result = parseContactQr('meshcore://contact/add?public_key=$key'); + + expect(result, isNotNull); + expect(result!.name, ''); + }); + }); + + group('parseContactQr legacy advert packet', () { + test('legacy hex form yields advert packet bytes', () { + final hex = '0a' * 98; + final result = parseContactQr('meshcore://$hex'); + + expect(result, isNotNull); + expect(result!.isAdvertPacket, isTrue); + expect(result.advertPacket!.length, 98); + expect(result.advertPacket![0], 0x0a); + }); + + test('odd-length hex is rejected', () { + final result = parseContactQr('meshcore://abc'); + + expect(result, isNull); + }); + + test('non-hex payload is rejected', () { + final result = parseContactQr('meshcore://zz${'00' * 97}'); + + expect(result, isNull); + }); + + test('payload shorter than the 98 byte advert minimum is rejected', () { + final result = parseContactQr('meshcore://${'ab' * 97}'); + + expect(result, isNull); + }); + + test('payload longer than the 171 byte frame limit is rejected', () { + final result = parseContactQr('meshcore://${'ab' * 172}'); + + expect(result, isNull); + }); + + test('payload at the 171 byte frame limit is accepted', () { + final result = parseContactQr('meshcore://${'ab' * 171}'); + + expect(result, isNotNull); + expect(result!.advertPacket!.length, 171); + }); + }); + + group('parseContactQr rejects unsupported input', () { + test('channel add link is not a contact', () { + final result = parseContactQr( + 'meshcore://channel/add?name=Public&secret=abcd', + ); + + expect(result, isNull); + }); + + test('non-meshcore scheme is rejected', () { + final result = parseContactQr('https://example.com/contact/add'); + + expect(result, isNull); + }); + + test('empty string is rejected', () { + expect(parseContactQr(''), isNull); + }); + + test('whitespace-only string is rejected', () { + expect(parseContactQr(' \n\t '), isNull); + }); + }); +} diff --git a/test/widgets/image_send_preview_sheet_test.dart b/test/widgets/image_send_preview_sheet_test.dart new file mode 100644 index 00000000..749690b4 --- /dev/null +++ b/test/widgets/image_send_preview_sheet_test.dart @@ -0,0 +1,339 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/utils/lora_airtime.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; +import 'package:meshcore_open/widgets/image_send_preview_sheet.dart'; + +/// A real 1x1 PNG. Image.memory reports decode failures through FlutterError, +/// which fails the test even though the sheet has an errorBuilder, so the test +/// must hand it bytes that actually decode. +final Uint8List _onePixelPng = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/' + 'q842iQAAAABJRU5ErkJggg==', +); + +/// Radio settings a connected device would report: SF10 / BW 250k / CR 4/5. +/// The coding rate is given in the raw 1..4 firmware domain on purpose, to keep +/// the sheet's normalisation on the tested path. +const ImageSendRadio _knownRadio = ImageSendRadio( + spreadingFactor: 10, + bandwidthHz: 250000, + rawCodingRate: 1, +); + +/// Packets the sheet must report for the fake codec's ft32 mean payload: +/// the chunker's own data-chunk count plus the XOR parity packet, which is on by +/// default. Derived, because the chunk capacities have moved before. +final int _expectedPackets = + imageChunkCount(ImageCodecRateStats.standard.meanBytes) + 1; + +/// Nothing known yet — the state right after connecting, before SELF_INFO. +const ImageSendRadio _unknownRadio = ImageSendRadio(); + +Future _openSheet( + WidgetTester tester, { + required ImageSendRadio radio, + ImageSendCodec codec = const FakeImageSendCodec(latency: Duration.zero), +}) async { + ImageSendPreviewResult? result; + var closed = false; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () async { + result = await showImageSendPreviewSheet( + context: context, + imageBytes: _onePixelPng, + originalFileBytes: 2 * 1024 * 1024, + codec: codec, + radio: radio, + ); + closed = true; + }, + child: const Text('open'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(closed, isFalse, reason: 'sheet should still be open'); + return result; +} + +/// Every string rendered by the sheet, so assertions can look for a value +/// without knowing which widget carries it. +List _texts(WidgetTester tester) => tester + .widgetList(find.byType(Text)) + .map((t) => t.data) + .whereType() + .toList(); + +void main() { + testWidgets('renders with a fake codec and shows the image preview', ( + tester, + ) async { + await _openSheet(tester, radio: _knownRadio); + + expect(find.byType(ImageSendPreviewSheet), findsOneWidget); + expect(find.byType(Image), findsOneWidget); + // The send action is enabled once the encode has settled. + final send = tester.widget(find.byType(FilledButton)); + expect(send.onPressed, isNotNull); + }); + + testWidgets('shows the packet count for the encoded ft32 payload', ( + tester, + ) async { + await _openSheet(tester, radio: _knownRadio); + + // FakeImageSendCodec emits the measured ft32 mean (156 B) -> one data chunk, + // plus the XOR parity packet, which is on by default. + final expected = estimateSendFromRadioParams( + payloadBytes: ImageCodecRateStats.standard.meanBytes, + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 1, + ); + expect(expected.chunkCount, inInclusiveRange(2, 3)); + expect(_texts(tester), contains('${expected.chunkCount}')); + }); + + testWidgets('shows a concrete airtime when the radio settings are known', ( + tester, + ) async { + await _openSheet(tester, radio: _knownRadio); + + final texts = _texts(tester); + expect( + texts, + isNot(contains('—')), + reason: 'a connected radio must not render the unknown placeholder', + ); + // The headline time figure is formatted as " s" by the sheet. + expect( + texts.any((t) => RegExp(r'^\d+(\.\d)? s$').hasMatch(t)), + isTrue, + reason: 'expected a seconds figure among: $texts', + ); + }); + + testWidgets('headline time is the paced wall clock, not raw airtime', ( + tester, + ) async { + await _openSheet(tester, radio: _knownRadio); + + final expected = estimateSendFromRadioParams( + payloadBytes: ImageCodecRateStats.standard.meanBytes, + spreadingFactor: 10, + bandwidthHz: 250000, + codingRate: 1, + ); + // Two packets, so pacing must have widened the figure. + expect( + expected.pacedWallClock!.inMicroseconds, + greaterThan(expected.totalAirtime!.inMicroseconds), + ); + + String seconds(Duration d) { + final total = d.inMilliseconds / 1000.0; + return total < 10 ? total.toStringAsFixed(1) : total.round().toString(); + } + + final texts = _texts(tester); + expect(texts, contains('${seconds(expected.pacedWallClock!)} s')); + expect(texts, isNot(contains('${seconds(expected.totalAirtime!)} s'))); + }); + + testWidgets('renders "unknown" airtime when the radio params are absent', ( + tester, + ) async { + await _openSheet(tester, radio: _unknownRadio); + + final texts = _texts(tester); + // The em dash placeholder, never a fabricated duration. + expect(texts, contains('—')); + expect( + texts.any((t) => RegExp(r'^\d+(\.\d)? s$').hasMatch(t)), + isFalse, + reason: 'no duration may be invented; got: $texts', + ); + // The packet count is still meaningful and must survive. + expect(texts, contains('$_expectedPackets')); + }); + + testWidgets('offers no quality selector', (tester) async { + await _openSheet(tester, radio: _knownRadio); + + final texts = _texts(tester); + final l10n = await AppLocalizations.delegate.load(const Locale('en')); + expect(texts, isNot(contains(l10n.imageSend_quality))); + expect(texts, isNot(contains(l10n.imageSend_qualityStandard))); + expect(texts, isNot(contains(l10n.imageSend_qualityHigh))); + expect(find.byIcon(Icons.radio_button_checked), findsNothing); + expect(find.byIcon(Icons.radio_button_unchecked), findsNothing); + }); + + testWidgets('returns null when the user cancels', (tester) async { + ImageSendPreviewResult? result; + var closed = false; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () async { + result = await showImageSendPreviewSheet( + context: context, + imageBytes: _onePixelPng, + originalFileBytes: 1024, + codec: const FakeImageSendCodec(latency: Duration.zero), + radio: _knownRadio, + ); + closed = true; + }, + child: const Text('open'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(OutlinedButton)); + await tester.pumpAndSettle(); + + expect(closed, isTrue); + expect(result, isNull); + expect(find.byType(ImageSendPreviewSheet), findsNothing); + }); + + testWidgets('confirming returns the payload, packet count and both times', ( + tester, + ) async { + ImageSendPreviewResult? result; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () async { + result = await showImageSendPreviewSheet( + context: context, + imageBytes: _onePixelPng, + originalFileBytes: 1024, + codec: const FakeImageSendCodec(latency: Duration.zero), + radio: _knownRadio, + ); + }, + child: const Text('open'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await tester.tap(find.byType(FilledButton)); + await tester.pumpAndSettle(); + + expect(result, isNotNull); + expect(result!.payload.length, ImageCodecRateStats.standard.meanBytes); + // ft32 is the only rate point the sheet can produce. + expect(result!.rate, kImageSendRatePoint); + expect(result!.includeParity, isTrue); + expect(result!.packetCount, _expectedPackets); + expect(result!.airtime, isNotNull); + expect( + result!.wallClock!.inMicroseconds, + greaterThan(result!.airtime!.inMicroseconds), + ); + }); + + testWidgets('a codec that is still downloading cannot be sent from', ( + tester, + ) async { + await _openSheet( + tester, + radio: _knownRadio, + codec: const FakeImageSendCodec( + availability: ImageCodecAvailability.downloading, + latency: Duration.zero, + ), + ); + + final l10n = await AppLocalizations.delegate.load(const Locale('en')); + expect(_texts(tester), contains(l10n.imageSend_codecDownloading)); + final send = tester.widget(find.byType(FilledButton)); + expect(send.onPressed, isNull); + }); + + testWidgets('an unavailable codec explains itself with unavailableReason, ' + 'not the generic string', (tester) async { + const reason = + 'This build ships the image decoder only. Encoding and ' + 'decoding a bitstream also needs the entropy-side graph and the rANS ' + 'coder, which are not included yet.'; + await _openSheet( + tester, + radio: _knownRadio, + codec: const FakeImageSendCodec( + availability: ImageCodecAvailability.unavailable, + unavailableReason: reason, + latency: Duration.zero, + ), + ); + + final l10n = await AppLocalizations.delegate.load(const Locale('en')); + final texts = _texts(tester); + expect(texts, contains(reason)); + expect( + texts, + isNot(contains(l10n.imageSend_codecUnavailable)), + reason: 'the concrete reason must REPLACE the generic sentence', + ); + final send = tester.widget(find.byType(FilledButton)); + expect(send.onPressed, isNull); + }); + + testWidgets('an unavailable codec that gives no reason falls back to the ' + 'generic string', (tester) async { + await _openSheet( + tester, + radio: _knownRadio, + codec: const FakeImageSendCodec( + availability: ImageCodecAvailability.unavailable, + latency: Duration.zero, + ), + ); + + final l10n = await AppLocalizations.delegate.load(const Locale('en')); + expect(_texts(tester), contains(l10n.imageSend_codecUnavailable)); + }); +} diff --git a/test/widgets/received_image_message_test.dart b/test/widgets/received_image_message_test.dart new file mode 100644 index 00000000..ad436554 --- /dev/null +++ b/test/widgets/received_image_message_test.dart @@ -0,0 +1,508 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/image_codec_support.dart'; +import 'package:meshcore_open/services/image_chunk_transport.dart'; +import 'package:meshcore_open/widgets/image_send_codec_binding.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/widgets/received_image_message.dart'; + +const String _png1x1 = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=='; + +/// A decoder seam whose availability the test controls. +/// +/// [decodeBitstream] never returns a picture: every tap-routing test only cares +/// about which of the two branches the bubble took, and a fake that produced +/// pixels would drag PNG decoding into an assertion about routing. +class _FakeDecoder implements ReceivedImageDecoder { + @override + final ImageCodecAvailability availability; + + @override + bool isBusy = false; + + int decodeCalls = 0; + int cancelCalls = 0; + + _FakeDecoder(this.availability); + + @override + Future decodeBitstream({ + required Uint8List bitstream, + required AeicRatePoint ratePoint, + required int resolution, + }) async { + decodeCalls++; + return null; + } + + @override + void cancelCodecJob() => cancelCalls++; +} + +/// Builds a store holding one entry that is `reassembled + needsManualDecode`, +/// i.e. the "bitstream complete, waiting for the user" placeholder state. +Future _awaitingStore({ + ReceivedImageDecoder? decoder, + int bytes = 156, + int packets = 2, +}) async { + final blobs = InMemoryReceivedImageBlobStore(); + await blobs.writeBitstream('await1', Uint8List(bytes)); + await blobs.writeSidecar( + 'await1', + jsonEncode({ + 'streamId': 'await1', + 'senderPrefix': 0x1a2b, + 'imgId': 7, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'reassembled', + 'receivedChunks': packets, + 'totalChunks': packets, + 'needsManualDecode': true, + 'bitstreamStored': true, + 'bitstreamByteCount': bytes, + }), + ); + final store = ReceivedImageStore(blobs: blobs, decoder: decoder); + await store.load(); + return store; +} + +Future _pumpBubble( + WidgetTester tester, + ReceivedImageStore store, { + String streamId = 'await1', + VoidCallback? onOpenCodecSettings, +}) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReceivedImageMessage( + streamId: streamId, + isOutgoing: false, + fallbackTextColor: Colors.black, + store: store, + onOpenCodecSettings: onOpenCodecSettings, + ), + ), + ), + ); + await tester.pump(); +} + +void main() { + testWidgets('decoded incoming bubble carries the R6 badge and caption', ( + tester, + ) async { + final blobs = InMemoryReceivedImageBlobStore(); + final store = ReceivedImageStore(blobs: blobs); + final png = base64Decode(_png1x1); + final entry = await store.registerOutgoing( + channelIndex: 0, + senderPrefix: 1, + imgId: 1, + previewPng: Uint8List.fromList(png), + rate: AeicRatePoint.ft32, + chunkCount: 1, + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReceivedImageMessage( + streamId: entry.streamId, + isOutgoing: true, + fallbackTextColor: Colors.black, + store: store, + ), + ), + ), + ); + await tester.pump(); + // Outgoing: real crop, so NO label. + expect(find.text('AI-reconstructed'), findsNothing); + + // Now an incoming decoded entry. + final blobs2 = InMemoryReceivedImageBlobStore(); + await blobs2.writeSidecar( + 'incoming', + jsonEncode({ + 'streamId': 'incoming', + 'senderPrefix': 2, + 'imgId': 2, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'decoded', + 'receivedChunks': 1, + 'totalChunks': 1, + }), + ); + await blobs2.writePng('incoming', Uint8List.fromList(png)); + final store2 = ReceivedImageStore(blobs: blobs2); + await store2.load(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReceivedImageMessage( + streamId: 'incoming', + isOutgoing: false, + fallbackTextColor: Colors.black, + store: store2, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + expect(find.text('AI-reconstructed'), findsOneWidget); + expect(find.textContaining('Fine detail is generated'), findsOneWidget); + }); + + testWidgets('receiving state shows the packet count', (tester) async { + final store = ReceivedImageStore(decoder: null); + final reassembler = ImageReassembler(selfPrefix: 0xbeef); + final set = buildImageChunks( + payload: Uint8List(kImageChunkFirstCapacity + 1), + metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard), + senderPrefix: 0x1a2b, + imgId: 5, + ); + final entry = await store.handleOutcome( + reassembler.addChunk(set.blobs[0], channelIndex: 0), + channelIndex: 0, + ); + expect(entry!.state, ReceivedImageState.receiving); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReceivedImageMessage( + streamId: entry.streamId, + isOutgoing: false, + fallbackTextColor: Colors.black, + store: store, + ), + ), + ), + ); + expect(find.text('1 of 2 packets'), findsOneWidget); + expect(find.text('AI-reconstructed'), findsNothing); + }); + + testWidgets( + 'awaiting card shows the bitstream size, the packet count and the ' + 'tap-to-process affordance', + (tester) async { + final store = await _awaitingStore(bytes: 156, packets: 2); + final entry = store.entryFor('await1')!; + expect(entry.state, ReceivedImageState.reassembled); + expect(entry.needsManualDecode, isTrue); + + await _pumpBubble(tester, store); + + expect(find.text('156 bytes · 2 packets'), findsOneWidget); + expect(find.text('Tap to process'), findsOneWidget); + // A placeholder is never dressed up as a picture. + expect(find.text('AI-reconstructed'), findsNothing); + expect(find.byType(Image), findsNothing); + }, + ); + + testWidgets('awaiting card honours injected strings', (tester) async { + final store = await _awaitingStore(bytes: 209, packets: 3); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReceivedImageMessage( + streamId: 'await1', + isOutgoing: false, + fallbackTextColor: Colors.black, + store: store, + strings: ReceivedImageStrings( + incoming: (r, t) => 'in $r/$t', + queued: 'queued', + tapToDecode: 'tap decode', + awaiting: (b, p) => 'LOC $b B in $p pkts', + tapToProcess: 'LOC process', + decoding: 'decoding', + incomplete: (r, t) => 'incomplete $r/$t', + corrupt: 'corrupt', + decoderMissing: 'missing', + evicted: 'evicted', + retry: 'retry', + decodeAgain: 'again', + openSettings: 'settings', + ), + ), + ), + ), + ); + await tester.pump(); + + expect(find.text('LOC 209 B in 3 pkts'), findsOneWidget); + expect(find.text('LOC process'), findsOneWidget); + }); + + testWidgets('tap with a ready codec requests a decode and does NOT open ' + 'settings', (tester) async { + final decoder = _FakeDecoder(ImageCodecAvailability.ready); + final store = await _awaitingStore(decoder: decoder); + var settingsOpened = 0; + + await _pumpBubble( + tester, + store, + onOpenCodecSettings: () => settingsOpened++, + ); + + await tester.tap(find.text('Tap to process')); + await tester.pump(); + await tester.pump(); + + expect(settingsOpened, 0); + expect(decoder.decodeCalls, 1); + }); + + testWidgets('tap with no model installed opens the image-messages setting ' + 'and never asks the store to decode', (tester) async { + final decoder = _FakeDecoder(ImageCodecAvailability.disabled); + final store = await _awaitingStore(decoder: decoder); + var settingsOpened = 0; + + await _pumpBubble( + tester, + store, + onOpenCodecSettings: () => settingsOpened++, + ); + + await tester.tap(find.text('Tap to process')); + await tester.pump(); + await tester.pump(); + + expect(settingsOpened, 1); + expect(decoder.decodeCalls, 0); + // The entry is untouched: it stays tappable rather than falling into + // `decoderUnavailable` behind the user's back. + expect(store.entryFor('await1')!.state, ReceivedImageState.reassembled); + }); + + testWidgets('tap with no codec and no settings route still asks the store, ' + 'so the card is never inert', (tester) async { + final store = await _awaitingStore(decoder: null); + + await _pumpBubble(tester, store); + await tester.tap(find.text('Tap to process')); + await tester.pump(); + await tester.pump(); + + // No decoder at all -> the store parks it as decoderUnavailable, which is + // the state that renders the "Set up" body. + expect( + store.entryFor('await1')!.state, + ReceivedImageState.decoderUnavailable, + ); + }); + + testWidgets('a queued (auto-decode) card is still tappable', (tester) async { + final blobs = InMemoryReceivedImageBlobStore(); + await blobs.writeBitstream('queued1', Uint8List(120)); + await blobs.writeSidecar( + 'queued1', + jsonEncode({ + 'streamId': 'queued1', + 'senderPrefix': 3, + 'imgId': 3, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'reassembled', + 'receivedChunks': 1, + 'totalChunks': 1, + 'needsManualDecode': false, + 'bitstreamStored': true, + 'bitstreamByteCount': 120, + }), + ); + final decoder = _FakeDecoder(ImageCodecAvailability.ready); + final store = ReceivedImageStore(blobs: blobs, decoder: decoder); + await store.load(); + + await _pumpBubble(tester, store, streamId: 'queued1'); + expect(find.text('Waiting to decode'), findsOneWidget); + + // load() does not enqueue, so without a tap target this card would sit on + // "Waiting to decode" forever. + await tester.tap(find.text('Waiting to decode')); + await tester.pump(); + await tester.pump(); + expect(decoder.decodeCalls, 1); + }); + + testWidgets('every non-decoded state renders a legible label', ( + tester, + ) async { + const cases = { + 'failedIncomplete': 'Image incomplete — 1 of 3 packets arrived', + 'failedCorrupt': 'Image could not be reconstructed', + 'decoderUnavailable': 'Image received — image decoding is off', + 'evicted': 'Image no longer stored', + 'decoding': 'Reconstructing… about 1 s', + }; + for (final entry in cases.entries) { + // A distinct id per case on purpose: the ListView-recycling guard in + // _ReceivedImageMessageState only re-resolves the store when the + // streamId changes, so reusing one id would keep showing the first case. + final id = 'st_${entry.key}'; + final blobs = InMemoryReceivedImageBlobStore(); + await blobs.writeSidecar( + id, + jsonEncode({ + 'streamId': id, + 'senderPrefix': 4, + 'imgId': 4, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': entry.key, + 'receivedChunks': 1, + 'totalChunks': 3, + }), + ); + final store = ReceivedImageStore(blobs: blobs, decoder: null); + await store.load(); + await _pumpBubble(tester, store, streamId: id); + // `decoding` is repaired to failedIncomplete on load (no bitstream on + // disk), which is exactly the label a user must see after a crash. + final expected = entry.key == 'decoding' + ? 'Image incomplete — 1 of 3 packets arrived' + : entry.value; + expect( + find.text(expected), + findsOneWidget, + reason: 'state ${entry.key} rendered nothing legible', + ); + } + }); + + testWidgets('a decoded incoming image always shows the label, whatever ' + 'strings the caller injects', (tester) async { + final blobs = InMemoryReceivedImageBlobStore(); + final png = Uint8List.fromList(base64Decode(_png1x1)); + await blobs.writePng('dec', png); + await blobs.writeSidecar( + 'dec', + jsonEncode({ + 'streamId': 'dec', + 'senderPrefix': 9, + 'imgId': 9, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'decoded', + 'receivedChunks': 1, + 'totalChunks': 1, + 'pngStored': true, + 'pngByteCount': 68, + }), + ); + final store = ReceivedImageStore(blobs: blobs, decoder: null); + await store.load(); + + await _pumpBubble(tester, store, streamId: 'dec'); + await tester.pump(); + + expect(find.text('AI-reconstructed'), findsOneWidget); + expect(find.textContaining('Reconstructed by an AI model'), findsOneWidget); + expect(find.textContaining('Fine detail is generated'), findsOneWidget); + }); + + testWidgets('the caption quotes the real bitstream size, not a nominal one', ( + tester, + ) async { + // It used to hardcode "~156 bytes" under every image, so a 209-byte image + // and a 110-byte one both claimed 156. The label's whole purpose is + // honesty about what was actually transmitted. + for (final bytes in [110, 209]) { + final id = 'sz$bytes'; + final blobs = InMemoryReceivedImageBlobStore(); + await blobs.writePng(id, Uint8List.fromList(base64Decode(_png1x1))); + // A real bitstream on disk: load() derives the size by stat rather than + // trusting the sidecar, which is why this must actually exist. + await blobs.writeBitstream(id, Uint8List(bytes)); + await blobs.writeSidecar( + id, + jsonEncode({ + 'streamId': id, + 'senderPrefix': 9, + 'imgId': 9, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'decoded', + 'receivedChunks': 1, + 'totalChunks': 1, + 'pngStored': true, + 'pngByteCount': 68, + 'bitstreamStored': true, + 'bitstreamByteCount': bytes, + }), + ); + final store = ReceivedImageStore(blobs: blobs, decoder: null); + await store.load(); + + await _pumpBubble(tester, store, streamId: id); + await tester.pump(); + + expect( + find.textContaining('$bytes bytes'), + findsOneWidget, + reason: 'caption must quote $bytes', + ); + expect( + find.textContaining('156 bytes'), + findsNothing, + reason: 'no nominal size may leak into the caption', + ); + } + }); + + testWidgets('the R6 caption is never truncated in a narrow bubble', ( + tester, + ) async { + // It used to be maxLines: 2 and clipped mid-sentence — the rendered text + // read "Details are invented. Not a", cutting off exactly where the + // warning was. A half-shown warning is worse than none. + final blobs = InMemoryReceivedImageBlobStore(); + await blobs.writePng('clip', Uint8List.fromList(base64Decode(_png1x1))); + await blobs.writeBitstream('clip', Uint8List(209)); + await blobs.writeSidecar( + 'clip', + jsonEncode({ + 'streamId': 'clip', + 'senderPrefix': 9, + 'imgId': 9, + 'channelIndex': 0, + 'firstSeenMs': DateTime.now().millisecondsSinceEpoch, + 'state': 'decoded', + 'receivedChunks': 1, + 'totalChunks': 1, + 'pngStored': true, + 'pngByteCount': 68, + 'bitstreamStored': true, + 'bitstreamByteCount': 209, + }), + ); + final store = ReceivedImageStore(blobs: blobs, decoder: null); + await store.load(); + + await _pumpBubble(tester, store, streamId: 'clip'); + await tester.pump(); + + final caption = tester.widget( + find.textContaining('Reconstructed by an AI model'), + ); + expect(caption.maxLines, isNull, reason: 'the sentence must wrap in full'); + expect(caption.overflow, isNot(TextOverflow.ellipsis)); + // And the tail of the sentence is actually present. + expect(find.textContaining('not transmitted'), findsOneWidget); + }); +} diff --git a/tools/aeic/README.md b/tools/aeic/README.md new file mode 100644 index 00000000..677fd7d3 --- /dev/null +++ b/tools/aeic/README.md @@ -0,0 +1,47 @@ +# Regenerating the AEIC test fixtures + +The image codec's tests are pinned against data produced by the reference +implementation, not by the Dart code. That is the whole point: a Dart encoder +and a Dart decoder that agree with each other prove nothing, because they would +agree just as happily on a wrong wire format. These scripts produce the data the +Dart side is checked against. + +They are committed here so `test/services/golden/` is reproducible. Nothing in +the app runs them. + +| script | produces | used by | +|---|---|---| +| `export_golden.py` | `golden/aeic_cdf_ft32.bin`, `golden/vectors/*.gv` | `rans_coder_test.dart`, `entropy_tables_test.dart` | +| `record_entropy_io.py` | `golden/e2e/*.aeicrec`, `golden/e2e/manifest.json` | `image_codec_e2e_test.dart` | + +## What they need + +Neither script is self-contained. Both drive the real AEIC model, so they need +the research checkout that is **not** part of this repository: + +- the AEIC source (`github.com/LuizScarlet/AEIC`) with the two local patches: + pybind11 bumped to v2.13.6 (2.10.4 silently returns stride-0 arrays under + NumPy 2), and `.contiguous()` on `z_hat` in both `compress()` and + `decompress()` (the encoder and decoder otherwise land in different memory + layouts, and the ~2.8e-7 drift that causes desynchronises the rANS decoder on + roughly one image in 26, with no error raised) +- the `AEIC_SE_ft32.pkl` checkpoint +- the compiled C++ rANS extension (`src/cpp`, CMake) — the golden bitstreams are + produced by it, which is what makes them worth comparing against +- PyTorch, onnxruntime, NumPy 2 + +## Running them + +```bash +cd +AEIC_DEVICE=cpu python export_golden.py # tables + symbol vectors +AEIC_DEVICE=cpu python record_entropy_io.py # ONNX I/O recordings +``` + +Then copy the output into `test/services/golden/`. + +## If you change the wire format + +Regenerate. The fixtures encode the chunk framing and the metadata byte layout, +so a format change makes them stale in a way the tests will report as a codec +bug — which is the correct behaviour, but only if you know to look here. diff --git a/tools/aeic/export_golden.py b/tools/aeic/export_golden.py new file mode 100644 index 00000000..8351d767 --- /dev/null +++ b/tools/aeic/export_golden.py @@ -0,0 +1,819 @@ +"""P1 -- export the AEIC ft32 entropy tables and golden rANS vectors for the Dart port. + +Produces three things under results/golden/: + + 1. `aeic_cdf_ft32.bin` -- the static entropy-coder tables (both CDF groups) in a + compact little-endian binary container. This file SHIPS in the download bundle. + Format documented in `results/rans_port_spec.md` (section "CDF table file"). + + 2. `vectors/.gv` -- the exact int16 symbol and index arrays handed to the + C++ rANS encoder, in a compact binary container. + + 3. `vectors/.bin` -- the exact bitstream bytes the C++ coder produced for + that image, plus `.json` with sizes/hashes/container split. + +Every bitstream is written to disk and then `os.stat(path).st_size` is asserted equal +to `len(stream)`, so byte counts are auditable by stat rather than by a Python int. + +Run: + PYTORCH_ENABLE_MPS_FALLBACK=1 AEIC_DEVICE=cpu .venv/bin/python exp/export_golden.py + ... --all # all 26 images instead of the default 10 + ... --no-verify # skip the in-process decode round-trip (faster) +""" +import argparse +import hashlib +import json +import math +import os +import struct +import sys +from pathlib import Path + +os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1") +os.environ.setdefault("AEIC_DEVICE", "cpu") + +import numpy as np +import torch +import torch.nn.functional as F + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(HERE)) + +import aeic_runner as R # noqa: E402 + +OUT = ROOT / "results" / "golden" +VEC = OUT / "vectors" + +# default corpus: 8 Kodak + the 2 custom images +DEFAULT_IMAGES = [ + "kodim01", "kodim02", "kodim05", "kodim08", + "kodim13", "kodim19", "kodim23", "kodim24", + "image2", "images", +] + +TABLE_MAGIC = b"AEICCDF\x01" # 8 bytes +GV_MAGIC = b"AEICGV\x00\x01" # 8 bytes +FORMAT_VERSION = 1 +PRECISION = 16 # rANS probability precision, bits +BYPASS_PRECISION = 2 +STREAM_PARTS = 2 # EntropyCoder() -> RansEncoder(ec_thread, 2) + +DT_INT16 = 0 +DT_INT32 = 1 + + +class _IdentityGS(torch.nn.Module): + """Stand-in for codec.g_s: hand the latent straight back, no UNet/VAE.""" + + def forward(self, y_hat): + return y_hat, None + + +# --------------------------------------------------------------------------- tables + +def write_table_file(codec, path): + """Serialize both CDF groups + the index-quantizer constants. + + Layout (all little-endian, no padding, no alignment guarantees beyond 4 bytes): + + char[8] magic = "AEICCDF\x01" + u32 version = 1 + u32 precision = 16 + u32 bypass_precision = 2 + u32 stream_parts = 2 + u32 num_groups = 2 + -- then num_groups group blocks, in order (group 0 = z, group 1 = y): + u32 num_cdfs R + u32 cdf_width W + i32[R] cdf_length + i32[R] offset + i32[R*W] quantized_cdf, row-major + -- then one index-quantizer block: + char[4] "IDXP" + f64 log_scale_min + f64 log_scale_step + u32 scales_levels = 64 + f32 scale_bound_lo = 0.08 (scales below this -> index -1) + f32 scale_floor = 1e-5 (torch.maximum floor) + f32[64] scale_table + -- trailer: + char[4] "END\x00" + """ + z_cdf = np.asarray(codec.z_quantized_cdf, dtype=np.int32) + z_len = np.asarray(codec.z_cdf_length, dtype=np.int32).reshape(-1) + z_off = np.asarray(codec.z_offset, dtype=np.int32).reshape(-1) + y_cdf = np.asarray(codec.y_quantized_cdf, dtype=np.int32) + y_len = np.asarray(codec.y_cdf_length, dtype=np.int32).reshape(-1) + y_off = np.asarray(codec.y_offset, dtype=np.int32).reshape(-1) + + groups = [("z", z_cdf, z_len, z_off), ("y", y_cdf, y_len, y_off)] + + buf = bytearray() + buf += TABLE_MAGIC + buf += struct.pack("<5I", FORMAT_VERSION, PRECISION, BYPASS_PRECISION, + STREAM_PARTS, len(groups)) + meta = [] + for name, cdf, ln, off in groups: + assert cdf.ndim == 2, (name, cdf.shape) + r, w = cdf.shape + assert ln.shape == (r,) and off.shape == (r,), (name, ln.shape, off.shape) + assert int(ln.max()) <= w, (name, int(ln.max()), w) + assert cdf.min() >= 0 and cdf.max() <= (1 << PRECISION), (name, cdf.min(), cdf.max()) + buf += struct.pack("<2I", r, w) + buf += ln.astype("> 4) + 1 + hdr = 2 if (flag & 0x0F) == 1 else 4 + off = 1 + sizes, total = [], 0 + for _ in range(n_streams - 1): + if hdr == 2: + sz = int.from_bytes(stream[off:off + 2], "little") + else: + sz = int.from_bytes(stream[off:off + 4], "little") + off += hdr + sizes.append(sz) + total += sz + sizes.append(len(stream) - off - total) + parts, p = [], off + for sz in sizes: + parts.append(stream[p:p + sz]) + p += sz + assert p == len(stream), (p, len(stream)) + return flag, hdr, sizes, parts + + +@torch.no_grad() +def capture(codec, x): + """Verbatim codec_practical.AEIC_Codec.compress(), capturing every rANS input.""" + B, C, H, W = x.shape + y_h, y_w = H // 32, W // 32 + z_h, z_w = math.ceil(y_h / 4), math.ceil(y_w / 4) + pad_h, pad_w = z_h * 4 - y_h, z_w * 4 - y_w + + masks = codec.get_mask_four_parts(1, codec.y_channel, y_h, y_w, device=x.device) + z_indexes, z_offset = codec.entropy_bottleneck.get_compress_info( + [1, codec.y_channel // 2, z_h, z_w]) + + y = codec.g_a(x) + y_padded = F.pad(y, (0, pad_w, 0, pad_h), mode="reflect") + z = codec.h_a(y_padded) + z_q = torch.round(z - z_offset) + z_hat = (z_q + z_offset).contiguous() + z_q_np = z_q.flatten().cpu().numpy() + + base = codec.h_s(z_hat)[:, :, :y_h, :y_w] + y_q_list, scales_list, last = [], [], None + for i in range(4): + mask = masks[i] + out = codec.adapter_out[i](codec.g_c(codec.adapter_in[i](base))) + means_supp, scales_supp = out.chunk(2, 1) + means = means_supp * mask + scales = scales_supp * mask + y_q = torch.round(y * mask - means) + y_q_list.append(y_q) + scales_list.append(scales) + last = y_q + means + if i < 3: + base = base * (1 - mask) + last + y_hat_enc = base * (1 - masks[3]) + last + + packed = codec.compress_group(y_q_list, scales_list) + yq = list(packed[:4]) + yidx = list(packed[4:]) + + codec.entropy_coder.reset() + codec.entropy_coder.encode_with_z4y_indexes( + z_q_np, z_indexes, codec.z_cdf_group_index, + yq[0], yidx[0], yq[1], yidx[1], yq[2], yidx[2], yq[3], yidx[3], + codec.y_cdf_group_index) + codec.entropy_coder.flush() + stream = codec.entropy_coder.get_encoded_stream() + + # exactly the int16 the pybind layer forcecasts to + z_q_i16 = z_q_np.astype(np.int16) + z_idx_i16 = z_indexes.reshape(-1).cpu().numpy().astype(np.int16) + yq_i16 = [a.reshape(-1).astype(np.int16) for a in yq] + yidx_i16 = [a.reshape(-1).astype(np.int16) for a in yidx] + + # the forcecast must be lossless: assert the float/int32 originals round-trip + assert np.array_equal(z_q_i16.astype(np.float64), z_q_np.astype(np.float64)) + for a, b in zip(yq_i16, yq): + assert np.array_equal(a.astype(np.float64), b.reshape(-1).astype(np.float64)) + for a, b in zip(yidx_i16, yidx): + assert np.array_equal(a.astype(np.int64), b.reshape(-1).astype(np.int64)) + + return { + "stream": stream, + "y_hat_enc": y_hat_enc, + "z_q": z_q_i16, "z_indexes": z_idx_i16, + "yq": yq_i16, "yidx": yidx_i16, + "shapes": {"y": list(y.shape), "z": list(z.shape), + "z_q_n": int(z_q_i16.size), "yq_n": int(yq_i16[0].size)}, + } + + +def make_synthetic(codec): + """Cases the real corpus never reaches: escape / bypass coding and skipped indexes. + + On ft32 the live symbols are tiny (y_q in [-2,2], z_q in [-3,2]) and sit far from + both ends of their CDF row, so `value == max_value` never fires and the whole + bypass branch of the coder is dead. A Dart port that got it wrong would still + pass every image vector. These hand-built cases exercise it. + + All arrays have EVEN length: py_rans splits each array in half across the two + encoders and its last-part memcpy over-runs the index vector when the length is + odd. Never feed it an odd-length array. + """ + zg, yg = int(codec.z_cdf_group_index), int(codec.y_cdf_group_index) + z_len = np.asarray(codec.z_cdf_length).reshape(-1).astype(np.int64) + z_off = np.asarray(codec.z_offset).reshape(-1).astype(np.int64) + y_len = np.asarray(codec.y_cdf_length).reshape(-1).astype(np.int64) + y_off = np.asarray(codec.y_offset).reshape(-1).astype(np.int64) + + def i16(a): + return np.asarray(a, dtype=np.int16) + + cases = [] + + # --- group z: value == max_value exactly (escape with raw_val == 0, n_bypass == 0) + idx = np.arange(0, 128, dtype=np.int64) + sym = z_off[idx] + (z_len[idx] - 2) # value == max_value + cases.append(("z_escape_exact", zg, i16(sym), i16(idx))) + + # --- group z: value < 0 (odd raw_val) and value > max_value (even raw_val), mixed + sym = np.where(idx % 2 == 0, z_off[idx] - 1 - (idx // 2), z_off[idx] + z_len[idx] + idx) + cases.append(("z_escape_mixed", zg, i16(sym), i16(idx))) + + # --- group z: every in-range symbol of every row, tiled (normal path, all rows) + reps = 16 + idx2 = np.repeat(idx, reps) + k = np.tile(np.arange(reps, dtype=np.int64), 128) % np.repeat(z_len[idx] - 2, reps) + cases.append(("z_dense_normal", zg, i16(z_off[idx2] + k), i16(idx2))) + + # --- group y: huge magnitudes -> long bypass runs (n_bypass >= 3 exercises the + # max_bypass_val continuation loop) + idx = np.arange(0, 64, dtype=np.int64) + big = np.array([32000, -32000, 20000, -20000, 4096, -4096, 3132, -3132], dtype=np.int64) + idx3 = np.repeat(idx, len(big)) + sym = np.tile(big, 64) + cases.append(("y_bypass_long", yg, i16(sym), i16(idx3))) + + # --- group y: index -1 must be skipped by the encoder and decode to 0 + idx4 = np.where(np.arange(128) % 3 == 0, -1, np.arange(128) % 64).astype(np.int64) + sym4 = np.where(idx4 < 0, 12345, y_off[np.maximum(idx4, 0)] + 1).astype(np.int64) + cases.append(("y_skip_indexes", yg, i16(sym4), i16(idx4))) + + # --- group y: near both edges of each row, without escaping + idx5 = np.repeat(idx, 4) + edge = np.tile(np.array([0, 1, -3, -2], dtype=np.int64), 64) + ml = np.repeat(y_len[idx] - 2, 4) + val = np.where(edge >= 0, edge, ml + edge) + cases.append(("y_edges_normal", yg, i16(y_off[idx5] + val), i16(idx5))) + + # --- smallest possible payload: two symbols + cases.append(("y_tiny", yg, i16([y_off[0], y_off[0] + 1]), i16([0, 0]))) + + for name, g, s, i in cases: + assert s.size == i.size and s.size % 2 == 0, (name, s.size, i.size) + return cases + + +def most_likely_symbol(cdf_row, cdf_len, offset): + """(symbol, cost-free-ish) -- the highest-frequency value of a CDF row. + + Used as filler: see pad_case(). + """ + n = int(cdf_len) - 2 + freqs = [int(cdf_row[j + 1]) - int(cdf_row[j]) for j in range(n)] + j = int(np.argmax(freqs)) + return int(offset) + j + + +def encode_case(codec, group, sym, idx): + codec.entropy_coder.reset() + codec.entropy_coder.encoder.encode_with_indexes(sym, idx, group) + codec.entropy_coder.flush() + return codec.entropy_coder.get_encoded_stream() + + +def pad_case(codec, group, sym, idx, cdfs, lens, offs): + """Pad a synthetic case until it is safe for the SHIPPED C++ encoder. + + RansEncoderLib::flush() allocates exactly `_syms.size()` output bytes and writes + backwards from the end, so any sub-stream longer than one byte per pushed symbol + ENTRY runs off the front of the allocation. That is a silent heap under-run: the + bytes are still readable on this platform so the call appears to succeed, but it + scribbles on the allocator and poisons every later encode in the process. + Escape/bypass symbols cost up to 16 bits each and blow that budget easily. + + So the search must never hand an unsafe case to the C++ encoder. Sizing is done + entirely with the pure-Python reference port below (which selfcheck() proves is + byte-identical to the C++ coder on the real image vectors), and the C++ encoder + is called exactly once, on an already-verified-safe case. + """ + row = int(idx[idx >= 0][0]) if (idx >= 0).any() else 0 + fill_sym = most_likely_symbol(cdfs[row], lens[row], offs[row]) + tbl = {group: (cdfs, lens, offs)} + n_fill = 64 + for _ in range(24): + fa = np.full(n_fill, fill_sym, dtype=np.int16) + ia = np.full(n_fill, row, dtype=np.int16) + s = np.concatenate([fa, sym, fa]).astype(np.int16) + i = np.concatenate([ia, idx, ia]).astype(np.int16) + assert s.size % 2 == 0 + each = s.size // 2 + safe = True + for p in range(STREAM_PARTS): + lo = p * each + hi = s.size if p == STREAM_PARTS - 1 else lo + each + ent = [] + ref_push_symbols(ent, s[lo:hi], i[lo:hi], cdfs, lens, offs) + if len(ref_flush(ent)) * 2 > len(ent): # demand 2x headroom + safe = False + break + if safe: + return s, i, n_fill + n_fill *= 2 + raise RuntimeError("could not pad case into the C++ encoder's byte budget") + + +def run_synthetic(codec, cases): + tables = { + int(codec.z_cdf_group_index): (np.asarray(codec.z_quantized_cdf), + np.asarray(codec.z_cdf_length).reshape(-1), + np.asarray(codec.z_offset).reshape(-1)), + int(codec.y_cdf_group_index): (np.asarray(codec.y_quantized_cdf), + np.asarray(codec.y_cdf_length).reshape(-1), + np.asarray(codec.y_offset).reshape(-1)), + } + rows = [] + for name, group, sym0, idx0 in cases: + cdfs, lens, offs = tables[group] + sym, idx, n_fill = pad_case(codec, group, sym0, idx0, cdfs, lens, offs) + stream = encode_case(codec, group, sym, idx) + + bin_path = VEC / f"synth_{name}.bin" + bin_path.write_bytes(stream) + st = os.stat(bin_path).st_size + assert st == len(stream), f"{name}: stat {st} != len {len(stream)}" + + flag, hdr, sizes, parts = parse_container(stream) + gv_path = VEC / f"synth_{name}.gv" + gv_bytes = write_gv_file(gv_path, [("symbols", sym), ("indexes", idx)]) + + # decode back through the C++ decoder; index<0 positions decode to 0 + codec.entropy_coder.decoder.set_stream(np.frombuffer(stream, dtype=np.uint8)) + dec = np.asarray(codec.entropy_coder.decoder.decode_stream(idx, group)) + expect = np.where(idx < 0, 0, sym).astype(np.int16) + ok = bool(np.array_equal(dec.astype(np.int16), expect)) + assert ok, f"{name}: decoder disagreed" + + rows.append({ + "name": name, "cdf_group": int(group), "n": int(sym.size), + "n_filler_each_end": int(n_fill), + "bitstream_file": bin_path.name, "bitstream_bytes_stat": st, + "bitstream_sha256": hashlib.sha256(stream).hexdigest(), + "container_flag": flag, "container_header_bytes": hdr, + "substream_sizes": sizes, + "vector_file": gv_path.name, "vector_bytes_stat": gv_bytes, + "expected_decode_sha256": hashlib.sha256( + expect.astype("6} B parts={sizes} " + f"sym[{sym.min()},{sym.max()}] skip={int((idx<0).sum())} rt={ok}", flush=True) + return rows + + +# ------------------------------------------------- independent reference port +# A from-scratch re-implementation of the C++ coder, written the way the Dart port +# should be written (plain ints, growable buffer, no numpy tricks). If this +# reproduces every golden bitstream byte-for-byte then results/rans_port_spec.md is +# correct and a Dart implementer never has to open the C++. + +RANS_L = 1 << 23 +MAX_BYPASS_VAL = (1 << BYPASS_PRECISION) - 1 + + +def ref_push_symbols(out, symbols, indexes, cdfs, cdf_lengths, offsets): + """Append (start, range) entries for one encode_with_indexes() call.""" + for i in range(len(symbols)): + cdf_idx = int(indexes[i]) + if cdf_idx < 0: + continue + max_value = int(cdf_lengths[cdf_idx]) - 2 + value = int(symbols[i]) - int(offsets[cdf_idx]) + raw_val = 0 + if value < 0: + raw_val = -2 * value - 1 + value = max_value + elif value >= max_value: + raw_val = 2 * (value - max_value) + value = max_value + row = cdfs[cdf_idx] + out.append((int(row[value]), int(row[value + 1]) - int(row[value]))) + if value == max_value: + n_bypass = 0 + while (raw_val >> (n_bypass * BYPASS_PRECISION)) != 0: + n_bypass += 1 + val = n_bypass + while val >= MAX_BYPASS_VAL: + out.append((MAX_BYPASS_VAL, 0)) + val -= MAX_BYPASS_VAL + out.append((val, 0)) + for j in range(n_bypass): + out.append(((raw_val >> (j * BYPASS_PRECISION)) & MAX_BYPASS_VAL, 0)) + + +def ref_flush(entries): + """rANS encode the entry list in reverse; returns the sub-stream bytes.""" + rev = bytearray() # bytes in emission order == reverse of stream order + x = RANS_L + for start, rng in reversed(entries): + if rng != 0: + x_max = rng << 15 + while x >= x_max: + rev.append(x & 0xFF) + x >>= 8 + x = ((x // rng) << PRECISION) + (x % rng) + start + else: + x_max = (1 << (PRECISION - BYPASS_PRECISION)) << 15 + while x >= x_max: + rev.append(x & 0xFF) + x >>= 8 + x = (x << BYPASS_PRECISION) | start + rev.append((x >> 24) & 0xFF) + rev.append((x >> 16) & 0xFF) + rev.append((x >> 8) & 0xFF) + rev.append(x & 0xFF) + rev.reverse() + return bytes(rev) + + +def ref_container(parts): + maximum = max((len(p) for p in parts[:-1]), default=0) + hdr = 4 if maximum > 65535 else 2 + flag = ((len(parts) - 1) << 4) | (1 if hdr == 2 else 0) + out = bytearray([flag]) + for p in parts[:-1]: + out += len(p).to_bytes(hdr, "little") + for p in parts: + out += p + return bytes(out) + + +def ref_encode(calls, tables, n_parts=STREAM_PARTS): + """calls: list of (symbols, indexes, cdf_group). Returns the shipped bytes.""" + entries = [[] for _ in range(n_parts)] + for symbols, indexes, group in calls: + cdfs, lens, offs = tables[group] + total = len(symbols) + each = total // n_parts + for p in range(n_parts): + lo = p * each + hi = total if p == n_parts - 1 else lo + each + ref_push_symbols(entries[p], symbols[lo:hi], indexes[lo:hi], cdfs, lens, offs) + return ref_container([ref_flush(e) for e in entries]) + + +def ref_decode(stream, index_calls, tables, n_parts=STREAM_PARTS): + """index_calls: list of (indexes, cdf_group). Returns list of symbol lists.""" + _, _, _, parts = parse_container(stream) + states, ptrs = [], [] + for p in parts: + states.append(int.from_bytes(p[0:4], "little")) + ptrs.append(4) + results = [] + for indexes, group in index_calls: + cdfs, lens, offs = tables[group] + total = len(indexes) + each = total // n_parts + out = [0] * total + for pi in range(n_parts): + lo = pi * each + hi = total if pi == n_parts - 1 else lo + each + buf = parts[pi] + x = states[pi] + ptr = ptrs[pi] + for i in range(lo, hi): + cdf_idx = int(indexes[i]) + if cdf_idx < 0: + out[i] = 0 + continue + row = cdfs[cdf_idx] + n = int(lens[cdf_idx]) + max_value = n - 2 + cum = x & ((1 << PRECISION) - 1) + s = -1 # upper_bound(row[0:n], cum) - 1 + loo, hii = 0, n + while loo < hii: + mid = (loo + hii) // 2 + if int(row[mid]) > cum: + hii = mid + else: + loo = mid + 1 + s = loo - 1 + start = int(row[s]) + rng = int(row[s + 1]) - start + x = rng * (x >> PRECISION) + (x & ((1 << PRECISION) - 1)) - start + if x < RANS_L: + while x < RANS_L: + x = ((x << 8) | buf[ptr]) & 0xFFFFFFFF + ptr += 1 + value = s + if value == max_value: + def get_bits(nb, _x=None): + nonlocal x, ptr + v = x & ((1 << nb) - 1) + x >>= nb + if x < RANS_L: + x = ((x << 8) | buf[ptr]) & 0xFFFFFFFF + ptr += 1 + return v + val = get_bits(BYPASS_PRECISION) + n_bypass = val + while val == MAX_BYPASS_VAL: + val = get_bits(BYPASS_PRECISION) + n_bypass += val + raw_val = 0 + for j in range(n_bypass): + raw_val |= get_bits(BYPASS_PRECISION) << (j * BYPASS_PRECISION) + value = raw_val >> 1 + if raw_val & 1: + value = -value - 1 + else: + value += max_value + out[i] = value + int(offs[cdf_idx]) + states[pi] = x + ptrs[pi] = ptr + results.append(out) + return results + + +def selfcheck(codec, manifest): + """Re-encode and re-decode every golden vector with the reference port.""" + tables = { + int(codec.z_cdf_group_index): (np.asarray(codec.z_quantized_cdf), + np.asarray(codec.z_cdf_length).reshape(-1), + np.asarray(codec.z_offset).reshape(-1)), + int(codec.y_cdf_group_index): (np.asarray(codec.y_quantized_cdf), + np.asarray(codec.y_cdf_length).reshape(-1), + np.asarray(codec.y_offset).reshape(-1)), + } + zg, yg = int(codec.z_cdf_group_index), int(codec.y_cdf_group_index) + n_ok = n_tot = 0 + + for rec in manifest["images"]: + arrs = read_gv_file(VEC / rec["vector_file"]) + calls = [(arrs["z_q"], arrs["z_indexes"], zg)] + calls += [(arrs[f"y_q{i}"], arrs[f"y_indexes{i}"], yg) for i in range(4)] + want = (VEC / rec["bitstream_file"]).read_bytes() + got = ref_encode(calls, tables) + enc_ok = got == want + dec = ref_decode(want, [(c[1], c[2]) for c in calls], tables) + dec_ok = all( + list(d) == [0 if int(ix) < 0 else int(sy) for sy, ix in zip(c[0], c[1])] + for d, c in zip(dec, calls)) + n_tot += 1 + n_ok += int(enc_ok and dec_ok) + print(f" ref {rec['stem']:<10} encode={'OK' if enc_ok else 'MISMATCH'} " + f"decode={'OK' if dec_ok else 'MISMATCH'} ({len(got)}/{len(want)} B)") + + for rec in manifest["synthetic"]: + arrs = read_gv_file(VEC / rec["vector_file"]) + g = rec["cdf_group"] + calls = [(arrs["symbols"], arrs["indexes"], g)] + want = (VEC / rec["bitstream_file"]).read_bytes() + got = ref_encode(calls, tables) + enc_ok = got == want + dec = ref_decode(want, [(arrs["indexes"], g)], tables) + expect = [0 if int(ix) < 0 else int(sy) + for sy, ix in zip(arrs["symbols"], arrs["indexes"])] + dec_ok = list(dec[0]) == expect + n_tot += 1 + n_ok += int(enc_ok and dec_ok) + print(f" ref synth_{rec['name']:<16} encode={'OK' if enc_ok else 'MISMATCH'} " + f"decode={'OK' if dec_ok else 'MISMATCH'} ({len(got)}/{len(want)} B)") + + print(f"reference port reproduces {n_ok}/{n_tot} vectors exactly") + return n_ok, n_tot + + +def read_gv_file(path): + raw = path.read_bytes() + assert raw[:8] == GV_MAGIC, path + ver, n = struct.unpack_from("<2I", raw, 8) + assert ver == FORMAT_VERSION + off = 16 + descs = [] + for _ in range(n): + name = raw[off:off + 16].rstrip(b"\x00").decode() + dt, cnt = struct.unpack_from("<2I", raw, off + 16) + descs.append((name, dt, cnt)) + off += 24 + out = {} + for name, dt, cnt in descs: + w = 2 if dt == DT_INT16 else 4 + out[name] = np.frombuffer(raw, dtype="", codec.update(force=True)) + real_g_s = codec._modules.pop("g_s") + codec.g_s = _IdentityGS() + + tbl_path = OUT / "aeic_cdf_ft32.bin" + tbl_bytes, tbl_meta = write_table_file(codec, tbl_path) + tbl_sha = hashlib.sha256(tbl_path.read_bytes()).hexdigest() + print(f"tables -> {tbl_path.name} {tbl_bytes} B sha256={tbl_sha[:16]}") + for m in tbl_meta: + print(f" group {m['group']}: {m['rows']}x{m['width']} " + f"cdf_length {m['cdf_length_min']}..{m['cdf_length_max']} " + f"offset {m['offset_min']}..{m['offset_max']} cdf_max {m['cdf_max']}") + + z_h = math.ceil((args.size // 32) / 4) + rows = [] + for path in images: + x = R.load_image(str(path), size=args.size) + cap = capture(codec, x) + stream = cap["stream"] + stem = path.stem + + bin_path = VEC / f"{stem}.bin" + bin_path.write_bytes(stream) + st = os.stat(bin_path).st_size + assert st == len(stream), f"{stem}: stat {st} != len {len(stream)}" + + flag, hdr, sizes, parts = parse_container(stream) + assert sum(sizes) + 1 + hdr * (len(sizes) - 1) == st + + arrays = [("z_q", cap["z_q"]), ("z_indexes", cap["z_indexes"])] + for i in range(4): + arrays.append((f"y_q{i}", cap["yq"][i])) + for i in range(4): + arrays.append((f"y_indexes{i}", cap["yidx"][i])) + gv_path = VEC / f"{stem}.gv" + gv_bytes = write_gv_file(gv_path, arrays) + + ok = None + if not args.no_verify: + codec.entropy_coder.reset() + codec.entropy_coder.set_stream(stream) + y_hat_dec, _ = codec.decompress( + (1, codec.y_channel // 2, z_h, z_h), args.size // 32, args.size // 32) + ok = bool(torch.equal(cap["y_hat_enc"], y_hat_dec)) + assert ok, f"{stem}: round-trip not bit-exact" + + rec = { + "image": path.name, + "stem": stem, + "bitstream_file": bin_path.name, + "bitstream_bytes_stat": st, + "bitstream_sha256": hashlib.sha256(stream).hexdigest(), + "container_flag": flag, + "container_header_bytes": hdr, + "substream_sizes": sizes, + "substream_sha256": [hashlib.sha256(p).hexdigest() for p in parts], + "vector_file": gv_path.name, + "vector_bytes_stat": gv_bytes, + "n_z_symbols": int(cap["z_q"].size), + "n_y_symbols_each": int(cap["yq"][0].size), + "z_q_min": int(cap["z_q"].min()), "z_q_max": int(cap["z_q"].max()), + "y_q_min": int(min(a.min() for a in cap["yq"])), + "y_q_max": int(max(a.max() for a in cap["yq"])), + "y_index_min": int(min(a.min() for a in cap["yidx"])), + "y_index_max": int(max(a.max() for a in cap["yidx"])), + "n_skipped_y_indexes": int(sum(int((a < 0).sum()) for a in cap["yidx"])), + "roundtrip_bitexact": ok, + } + rows.append(rec) + print(f" {stem:<10} {st:>4} B parts={sizes} gv={gv_bytes} B " + f"z_q[{rec['z_q_min']},{rec['z_q_max']}] " + f"y_q[{rec['y_q_min']},{rec['y_q_max']}] " + f"idx[{rec['y_index_min']},{rec['y_index_max']}] " + f"skip={rec['n_skipped_y_indexes']} rt={ok}", flush=True) + + print("synthetic (escape / bypass / skip coverage):") + synth = run_synthetic(codec, make_synthetic(codec)) + + codec._modules["g_s"] = real_g_s + + manifest = { + "checkpoint": args.ckpt, + "size": args.size, + "precision": PRECISION, + "bypass_precision": BYPASS_PRECISION, + "stream_parts": STREAM_PARTS, + "table_file": tbl_path.name, + "table_bytes": tbl_bytes, + "table_sha256": tbl_sha, + "table_groups": tbl_meta, + "z_cdf_group_index": int(codec.z_cdf_group_index), + "y_cdf_group_index": int(codec.y_cdf_group_index), + "images": rows, + "synthetic": synth, + } + (OUT / "manifest.json").write_text(json.dumps(manifest, indent=1)) + + print("\nreference-port self-check (validates results/rans_port_spec.md):") + ok, tot = selfcheck(codec, manifest) + manifest["reference_port_selfcheck"] = {"ok": ok, "total": tot} + (OUT / "manifest.json").write_text(json.dumps(manifest, indent=1)) + assert ok == tot, "reference port does not match the C++ coder" + + n = len(rows) + b = [r["bitstream_bytes_stat"] for r in rows] + print(f"\n{n} vectors, bitstream {min(b)}-{max(b)} B mean {sum(b)/n:.1f}") + print(f"round-trip bit-exact {sum(1 for r in rows if r['roundtrip_bitexact'])}/{n}") + print(f"wrote {OUT / 'manifest.json'}") + + +if __name__ == "__main__": + main() diff --git a/tools/aeic/record_entropy_io.py b/tools/aeic/record_entropy_io.py new file mode 100644 index 00000000..b328766d --- /dev/null +++ b/tools/aeic/record_entropy_io.py @@ -0,0 +1,558 @@ +"""E2 -- record ONNX entropy tensors so the Dart four-stage loop can be tested +end to end inside `flutter test`, where the flutter_onnxruntime platform channel +does not exist. + +lib/services/image_codec_entropy.dart defines an abstract `AeicEntropyNetwork` +seam with exactly three entry points: + + runEncodeSide(image) -> z_q, yq0..3, sc0..3 + runHyperSynthesis(z_q) -> base0 + runStage(stage, base) -> means_supp, scales_supp (UNMASKED) + +A test can inject a fake that replays recorded tensors positionally and so +exercise the REAL Dart masking / build_indexes / rANS code against REAL data. +This script produces one self-describing binary per image containing every +tensor that crosses that seam, in call order, plus the exact rANS bitstream. + +Container format: see CONTAINER_DOC at the bottom of this file (and the report). + +Run: + .venv/bin/python exp/record_entropy_io.py + .venv/bin/python exp/record_entropy_io.py --verify-only # re-check on disk +""" +import argparse +import hashlib +import json +import math +import os +import struct +import sys +from pathlib import Path + +os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1") +os.environ.setdefault("AEIC_DEVICE", "cpu") + +import numpy as np +import torch +import torch.nn as nn + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(HERE)) + +import aeic_runner as R # noqa: E402 +from bitexact_encoder import EntropySide, build_stream # noqa: E402 + +SCRATCH = Path(os.environ.get( + "AEIC_SCRATCH", + "/private/tmp/claude-502/-Users-Zach-Documents-mycode-aic/" + "2e06b1a7-5277-4c57-95e0-74b34e166761/scratchpad")) + +OUT_DIR = ROOT / "results" / "golden" / "e2e" +ENC_GRAPH = ROOT / "onnx" / "aeic_entropy_side_fp32_op17.onnx" +# The shipped decode-side graph (task E1). Used when present; otherwise the +# recorder exports its own equivalent scratch graph so it can still run. +SHIPPED_DECODE = ROOT / "onnx" / "aeic_entropy_decode_fp32_op17.onnx" + +MAGIC = b"AEICREC1" +VERSION = 1 +HEADER_BYTES = 32 +ALIGN = 8 + +ENC_NAMES = [ + "y", "z", "z_q", "base0", "means_all", "scales_all", "y_hat", + "yq0", "yq1", "yq2", "yq3", "sc0", "sc1", "sc2", "sc3", +] + +DTYPES = { + np.dtype("float32"): "f32", + np.dtype("int32"): "i32", + np.dtype("int16"): "i16", + np.dtype("uint8"): "u8", +} + + +# -------------------------------------------------------------------------- +# container writer / reader +# -------------------------------------------------------------------------- +class Recording: + """Ordered name -> ndarray map with a JSON index, written little-endian.""" + + def __init__(self, meta=None): + self.arrays = {} + self.order = [] + self.meta = dict(meta or {}) + self.calls = [] + + def put(self, name, arr): + arr = np.ascontiguousarray(arr) + if arr.dtype not in DTYPES: + raise TypeError(f"{name}: unsupported dtype {arr.dtype}") + if name in self.arrays: + raise KeyError(f"duplicate entry {name}") + self.arrays[name] = arr + self.order.append(name) + return name + + def write(self, path): + entries, blob, off = [], [], HEADER_BYTES + for name in self.order: + a = self.arrays[name] + pad = (-off) % ALIGN + if pad: + blob.append(b"\0" * pad) + off += pad + raw = a.tobytes(order="C") + entries.append({"name": name, "dtype": DTYPES[a.dtype], + "shape": list(a.shape), "offset": off, + "length": len(raw)}) + blob.append(raw) + off += len(raw) + pad = (-off) % ALIGN + if pad: + blob.append(b"\0" * pad) + off += pad + index = json.dumps({"meta": self.meta, "calls": self.calls, + "entries": entries}, separators=(",", ":")).encode() + head = (MAGIC + struct.pack(" base0, and base -> (means_supp, scales_supp) for all four stages. + + One graph, two inputs, nine outputs; the recorder asks onnxruntime for a + SUBSET of outputs per call, which prunes the graph exactly the way the + shipped stage-branching decode graph does. Unmasked on purpose: the Dart + seam applies the mask itself. + """ + + def __init__(self, codec, y_h, y_w, z_offset): + super().__init__() + self.h_s = codec.h_s + self.g_c = codec.g_c + self.adapter_in = codec.adapter_in + self.adapter_out = codec.adapter_out + self.y_h, self.y_w = y_h, y_w + self.register_buffer("z_offset", z_offset.clone()) + + def forward(self, z_q, base): + z_hat = (z_q + self.z_offset).contiguous() + base0 = self.h_s(z_hat)[:, :, : self.y_h, : self.y_w] + outs = [] + for i in range(4): + out = self.adapter_out[i](self.g_c(self.adapter_in[i](base))) + m, s = out.chunk(2, 1) + outs += [m, s] + return (base0, *outs) + + +DEC_OUT_NAMES = ["base0"] + [n for i in range(4) + for n in (f"means{i}", f"scales{i}")] + + +class OrtDecodeSide: + """Runner for the scratch nine-output recording graph.""" + + def __init__(self, sess, y_shape, z_shape): + self.sess = sess + self.zero_base = np.zeros(y_shape, dtype=np.float32) + self.zero_zq = np.zeros(z_shape, dtype=np.float32) + + def hyper(self, z_q): + return self.sess.run(["base0"], {"z_q": z_q, "base": self.zero_base})[0] + + def stage(self, i, base): + m, s = self.sess.run([f"means{i}", f"scales{i}"], + {"z_q": self.zero_zq, "base": base}) + return m, s + + +class OrtShippedDecodeSide: + """Runner for the SHIPPED decode graph (inputs z_q, base, stage; outputs + base0, means, scales), driven exactly the way OnnxAeicEntropyNetwork drives + it: every call passes all three inputs and fetches all three outputs, + because flutter_onnxruntime's session.run() has no output-subset API.""" + + def __init__(self, sess, y_shape, z_shape): + self.sess = sess + self.zero_base = np.zeros(y_shape, dtype=np.float32) + self.zero_zq = np.zeros(z_shape, dtype=np.float32) + self.names = [o.name for o in sess.get_outputs()] + + def _run(self, z_q, base, stage): + out = self.sess.run(None, { + "z_q": z_q, "base": base, + "stage": np.asarray([stage], dtype=np.int32)}) + return dict(zip(self.names, out)) + + def hyper(self, z_q): + return self._run(z_q, self.zero_base, -1)["base0"] + + def stage(self, i, base): + o = self._run(self.zero_zq, base, i) + return o["means"], o["scales"] + + +# -------------------------------------------------------------------------- +# the arithmetic the Dart loop mirrors (kept in numpy/torch, verbatim) +# -------------------------------------------------------------------------- +def sequeeze(t): + a, b, c, d = np.split(t, 4, axis=1) + return (a + b) + (c + d) + + +def unsequeeze_with_mask(sq, mask): + parts = np.split(mask, 4, axis=1) + return np.concatenate([sq * p for p in parts], axis=1) + + +def build_indexes(codec, scales_np): + s = torch.from_numpy(np.ascontiguousarray(scales_np)) + return codec.my_build_indexes(s).numpy() + + +def decode_loop(codec, dec, masks_np, coder, z_indexes_t, z_shape, + record=None): + """codec.decompress(), driven through `dec` and recording every call.""" + z_sym = coder.decode_stream(z_indexes_t, codec.z_cdf_group_index) + z_q = z_sym.numpy().reshape(z_shape).astype(np.float32) + + base = dec.hyper(z_q) + if record is not None: + record(0, "hyper_synthesis", -1, + {"z_q": z_q, "stage": np.asarray([-1], dtype=np.int32)}, + {"base0": base}) + + y_parts = [] + for i in range(4): + mask = masks_np[i] + m_supp, s_supp = dec.stage(i, base) + if record is not None: + record(1 + i, "stage", i, + {"base": base, "stage": np.asarray([i], dtype=np.int32)}, + {"means": m_supp, "scales": s_supp}) + means, scales = m_supp * mask, s_supp * mask + sq_scales = sequeeze(scales) + idx = build_indexes(codec, sq_scales) + sym = coder.decode_stream(torch.from_numpy(idx).reshape(-1), + codec.y_cdf_group_index) + sym = sym.numpy().astype(np.float32).reshape(sq_scales.shape) + latent = unsequeeze_with_mask(sym + sequeeze(means), mask) + y_parts.append(latent) + if i < 3: + base = base * (1 - mask) + latent + y_hat = base * (1 - masks_np[3]) + y_parts[3] + return y_hat + + +# -------------------------------------------------------------------------- +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", default="AEIC_SE_ft32.pkl") + ap.add_argument("--size", type=int, default=512) + ap.add_argument("--images", nargs="*", default=None) + ap.add_argument("--decode-graph", default=None, + help="reuse an existing decode-side graph instead of " + "exporting the scratch recording graph") + ap.add_argument("--scratch", default=str(SCRATCH)) + ap.add_argument("--verify-only", action="store_true") + args = ap.parse_args() + + if args.verify_only: + return verify_only() + + import onnxruntime as ort + + images = args.images or [ + str(ROOT / "data" / "kodak_raw" / "kodim01.png"), + str(ROOT / "data" / "kodak_raw" / "kodim02.png"), + str(ROOT / "data" / "kodak_raw" / "kodim05.png"), + str(ROOT / "data" / "custom" / "image2.webp"), + str(ROOT / "data" / "custom" / "images.jpeg"), + ] + + net, _ = R.load_model(ckpt=args.ckpt) + codec = net.codec + print("codec.update(force=True) ->", codec.update(force=True)) + + y_h = y_w = args.size // 32 + z_h = z_w = math.ceil(y_h / 4) + z_shape = (1, codec.y_channel // 2, z_h, z_w) + y_shape = (1, codec.y_channel, y_h, y_w) + z_indexes, z_offset = codec.entropy_bottleneck.get_compress_info(list(z_shape)) + + masks = codec.get_mask_four_parts(1, codec.y_channel, y_h, y_w, device="cpu") + masks_np = [m.numpy().astype(np.float32) for m in masks] + + # --- sessions ------------------------------------------------------- + so = ort.SessionOptions() + so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + enc_sess = ort.InferenceSession(str(ENC_GRAPH), so, + providers=["CPUExecutionProvider"]) + enc_names = [o.name for o in enc_sess.get_outputs()] + print(f"encode graph {ENC_GRAPH.name} outputs: {enc_names}") + + scratch = Path(args.scratch) + scratch.mkdir(parents=True, exist_ok=True) + if args.decode_graph: + dec_path = Path(args.decode_graph) + elif SHIPPED_DECODE.exists(): + dec_path = SHIPPED_DECODE + else: + dec_path = scratch / "aeic_entropy_decode_record_fp32.onnx" + if not dec_path.exists(): + print(f"exporting decode-side recording graph -> {dec_path}") + mod = DecodeSideAll(codec, y_h, y_w, z_offset).eval() + with torch.no_grad(): + torch.onnx.export( + mod, + (torch.zeros(z_shape), torch.zeros(y_shape)), + str(dec_path), + input_names=["z_q", "base"], output_names=DEC_OUT_NAMES, + opset_version=17, do_constant_folding=True, dynamo=False) + print(f" decode graph {dec_path.name} " + f"{dec_path.stat().st_size / 2**20:.1f} MB") + dec_sess = ort.InferenceSession(str(dec_path), so, + providers=["CPUExecutionProvider"]) + dec_inputs = [i.name for i in dec_sess.get_inputs()] + dec_outputs = [o.name for o in dec_sess.get_outputs()] + print(f" decode graph inputs {dec_inputs} outputs {dec_outputs}") + if "stage" in dec_inputs: + dec = OrtShippedDecodeSide(dec_sess, y_shape, z_shape) + else: + dec = OrtDecodeSide(dec_sess, y_shape, z_shape) + + # PyTorch reference module, only to prove the ONNX encode graph still + # matches torch on these images (cheap, and it catches a stale graph). + ref = EntropySide(codec, y_h, y_w, z_offset).eval() + + golden_dir = ROOT / "results" / "golden" / "vectors" + written = [] + for path in images: + stem = Path(path).stem + x = R.load_image(path, size=args.size) + xnp = x.cpu().numpy() + + enc = dict(zip(enc_names, enc_sess.run(None, {"image": xnp}))) + with torch.no_grad(): + t_out = ref(x) + tref = {n: v.cpu().numpy() for n, v in zip(ENC_NAMES, t_out)} + # Only the INTEGERS have to match torch: ~99% of the float tensors + # differ between runtimes and that is fine (see results/bitexact_encoder.md). + # For the scales, the integer that matters is my_build_indexes(scales). + torch_match = ( + np.array_equal(enc["z_q"], tref["z_q"]) + and all(np.array_equal(enc[f"yq{i}"], tref[f"yq{i}"]) for i in range(4)) + and all(np.array_equal( + build_indexes(codec, sequeeze(enc[f"sc{i}"])), + build_indexes(codec, sequeeze(tref[f"sc{i}"]))) for i in range(4))) + + stream, sym, idx = build_stream( + codec, enc["z_q"].reshape(-1).copy(), z_indexes, + [torch.from_numpy(enc[f"yq{i}"]) for i in range(4)], + [torch.from_numpy(enc[f"sc{i}"]) for i in range(4)]) + + golden = golden_dir / f"{stem}.bin" + golden_match = None + if golden.exists(): + golden_match = (golden.read_bytes() == stream) + + # --- decode replay, recording every seam call ------------------- + rec = Recording(meta={ + "format": "aeic-entropy-e2e-recording", + "version": VERSION, + "image": Path(path).name, + "stem": stem, + "checkpoint": args.ckpt, + "size": args.size, + "y_shape": list(y_shape), + "z_shape": list(z_shape), + "squeezed_shape": [1, codec.y_channel // 4, y_h, y_w], + "encode_graph": ENC_GRAPH.name, + "encode_graph_sha256": _sha(ENC_GRAPH), + "decode_graph": dec_path.name, + "decode_graph_sha256": _sha(dec_path), + "z_cdf_group": int(codec.z_cdf_group_index), + "y_cdf_group": int(codec.y_cdf_group_index), + "cdf_table": "aeic_cdf_ft32.bin", + "byte_order": "little", + }) + for n in ENC_NAMES: + rec.put(f"enc/{n}", enc[n]) + rec.put("enc/bitstream", np.frombuffer(stream, dtype=np.uint8)) + rec.put("enc/z_indexes", z_indexes.reshape(-1).numpy().astype(np.int16)) + rec.put("enc/z_symbols", + np.asarray(enc["z_q"], dtype=np.int16).reshape(-1)) + for i in range(4): + rec.put(f"enc/symbols{i}", np.asarray(sym[i], dtype=np.int16)) + rec.put(f"enc/indexes{i}", np.asarray(idx[i], dtype=np.int16)) + + def record(k, kind, stage, ins, outs): + e = {"index": k, "kind": kind, "stage": stage, + "inputs": {}, "outputs": {}} + for kk, v in ins.items(): + e["inputs"][kk] = rec.put(f"dec/call{k}/in/{kk}", np.asarray(v)) + for kk, v in outs.items(): + e["outputs"][kk] = rec.put(f"dec/call{k}/out/{kk}", + np.asarray(v, dtype=np.float32)) + rec.calls.append(e) + + codec.entropy_coder.set_stream(stream) + y_hat_dec = decode_loop(codec, dec, masks_np, codec.entropy_coder, + z_indexes.reshape(-1), z_shape, record=record) + rec.put("dec/y_hat", y_hat_dec.astype(np.float32)) + rec.meta["bitstream_bytes"] = len(stream) + rec.meta["bitstream_sha256"] = hashlib.sha256(stream).hexdigest() + rec.meta["encode_graph_matches_torch_symbols"] = bool(torch_match) + rec.meta["golden_vector_match"] = golden_match + rec.meta["decoded_y_hat_equals_encoder_y_hat"] = bool( + np.array_equal(y_hat_dec, enc["y_hat"])) + rec.meta["decoded_y_hat_max_abs_diff"] = float( + np.abs(y_hat_dec.astype(np.float64) + - enc["y_hat"].astype(np.float64)).max()) + + dst = OUT_DIR / f"{stem}.aeicrec" + nbytes = rec.write(dst) + written.append(dst) + print(f" {stem:<10} stream={len(stream)}B golden={golden_match} " + f"torch_sym={torch_match} " + f"y_hat_exact={rec.meta['decoded_y_hat_equals_encoder_y_hat']} " + f"(max {rec.meta['decoded_y_hat_max_abs_diff']:.3g}) " + f"-> {dst.name} {nbytes/2**20:.2f} MB", flush=True) + + # index file so a Dart test can enumerate fixtures without a directory scan + manifest = {"format": "aeic-entropy-e2e-recording", "version": VERSION, + "checkpoint": args.ckpt, "size": args.size, + "files": [{"file": p.name, + "bytes": p.stat().st_size, + "sha256": hashlib.sha256(p.read_bytes()).hexdigest()} + for p in written]} + (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=1)) + print(f"wrote {OUT_DIR}/manifest.json") + + print("\n=== verifying recordings from disk ===") + verify_only() + + +def verify_only(): + """Reload every recording and prove it round-trips through the C++ coder.""" + net, _ = R.load_model(ckpt="AEIC_SE_ft32.pkl") + codec = net.codec + codec.update(force=True) + ok_all = True + for path in sorted(OUT_DIR.glob("*.aeicrec")): + index, t = read_recording(path) + meta = index["meta"] + stream = t["enc/bitstream"].tobytes() + + # 1) recorded encode tensors -> bitstream + s2, sym2, idx2 = build_stream( + codec, t["enc/z_q"].reshape(-1).astype(np.float32).copy(), + torch.from_numpy(t["enc/z_indexes"].astype(np.int32)).reshape( + meta["z_shape"]), + [torch.from_numpy(t[f"enc/yq{i}"].copy()) for i in range(4)], + [torch.from_numpy(t[f"enc/sc{i}"].copy()) for i in range(4)]) + enc_ok = (s2 == stream) + sym_ok = all(np.array_equal(np.asarray(sym2[i], dtype=np.int16), + t[f"enc/symbols{i}"]) for i in range(4)) + idx_ok = all(np.array_equal(np.asarray(idx2[i], dtype=np.int16), + t[f"enc/indexes{i}"]) for i in range(4)) + + # 2) recorded decode tensors -> same symbols, same y_hat + masks = codec.get_mask_four_parts(1, codec.y_channel, + meta["y_shape"][2], meta["y_shape"][3], + device="cpu") + masks_np = [m.numpy().astype(np.float32) for m in masks] + calls = index["calls"] + + class Replay: + def hyper(self, z_q): + assert np.array_equal(z_q, t[calls[0]["inputs"]["z_q"]]) + return t[calls[0]["outputs"]["base0"]] + + def stage(self, i, base): + c = calls[1 + i] + assert np.array_equal(base, t[c["inputs"]["base"]]), \ + f"{path.name}: stage {i} base input drifted" + return t[c["outputs"]["means"]], t[c["outputs"]["scales"]] + + codec.entropy_coder.set_stream(stream) + y_hat = decode_loop( + codec, Replay(), masks_np, codec.entropy_coder, + torch.from_numpy(t["enc/z_indexes"].astype(np.int32)), + tuple(meta["z_shape"])) + dec_ok = np.array_equal(y_hat, t["dec/y_hat"]) + + ok = enc_ok and sym_ok and idx_ok and dec_ok + ok_all &= ok + print(f" {path.name:<22} {path.stat().st_size/2**20:5.2f} MB " + f"encode->bitstream={enc_ok} symbols={sym_ok} indexes={idx_ok} " + f"decode_replay_y_hat={dec_ok} " + f"golden={meta.get('golden_vector_match')} {'OK' if ok else 'FAIL'}") + print("ALL RECORDINGS VERIFIED" if ok_all else "VERIFICATION FAILED") + return 0 if ok_all else 1 + + +CONTAINER_DOC = """ +.aeicrec container (little-endian throughout) + + 0 8 magic b"AEICREC1" + 8 4 uint32 version = 1 + 12 4 uint32 flags = 0 + 16 8 uint64 index_offset (byte offset of the JSON index) + 24 4 uint32 index_length (bytes of the JSON index) + 28 4 uint32 reserved = 0 + 32 .. tensor blob, every tensor 8-byte aligned, C order + index_offset .. +index_length UTF-8 JSON index + +JSON index: + {"meta": {...}, "calls": [...], "entries": + [{"name":..., "dtype":"f32"|"i32"|"i16"|"u8", "shape":[...], + "offset":, "length":}, ...]} + +Dart: read the 32-byte header, jsonDecode the index, then for f32 entries use +ByteData/Float32List.view(buffer, offset, length ~/ 4) -- offsets are 8-byte +aligned so the typed-data views are always legal. +""" + +if __name__ == "__main__": + sys.exit(main() or 0) diff --git a/untranslated.json b/untranslated.json index f42fd2c3..607aa788 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,311 +1,1373 @@ { "bg": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "de": [ - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "es": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "fr": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "hu": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "it": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "ja": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "ko": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "nl": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "pl": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "pt": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "ru": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "sk": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "sl": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "sv": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "uk": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ], "zh": [ - "settings_regionSettings", - "settings_regionSettingsSubtitle", - "settings_regionManagement_screenTitle", - "settings_regionNameHint", - "settings_regionAddRegion", - "settings_regionFetchRegions", - "settings_regionFetchRegionsFail", - "settings_regionFetchRegionsAlreadyExists", - "settings_regionName", - "settings_regionDeleted", - "settings_deleteRegion", - "settings_deleteRegionConfirm", - "channels_regionSetTo", - "channels_regionNotSet", - "channels_regionSelect_Title", - "channels_clearRegion" + "messageStatus_failedChannel", + "messageStatus_resending", + "messageStatus_hopsNotReached", + "messageStatus_sentChannel", + "messageStatus_sentDirect", + "messageStatus_heardRepeatedCount", + "settings_regionEmptyExplanation", + "settings_regionFetchFromRepeaters", + "settings_regionDefault", + "settings_regionDefaultSubtitle", + "settings_regionDefaultNone", + "settings_telemetryPerContactHint", + "settings_multiAckSubtitle", + "settings_presetCustom", + "settings_radioMatchWarning", + "settings_txPowerRangeHelper", + "settings_clientRepeatFrequencyNote", + "settings_pathHashModeHelper", + "settings_requiresFirmware", + "appSettings_channelMinHops", + "appSettings_channelMinHopsSubtitle", + "appSettings_channelMinHopsCount", + "appSettings_channelMinHopsRetries", + "appSettings_batteryOptimization", + "appSettings_batteryOptimizationSubtitle", + "contacts_removeFromContacts", + "contacts_removeFromContactsConfirm", + "contacts_keepChatHistory", + "contacts_remove", + "contacts_discoveredNearby", + "contacts_noContactsDiscoveredHint", + "channels_hashtag", + "channels_addSectionJoin", + "channels_addSectionCreate", + "channels_dragToReorder", + "channels_regionDefaultSuffix", + "channels_regionSelectExplanation", + "channels_regionEmpty", + "channels_manageRegions", + "chat_removeGif", + "chat_cancelReply", + "chat_viewPathOnMap", + "chat_today", + "chat_yesterday", + "map_centerOnMe", + "map_noNodesLocationHint", + "map_clusterNodes", + "map_groupChip", + "map_clusterNodesSubtitle", + "map_manageServer", + "login_showPassword", + "login_hidePassword", + "login_advanced", + "common_clearSearch", + "repeater_roleAdmin", + "repeater_roleGuest", + "repeater_refreshAll", + "repeater_settingsNotLoaded", + "repeater_settingsLoadIncomplete", + "contacts_scanQrCode", + "contacts_scanQrInstructions", + "contacts_qrFromGallery", + "contacts_noQrCodeFound", + "contacts_qrGalleryFailed", + "snrIndicator_nearByRepeatersDescription", + "radioStats_sectionSignal", + "radioStats_sectionAirtime", + "imageSend_lossyNote", + "imageSend_viewOriginal", + "imageSend_viewReconstruction", + "imageSend_reconstructionUnavailable", + "imageSend_modelNotDownloaded", + "receivedImage_save", + "receivedImage_shareCaption", + "receivedImage_packetInfo", + "receivedImage_parityRecovered", + "receivedImage_decodeTime", + "receivedImage_saveFailed" ] } diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index cd4fc19b..d321cc51 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,13 +6,19 @@ #include "generated_plugin_registrant.h" +#include #include +#include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); FlutterBluePlusPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterBluePlusPlugin")); + FlutterOnnxruntimePluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterOnnxruntimePlugin")); SharePlusWindowsPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); UrlLauncherWindowsRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index f02857f4..ae56b7cf 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,7 +3,9 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows flutter_blue_plus_winrt + flutter_onnxruntime share_plus url_launcher_windows ) @@ -11,6 +13,7 @@ list(APPEND FLUTTER_PLUGIN_LIST list(APPEND FLUTTER_FFI_PLUGIN_LIST flserial flutter_local_notifications_windows + jni ) set(PLUGIN_BUNDLED_LIBRARIES)