diff --git a/documentation/contacts.md b/documentation/contacts.md index 00fc01e5..69559665 100644 --- a/documentation/contacts.md +++ b/documentation/contacts.md @@ -23,15 +23,18 @@ The Contacts screen is the primary hub for managing mesh nodes your radio has a Each contact is displayed as a list tile showing: - **Avatar**: Color-coded circle with type icon (or first emoji of the contact's name if it starts with one) -- **Name**: Contact name (single line) +- **Name**: Contact name on its own line, wrapping to a second line if it's long +- **Favorite star**: Amber star icon after the name if favorited +- **Location pin**: Grey pin icon after the name if the contact has GPS coordinates +- **Key prefix**: The contact's routing hash (public-key prefix) in a small badge, for matching against hops in paths - **Path label**: "Direct", "N hops", or "Flood" (with forced variants if a path override is active) -- **Public key**: Shortened hex format `` -- **Unread badge**: Red pill with count (if unread messages exist) -- **Last seen**: Relative timestamp ("Now", "5 mins ago", "2 hours ago", "3 days ago"). For chat contacts, this shows whichever is more recent: the last advertisement time or the last message time -- **Favorite star**: Amber star icon if favorited -- **Location pin**: Grey pin icon if the contact has GPS coordinates +- **Last seen**: Relative time at the end of the second line ("recently", "~ 5 min.", "~ 2 hours", "~ 3 days"). It shows whichever is most recent: the last advertisement or telemetry location update, or for chat contacts the last message +- **Unread badge**: Red pill with count at the right edge (if unread messages exist) +- **Manage button**: Shield icon at the right edge for repeaters and rooms -Pull-to-refresh re-fetches the full contact list from the device. +The **Discovered nearby** row at the top of the list opens the Discovery screen and scrolls with the list. + +Pull-to-refresh re-fetches the full contact list from the device. Telemetry locations survive the refresh until the node sends a newer advert. ## Search and Filter diff --git a/documentation/map-and-location.md b/documentation/map-and-location.md index 634235ef..ca3acfa4 100644 --- a/documentation/map-and-location.md +++ b/documentation/map-and-location.md @@ -79,10 +79,24 @@ In a mesh network, every message hops through one or more repeaters on its way t Standard pinch-to-zoom (range 2–18). Initial camera position is calculated from the statistical spread of all plotted points. ### Tap on a Node Marker -Opens a dialog showing: type, path (hop chain), coordinates, last-seen time, and public key. Action buttons vary by type: +Opens a card at the bottom of the map showing the node's status, type, last-seen time, path, node ID, and coordinates, with buttons to center on the node or close the card. Action buttons vary by type: - **Chat nodes**: "Open Chat" - **Repeaters**: "Manage Repeater" -- **Rooms**: "Join Room" +- **Rooms**: "Join Room" and "Manage Server" +- **Chat nodes and sensors in your contacts**: "Update location" (see below) +- **All nodes**: "Details" opens the full node info sheet + +### Update Location +**Update location** asks the node for its telemetry. If the reply includes a GPS position, the marker moves there right away and the last-seen time updates; a snackbar confirms it. You can also refresh a node's position from its Telemetry screen: any telemetry reply with a GPS position updates the map the same way. + +The node decides whether to include its position: +- **Companion radios** only include a position if they have a working GPS module and their owner allows location in telemetry, for everyone or only for favourites (**Settings → Privacy → Telemetry Location Mode**). A companion without GPS hardware never sends one, even if its adverts carry a manually set location. The app then says the node replied without a location. +- **Sensors** include their position (if they have GPS) for any client they accept, including guests. A sensor only answers clients it knows, so you may need to log in to it first. +- **Repeaters and rooms** only send their position to logged-in admins, so the button isn't shown for them. Their position normally comes from their adverts. + +If the node doesn't answer before the request times out, the app says there was no reply. The node has to be in your contacts (not only discovered) for the button to appear. + +A telemetry position stays on the map until the node sends a newer advert, which then replaces it. Refreshing or re-syncing the contact list from the radio keeps it. ### Long-Press on Empty Map Area Shows a bottom sheet with: @@ -201,6 +215,7 @@ The phone's own GPS is **never used**. All location data comes from the mesh: 1. **Device self-location**: Read from firmware device-info response. Set manually in Settings → Location, or updated automatically if the device has a GPS module. 2. **Remote node locations**: Extracted from advertisement packets received over the mesh. Encoded as integer lat/lon × 1,000,000. +3. **Telemetry replies**: A GPS position in a node's telemetry (from **Update location** or the Telemetry screen) replaces its advert position until the node adverts again. Telemetry positions have about 11 m precision (Cayenne LPP). ## Regions and offline use diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 0784a1ed..c12dca7c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -810,6 +810,82 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Applies a GPS fix from a telemetry reply to the contact so the map and + /// lists show where the node is now, not where its last advert put it. + /// [lastSeen] is left alone: it is the node's advert timestamp, which path + /// and flag writes send back to the radio. + void updateContactLocationFromTelemetry( + String contactKeyHex, + double latitude, + double longitude, + ) { + final index = _contacts.indexWhere((c) => c.publicKeyHex == contactKeyHex); + if (index < 0) return; + final updated = _contacts[index].copyWith( + latitude: latitude, + longitude: longitude, + telemetryFixAt: DateTime.now(), + ); + if (!updated.hasLocation) return; + _contacts[index] = updated; + notifyListeners(); + unawaited(_persistContacts()); + } + + /// Carries [previous]'s telemetry fix onto [incoming], a record the radio + /// just returned, while it still holds the advert that fix superseded. A + /// newer advert (by the node's own clock) wins. + Contact? _withTelemetryFix(Contact previous, Contact incoming) { + final fixAt = previous.telemetryFixAt; + if (fixAt == null || incoming.lastSeen.isAfter(previous.lastSeen)) { + return null; + } + return incoming.copyWith( + latitude: previous.latitude, + longitude: previous.longitude, + telemetryFixAt: fixAt, + ); + } + + /// Merges a contact record from the radio (contact list or advert) into the + /// one we already hold, keeping the user's path choice and any telemetry + /// fix still newer than the radio's advert. + Contact _mergeRefreshedContact( + Contact existing, + Contact incoming, { + bool keepLocationWhenMissing = false, + }) { + final mergedLastMessageAt = + existing.lastMessageAt.isAfter(incoming.lastMessageAt) + ? existing.lastMessageAt + : incoming.lastMessageAt; + final base = incoming.copyWith( + lastMessageAt: mergedLastMessageAt, + pathOverride: existing.pathOverride, // Preserve user's path choice + pathOverrideBytes: existing.pathOverrideBytes, + latitude: keepLocationWhenMissing + ? incoming.latitude ?? existing.latitude + : incoming.latitude, + longitude: keepLocationWhenMissing + ? incoming.longitude ?? existing.longitude + : incoming.longitude, + clearTelemetryFix: true, + ); + return _withTelemetryFix(existing, base) ?? base; + } + + /// Telemetry fixes held across a full contact sync, which clears the list + /// before the radio resends it. + final Map _telemetryFixesDuringSync = {}; + + void _stashTelemetryFixes() { + for (final c in _contacts) { + if (c.telemetryFixAt != null) { + _telemetryFixesDuringSync[c.publicKeyHex] = c; + } + } + } + String _batteryChemistryForDevice() { final deviceId = batteryDeviceKey; if (deviceId == null || _appSettingsService == null) return 'nmc'; @@ -4226,6 +4302,7 @@ class MeshCoreConnector extends ChangeNotifier { _contactSyncUsesSinceFilter = since != null; if (!preserveExisting) { _hasLoadedContacts = false; + _stashTelemetryFixes(); _contacts.clear(); } _armContactSyncWatchdog(); @@ -6021,6 +6098,7 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeContactsStart: debugPrint('Got CONTACTS_START'); if (!_preserveContactsOnRefresh) { + _stashTelemetryFixes(); _contacts.clear(); } _isLoadingContacts = true; @@ -6096,6 +6174,7 @@ class MeshCoreConnector extends ChangeNotifier { } _hasLoadedContacts = true; _preserveContactsOnRefresh = false; + _telemetryFixesDuringSync.clear(); _contactSyncUsesSinceFilter = false; unawaited(updateKnownDiscovered()); notifyListeners(); @@ -6861,10 +6940,6 @@ class MeshCoreConnector extends ChangeNotifier { if (existingIndex >= 0) { final existing = _contacts[existingIndex]; - final mergedLastMessageAt = - existing.lastMessageAt.isAfter(contact.lastMessageAt) - ? existing.lastMessageAt - : contact.lastMessageAt; appLogger.info( 'Refreshing contact ${contact.name}: devicePath=${contact.pathLength}, existingOverride=${existing.pathOverride}', @@ -6873,12 +6948,10 @@ class MeshCoreConnector extends ChangeNotifier { // Preserve user-selected path settings and previously known GPS when // refreshed frames omit coordinates (lat/lon encoded as 0,0). - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, - latitude: contact.latitude ?? existing.latitude, - longitude: contact.longitude ?? existing.longitude, + _contacts[existingIndex] = _mergeRefreshedContact( + existing, + contact, + keepLocationWhenMissing: true, ); appLogger.info( @@ -6886,7 +6959,12 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); } else { - _contacts.add(contact); + // A full sync cleared the list; restore a telemetry fix it held. + final stashed = _telemetryFixesDuringSync.remove(contact.publicKeyHex); + _contacts.add( + (stashed == null ? null : _withTelemetryFix(stashed, contact)) ?? + contact, + ); appLogger.info( 'Added new contact ${contact.name}: pathLen=${contact.pathLength}', tag: 'Connector', @@ -6945,10 +7023,6 @@ class MeshCoreConnector extends ChangeNotifier { if (existingIndex >= 0) { final existing = _contacts[existingIndex]; - final mergedLastMessageAt = - existing.lastMessageAt.isAfter(contact.lastMessageAt) - ? existing.lastMessageAt - : contact.lastMessageAt; appLogger.info( 'Refreshing contact ${contact.name}: devicePath=${contact.pathLength}, existingOverride=${existing.pathOverride}', @@ -6956,11 +7030,7 @@ class MeshCoreConnector extends ChangeNotifier { ); // CRITICAL: Preserve user's path override when contact is refreshed from device - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, - ); + _contacts[existingIndex] = _mergeRefreshedContact(existing, contact); appLogger.info( 'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_contacts[existingIndex].pathLength}', diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index 41acba45..8a4752d7 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -77,6 +77,7 @@ class LinkHandler { final shouldOpen = await showDialog( context: context, builder: (context) => AlertDialog( + scrollable: true, title: Text(context.l10n.chat_openLink), content: Column( mainAxisSize: MainAxisSize.min, diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 31faa683..1e65d44c 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3301,6 +3301,10 @@ "map_youWithMarkers": "Вие и {count} маркера", "map_sharedMarkerSemantics": "Споделен маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Обнови местоположението", + "map_locationUpdated": "Местоположението е обновено", + "map_locationNotShared": "{name} отговори без местоположение", + "map_locationRequestFailed": "Няма отговор от {name}", "mapCache_zoomLevel": "Мащаб {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 34f6e580..16f1c302 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3436,6 +3436,10 @@ "map_youWithMarkers": "Du und {count} Marker", "map_sharedMarkerSemantics": "Geteilter Marker: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Standort aktualisieren", + "map_locationUpdated": "Standort aktualisiert", + "map_locationNotShared": "{name} hat ohne Standort geantwortet", + "map_locationRequestFailed": "Keine Antwort von {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e1a0c35d..01d38be4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3455,6 +3455,12 @@ "@map_sharedMarkerSemantics": {"placeholders": {"label": {"type": "String"}}}, "map_nodeMarkerSemantics": "{name}, {type}, {status}", "@map_nodeMarkerSemantics": {"placeholders": {"name": {"type": "String"}, "type": {"type": "String"}, "status": {"type": "String"}}}, + "map_requestLocation": "Update location", + "map_locationUpdated": "Location updated", + "map_locationNotShared": "{name} replied without a location", + "@map_locationNotShared": {"placeholders": {"name": {"type": "String"}}}, + "map_locationRequestFailed": "No reply from {name}", + "@map_locationRequestFailed": {"placeholders": {"name": {"type": "String"}}}, "mapCache_zoomLevel": "Zoom {zoom}", "@mapCache_zoomLevel": {"placeholders": {"zoom": {"type": "int"}}}, "mapCache_sizeBytes": "{size} B", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index a435a366..cbf53be7 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Tú y {count} marcadores", "map_sharedMarkerSemantics": "Marcador compartido: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Actualizar ubicación", + "map_locationUpdated": "Ubicación actualizada", + "map_locationNotShared": "{name} respondió sin ubicación", + "map_locationRequestFailed": "Sin respuesta de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index a6a75dd0..72e9b92f 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Vous et {count} marqueurs", "map_sharedMarkerSemantics": "Marqueur partagé : {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Actualiser la position", + "map_locationUpdated": "Position actualisée", + "map_locationNotShared": "{name} a répondu sans position", + "map_locationRequestFailed": "Aucune réponse de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} o", "mapCache_sizeKilobytes": "{size} Ko", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 08adc56d..fe2e8760 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3340,6 +3340,10 @@ "map_youWithMarkers": "Ön és {count} jelölő", "map_sharedMarkerSemantics": "Megosztott jelölő: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Hely frissítése", + "map_locationUpdated": "Hely frissítve", + "map_locationNotShared": "{name} helyadat nélkül válaszolt", + "map_locationRequestFailed": "Nincs válasz tőle: {name}", "mapCache_zoomLevel": "Nagyítás: {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 20b61e49..29f5323a 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Tu e {count} segnaposti", "map_sharedMarkerSemantics": "Segnaposto condiviso: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Aggiorna posizione", + "map_locationUpdated": "Posizione aggiornata", + "map_locationNotShared": "{name} ha risposto senza posizione", + "map_locationRequestFailed": "Nessuna risposta da {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 525ceac7..af3e173b 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "自分と{count}件のマーカー", "map_sharedMarkerSemantics": "共有マーカー: {label}", "map_nodeMarkerSemantics": "{name}、{type}、{status}", + "map_requestLocation": "位置情報を更新", + "map_locationUpdated": "位置情報を更新しました", + "map_locationNotShared": "{name} は位置情報なしで応答しました", + "map_locationRequestFailed": "{name} から応答がありません", "mapCache_zoomLevel": "ズーム {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 21b017ac..f0d9a4e2 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "나와 마커 {count}개", "map_sharedMarkerSemantics": "공유 마커: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "위치 업데이트", + "map_locationUpdated": "위치가 업데이트되었습니다", + "map_locationNotShared": "{name}이(가) 위치 없이 응답했습니다", + "map_locationRequestFailed": "{name}의 응답이 없습니다", "mapCache_zoomLevel": "줌 {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4a309227..2e999b8c 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -10238,6 +10238,30 @@ abstract class AppLocalizations { /// **'{name}, {type}, {status}'** String map_nodeMarkerSemantics(String name, String type, String status); + /// No description provided for @map_requestLocation. + /// + /// In en, this message translates to: + /// **'Update location'** + String get map_requestLocation; + + /// No description provided for @map_locationUpdated. + /// + /// In en, this message translates to: + /// **'Location updated'** + String get map_locationUpdated; + + /// No description provided for @map_locationNotShared. + /// + /// In en, this message translates to: + /// **'{name} replied without a location'** + String map_locationNotShared(String name); + + /// No description provided for @map_locationRequestFailed. + /// + /// In en, this message translates to: + /// **'No reply from {name}'** + String map_locationRequestFailed(String name); + /// No description provided for @mapCache_zoomLevel. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 11561b05..77a7d5fe 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -6083,6 +6083,22 @@ class AppLocalizationsBg extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Обнови местоположението'; + + @override + String get map_locationUpdated => 'Местоположението е обновено'; + + @override + String map_locationNotShared(String name) { + return '$name отговори без местоположение'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Няма отговор от $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Мащаб $zoom'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index c6b5c63e..97bb05dc 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -6097,6 +6097,22 @@ class AppLocalizationsDe extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Standort aktualisieren'; + + @override + String get map_locationUpdated => 'Standort aktualisiert'; + + @override + String map_locationNotShared(String name) { + return '$name hat ohne Standort geantwortet'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Keine Antwort von $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 586a9b1c..fcbdda5a 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -5998,6 +5998,22 @@ class AppLocalizationsEn extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Update location'; + + @override + String get map_locationUpdated => 'Location updated'; + + @override + String map_locationNotShared(String name) { + return '$name replied without a location'; + } + + @override + String map_locationRequestFailed(String name) { + return 'No reply from $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 5a81f399..95cbe0b3 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -6087,6 +6087,22 @@ class AppLocalizationsEs extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Actualizar ubicación'; + + @override + String get map_locationUpdated => 'Ubicación actualizada'; + + @override + String map_locationNotShared(String name) { + return '$name respondió sin ubicación'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Sin respuesta de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index e69000f7..1d9aa184 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -6110,6 +6110,22 @@ class AppLocalizationsFr extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Actualiser la position'; + + @override + String get map_locationUpdated => 'Position actualisée'; + + @override + String map_locationNotShared(String name) { + return '$name a répondu sans position'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Aucune réponse de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 1e5a433e..d214bf44 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -6075,6 +6075,22 @@ class AppLocalizationsHu extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Hely frissítése'; + + @override + String get map_locationUpdated => 'Hely frissítve'; + + @override + String map_locationNotShared(String name) { + return '$name helyadat nélkül válaszolt'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Nincs válasz tőle: $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Nagyítás: $zoom'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index cf90297e..c86a6c9e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -6093,6 +6093,22 @@ class AppLocalizationsIt extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Aggiorna posizione'; + + @override + String get map_locationUpdated => 'Posizione aggiornata'; + + @override + String map_locationNotShared(String name) { + return '$name ha risposto senza posizione'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Nessuna risposta da $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 57043f48..2fc11840 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5799,6 +5799,22 @@ class AppLocalizationsJa extends AppLocalizations { return '$name、$type、$status'; } + @override + String get map_requestLocation => '位置情報を更新'; + + @override + String get map_locationUpdated => '位置情報を更新しました'; + + @override + String map_locationNotShared(String name) { + return '$name は位置情報なしで応答しました'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name から応答がありません'; + } + @override String mapCache_zoomLevel(int zoom) { return 'ズーム $zoom'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index e1eb65df..b68ed368 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5806,6 +5806,22 @@ class AppLocalizationsKo extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => '위치 업데이트'; + + @override + String get map_locationUpdated => '위치가 업데이트되었습니다'; + + @override + String map_locationNotShared(String name) { + return '$name이(가) 위치 없이 응답했습니다'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name의 응답이 없습니다'; + } + @override String mapCache_zoomLevel(int zoom) { return '줌 $zoom'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 55c59595..6e8d5a27 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -6053,6 +6053,22 @@ class AppLocalizationsNl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Locatie bijwerken'; + + @override + String get map_locationUpdated => 'Locatie bijgewerkt'; + + @override + String map_locationNotShared(String name) { + return '$name antwoordde zonder locatie'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Geen antwoord van $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index bbd9758b..376647e6 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -6117,6 +6117,22 @@ class AppLocalizationsPl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Zaktualizuj lokalizację'; + + @override + String get map_locationUpdated => 'Lokalizacja zaktualizowana'; + + @override + String map_locationNotShared(String name) { + return '$name odpowiedział bez lokalizacji'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Brak odpowiedzi od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index ee29d2b6..e1e839b9 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -6082,6 +6082,22 @@ class AppLocalizationsPt extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Atualizar localização'; + + @override + String get map_locationUpdated => 'Localização atualizada'; + + @override + String map_locationNotShared(String name) { + return '$name respondeu sem localização'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Sem resposta de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index dec6ceee..af5cf4cd 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -6104,6 +6104,22 @@ class AppLocalizationsRu extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Обновить местоположение'; + + @override + String get map_locationUpdated => 'Местоположение обновлено'; + + @override + String map_locationNotShared(String name) { + return '$name ответил без местоположения'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Нет ответа от $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Масштаб $zoom'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index fee4b155..663775a1 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -6066,6 +6066,22 @@ class AppLocalizationsSk extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Aktualizovať polohu'; + + @override + String get map_locationUpdated => 'Poloha aktualizovaná'; + + @override + String map_locationNotShared(String name) { + return '$name odpovedal bez polohy'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Žiadna odpoveď od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Priblíženie $zoom'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e42cbf0a..5eceb5df 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -6069,6 +6069,22 @@ class AppLocalizationsSl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Posodobi lokacijo'; + + @override + String get map_locationUpdated => 'Lokacija posodobljena'; + + @override + String map_locationNotShared(String name) { + return '$name je odgovoril brez lokacije'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Ni odgovora od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Povečava $zoom'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 4ed1fd88..c507128d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -6033,6 +6033,22 @@ class AppLocalizationsSv extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Uppdatera plats'; + + @override + String get map_locationUpdated => 'Platsen uppdaterad'; + + @override + String map_locationNotShared(String name) { + return '$name svarade utan plats'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Inget svar från $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 7fa20972..4647cb65 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -6107,6 +6107,22 @@ class AppLocalizationsUk extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Оновити геопозицію'; + + @override + String get map_locationUpdated => 'Геопозицію оновлено'; + + @override + String map_locationNotShared(String name) { + return '$name відповів без геопозиції'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Немає відповіді від $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Масштаб $zoom'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 68b6ea28..df3779a0 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5658,6 +5658,22 @@ class AppLocalizationsZh extends AppLocalizations { return '$name,$type,$status'; } + @override + String get map_requestLocation => '更新位置'; + + @override + String get map_locationUpdated => '位置已更新'; + + @override + String map_locationNotShared(String name) { + return '$name 回复中未包含位置'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name 没有回复'; + } + @override String mapCache_zoomLevel(int zoom) { return '缩放 $zoom'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index d2804e84..629e3a8f 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3202,6 +3202,10 @@ "map_youWithMarkers": "Jij en {count} markeringen", "map_sharedMarkerSemantics": "Gedeelde markering: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Locatie bijwerken", + "map_locationUpdated": "Locatie bijgewerkt", + "map_locationNotShared": "{name} antwoordde zonder locatie", + "map_locationRequestFailed": "Geen antwoord van {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index d4b46891..b78d70fd 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3334,6 +3334,10 @@ "map_youWithMarkers": "Ty i znaczniki: {count}", "map_sharedMarkerSemantics": "Udostępniony znacznik: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Zaktualizuj lokalizację", + "map_locationUpdated": "Lokalizacja zaktualizowana", + "map_locationNotShared": "{name} odpowiedział bez lokalizacji", + "map_locationRequestFailed": "Brak odpowiedzi od {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 40590afb..c123ddba 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3184,6 +3184,10 @@ "map_youWithMarkers": "Você e {count} marcadores", "map_sharedMarkerSemantics": "Marcador compartilhado: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Atualizar localização", + "map_locationUpdated": "Localização atualizada", + "map_locationNotShared": "{name} respondeu sem localização", + "map_locationRequestFailed": "Sem resposta de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 2771a68c..cdf1b5fc 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2598,6 +2598,10 @@ "map_youWithMarkers": "Вы и маркеров: {count}", "map_sharedMarkerSemantics": "Общий маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Обновить местоположение", + "map_locationUpdated": "Местоположение обновлено", + "map_locationNotShared": "{name} ответил без местоположения", + "map_locationRequestFailed": "Нет ответа от {name}", "mapCache_zoomLevel": "Масштаб {zoom}", "mapCache_sizeBytes": "{size} Б", "mapCache_sizeKilobytes": "{size} КБ", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index e8938a13..90a8c4d6 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3302,6 +3302,10 @@ "map_youWithMarkers": "Vy a značky: {count}", "map_sharedMarkerSemantics": "Zdieľaná značka: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Aktualizovať polohu", + "map_locationUpdated": "Poloha aktualizovaná", + "map_locationNotShared": "{name} odpovedal bez polohy", + "map_locationRequestFailed": "Žiadna odpoveď od {name}", "mapCache_zoomLevel": "Priblíženie {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 9148675c..5d9a18a2 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3185,6 +3185,10 @@ "map_youWithMarkers": "Vi in oznak: {count}", "map_sharedMarkerSemantics": "Deljena oznaka: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Posodobi lokacijo", + "map_locationUpdated": "Lokacija posodobljena", + "map_locationNotShared": "{name} je odgovoril brez lokacije", + "map_locationRequestFailed": "Ni odgovora od {name}", "mapCache_zoomLevel": "Povečava {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 9fd33f8f..0956dec1 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3179,6 +3179,10 @@ "map_youWithMarkers": "Du och {count} markörer", "map_sharedMarkerSemantics": "Delad markör: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Uppdatera plats", + "map_locationUpdated": "Platsen uppdaterad", + "map_locationNotShared": "{name} svarade utan plats", + "map_locationRequestFailed": "Inget svar från {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index ce219889..a017fc1f 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3281,6 +3281,10 @@ "map_youWithMarkers": "Ви та маркерів: {count}", "map_sharedMarkerSemantics": "Спільний маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Оновити геопозицію", + "map_locationUpdated": "Геопозицію оновлено", + "map_locationNotShared": "{name} відповів без геопозиції", + "map_locationRequestFailed": "Немає відповіді від {name}", "mapCache_zoomLevel": "Масштаб {zoom}", "mapCache_sizeBytes": "{size} Б", "mapCache_sizeKilobytes": "{size} КБ", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 51a8e2d3..0b627b1d 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3189,6 +3189,10 @@ "map_youWithMarkers": "你和 {count} 个标记", "map_sharedMarkerSemantics": "共享标记:{label}", "map_nodeMarkerSemantics": "{name},{type},{status}", + "map_requestLocation": "更新位置", + "map_locationUpdated": "位置已更新", + "map_locationNotShared": "{name} 回复中未包含位置", + "map_locationRequestFailed": "{name} 没有回复", "mapCache_zoomLevel": "缩放 {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 27a276ca..f37ddf60 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -22,6 +22,12 @@ class Contact { final bool isActive; final Uint8List? rawPacket; + /// When [latitude]/[longitude] came from a telemetry reply rather than the + /// advert, the phone time of that reply. [lastSeen] stays the node's advert + /// timestamp (it is written back to the radio), so a radio refresh carrying + /// the same advert keeps the fix and a newer advert replaces it. + final DateTime? telemetryFixAt; + Contact({ required this.publicKey, required this.name, @@ -39,6 +45,7 @@ class Contact { DateTime? lastMessageAt, this.isActive = true, this.rawPacket, + this.telemetryFixAt, }) : lastMessageAt = lastMessageAt ?? lastSeen; /// Cached: it backs ==, hashCode and the per-frame contact lookups, and @@ -85,6 +92,12 @@ class Contact { lon <= 180.0; } + /// The latest time we heard from the node: its advert or a telemetry fix. + DateTime get lastHeard { + final fixAt = telemetryFixAt; + return fixAt != null && fixAt.isAfter(lastSeen) ? fixAt : lastSeen; + } + bool get isFavorite => (flags & contactFlagFavorite) != 0; Contact copyWith({ @@ -105,6 +118,8 @@ class Contact { DateTime? lastModified, bool? isActive, Uint8List? rawPacket, + DateTime? telemetryFixAt, + bool clearTelemetryFix = false, }) { return Contact( publicKey: publicKey ?? this.publicKey, @@ -127,6 +142,9 @@ class Contact { lastModified: lastModified ?? this.lastModified, isActive: isActive ?? this.isActive, rawPacket: rawPacket ?? this.rawPacket, + telemetryFixAt: clearTelemetryFix + ? null + : (telemetryFixAt ?? this.telemetryFixAt), ); } diff --git a/lib/review_mode/review_mode_banner.dart b/lib/review_mode/review_mode_banner.dart index ff137d25..d58e30c3 100644 --- a/lib/review_mode/review_mode_banner.dart +++ b/lib/review_mode/review_mode_banner.dart @@ -26,46 +26,51 @@ class ReviewModeBanner extends StatelessWidget { minimumSize: const Size(48, 48), ); - return Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: const BoxDecoration( - color: MeshPalette.bg3, - border: Border(bottom: BorderSide(color: MeshPalette.warnLine)), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - const Icon(Icons.science, color: MeshPalette.warn, size: 24), - const SizedBox(width: 8), - Expanded(child: Text(l10n.reviewMode_banner, style: textStyle)), - ], - ), - Wrap( - spacing: 8, - children: [ - TextButton( - style: buttonStyle, - onPressed: () { - connector.sendReviewTestMessage(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(l10n.reviewMode_testSent)), - ); - }, - child: Text(l10n.reviewMode_sendTest), - ), - TextButton( - style: buttonStyle, - // The screens hosting the banner return to the Connect screen - // themselves once disconnected. - onPressed: () => connector.disconnect(manual: true), - child: Text(l10n.reviewMode_exit), - ), - ], - ), - ], + // A status strip on every main screen: capped so that at the largest + // text sizes it can't take over a small phone's screen. + return MediaQuery.withClampedTextScaling( + maxScaleFactor: 1.3, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: const BoxDecoration( + color: MeshPalette.bg3, + border: Border(bottom: BorderSide(color: MeshPalette.warnLine)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.science, color: MeshPalette.warn, size: 24), + const SizedBox(width: 8), + Expanded(child: Text(l10n.reviewMode_banner, style: textStyle)), + ], + ), + Wrap( + spacing: 8, + children: [ + TextButton( + style: buttonStyle, + onPressed: () { + connector.sendReviewTestMessage(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.reviewMode_testSent)), + ); + }, + child: Text(l10n.reviewMode_sendTest), + ), + TextButton( + style: buttonStyle, + // The screens hosting the banner return to the Connect screen + // themselves once disconnected. + onPressed: () => connector.disconnect(manual: true), + child: Text(l10n.reviewMode_exit), + ), + ], + ), + ], + ), ), ); } diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 75b556d4..c8418fdc 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -1418,56 +1418,58 @@ class AppSettingsScreen extends StatelessWidget { ) { showMeshSheet( context, - builder: (ctx) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader(title: context.l10n.appSettings_mapTimeFilter), - Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), - child: Text(context.l10n.appSettings_showNodesDiscoveredWithin), - ), - MeshSheetOption( - label: context.l10n.appSettings_allTime, - selected: settingsService.settings.mapTimeFilterHours == 0, - onTap: () { - settingsService.setMapTimeFilterHours(0); - Navigator.pop(ctx); - }, - ), - MeshSheetOption( - label: context.l10n.appSettings_lastHour, - selected: settingsService.settings.mapTimeFilterHours == 1, - onTap: () { - settingsService.setMapTimeFilterHours(1); - Navigator.pop(ctx); - }, - ), - MeshSheetOption( - label: context.l10n.appSettings_last6Hours, - selected: settingsService.settings.mapTimeFilterHours == 6, - onTap: () { - settingsService.setMapTimeFilterHours(6); - Navigator.pop(ctx); - }, - ), - MeshSheetOption( - label: context.l10n.appSettings_last24Hours, - selected: settingsService.settings.mapTimeFilterHours == 24, - onTap: () { - settingsService.setMapTimeFilterHours(24); - Navigator.pop(ctx); - }, - ), - MeshSheetOption( - label: context.l10n.appSettings_lastWeek, - selected: settingsService.settings.mapTimeFilterHours == 168, - onTap: () { - settingsService.setMapTimeFilterHours(168); - Navigator.pop(ctx); - }, - ), - SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), - ], + builder: (ctx) => SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader(title: context.l10n.appSettings_mapTimeFilter), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), + child: Text(context.l10n.appSettings_showNodesDiscoveredWithin), + ), + MeshSheetOption( + label: context.l10n.appSettings_allTime, + selected: settingsService.settings.mapTimeFilterHours == 0, + onTap: () { + settingsService.setMapTimeFilterHours(0); + Navigator.pop(ctx); + }, + ), + MeshSheetOption( + label: context.l10n.appSettings_lastHour, + selected: settingsService.settings.mapTimeFilterHours == 1, + onTap: () { + settingsService.setMapTimeFilterHours(1); + Navigator.pop(ctx); + }, + ), + MeshSheetOption( + label: context.l10n.appSettings_last6Hours, + selected: settingsService.settings.mapTimeFilterHours == 6, + onTap: () { + settingsService.setMapTimeFilterHours(6); + Navigator.pop(ctx); + }, + ), + MeshSheetOption( + label: context.l10n.appSettings_last24Hours, + selected: settingsService.settings.mapTimeFilterHours == 24, + onTap: () { + settingsService.setMapTimeFilterHours(24); + Navigator.pop(ctx); + }, + ), + MeshSheetOption( + label: context.l10n.appSettings_lastWeek, + selected: settingsService.settings.mapTimeFilterHours == 168, + onTap: () { + settingsService.setMapTimeFilterHours(168); + Navigator.pop(ctx); + }, + ), + SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), + ], + ), ), ); } @@ -1478,29 +1480,32 @@ class AppSettingsScreen extends StatelessWidget { ) { showMeshSheet( context, - builder: (ctx) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader(title: context.l10n.appSettings_unitsTitle), - MeshSheetOption( - label: context.l10n.appSettings_unitsMetric, - selected: settingsService.settings.unitSystem == UnitSystem.metric, - onTap: () { - settingsService.setUnitSystem(UnitSystem.metric); - Navigator.pop(ctx); - }, - ), - MeshSheetOption( - label: context.l10n.appSettings_unitsImperial, - selected: - settingsService.settings.unitSystem == UnitSystem.imperial, - onTap: () { - settingsService.setUnitSystem(UnitSystem.imperial); - Navigator.pop(ctx); - }, - ), - SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), - ], + builder: (ctx) => SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader(title: context.l10n.appSettings_unitsTitle), + MeshSheetOption( + label: context.l10n.appSettings_unitsMetric, + selected: + settingsService.settings.unitSystem == UnitSystem.metric, + onTap: () { + settingsService.setUnitSystem(UnitSystem.metric); + Navigator.pop(ctx); + }, + ), + MeshSheetOption( + label: context.l10n.appSettings_unitsImperial, + selected: + settingsService.settings.unitSystem == UnitSystem.imperial, + onTap: () { + settingsService.setUnitSystem(UnitSystem.imperial); + Navigator.pop(ctx); + }, + ), + SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8), + ], + ), ), ); } @@ -1917,6 +1922,7 @@ class _MapApiKeyDialogState extends State<_MapApiKeyDialog> { Widget build(BuildContext context) { final l10n = context.l10n; return AlertDialog( + scrollable: true, title: Text(l10n.appSettings_stadiaApiKey), content: SizedBox( width: 420, diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 06805668..97a16208 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1775,57 +1775,59 @@ class _ChannelChatScreenState extends State { showMeshSheet( context, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader( - title: l10n.receivedImage_awaiting( - entry.bitstreamByteCount, - entry.totalChunks, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: l10n.receivedImage_awaiting( + entry.bitstreamByteCount, + entry.totalChunks, + ), + subtitle: _imageSenderLabel(entry), ), - subtitle: _imageSenderLabel(entry), - ), - if (canSave) + 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.save_alt), - title: Text(l10n.receivedImage_save), + leading: const Icon(Icons.info_outline), + title: Text(l10n.receivedImage_packetInfo), onTap: () { Navigator.pop(sheetContext); - _saveImage(entry); + _showImagePacketInfo(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, + 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), + ); + }, ), - 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), - ], + const SizedBox(height: 8), + ], + ), ), ), ); @@ -1860,6 +1862,7 @@ class _ChannelChatScreenState extends State { showDialog( context: context, builder: (dialogContext) => AlertDialog( + scrollable: true, title: Text(l10n.receivedImage_packetInfo), content: Column( mainAxisSize: MainAxisSize.min, @@ -2234,109 +2237,111 @@ class _ChannelChatScreenState extends State { showMeshSheet( context, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader( - title: message.text.characters.length > 40 - ? '${message.text.characters.take(40)}…' - : message.text, - subtitle: message.senderName.isNotEmpty - ? message.senderName - : null, - ), - ListTile( - leading: const Icon(Icons.reply), - title: Text(context.l10n.chat_reply), - onTap: () { - Navigator.pop(sheetContext); - _setReplyingTo(message); - }, - ), - ListTile( - leading: const Icon(Icons.route), - title: Text(context.l10n.chat_path), - onTap: () { - Navigator.pop(sheetContext); - _showMessagePathInfo(message); - }, - ), - if (message.pathBytes.isNotEmpty) + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: message.text.characters.length > 40 + ? '${message.text.characters.take(40)}…' + : message.text, + subtitle: message.senderName.isNotEmpty + ? message.senderName + : null, + ), ListTile( - leading: const Icon(Icons.map_outlined), - title: Text(context.l10n.chat_viewPathOnMap), + leading: const Icon(Icons.reply), + title: Text(context.l10n.chat_reply), onTap: () { Navigator.pop(sheetContext); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ChannelMessagePathMapScreen( - message: message, - channelMessage: true, + _setReplyingTo(message); + }, + ), + ListTile( + leading: const Icon(Icons.route), + title: Text(context.l10n.chat_path), + onTap: () { + Navigator.pop(sheetContext); + _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) + ); + }, + ), + // Can't react to your own messages + if (!message.isOutgoing) + ListTile( + leading: const Icon(Icons.add_reaction_outlined), + title: Text(context.l10n.chat_addReaction), + onTap: () { + Navigator.pop(sheetContext); + _showEmojiPicker(message); + }, + ), ListTile( - leading: const Icon(Icons.add_reaction_outlined), - title: Text(context.l10n.chat_addReaction), + leading: const Icon(Icons.copy), + title: Text(context.l10n.common_copy), onTap: () { Navigator.pop(sheetContext); - _showEmojiPicker(message); + copyChatMessageText(context, message.text); }, ), - ListTile( - leading: const Icon(Icons.copy), - title: Text(context.l10n.common_copy), - onTap: () { - Navigator.pop(sheetContext); - copyChatMessageText(context, message.text); - }, - ), - if (canTranslateMessage) + if (canTranslateMessage) + ListTile( + leading: const Icon(Icons.translate), + title: Text(context.l10n.translation_translateMessage), + onTap: () { + Navigator.pop(sheetContext); + unawaited( + context.read().translateChannelMessage( + widget.channel.index, + message, + manualTranslation: true, + ), + ); + }, + ), + if (!message.isOutgoing) + ListTile( + leading: const Icon(Icons.mark_chat_unread_outlined), + title: Text(context.l10n.chat_markAsUnread), + onTap: () { + Navigator.pop(sheetContext); + _markAsUnread(message); + }, + ), + const Divider(height: 1), ListTile( - leading: const Icon(Icons.translate), - title: Text(context.l10n.translation_translateMessage), - onTap: () { + leading: Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + title: Text( + context.l10n.common_delete, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + onTap: () async { Navigator.pop(sheetContext); - unawaited( - context.read().translateChannelMessage( - widget.channel.index, - message, - manualTranslation: true, - ), - ); + await _deleteMessage(message); }, ), - if (!message.isOutgoing) - ListTile( - leading: const Icon(Icons.mark_chat_unread_outlined), - title: Text(context.l10n.chat_markAsUnread), - onTap: () { - Navigator.pop(sheetContext); - _markAsUnread(message); - }, - ), - const Divider(height: 1), - ListTile( - leading: Icon( - Icons.delete_outline, - color: Theme.of(context).colorScheme.error, - ), - title: Text( - context.l10n.common_delete, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - onTap: () async { - Navigator.pop(sheetContext); - await _deleteMessage(message); - }, - ), - const SizedBox(height: 8), - ], + const SizedBox(height: 8), + ], + ), ), ), ); diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index f8c4daf9..01e8cd47 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -631,56 +631,58 @@ class _ChannelsScreenState extends State showMeshSheet( parentContext, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - leading: const Icon(Icons.edit_outlined), - title: Text(sheetContext.l10n.channels_editChannel), - onTap: () async { - Navigator.pop(sheetContext); - await Future.delayed(const Duration(milliseconds: 100)); - if (parentContext.mounted) { - _showEditChannelDialog(parentContext, connector, channel); - } - }, - ), - // Notification mode selection - ListTile( - leading: const Icon(Icons.notifications_outlined), - title: Text(sheetContext.l10n.channels_notificationSettings), - trailing: const Icon(Icons.chevron_right), - onTap: () async { - Navigator.pop(sheetContext); - await Future.delayed(const Duration(milliseconds: 100)); - if (parentContext.mounted) { - showChannelNotificationModeSheet( - parentContext, - channel.muteKey, - ); - } - }, - ), - ListTile( - leading: Icon( - Icons.delete_outline, - color: Theme.of(sheetContext).colorScheme.error, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.edit_outlined), + title: Text(sheetContext.l10n.channels_editChannel), + onTap: () async { + Navigator.pop(sheetContext); + await Future.delayed(const Duration(milliseconds: 100)); + if (parentContext.mounted) { + _showEditChannelDialog(parentContext, connector, channel); + } + }, ), - title: Text( - sheetContext.l10n.channels_deleteChannel, - style: TextStyle( + // Notification mode selection + ListTile( + leading: const Icon(Icons.notifications_outlined), + title: Text(sheetContext.l10n.channels_notificationSettings), + trailing: const Icon(Icons.chevron_right), + onTap: () async { + Navigator.pop(sheetContext); + await Future.delayed(const Duration(milliseconds: 100)); + if (parentContext.mounted) { + showChannelNotificationModeSheet( + parentContext, + channel.muteKey, + ); + } + }, + ), + ListTile( + leading: Icon( + Icons.delete_outline, color: Theme.of(sheetContext).colorScheme.error, ), + title: Text( + sheetContext.l10n.channels_deleteChannel, + style: TextStyle( + color: Theme.of(sheetContext).colorScheme.error, + ), + ), + onTap: () async { + Navigator.pop(sheetContext); + await Future.delayed(const Duration(milliseconds: 100)); + if (parentContext.mounted) { + _confirmDeleteChannel(parentContext, connector, channel); + } + }, ), - onTap: () async { - Navigator.pop(sheetContext); - await Future.delayed(const Duration(milliseconds: 100)); - if (parentContext.mounted) { - _confirmDeleteChannel(parentContext, connector, channel); - } - }, - ), - ], + ], + ), ), ), ); @@ -1191,12 +1193,16 @@ class _ChannelsScreenState extends State vertical: 8, ), child: DropdownButtonFormField( + isExpanded: true, initialValue: selectedCommunity, items: _communities .map( (c) => DropdownMenuItem( value: c, - child: Text(c.name), + child: Text( + c.name, + overflow: TextOverflow.ellipsis, + ), ), ) .toList(), @@ -1751,6 +1757,7 @@ class _ChannelsScreenState extends State Padding( padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), child: DropdownButtonFormField( + isExpanded: true, initialValue: selectedCyr2LatProfileId, decoration: InputDecoration( labelText: sheetContext @@ -1762,7 +1769,10 @@ class _ChannelsScreenState extends State .map((profile) { return DropdownMenuItem( value: profile.id, - child: Text(profile.name), + child: Text( + profile.name, + overflow: TextOverflow.ellipsis, + ), ); }) .toList(), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 43d30804..79d2f149 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -870,6 +870,7 @@ class _ChatScreenState extends State { Padding( padding: const EdgeInsets.fromLTRB(0, 8, 0, 8), child: DropdownButtonFormField( + isExpanded: true, initialValue: selectedCyr2LatProfileId, decoration: InputDecoration( labelText: @@ -881,7 +882,10 @@ class _ChatScreenState extends State { ) { return DropdownMenuItem( value: profile.id, - child: Text(profile.name), + child: Text( + profile.name, + overflow: TextOverflow.ellipsis, + ), ); }).toList(), onChanged: (value) { @@ -1071,109 +1075,111 @@ class _ChatScreenState extends State { showMeshSheet( context, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader( - title: message.text.characters.length > 40 - ? '${message.text.characters.take(40)}…' - : message.text, - ), - // Can't react to your own messages - if (!message.isOutgoing) + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: message.text.characters.length > 40 + ? '${message.text.characters.take(40)}…' + : message.text, + ), + // Can't react to your own messages + if (!message.isOutgoing) + ListTile( + leading: const Icon(Icons.add_reaction_outlined), + title: Text(context.l10n.chat_addReaction), + onTap: () { + Navigator.pop(sheetContext); + _showEmojiPicker(message, contact); + }, + ), ListTile( - leading: const Icon(Icons.add_reaction_outlined), - title: Text(context.l10n.chat_addReaction), + leading: const Icon(Icons.route), + title: Text(context.l10n.chat_path), onTap: () { Navigator.pop(sheetContext); - _showEmojiPicker(message, contact); + _openMessagePath(message, contact); }, ), - ListTile( - leading: const Icon(Icons.route), - title: Text(context.l10n.chat_path), - onTap: () { - Navigator.pop(sheetContext); - _openMessagePath(message, contact); - }, - ), - if (message.pathBytes.isNotEmpty) + 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.map_outlined), - title: Text(context.l10n.chat_viewPathOnMap), + leading: const Icon(Icons.copy), + title: Text(context.l10n.common_copy), onTap: () { Navigator.pop(sheetContext); - _openMessagePath(message, contact, openMap: true); + copyChatMessageText(context, message.text); }, ), - ListTile( - leading: const Icon(Icons.copy), - title: Text(context.l10n.common_copy), - onTap: () { - Navigator.pop(sheetContext); - copyChatMessageText(context, message.text); - }, - ), - if (canTranslateMessage) + if (canTranslateMessage) + ListTile( + leading: const Icon(Icons.translate), + title: Text(context.l10n.translation_translateMessage), + onTap: () { + Navigator.pop(sheetContext); + unawaited( + context.read().translateContactMessage( + widget.contact.publicKeyHex, + message, + manualTranslation: true, + ), + ); + }, + ), + if (!message.isOutgoing) + ListTile( + leading: const Icon(Icons.mark_chat_unread_outlined), + title: Text(context.l10n.chat_markAsUnread), + onTap: () { + Navigator.pop(sheetContext); + _markAsUnread(message); + }, + ), + if (message.isOutgoing && message.status == MessageStatus.failed) + ListTile( + leading: const Icon(Icons.refresh), + title: Text(context.l10n.common_retry), + onTap: () { + Navigator.pop(sheetContext); + _retryMessage(message); + }, + ), + if (_resolveContact(context.read()).type == + advTypeRoom) + ListTile( + leading: const Icon(Icons.chat), + title: Text(context.l10n.contacts_openChat), + onTap: () { + Navigator.pop(sheetContext); + _openChat(context, contact); + }, + ), + const Divider(height: 1), ListTile( - leading: const Icon(Icons.translate), - title: Text(context.l10n.translation_translateMessage), - onTap: () { + leading: Icon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + title: Text( + context.l10n.common_delete, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + onTap: () async { Navigator.pop(sheetContext); - unawaited( - context.read().translateContactMessage( - widget.contact.publicKeyHex, - message, - manualTranslation: true, - ), - ); + await _deleteMessage(message); }, ), - if (!message.isOutgoing) - ListTile( - leading: const Icon(Icons.mark_chat_unread_outlined), - title: Text(context.l10n.chat_markAsUnread), - onTap: () { - Navigator.pop(sheetContext); - _markAsUnread(message); - }, - ), - if (message.isOutgoing && message.status == MessageStatus.failed) - ListTile( - leading: const Icon(Icons.refresh), - title: Text(context.l10n.common_retry), - onTap: () { - Navigator.pop(sheetContext); - _retryMessage(message); - }, - ), - if (_resolveContact(context.read()).type == - advTypeRoom) - ListTile( - leading: const Icon(Icons.chat), - title: Text(context.l10n.contacts_openChat), - onTap: () { - Navigator.pop(sheetContext); - _openChat(context, contact); - }, - ), - const Divider(height: 1), - ListTile( - leading: Icon( - Icons.delete_outline, - color: Theme.of(context).colorScheme.error, - ), - title: Text( - context.l10n.common_delete, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - onTap: () async { - Navigator.pop(sheetContext); - await _deleteMessage(message); - }, - ), - const SizedBox(height: 8), - ], + const SizedBox(height: 8), + ], + ), ), ), ); diff --git a/lib/screens/community_qr_scanner_screen.dart b/lib/screens/community_qr_scanner_screen.dart index 3b565520..c347484d 100644 --- a/lib/screens/community_qr_scanner_screen.dart +++ b/lib/screens/community_qr_scanner_screen.dart @@ -168,61 +168,63 @@ class _CommunityQrScannerScreenState extends State { context, builder: (sheetContext) { final sheetScheme = Theme.of(sheetContext).colorScheme; - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - BottomSheetHeader(title: context.l10n.channels_joinChannelTitle), - Padding( - padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), - child: Text( - context.l10n.channels_joinChannelConfirm(name), - style: TextStyle(color: sheetScheme.onSurfaceVariant), + return SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BottomSheetHeader(title: context.l10n.channels_joinChannelTitle), + Padding( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), + child: Text( + context.l10n.channels_joinChannelConfirm(name), + style: TextStyle(color: sheetScheme.onSurfaceVariant), + ), ), - ), - MeshCard( - child: Row( - children: [ - AvatarCircle( - name: name, - icon: Icons.lock, - color: MeshPalette.blue, - size: 44, - ), - const SizedBox(width: 14), - Expanded( - child: Text( - name, - style: const TextStyle( - fontWeight: FontWeight.w600, - fontSize: 15, + MeshCard( + child: Row( + children: [ + AvatarCircle( + name: name, + icon: Icons.lock, + color: MeshPalette.blue, + size: 44, + ), + const SizedBox(width: 14), + Expanded( + child: Text( + name, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 15, + ), ), ), - ), - ], + ], + ), ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Row( - children: [ - Expanded( - child: OutlinedButton( - onPressed: () => Navigator.pop(sheetContext, false), - child: Text(context.l10n.common_cancel), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => Navigator.pop(sheetContext, false), + child: Text(context.l10n.common_cancel), + ), ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - onPressed: () => Navigator.pop(sheetContext, true), - child: Text(context.l10n.common_add), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + onPressed: () => Navigator.pop(sheetContext, true), + child: Text(context.l10n.common_add), + ), ), - ), - ], + ], + ), ), - ), - ], + ], + ), ); }, ); @@ -271,61 +273,63 @@ class _CommunityQrScannerScreenState extends State { context, builder: (sheetContext) { final sheetScheme = Theme.of(sheetContext).colorScheme; - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - BottomSheetHeader(title: context.l10n.community_alreadyMember), - Padding( - padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), - child: Text( - context.l10n.community_alreadyMemberMessage(community.name), - style: TextStyle(color: sheetScheme.onSurfaceVariant), + return SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BottomSheetHeader(title: context.l10n.community_alreadyMember), + Padding( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), + child: Text( + context.l10n.community_alreadyMemberMessage(community.name), + style: TextStyle(color: sheetScheme.onSurfaceVariant), + ), ), - ), - MeshCard( - child: Row( - children: [ - const Icon( - Icons.groups, - color: MeshPalette.magenta, - size: 32, - ), - const SizedBox(width: 14), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - community.name, - style: const TextStyle( - fontWeight: FontWeight.w600, - fontSize: 15, - ), - ), - Text( - context.l10n.community_shortId( - community.shortCommunityId, - ), - style: MeshTheme.mono( - fontSize: 13, - color: sheetScheme.onSurfaceVariant, - ), - ), - ], + MeshCard( + child: Row( + children: [ + const Icon( + Icons.groups, + color: MeshPalette.magenta, + size: 32, ), - ), - ], + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + community.name, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 15, + ), + ), + Text( + context.l10n.community_shortId( + community.shortCommunityId, + ), + style: MeshTheme.mono( + fontSize: 13, + color: sheetScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: FilledButton( - onPressed: () => Navigator.pop(sheetContext, true), - child: Text(context.l10n.common_ok), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: FilledButton( + onPressed: () => Navigator.pop(sheetContext, true), + child: Text(context.l10n.common_ok), + ), ), - ), - ], + ], + ), ); }, ); @@ -348,93 +352,95 @@ class _CommunityQrScannerScreenState extends State { builder: (sheetContext) => StatefulBuilder( builder: (sheetContext, setSheetState) { final joinScheme = Theme.of(sheetContext).colorScheme; - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - BottomSheetHeader(title: context.l10n.community_joinTitle), - Padding( - padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), - child: Text( - context.l10n.community_joinConfirmation(community.name), - style: TextStyle(color: joinScheme.onSurfaceVariant), + return SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BottomSheetHeader(title: context.l10n.community_joinTitle), + Padding( + padding: const EdgeInsets.fromLTRB(20, 0, 20, 4), + child: Text( + context.l10n.community_joinConfirmation(community.name), + style: TextStyle(color: joinScheme.onSurfaceVariant), + ), ), - ), - MeshCard( - child: Row( - children: [ - AvatarCircle( - name: community.name, - icon: Icons.groups, - color: MeshPalette.magenta, - size: 44, - ), - const SizedBox(width: 14), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - community.name, - style: const TextStyle( - fontWeight: FontWeight.w600, - fontSize: 15, - ), - ), - Text( - context.l10n.community_shortId( - community.shortCommunityId, - ), - style: MeshTheme.mono( - fontSize: 13, - color: joinScheme.onSurfaceVariant, - ), - ), - ], + MeshCard( + child: Row( + children: [ + AvatarCircle( + name: community.name, + icon: Icons.groups, + color: MeshPalette.magenta, + size: 44, ), - ), - ], + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + community.name, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 15, + ), + ), + Text( + context.l10n.community_shortId( + community.shortCommunityId, + ), + style: MeshTheme.mono( + fontSize: 13, + color: joinScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), ), - ), - CheckboxListTile( - value: addPublicChannel, - onChanged: (value) { - setSheetState(() { - addPublicChannel = value ?? true; - }); - }, - title: Text(context.l10n.community_addPublicChannel), - subtitle: Text(context.l10n.community_addPublicChannelHint), - controlAffinity: ListTileControlAffinity.leading, - contentPadding: const EdgeInsets.symmetric(horizontal: 16), - ), - Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Row( - children: [ - Expanded( - child: OutlinedButton( - onPressed: () { - completer.complete(false); - Navigator.pop(sheetContext); - }, - child: Text(context.l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - onPressed: () { - completer.complete(true); - Navigator.pop(sheetContext); - }, - child: Text(context.l10n.community_join), - ), - ), - ], + CheckboxListTile( + value: addPublicChannel, + onChanged: (value) { + setSheetState(() { + addPublicChannel = value ?? true; + }); + }, + title: Text(context.l10n.community_addPublicChannel), + subtitle: Text(context.l10n.community_addPublicChannelHint), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: const EdgeInsets.symmetric(horizontal: 16), ), - ), - ], + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () { + completer.complete(false); + Navigator.pop(sheetContext); + }, + child: Text(context.l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + onPressed: () { + completer.complete(true); + Navigator.pop(sheetContext); + }, + child: Text(context.l10n.community_join), + ), + ), + ], + ), + ), + ], + ), ); }, ), diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index c8923ec5..e49c59e9 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -544,46 +545,48 @@ class _ContactsScreenState extends State showMeshSheet( context, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader(title: context.l10n.contacts_title), - ListTile( - leading: const Icon(Icons.paste), - title: Text(context.l10n.contacts_addContactFromClipboard), - onTap: () { - Navigator.pop(sheetContext); - _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), - onTap: () { - Navigator.pop(sheetContext); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const DiscoveryScreen(), - ), - ); - }, - ), - const SizedBox(height: 8), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader(title: context.l10n.contacts_title), + ListTile( + leading: const Icon(Icons.paste), + title: Text(context.l10n.contacts_addContactFromClipboard), + onTap: () { + Navigator.pop(sheetContext); + _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), + onTap: () { + Navigator.pop(sheetContext); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const DiscoveryScreen(), + ), + ); + }, + ), + const SizedBox(height: 8), + ], + ), ), ), ); @@ -915,6 +918,23 @@ class _ContactsScreenState extends State 120.0, ); //two 48px icon buttons + 1px divider + // Scrolls with the list rather than staying pinned above it, so large + // text or an open keyboard on a short screen can't squeeze the list out. + final discoveredTile = 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()), + ), + ); + return Column( children: [ Padding( @@ -1038,20 +1058,6 @@ 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(), @@ -1060,9 +1066,13 @@ class _ContactsScreenState extends State builder: (context, constraints) => ListView( physics: const AlwaysScrollableScrollPhysics(), children: [ + discoveredTile, ConstrainedBox( constraints: BoxConstraints( - minHeight: constraints.maxHeight, + minHeight: math.max( + 0, + constraints.maxHeight - kMinInteractiveDimension, + ), ), child: EmptyState( icon: Icons.search_off, @@ -1076,8 +1086,10 @@ class _ContactsScreenState extends State ) : ListView.builder( padding: const EdgeInsets.only(bottom: 88), - itemCount: filteredAndSorted.length, - itemBuilder: (context, index) { + itemCount: filteredAndSorted.length + 1, + itemBuilder: (context, row) { + if (row == 0) return discoveredTile; + final index = row - 1; final contact = filteredAndSorted[index]; final unreadCount = connector.getUnreadCountForContact( contact, @@ -1561,98 +1573,18 @@ class _ContactsScreenState extends State showMeshSheet( context, builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader( - title: contact.name, - subtitle: contact.typeLabel(context.l10n), - ), - if (isRepeater) ...[ - ListTile( - leading: Icon(Icons.radar, color: MeshPalette.signal), - title: Text(context.l10n.contacts_ping), - onTap: () { - Navigator.pop(sheetContext); - final hw = context - .read() - .pathHashByteWidth; - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PathTraceMapScreen( - title: context.l10n.contacts_repeaterPing, - path: contact.pathBytesForDisplay.isNotEmpty - ? contact.pathBytesForDisplay - : _contactPathPrefix(contact, hw), - flipPathAround: true, - targetContact: contact, - pathHashByteWidth: hw, - ), - ), - ); - }, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: contact.name, + subtitle: contact.typeLabel(context.l10n), ), - ListTile( - leading: Icon(Icons.cell_tower, color: MeshPalette.warn), - title: Text(context.l10n.contacts_manageRepeater), - onTap: () { - Navigator.pop(sheetContext); - _showRepeaterLogin(context, contact); - }, - ), - ] else if (isRoom) ...[ - ListTile( - leading: Icon(Icons.radar, color: MeshPalette.signal), - title: Text(context.l10n.contacts_pathTrace), - onTap: () { - Navigator.pop(sheetContext); - final hw = context - .read() - .pathHashByteWidth; - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PathTraceMapScreen( - title: contact.pathBytesForDisplay.isNotEmpty - ? context.l10n.contacts_roomPathTrace - : context.l10n.contacts_roomPing, - path: contact.pathBytesForDisplay.isNotEmpty - ? contact.pathBytesForDisplay - : _contactPathPrefix(contact, hw), - flipPathAround: true, - targetContact: contact, - pathHashByteWidth: hw, - ), - ), - ); - }, - ), - ListTile( - leading: Icon(Icons.meeting_room, color: MeshPalette.blue), - title: Text(context.l10n.contacts_roomLogin), - onTap: () { - Navigator.pop(sheetContext); - _showRoomLogin(context, contact, RoomLoginDestination.chat); - }, - ), - ListTile( - leading: Icon(Icons.room_preferences, color: MeshPalette.warn), - title: Text(context.l10n.room_management), - onTap: () { - Navigator.pop(sheetContext); - _showRoomLogin( - context, - contact, - RoomLoginDestination.management, - ); - }, - ), - ] else ...[ - if (contact.pathLength > 0) + if (isRepeater) ...[ ListTile( leading: Icon(Icons.radar, color: MeshPalette.signal), - title: Text(context.l10n.contacts_chatTraceRoute), + title: Text(context.l10n.contacts_ping), onTap: () { Navigator.pop(sheetContext); final hw = context @@ -1662,10 +1594,10 @@ class _ContactsScreenState extends State context, MaterialPageRoute( builder: (context) => PathTraceMapScreen( - title: context.l10n.contacts_pathTraceTo( - contact.name, - ), - path: contact.pathBytesForDisplay, + title: context.l10n.contacts_repeaterPing, + path: contact.pathBytesForDisplay.isNotEmpty + ? contact.pathBytesForDisplay + : _contactPathPrefix(contact, hw), flipPathAround: true, targetContact: contact, pathHashByteWidth: hw, @@ -1674,57 +1606,142 @@ class _ContactsScreenState extends State ); }, ), + ListTile( + leading: Icon(Icons.cell_tower, color: MeshPalette.warn), + title: Text(context.l10n.contacts_manageRepeater), + onTap: () { + Navigator.pop(sheetContext); + _showRepeaterLogin(context, contact); + }, + ), + ] else if (isRoom) ...[ + ListTile( + leading: Icon(Icons.radar, color: MeshPalette.signal), + title: Text(context.l10n.contacts_pathTrace), + onTap: () { + Navigator.pop(sheetContext); + final hw = context + .read() + .pathHashByteWidth; + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PathTraceMapScreen( + title: contact.pathBytesForDisplay.isNotEmpty + ? context.l10n.contacts_roomPathTrace + : context.l10n.contacts_roomPing, + path: contact.pathBytesForDisplay.isNotEmpty + ? contact.pathBytesForDisplay + : _contactPathPrefix(contact, hw), + flipPathAround: true, + targetContact: contact, + pathHashByteWidth: hw, + ), + ), + ); + }, + ), + ListTile( + leading: Icon(Icons.meeting_room, color: MeshPalette.blue), + title: Text(context.l10n.contacts_roomLogin), + onTap: () { + Navigator.pop(sheetContext); + _showRoomLogin(context, contact, RoomLoginDestination.chat); + }, + ), + ListTile( + leading: Icon( + Icons.room_preferences, + color: MeshPalette.warn, + ), + title: Text(context.l10n.room_management), + onTap: () { + Navigator.pop(sheetContext); + _showRoomLogin( + context, + contact, + RoomLoginDestination.management, + ); + }, + ), + ] else ...[ + if (contact.pathLength > 0) + ListTile( + leading: Icon(Icons.radar, color: MeshPalette.signal), + title: Text(context.l10n.contacts_chatTraceRoute), + onTap: () { + Navigator.pop(sheetContext); + final hw = context + .read() + .pathHashByteWidth; + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PathTraceMapScreen( + title: context.l10n.contacts_pathTraceTo( + contact.name, + ), + path: contact.pathBytesForDisplay, + flipPathAround: true, + targetContact: contact, + pathHashByteWidth: hw, + ), + ), + ); + }, + ), + ], + ListTile( + leading: Icon( + isFavorite ? Icons.star : Icons.star_border, + color: MeshPalette.warn, + ), + title: Text( + isFavorite + ? context.l10n.listFilter_removeFromFavorites + : context.l10n.listFilter_addToFavorites, + ), + onTap: () async { + Navigator.pop(sheetContext); + await connector.setContactFlags( + contact, + isFavorite: !isFavorite, + ); + }, + ), + ListTile( + leading: const Icon(Icons.copy), + title: Text(context.l10n.contacts_ShareContact), + onTap: () { + Navigator.pop(sheetContext); + _contactExport(contact.publicKey); + }, + ), + ListTile( + leading: const Icon(Icons.connect_without_contact), + title: Text(context.l10n.contacts_ShareContactZeroHop), + onTap: () { + Navigator.pop(sheetContext); + _contactZeroHop(contact.publicKey); + }, + ), + ListTile( + leading: Icon( + Icons.delete, + color: Theme.of(context).colorScheme.error, + ), + title: Text( + context.l10n.contacts_removeFromContacts, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + onTap: () { + Navigator.pop(sheetContext); + _confirmDelete(context, connector, contact); + }, + ), + const SizedBox(height: 8), ], - ListTile( - leading: Icon( - isFavorite ? Icons.star : Icons.star_border, - color: MeshPalette.warn, - ), - title: Text( - isFavorite - ? context.l10n.listFilter_removeFromFavorites - : context.l10n.listFilter_addToFavorites, - ), - onTap: () async { - Navigator.pop(sheetContext); - await connector.setContactFlags( - contact, - isFavorite: !isFavorite, - ); - }, - ), - ListTile( - leading: const Icon(Icons.copy), - title: Text(context.l10n.contacts_ShareContact), - onTap: () { - Navigator.pop(sheetContext); - _contactExport(contact.publicKey); - }, - ), - ListTile( - leading: const Icon(Icons.connect_without_contact), - title: Text(context.l10n.contacts_ShareContactZeroHop), - onTap: () { - Navigator.pop(sheetContext); - _contactZeroHop(contact.publicKey); - }, - ), - ListTile( - leading: Icon( - Icons.delete, - color: Theme.of(context).colorScheme.error, - ), - title: Text( - context.l10n.contacts_removeFromContacts, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - onTap: () { - Navigator.pop(sheetContext); - _confirmDelete(context, connector, contact); - }, - ), - const SizedBox(height: 8), - ], + ), ), ), ); @@ -1750,6 +1767,7 @@ class _ContactsScreenState extends State context: context, builder: (dialogContext) => StatefulBuilder( builder: (dialogContext, setDialogState) => AlertDialog( + scrollable: true, title: Text(context.l10n.contacts_removeFromContacts), content: Column( mainAxisSize: MainAxisSize.min, @@ -1871,45 +1889,61 @@ class _ContactTile extends StatelessWidget { icon: contactTypeIcon(contact.type), ), const SizedBox(width: 12), - // Main content + // Main content. The name owns the whole first row (wrapping to + // a second line if needed); last-seen and the route share the row + // below so long names stay readable on narrow screens and large + // text scales. Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - // Name row + route chip - Row( - children: [ - Expanded( - child: Text( - contact.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontWeight: unreadCount > 0 - ? FontWeight.w700 - : FontWeight.w500, - fontSize: 15, - color: scheme.onSurface, + Text.rich( + TextSpan( + text: contact.name, + children: [ + if (isFavorite) + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: 4, + ), + child: Icon( + Icons.star, + size: 16, + color: MeshPalette.warn, + ), + ), + ), + if (contact.hasLocation) + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: 4, + ), + child: Icon( + Icons.location_on, + size: 16, + color: scheme.onSurfaceVariant, + ), + ), ), - ), - ), - if (isFavorite) ...[ - const SizedBox(width: 4), - Icon(Icons.star, size: 16, color: MeshPalette.warn), ], - if (contact.hasLocation) ...[ - const SizedBox(width: 4), - Icon( - Icons.location_on, - size: 16, - color: scheme.onSurfaceVariant, - ), - ], - ], + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontWeight: unreadCount > 0 + ? FontWeight.w700 + : FontWeight.w500, + fontSize: 15, + color: scheme.onSurface, + ), ), const SizedBox(height: 3), - // Key prefix + path / subtitle row + // Key prefix + path + last seen Row( children: [ _KeyPrefixBadge( @@ -1917,6 +1951,7 @@ class _ContactTile extends StatelessWidget { ), const SizedBox(width: 8), Expanded( + flex: 3, child: Text( contact.pathLabel( context.l10n, @@ -1930,42 +1965,33 @@ class _ContactTile extends StatelessWidget { ), ), ), + const SizedBox(width: 8), + // Fills its share and right-aligns, so the time sits at + // the row's end on wide screens too. + Expanded( + flex: 2, + child: Text( + formatContactLastSeen(context.l10n, lastSeen), + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + style: MeshTheme.mono( + fontSize: 12.5, + color: unreadCount > 0 + ? MeshPalette.blue + : scheme.onSurfaceVariant, + ), + ), + ), ], ), ], ), ), - const SizedBox(width: 10), - // Trailing: time + unread badge. A width cap + wrapping keeps - // large text scales from overflowing without clamping them. - ConstrainedBox( - constraints: BoxConstraints( - maxWidth: MediaQuery.sizeOf(context).width * 0.25, - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - if (unreadCount > 0) ...[ - UnreadBadge(count: unreadCount), - const SizedBox(height: 4), - ], - Text( - formatContactLastSeen(context.l10n, lastSeen), - maxLines: 2, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.right, - style: MeshTheme.mono( - fontSize: 12.5, - color: unreadCount > 0 - ? MeshPalette.blue - : scheme.onSurfaceVariant, - ), - ), - ], - ), - ), + if (unreadCount > 0) ...[ + const SizedBox(width: 10), + UnreadBadge(count: unreadCount), + ], if (onManage != null) IconButton( icon: const Icon(Icons.admin_panel_settings_outlined), diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index adaefd02..a7e3079e 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -345,25 +345,27 @@ class _DiscoveryScreenState extends State { builder: (sheetContext) { final l10n = context.l10n; return SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BottomSheetHeader( - title: contact.name, - subtitle: contact.typeLabel(l10n), - ), - ListTile( - leading: const Icon(Icons.copy), - title: Text(l10n.discoveredContacts_copyContact), - onTap: () => Navigator.of(sheetContext).pop('copy_contact'), - ), - ListTile( - leading: const Icon(Icons.delete), - title: Text(l10n.discoveredContacts_deleteContact), - onTap: () => Navigator.of(sheetContext).pop('delete_contact'), - ), - const SizedBox(height: 8), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: contact.name, + subtitle: contact.typeLabel(l10n), + ), + ListTile( + leading: const Icon(Icons.copy), + title: Text(l10n.discoveredContacts_copyContact), + onTap: () => Navigator.of(sheetContext).pop('copy_contact'), + ), + ListTile( + leading: const Icon(Icons.delete), + title: Text(l10n.discoveredContacts_deleteContact), + onTap: () => Navigator.of(sheetContext).pop('delete_contact'), + ), + const SizedBox(height: 8), + ], + ), ), ); }, diff --git a/lib/screens/map_cache_screen.dart b/lib/screens/map_cache_screen.dart index df954a2e..784d3b21 100644 --- a/lib/screens/map_cache_screen.dart +++ b/lib/screens/map_cache_screen.dart @@ -735,15 +735,22 @@ class _MapCacheScreenState extends State { ), ), const SizedBox(width: 12), - OutlinedButton( - style: OutlinedButton.styleFrom( - foregroundColor: MeshPalette.alert, - side: const BorderSide( - color: MeshPalette.alertLine, + // Flexible lets the label wrap instead of pushing + // the row past the screen edge at large text sizes. + Flexible( + child: OutlinedButton( + style: OutlinedButton.styleFrom( + foregroundColor: MeshPalette.alert, + side: const BorderSide( + color: MeshPalette.alertLine, + ), + ), + onPressed: _isDownloading ? null : _clearCache, + child: Text( + l10n.mapCache_clearCacheButton, + textAlign: TextAlign.center, ), ), - onPressed: _isDownloading ? null : _clearCache, - child: Text(l10n.mapCache_clearCacheButton), ), ], ), diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 2c62f423..335bf4d1 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -24,6 +24,7 @@ import '../services/app_settings_service.dart'; import '../services/path_history_service.dart'; import '../services/map_marker_service.dart'; import '../services/map_tile_cache_service.dart'; +import '../services/telemetry_location_request.dart'; import '../services/network_map/network_map_api_client.dart'; import '../services/ui_view_state_service.dart'; import '../storage/prefs_manager.dart'; @@ -104,6 +105,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { bool _showNodeLabels = true; double _zoom = 10.0; String? _selectedKey; + String? _locatingKey; LatLng? _selectedGuessPos; _Freshness _freshness = _Freshness.all; final TextEditingController _searchController = TextEditingController(); @@ -196,7 +198,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { : MapPalette.markerShadow.withValues(alpha: 0.18); _NodeAge _ageOf(Contact contact) { - final d = DateTime.now().difference(contact.lastSeen); + final d = DateTime.now().difference(contact.lastHeard); if (d.inMinutes <= 60) return _NodeAge.online; if (d.inHours <= 24) return _NodeAge.recent; return _NodeAge.stale; @@ -541,7 +543,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { final filteredByTime = settings.mapTimeFilterHours == 0 ? contacts : contacts.where((c) { - final hoursSinceLastSeen = now.difference(c.lastSeen).inHours; + final hoursSinceLastSeen = now.difference(c.lastHeard).inHours; return hoursSinceLastSeen <= settings.mapTimeFilterHours; }).toList(); @@ -2119,7 +2121,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { if (a.hasLocation != b.hasLocation) { return a.hasLocation ? -1 : 1; } - return b.lastSeen.compareTo(a.lastSeen); + return b.lastHeard.compareTo(a.lastHeard); }); final results = matches.take(8).toList(); return Container( @@ -2467,7 +2469,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { children: [ _miniMeta( context.l10n.map_lastSeen, - formatNodeLastSeen(context.l10n, contact.lastSeen), + formatNodeLastSeen(context.l10n, contact.lastHeard), ), _miniMeta( context.l10n.map_path, @@ -2494,6 +2496,33 @@ class _MapScreenState extends State with DisconnectNavigationMixin { crossAxisAlignment: WrapCrossAlignment.center, children: [ ..._selectedNodeActions(context, contact, connector), + // Repeaters and rooms only send GPS to logged-in admins. + if (contact.isActive && + (contact.type == advTypeChat || + contact.type == advTypeSensor)) + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: _overlayPrimaryTextColor, + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + minimumSize: const Size(0, 44), + ), + onPressed: _locatingKey == null + ? () => _requestNodeLocation(contact, connector) + : null, + icon: _locatingKey == contact.publicKeyHex + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.my_location, size: 18), + label: Text( + context.l10n.map_requestLocation, + style: const TextStyle(fontSize: 14), + ), + ), TextButton( style: TextButton.styleFrom( foregroundColor: MapPalette.selected, @@ -2519,6 +2548,36 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + /// Asks the node for telemetry; a GPS fix in the reply moves its marker. + Future _requestNodeLocation( + Contact contact, + MeshCoreConnector connector, + ) async { + setState(() => _locatingKey = contact.publicKeyHex); + final result = await requestTelemetryLocation(connector, contact); + if (!mounted) return; + setState(() => _locatingKey = null); + final l10n = context.l10n; + final message = switch (result) { + TelemetryLocationResult.located => l10n.map_locationUpdated, + TelemetryLocationResult.noLocation => l10n.map_locationNotShared( + contact.name, + ), + TelemetryLocationResult.failed => l10n.map_locationRequestFailed( + contact.name, + ), + }; + showDismissibleSnackBar(context, content: Text(message)); + final updated = connector.contacts + .where((c) => c.publicKeyHex == contact.publicKeyHex) + .firstOrNull; + if (result == TelemetryLocationResult.located && + updated != null && + updated.hasLocation) { + _mapController.move(LatLng(updated.latitude!, updated.longitude!), _zoom); + } + } + Widget _miniMeta(String label, String value) { return Column( mainAxisSize: MainAxisSize.min, @@ -2999,6 +3058,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { showDialog( context: context, builder: (dialogContext) => AlertDialog( + scrollable: true, title: Text( marker.label.isEmpty ? context.l10n.map_sharedPin : marker.label, ), @@ -3994,7 +4054,7 @@ int _mapContactSignature(Contact contact) { _bytesSignature(contact.pathOverrideBytes), contact.latitude, contact.longitude, - contact.lastSeen.millisecondsSinceEpoch, + contact.lastHeard.millisecondsSinceEpoch, contact.lastMessageAt.millisecondsSinceEpoch, contact.isActive, ); diff --git a/lib/screens/region_management_screen.dart b/lib/screens/region_management_screen.dart index ec81471b..25b20ee5 100644 --- a/lib/screens/region_management_screen.dart +++ b/lib/screens/region_management_screen.dart @@ -180,9 +180,11 @@ class _RegionManagementScreenState extends State { child: DropdownButtonFormField( key: ValueKey(current), initialValue: current, + isExpanded: true, decoration: InputDecoration( labelText: l10n.settings_regionDefault, helperText: l10n.settings_regionDefaultSubtitle, + helperMaxLines: 3, border: const OutlineInputBorder(), ), items: [ @@ -192,15 +194,22 @@ class _RegionManagementScreenState extends State { radioDefault == null ? l10n.settings_regionDefaultNone : l10n.settings_regionUseRadioDefault(radioDefault), + overflow: TextOverflow.ellipsis, ), ), if (canForceUnscoped) DropdownMenuItem( value: kUnscopedRegion, - child: Text(l10n.settings_regionNoRegion), + child: Text( + l10n.settings_regionNoRegion, + overflow: TextOverflow.ellipsis, + ), ), for (final region in _regions) - DropdownMenuItem(value: region, child: Text(region)), + DropdownMenuItem( + value: region, + child: Text(region, overflow: TextOverflow.ellipsis), + ), ], onChanged: (value) => connector.setDefaultRegion(value ?? ''), ), @@ -222,6 +231,7 @@ class _RegionManagementScreenState extends State { return Padding( padding: const EdgeInsets.only(top: 8, bottom: 8), child: DropdownButtonFormField( + isExpanded: true, key: ValueKey('radio-default-$radioDefault'), initialValue: radioDefault, decoration: InputDecoration( @@ -233,10 +243,16 @@ class _RegionManagementScreenState extends State { items: [ DropdownMenuItem( value: '', - child: Text(l10n.settings_regionDefaultNone), + child: Text( + l10n.settings_regionDefaultNone, + overflow: TextOverflow.ellipsis, + ), ), for (final region in options) - DropdownMenuItem(value: region, child: Text(region)), + DropdownMenuItem( + value: region, + child: Text(region, overflow: TextOverflow.ellipsis), + ), ], onChanged: (value) => _setRadioDefaultRegion(connector, value ?? ''), ), diff --git a/lib/screens/repeater_cli_screen.dart b/lib/screens/repeater_cli_screen.dart index da479275..979f0423 100644 --- a/lib/screens/repeater_cli_screen.dart +++ b/lib/screens/repeater_cli_screen.dart @@ -471,7 +471,6 @@ class _RepeaterCliScreenState extends State { ), body: Column( children: [ - const RadioDisconnectedBanner(), // Quick commands bar Container( color: scheme.surfaceContainer, @@ -506,10 +505,29 @@ class _RepeaterCliScreenState extends State { Divider(height: 1, color: scheme.outlineVariant), // Output area + // The disconnected banner lives in the output area and is capped at + // half of it, so large text or an open keyboard can't push the + // command input off screen. Expanded( - child: _commandHistory.isEmpty - ? _buildEmptyState() - : _buildCommandHistory(), + child: LayoutBuilder( + builder: (context, constraints) => Column( + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxHeight: constraints.maxHeight / 2, + ), + child: const SingleChildScrollView( + child: RadioDisconnectedBanner(), + ), + ), + Expanded( + child: _commandHistory.isEmpty + ? _buildEmptyState() + : _buildCommandHistory(), + ), + ], + ), + ), ), Divider(height: 1, color: scheme.outlineVariant), @@ -616,10 +634,10 @@ class _RepeaterCliScreenState extends State { final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; return Center( - child: Padding( + child: SingleChildScrollView( padding: const EdgeInsets.all(24), child: Column( - mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.terminal, size: 48, color: scheme.onSurfaceVariant), const SizedBox(height: 12), diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index 7c4cdcd6..e5d30519 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -1411,14 +1411,21 @@ class _RepeaterSettingsScreenState extends State { Padding( padding: const EdgeInsets.only(top: 16), child: MeshCard( - child: Row( + // The button sits under the message so neither is + // squeezed on narrow screens or large text. + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, children: [ - const Icon(Icons.info_outline, size: 20), - const SizedBox(width: 12), - Expanded( - child: Text( - context.l10n.repeater_settingsNotLoaded, - ), + Row( + children: [ + const Icon(Icons.info_outline, size: 20), + const SizedBox(width: 12), + Expanded( + child: Text( + context.l10n.repeater_settingsNotLoaded, + ), + ), + ], ), TextButton( onPressed: _isLoading || !connected @@ -1626,12 +1633,16 @@ class _RepeaterSettingsScreenState extends State { ), const SizedBox(height: 12), DropdownButtonFormField( + isExpanded: true, initialValue: _bandwidth, decoration: InputDecoration(labelText: l10n.repeater_bandwidth), items: _bandwidthOptions.map((bw) { return DropdownMenuItem( value: bw, - child: Text(_formatBandwidthLabel(bw)), + child: Text( + _formatBandwidthLabel(bw), + overflow: TextOverflow.ellipsis, + ), ); }).toList(), onChanged: !_loaded('radio') @@ -1647,12 +1658,16 @@ class _RepeaterSettingsScreenState extends State { ), const SizedBox(height: 12), DropdownButtonFormField( + isExpanded: true, initialValue: _spreadingFactor, decoration: InputDecoration( labelText: l10n.repeater_spreadingFactor, ), items: _spreadingFactorOptions.map((sf) { - return DropdownMenuItem(value: sf, child: Text('SF$sf')); + return DropdownMenuItem( + value: sf, + child: Text('SF$sf', overflow: TextOverflow.ellipsis), + ); }).toList(), onChanged: !_loaded('radio') ? null @@ -1667,12 +1682,16 @@ class _RepeaterSettingsScreenState extends State { ), const SizedBox(height: 12), DropdownButtonFormField( + isExpanded: true, initialValue: _codingRate, decoration: InputDecoration( labelText: l10n.repeater_codingRate, ), items: _codingRateOptions.map((cr) { - return DropdownMenuItem(value: cr, child: Text('4/$cr')); + return DropdownMenuItem( + value: cr, + child: Text('4/$cr', overflow: TextOverflow.ellipsis), + ); }).toList(), onChanged: !_loaded('radio') ? null @@ -2122,6 +2141,7 @@ class _RepeaterSettingsScreenState extends State { children: [ Expanded( child: DropdownButtonFormField( + isExpanded: true, initialValue: _loaded('loop.detect') ? _loopDetect : null, decoration: InputDecoration( labelText: l10n.repeater_loopDetect, @@ -2131,19 +2151,31 @@ class _RepeaterSettingsScreenState extends State { items: [ DropdownMenuItem( value: 'off', - child: Text(l10n.repeater_loopDetectOff), + child: Text( + l10n.repeater_loopDetectOff, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 'minimal', - child: Text(l10n.repeater_loopDetectMinimal), + child: Text( + l10n.repeater_loopDetectMinimal, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 'moderate', - child: Text(l10n.repeater_loopDetectModerate), + child: Text( + l10n.repeater_loopDetectModerate, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 'strict', - child: Text(l10n.repeater_loopDetectStrict), + child: Text( + l10n.repeater_loopDetectStrict, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: !_loaded('loop.detect') @@ -2322,6 +2354,7 @@ class _RepeaterSettingsScreenState extends State { children: [ Expanded( child: DropdownButtonFormField( + isExpanded: true, initialValue: _loaded('path.hash.mode') ? _pathHashMode : null, @@ -2333,15 +2366,24 @@ class _RepeaterSettingsScreenState extends State { items: [ DropdownMenuItem( value: 0, - child: Text(l10n.repeater_pathHashModeOption0), + child: Text( + l10n.repeater_pathHashModeOption0, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 1, - child: Text(l10n.repeater_pathHashModeOption1), + child: Text( + l10n.repeater_pathHashModeOption1, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 2, - child: Text(l10n.repeater_pathHashModeOption2), + child: Text( + l10n.repeater_pathHashModeOption2, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: !_loaded('path.hash.mode') diff --git a/lib/screens/repeater_status_screen.dart b/lib/screens/repeater_status_screen.dart index 5faf8708..4f4bcd5e 100644 --- a/lib/screens/repeater_status_screen.dart +++ b/lib/screens/repeater_status_screen.dart @@ -705,25 +705,38 @@ class _RepeaterStatusScreenState extends State { 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, - ); - }, + // Rows size to their tallest tile, so labels that wrap at large + // text scales grow the row instead of overflowing a fixed extent. + Widget tile(_StatItem item) => StatTile( + icon: item.icon, + label: item.label, + value: item.value, + color: item.color, + ); + return Column( + children: [ + for (var i = 0; i < items.length; i += columns) + Padding( + padding: EdgeInsets.only( + bottom: i + columns < items.length ? 8 : 0, + ), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var j = 0; j < columns; j++) ...[ + if (j > 0) const SizedBox(width: 8), + Expanded( + child: i + j < items.length + ? tile(items[i + j]) + : const SizedBox.shrink(), + ), + ], + ], + ), + ), + ), + ], ); }, ); diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 74ca3e2c..6ec9dc84 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -805,12 +805,14 @@ class _SettingsScreenState extends State { context: context, builder: (dialogContext) => StatefulBuilder( builder: (builderContext, setDialogState) => AlertDialog( + scrollable: true, title: Text(l10n.repeater_pathHashMode), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DropdownButtonFormField( + isExpanded: true, initialValue: selectedMode, decoration: InputDecoration( labelText: l10n.repeater_pathHashMode, @@ -819,15 +821,24 @@ class _SettingsScreenState extends State { items: [ DropdownMenuItem( value: 0, - child: Text(l10n.repeater_pathHashModeOption0), + child: Text( + l10n.repeater_pathHashModeOption0, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 1, - child: Text(l10n.repeater_pathHashModeOption1), + child: Text( + l10n.repeater_pathHashModeOption1, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 2, - child: Text(l10n.repeater_pathHashModeOption2), + child: Text( + l10n.repeater_pathHashModeOption2, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: (value) { diff --git a/lib/screens/telemetry_screen.dart b/lib/screens/telemetry_screen.dart index b6f085e8..f73e7040 100644 --- a/lib/screens/telemetry_screen.dart +++ b/lib/screens/telemetry_screen.dart @@ -12,6 +12,7 @@ import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../services/app_settings_service.dart'; import '../services/repeater_command_service.dart'; +import '../services/telemetry_location_request.dart'; import '../utils/app_logger.dart'; import '../widgets/routing_sheet.dart'; import '../helpers/cayenne_lpp.dart'; @@ -208,6 +209,14 @@ class _TelemetryScreenState extends State { source: 'telemetry', ); } + final fix = telemetryGpsFix(parsedTelemetry); + if (fix != null && !widget.isSelf) { + context.read().updateContactLocationFromTelemetry( + widget.contact.publicKeyHex, + fix.latitude, + fix.longitude, + ); + } if (!mounted) return; final isAutoRefreshRequest = _activeTelemetryRequestIsAutoRefresh; setState(() { diff --git a/lib/services/telemetry_location_request.dart b/lib/services/telemetry_location_request.dart new file mode 100644 index 00000000..53b03923 --- /dev/null +++ b/lib/services/telemetry_location_request.dart @@ -0,0 +1,130 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/cayenne_lpp.dart'; +import '../models/contact.dart'; +import '../models/path_selection.dart'; +import '../utils/app_logger.dart'; + +enum TelemetryLocationResult { located, noLocation, failed } + +/// Returns the first valid GPS fix in parsed Cayenne LPP telemetry, or null. +({double latitude, double longitude})? telemetryGpsFix( + List> entries, +) { + for (final entry in entries) { + final values = entry['values']; + if (values is! Map) continue; + final gps = values['gps']; + if (gps is! Map) continue; + final lat = gps['latitude']; + final lon = gps['longitude']; + if (lat is! num || lon is! num) continue; + final latitude = lat.toDouble(); + final longitude = lon.toDouble(); + const double epsilon = 1e-6; + final valid = + (latitude.abs() > epsilon || longitude.abs() > epsilon) && + latitude >= -90.0 && + latitude <= 90.0 && + longitude >= -180.0 && + longitude <= 180.0; + if (valid) return (latitude: latitude, longitude: longitude); + } + return null; +} + +/// Asks [contact] for its telemetry and, when the reply carries a GPS fix, +/// stores it on the contact so the map moves the node right away. +Future requestTelemetryLocation( + MeshCoreConnector connector, + Contact contact, +) async { + final completer = Completer>?>(); + // Armed just before our send: a background retry's RESP_CODE_SENT that + // lands while the path is being prepared must not be taken for ours. + var awaitingSent = false; + int? tag; + Timer? timeout; + void finish(List>? parsed) { + if (completer.isCompleted) return; + timeout?.cancel(); + completer.complete(parsed); + } + + final isChat = contact.type == advTypeChat; + final subscription = connector.receivedFrames.listen((frame) { + if (frame.isEmpty || completer.isCompleted) return; + final reader = BufferReader(frame); + try { + final cmd = reader.readByte(); + if (cmd == respCodeSent && awaitingSent) { + awaitingSent = false; + reader.skipBytes(1); // reserved + tag = reader.readUInt32LE(); + final tripTime = reader.readUInt32LE(); + timeout?.cancel(); + timeout = Timer(Duration(milliseconds: tripTime), () => finish(null)); + } else if (cmd == respCodeErr && awaitingSent) { + awaitingSent = false; + finish(null); + } else if (cmd == pushCodeBinaryResponse) { + // Binary requests always answer here. A chat telemetry reply also + // lands here, tagged, when another request replaced it as the + // radio's pending request. + reader.skipBytes(1); // reserved + if (tag == null || reader.readUInt32LE() != tag) return; + finish(CayenneLpp.parseByChannel(reader.readRemainingBytes())); + } else if (cmd == pushCodeTelemetryResponse && isChat) { + reader.skipBytes(1); // reserved + final prefix = reader.readBytes(6); + if (!listEquals(contact.publicKey.sublist(0, 6), prefix)) return; + finish(CayenneLpp.parseByChannel(reader.readRemainingBytes())); + } + } catch (e) { + appLogger.error('Error parsing telemetry location frame: $e'); + } + }); + + PathSelection? selection; + try { + selection = await connector.preparePathForContactSend(contact); + awaitingSent = true; + // Guards the wait for the radio's send ack; its trip time replaces this. + timeout = Timer(const Duration(seconds: 10), () => finish(null)); + await connector.sendFrame( + isChat + ? buildSendTelemetryReq(contact.publicKey) + : buildSendBinaryReq( + contact.publicKey, + payload: buildTelemetryBinaryPayload(), + ), + ); + } catch (e) { + appLogger.error('Telemetry location request failed: $e'); + finish(null); + } + + final parsed = await completer.future; + await subscription.cancel(); + if (selection != null) { + connector.recordRepeaterPathResult( + contact, + selection, + parsed != null, + null, + ); + } + if (parsed == null) return TelemetryLocationResult.failed; + final fix = telemetryGpsFix(parsed); + if (fix == null) return TelemetryLocationResult.noLocation; + connector.updateContactLocationFromTelemetry( + contact.publicKeyHex, + fix.latitude, + fix.longitude, + ); + return TelemetryLocationResult.located; +} diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index e80ee952..3fc45187 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -92,6 +92,7 @@ class ContactStore { 'rawPacket': contact.rawPacket != null ? base64Encode(contact.rawPacket!) : null, + 'telemetryFixAt': contact.telemetryFixAt?.millisecondsSinceEpoch, }; } @@ -99,6 +100,7 @@ class ContactStore { final lastSeenMs = json['lastSeen'] as int? ?? 0; final lastMessageMs = json['lastMessageAt'] as int?; final lastModifiedMs = json['lastModified'] as int?; + final telemetryFixMs = json['telemetryFixAt'] as int?; final rawPathLength = json['pathLength'] as int? ?? -1; final rawPath = json['path'] != null @@ -157,6 +159,9 @@ class ContactStore { rawPacket: json['rawPacket'] != null ? Uint8List.fromList(base64Decode(json['rawPacket'] as String)) : null, + telemetryFixAt: telemetryFixMs == null + ? null + : DateTime.fromMillisecondsSinceEpoch(telemetryFixMs), ); } } diff --git a/lib/widgets/channel_notification_mode_sheet.dart b/lib/widgets/channel_notification_mode_sheet.dart index 9239aff2..8b062a29 100644 --- a/lib/widgets/channel_notification_mode_sheet.dart +++ b/lib/widgets/channel_notification_mode_sheet.dart @@ -36,28 +36,32 @@ void showChannelNotificationModeSheet(BuildContext context, String muteKey) { builder: (sheetContext) { final scheme = Theme.of(sheetContext).colorScheme; return SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final mode in ChannelNotificationMode.values) - ListTile( - leading: Icon( - channelNotificationModeIcon(mode), - color: mode == currentMode - ? scheme.primary - : scheme.onSurfaceVariant, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final mode in ChannelNotificationMode.values) + ListTile( + leading: Icon( + channelNotificationModeIcon(mode), + color: mode == currentMode + ? scheme.primary + : scheme.onSurfaceVariant, + ), + title: Text(channelNotificationModeLabel(sheetContext, mode)), + trailing: mode == currentMode + ? const Icon(Icons.check) + : null, + onTap: () async { + Navigator.pop(sheetContext); + await settingsService.setChannelNotificationMode( + muteKey, + mode, + ); + }, ), - title: Text(channelNotificationModeLabel(sheetContext, mode)), - trailing: mode == currentMode ? const Icon(Icons.check) : null, - onTap: () async { - Navigator.pop(sheetContext); - await settingsService.setChannelNotificationMode( - muteKey, - mode, - ); - }, - ), - ], + ], + ), ), ); }, diff --git a/lib/widgets/contact_visuals.dart b/lib/widgets/contact_visuals.dart index ace35429..64117921 100644 --- a/lib/widgets/contact_visuals.dart +++ b/lib/widgets/contact_visuals.dart @@ -41,12 +41,11 @@ IconData? contactTypeIcon(int type) { } /// The most recent activity for [contact]: for chat nodes this includes the -/// last message, for other node types only the last advert. +/// last message, for other node types only the last advert or telemetry fix. DateTime resolveContactLastSeen(Contact contact) { - if (contact.type != advTypeChat) return contact.lastSeen; - return contact.lastMessageAt.isAfter(contact.lastSeen) - ? contact.lastMessageAt - : contact.lastSeen; + final heard = contact.lastHeard; + if (contact.type != advTypeChat) return heard; + return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard; } /// Short relative "last seen" label ("now", "5 mins ago", "2 days ago"). diff --git a/lib/widgets/empty_state.dart b/lib/widgets/empty_state.dart index 2f0c9847..5094a1fb 100644 --- a/lib/widgets/empty_state.dart +++ b/lib/widgets/empty_state.dart @@ -55,56 +55,70 @@ class _EmptyStateState extends State begin: const Offset(0, 0.06), end: Offset.zero, ).animate(_curve), - child: Center( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 40), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - width: 80, - height: 80, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: scheme.primary.withValues(alpha: 0.08), - border: Border.all( - color: scheme.primary.withValues(alpha: 0.18), - width: 1.5, - ), - ), - child: Icon( - widget.icon, - size: 36, - color: scheme.onSurfaceVariant, + // Scrolls instead of overflowing when a short screen or a large text + // scale makes the content taller than the space it gets. + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: constraints.hasBoundedHeight + ? constraints.maxHeight + : 0, + ), + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.primary.withValues(alpha: 0.08), + border: Border.all( + color: scheme.primary.withValues(alpha: 0.18), + width: 1.5, + ), + ), + child: Icon( + widget.icon, + size: 36, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 20), + Text( + widget.title, + style: Theme.of(context).textTheme.titleMedium + ?.copyWith( + fontWeight: FontWeight.w600, + color: scheme.onSurface, + letterSpacing: -0.1, + ), + textAlign: TextAlign.center, + ), + if (widget.subtitle != null) ...[ + const SizedBox(height: 8), + Text( + widget.subtitle!, + style: TextStyle( + fontSize: 13.5, + color: scheme.onSurfaceVariant, + height: 1.45, + ), + textAlign: TextAlign.center, + ), + ], + if (widget.action != null) ...[ + const SizedBox(height: 28), + widget.action!, + ], + ], ), ), - const SizedBox(height: 20), - Text( - widget.title, - style: Theme.of(context).textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w600, - color: scheme.onSurface, - letterSpacing: -0.1, - ), - textAlign: TextAlign.center, - ), - if (widget.subtitle != null) ...[ - const SizedBox(height: 8), - Text( - widget.subtitle!, - style: TextStyle( - fontSize: 13.5, - color: scheme.onSurfaceVariant, - height: 1.45, - ), - textAlign: TextAlign.center, - ), - ], - if (widget.action != null) ...[ - const SizedBox(height: 28), - widget.action!, - ], - ], + ), ), ), ), diff --git a/lib/widgets/language_picker_sheet.dart b/lib/widgets/language_picker_sheet.dart index e922289d..178fa13f 100644 --- a/lib/widgets/language_picker_sheet.dart +++ b/lib/widgets/language_picker_sheet.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import '../l10n/app_localizations.dart'; @@ -55,7 +57,8 @@ void showLanguagePickerSheet( children: [ BottomSheetHeader(title: l10n.appSettings_language), SizedBox( - height: 400, + // Capped so the sheet still fits short screens and landscape. + height: math.min(400, MediaQuery.sizeOf(ctx).height * 0.6), child: ListView( children: [ for (final (code, label) in appLanguageOptions) diff --git a/lib/widgets/node_info_sheet.dart b/lib/widgets/node_info_sheet.dart index 1e3bb073..3d10e0ec 100644 --- a/lib/widgets/node_info_sheet.dart +++ b/lib/widgets/node_info_sheet.dart @@ -262,7 +262,7 @@ void showNodeInfoSheet( ), NodeInfoRow( label: l10n.map_lastSeen, - value: formatNodeLastSeen(l10n, contact.lastSeen), + value: formatNodeLastSeen(l10n, contact.lastHeard), ), NodeInfoRow( label: l10n.map_publicKey, diff --git a/lib/widgets/radio_settings_dialog.dart b/lib/widgets/radio_settings_dialog.dart index aa00e3d9..8fb29c9f 100644 --- a/lib/widgets/radio_settings_dialog.dart +++ b/lib/widgets/radio_settings_dialog.dart @@ -645,6 +645,7 @@ class _RadioSettingsDialogState extends State { ), const SizedBox(height: 16), DropdownButtonFormField( + isExpanded: true, initialValue: _bandwidth, decoration: InputDecoration( labelText: l10n.settings_bandwidth, @@ -652,7 +653,10 @@ class _RadioSettingsDialogState extends State { ), items: LoRaBandwidth.values .map( - (bw) => DropdownMenuItem(value: bw, child: Text(bw.label)), + (bw) => DropdownMenuItem( + value: bw, + child: Text(bw.label, overflow: TextOverflow.ellipsis), + ), ) .toList(), onChanged: (value) { @@ -667,6 +671,7 @@ class _RadioSettingsDialogState extends State { ), const SizedBox(height: 16), DropdownButtonFormField( + isExpanded: true, initialValue: _spreadingFactor, decoration: InputDecoration( labelText: l10n.settings_spreadingFactor, @@ -674,7 +679,10 @@ class _RadioSettingsDialogState extends State { ), items: LoRaSpreadingFactor.values .map( - (sf) => DropdownMenuItem(value: sf, child: Text(sf.label)), + (sf) => DropdownMenuItem( + value: sf, + child: Text(sf.label, overflow: TextOverflow.ellipsis), + ), ) .toList(), onChanged: (value) { @@ -691,6 +699,7 @@ class _RadioSettingsDialogState extends State { ), const SizedBox(height: 16), DropdownButtonFormField( + isExpanded: true, initialValue: _codingRate, decoration: InputDecoration( labelText: l10n.settings_codingRate, @@ -698,7 +707,10 @@ class _RadioSettingsDialogState extends State { ), items: LoRaCodingRate.values .map( - (cr) => DropdownMenuItem(value: cr, child: Text(cr.label)), + (cr) => DropdownMenuItem( + value: cr, + child: Text(cr.label, overflow: TextOverflow.ellipsis), + ), ) .toList(), onChanged: (value) { @@ -716,6 +728,7 @@ class _RadioSettingsDialogState extends State { // Values are path hash modes (0-2, byte width - 1), matching // the selectors in settings_screen and repeater_settings_screen. DropdownButtonFormField( + isExpanded: true, initialValue: (_pathHashByteWidth - 1).clamp(0, 2).toInt(), decoration: InputDecoration( labelText: l10n.repeater_pathHashMode, @@ -726,15 +739,24 @@ class _RadioSettingsDialogState extends State { items: [ DropdownMenuItem( value: 0, - child: Text(l10n.repeater_pathHashModeOption0), + child: Text( + l10n.repeater_pathHashModeOption0, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 1, - child: Text(l10n.repeater_pathHashModeOption1), + child: Text( + l10n.repeater_pathHashModeOption1, + overflow: TextOverflow.ellipsis, + ), ), DropdownMenuItem( value: 2, - child: Text(l10n.repeater_pathHashModeOption2), + child: Text( + l10n.repeater_pathHashModeOption2, + overflow: TextOverflow.ellipsis, + ), ), ], onChanged: (value) { diff --git a/lib/widgets/routing_sheet.dart b/lib/widgets/routing_sheet.dart index 21b98920..5bc19d71 100644 --- a/lib/widgets/routing_sheet.dart +++ b/lib/widgets/routing_sheet.dart @@ -313,6 +313,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> { showDialog( context: context, builder: (dialogContext) => AlertDialog( + scrollable: true, title: Text(l10n.chat_fullPath), content: Column( mainAxisSize: MainAxisSize.min, diff --git a/test/connector/telemetry_location_test.dart b/test/connector/telemetry_location_test.dart new file mode 100644 index 00000000..098ba731 --- /dev/null +++ b/test/connector/telemetry_location_test.dart @@ -0,0 +1,216 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/cayenne_lpp.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/path_selection.dart'; +import 'package:meshcore_open/services/telemetry_location_request.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _contactFrame( + Uint8List key, { + required int advertTimestamp, + required double lat, + required double lon, + int type = advTypeChat, +}) { + final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12); + final bytes = data.buffer.asUint8List(); + bytes[0] = respCodeContact; + bytes.setRange(1, 33, key); + bytes[33] = type; + bytes[35] = 0xFF; // path unknown + bytes.setRange(100, 103, 'Bob'.codeUnits); + data.setUint32(132, advertTimestamp, Endian.little); + data.setInt32(136, (lat * 1e6).round(), Endian.little); + data.setInt32(140, (lon * 1e6).round(), Endian.little); + return bytes; +} + +Uint8List _sentFrame(int tag) { + final data = ByteData(10); + data.setUint8(0, respCodeSent); + data.setUint32(2, tag, Endian.little); + data.setUint32(6, 5000, Endian.little); // est. timeout ms + return data.buffer.asUint8List(); +} + +/// A sensor's binary telemetry reply carrying a Cayenne LPP GPS fix. +Uint8List _gpsResponse(int tag, double lat, double lon) { + int24(double v) { + final n = v.round() & 0xFFFFFF; + return [(n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF]; + } + + final tagBytes = ByteData(4)..setUint32(0, tag, Endian.little); + return Uint8List.fromList([ + pushCodeBinaryResponse, + 0, + ...tagBytes.buffer.asUint8List(), + 1, + CayenneLpp.lppGps, + ...int24(lat * 10000), + ...int24(lon * 10000), + ...int24(0), + ]); +} + +/// Replays radio traffic around a telemetry request: an unrelated send ack +/// arrives while the path is prepared, then the request's own ack and reply. +class _RadioConnector extends MeshCoreConnector { + @override + bool get isConnected => true; + + @override + Future preparePathForContactSend(Contact contact) async { + handleFrameForTest(_sentFrame(111)); // a background retry's ack + return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true); + } + + @override + Future sendFrame( + Uint8List data, { + String? channelSendQueueId, + bool expectsGenericAck = false, + bool waitForGenericAck = false, + }) async { + handleFrameForTest(_sentFrame(222)); + handleFrameForTest(_gpsResponse(222, 45.5, -122.6)); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + final key = Uint8List.fromList(List.generate(32, (i) => i + 1)); + + test('telemetry fix survives a refresh of the same advert', () { + final connector = MeshCoreConnector(); + final frame = _contactFrame( + key, + advertTimestamp: 1700000000, + lat: 10, + lon: 20, + ); + connector.handleFrameForTest(frame); + final keyHex = connector.contacts.single.publicKeyHex; + + connector.updateContactLocationFromTelemetry(keyHex, 11.5, 21.5); + final fixed = connector.contacts.single; + expect(fixed.latitude, 11.5); + expect(fixed.longitude, 21.5); + // lastSeen stays the advert time the radio holds (path and flag writes + // send it back); the fix only moves lastHeard. + final advertTime = DateTime.fromMillisecondsSinceEpoch(1700000000 * 1000); + expect(fixed.lastSeen, advertTime); + expect(fixed.lastHeard.isAfter(advertTime), isTrue); + + connector.handleFrameForTest(frame); + final refreshed = connector.contacts.single; + expect(refreshed.latitude, 11.5); + expect(refreshed.longitude, 21.5); + expect(refreshed.lastSeen, advertTime); + expect(refreshed.telemetryFixAt, fixed.telemetryFixAt); + }); + + test('telemetry fix survives a full contact sync', () { + final connector = MeshCoreConnector(); + final frame = _contactFrame( + key, + advertTimestamp: 1700000000, + lat: 10, + lon: 20, + ); + connector.handleFrameForTest(frame); + final keyHex = connector.contacts.single.publicKeyHex; + connector.updateContactLocationFromTelemetry(keyHex, 11.5, 21.5); + + // A full sync clears the list on CONTACTS_START and the radio resends + // the same advert record. + connector.handleFrameForTest([respCodeContactsStart]); + expect(connector.contacts, isEmpty); + connector.handleFrameForTest(frame); + connector.handleFrameForTest([respCodeEndOfContacts]); + + final contact = connector.contacts.single; + expect(contact.latitude, 11.5); + expect(contact.longitude, 21.5); + expect(contact.telemetryFixAt, isNotNull); + }); + + test('a newer advert replaces the telemetry fix', () { + final connector = MeshCoreConnector(); + connector.handleFrameForTest( + _contactFrame(key, advertTimestamp: 1700000000, lat: 10, lon: 20), + ); + final keyHex = connector.contacts.single.publicKeyHex; + connector.updateContactLocationFromTelemetry(keyHex, 11.5, 21.5); + + connector.handleFrameForTest( + _contactFrame(key, advertTimestamp: 1700000100, lat: 12, lon: 22), + ); + final contact = connector.contacts.single; + expect(contact.latitude, 12); + expect(contact.longitude, 22); + expect(contact.telemetryFixAt, isNull); + }); + + test('a send ack during path preparation is not taken as ours', () async { + final connector = _RadioConnector(); + connector.handleFrameForTest( + _contactFrame( + key, + advertTimestamp: 1700000000, + lat: 10, + lon: 20, + type: advTypeSensor, + ), + ); + final sensor = connector.contacts.single; + + final result = await requestTelemetryLocation(connector, sensor); + + expect(result, TelemetryLocationResult.located); + expect(connector.contacts.single.latitude, closeTo(45.5, 1e-4)); + expect(connector.contacts.single.longitude, closeTo(-122.6, 1e-4)); + }); + + test('telemetryGpsFix skips missing and null-island fixes', () { + expect(telemetryGpsFix([]), isNull); + expect( + telemetryGpsFix([ + { + 'channel': 1, + 'values': { + 'gps': {'latitude': 0.0, 'longitude': 0.0, 'altitude': 0.0}, + }, + }, + ]), + isNull, + ); + expect( + telemetryGpsFix([ + { + 'channel': 1, + 'values': {'voltage': 4.1}, + }, + { + 'channel': 2, + 'values': { + 'gps': {'latitude': 45.5, 'longitude': -122.6, 'altitude': 10.0}, + }, + }, + ]), + (latitude: 45.5, longitude: -122.6), + ); + }); +} diff --git a/test/screens/small_screen_layout_test.dart b/test/screens/small_screen_layout_test.dart new file mode 100644 index 00000000..d753116e --- /dev/null +++ b/test/screens/small_screen_layout_test.dart @@ -0,0 +1,315 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/app_debug_log_screen.dart'; +import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/screens/ble_debug_log_screen.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/channel_message_path_screen.dart'; +import 'package:meshcore_open/screens/channels_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/screens/chrome_required_screen.dart'; +import 'package:meshcore_open/screens/companion_radio_stats_screen.dart'; +import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/screens/discovery_screen.dart'; +import 'package:meshcore_open/screens/line_of_sight_map_screen.dart'; +import 'package:meshcore_open/screens/map_cache_screen.dart'; +import 'package:meshcore_open/screens/map_screen.dart'; +import 'package:meshcore_open/screens/neighbors_screen.dart'; +import 'package:meshcore_open/screens/path_trace_map.dart'; +import 'package:meshcore_open/screens/region_management_screen.dart'; +import 'package:meshcore_open/screens/repeater_cli_screen.dart'; +import 'package:meshcore_open/screens/repeater_hub_screen.dart'; +import 'package:meshcore_open/screens/repeater_settings_screen.dart'; +import 'package:meshcore_open/screens/repeater_status_screen.dart'; +import 'package:meshcore_open/screens/scanner_screen.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/screens/tcp_screen.dart'; +import 'package:meshcore_open/screens/telemetry_screen.dart'; +import 'package:meshcore_open/screens/usb_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/network_map/network_map_upload_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; + +/// Renders every screen on a small phone (320x568, the narrowest common +/// width) at several text scales, plus a desktop window, and fails on any +/// layout overflow. +const _layouts = [ + (Size(320, 568), [1.0, 1.3, 2.0]), + (Size(1280, 800), [1.0]), +]; + +class _Env { + final MeshCoreConnector connector; + final List providers; + _Env(this.connector, this.providers); +} + +Future<_Env> _connect(WidgetTester tester) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + final env = _Env(connector, [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ChangeNotifierProvider.value( + value: NetworkMapUploadService(connector: connector, settings: settings), + ), + ]); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || connector.channels.isEmpty) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + return env; +} + +Contact _contactOfType(MeshCoreConnector c, int type) => c.contacts.firstWhere( + (x) => x.type == type, + orElse: () => c.contacts.first, +); + +_Env? _shared; + +typedef _ScreenBuilder = Widget Function(MeshCoreConnector c); + +/// Screens that open a sheet after the first frame, keyed like [_screens]. +final Map Function(WidgetTester t, MeshCoreConnector c)> +_interactions = { + 'Contacts options sheet': (t, _) async { + // At large text the first contact can start below the fold. + await t.drag(find.byType(RefreshIndicator), const Offset(0, -150)); + await t.pump(const Duration(milliseconds: 500)); + await t.longPress( + find + .byWidgetPredicate((w) => w.runtimeType.toString() == '_ContactTile') + .first, + ); + }, + 'Contacts add sheet': (t, _) async { + await t.tap(find.byType(FloatingActionButton)); + }, +}; + +final Map _screens = { + 'Contacts options sheet': (_) => const ContactsScreen(), + 'Contacts add sheet': (_) => const ContactsScreen(), + 'Scanner': (_) => const ScannerScreen(), + 'Tcp': (_) => const TcpScreen(), + 'Usb': (_) => const UsbScreen(), + 'ChromeRequired': (_) => const ChromeRequiredScreen(), + 'Contacts': (_) => const ContactsScreen(), + 'Channels': (_) => const ChannelsScreen(), + 'Settings': (_) => const SettingsScreen(), + 'AppSettings': (_) => const AppSettingsScreen(), + 'Discovery': (_) => const DiscoveryScreen(), + 'RegionManagement': (_) => const RegionManagementScreen(), + 'MapCache': (_) => const MapCacheScreen(), + 'CompanionRadioStats': (_) => const CompanionRadioStatsScreen(), + 'AppDebugLog': (_) => const AppDebugLogScreen(), + 'BleDebugLog': (_) => const BleDebugLogScreen(), + 'Map': (_) => const MapScreen(), + 'Chat': (c) => ChatScreen(contact: _contactOfType(c, advTypeChat)), + 'ChannelChat': (c) => ChannelChatScreen(channel: c.channels.first), + 'ChannelMessagePath': (c) { + final msgs = c.getChannelMessages(c.channels.first); + return ChannelMessagePathScreen(message: msgs.last); + }, + 'Telemetry': (c) => TelemetryScreen(contact: _contactOfType(c, advTypeChat)), + 'RepeaterHub': (c) => RepeaterHubScreen( + repeater: _contactOfType(c, advTypeRepeater), + password: '', + isAdmin: true, + ), + 'RepeaterStatus': (c) => RepeaterStatusScreen( + repeater: _contactOfType(c, advTypeRepeater), + password: '', + ), + 'RepeaterSettings': (c) => RepeaterSettingsScreen( + repeater: _contactOfType(c, advTypeRepeater), + password: '', + ), + 'RepeaterCli': (c) => RepeaterCliScreen( + repeater: _contactOfType(c, advTypeRepeater), + password: '', + ), + 'Neighbors': (c) => NeighborsScreen( + repeater: _contactOfType(c, advTypeRepeater), + password: '', + ), + 'PathTraceMap': (c) { + final r = _contactOfType(c, advTypeRepeater); + return PathTraceMapScreen( + title: 'Trace', + path: r.publicKey.sublist(0, 1), + targetContact: r, + ); + }, + 'LineOfSightMap': (_) => const LineOfSightMapScreen( + title: 'Line of sight', + candidates: [ + LineOfSightEndpoint(label: 'A', point: LatLng(45.5, -122.6)), + LineOfSightEndpoint(label: 'B', point: LatLng(45.6, -122.7)), + ], + ), +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('small_screen_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + final variants = [ + for (final entry in _screens.entries) (entry, false), + // Repeater screens add a banner while the companion radio is offline. + for (final entry in _screens.entries) + if (entry.key.startsWith('Repeater') || entry.key == 'Neighbors') + (entry, true), + ]; + for (final (entry, offline) in variants) { + for (final (size, scales) in _layouts) { + for (final scale in scales) { + final state = offline ? ' (radio offline)' : ''; + testWidgets('${entry.key}$state fits ${size.width.toInt()}dp at ' + '${scale}x', (tester) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final shared = _shared ??= await _connect(tester); + final env = offline + ? _Env(shared.connector, [ + ChangeNotifierProvider.value(value: MeshCoreConnector()), + ...shared.providers.skip(1), + ]) + : shared; + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (!text.contains('overflowed')) { + previous?.call(details); + return; + } + // The creation location names the overflowing Flex in lib/. + final where = RegExp(r'lib/[\w/]+\.dart:\d+') + .allMatches(details.toString()) + .map((m) => m[0]) + .toSet() + .join(', '); + overflows.add('${text.split('\n').first} at $where'); + }; + addTearDown(() => FlutterError.onError = previous); + + await tester.pumpWidget( + MultiProvider( + providers: env.providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: entry.value(env.connector), + ), + ), + ); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + final interaction = _interactions[entry.key]; + if (interaction != null) { + await interaction(tester, env.connector); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + await tester.pumpWidget(const SizedBox()); + // Let one-shot timers (scan and request timeouts) run out. + await tester.pump(const Duration(minutes: 1)); + + FlutterError.onError = previous; + expect(overflows, isEmpty, reason: overflows.join('\n---\n')); + }); + } + } + } +}