- Czech UI locale (app_cs.arb), selectable in the language picker and as a message translation language; language names added to every locale. - Fix wrong language names: Slovak shown as Slovenian in it/ja/pt/sl, garbled Slovak/Bulgarian in pl, Ukrainian in ru, Hungarian in ko/zh. - Search inside DM and channel chats across the full stored history, with highlighted matches; filtered channel messages are excluded. - Path trace by typed hashes (e.g. A1,B2,C3) from the Contacts and map menus, without needing node locations; the map trace panel can hand its hops to it. - Share contacts in chats using the official app's <pubkey:type:name> format; received cards have a one-tap Add contact button that reuses the QR card import path. - Translations for all new strings in every locale; docs updated.
4515 lines
156 KiB
Dart
4515 lines
156 KiB
Dart
import 'dart:async';
|
|
import 'dart:math';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter_map/flutter_map.dart';
|
|
import 'package:latlong2/latlong.dart';
|
|
import 'package:meshcore_open/helpers/path_helper.dart';
|
|
import 'package:meshcore_open/screens/path_trace_map.dart';
|
|
import 'package:meshcore_open/widgets/app_bar.dart';
|
|
import 'package:provider/provider.dart';
|
|
|
|
import '../connector/meshcore_connector.dart';
|
|
import '../connector/meshcore_protocol.dart';
|
|
import '../l10n/l10n.dart';
|
|
import '../models/app_settings.dart';
|
|
import '../models/channel.dart';
|
|
import '../models/map_path_trace_draft.dart';
|
|
import '../models/contact.dart';
|
|
import '../models/path_history.dart';
|
|
import '../l10n/contact_localization.dart';
|
|
import '../services/app_settings_service.dart';
|
|
import '../services/path_history_service.dart';
|
|
import '../services/map_marker_service.dart';
|
|
import '../services/map_tile_cache_service.dart';
|
|
import '../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';
|
|
import '../utils/contact_search.dart';
|
|
import '../utils/disconnect_navigation_mixin.dart';
|
|
import '../utils/battery_utils.dart';
|
|
import '../utils/route_transitions.dart';
|
|
import '../widgets/map_poi_cluster.dart';
|
|
import '../widgets/marker_label_dialog.dart';
|
|
import '../widgets/network_map_online_layer.dart';
|
|
import '../widgets/quick_switch_bar.dart';
|
|
import '../widgets/sync_progress_overlay.dart';
|
|
import '../icons/los_icon.dart';
|
|
import 'channels_screen.dart';
|
|
import 'manual_path_trace_screen.dart';
|
|
import 'chat_screen.dart';
|
|
import 'contacts_screen.dart';
|
|
import '../theme/mesh_theme.dart';
|
|
import '../widgets/mesh_ui.dart';
|
|
import '../widgets/node_info_sheet.dart';
|
|
import '../widgets/set_my_location_dialog.dart';
|
|
import '../helpers/guessed_location_estimator.dart';
|
|
import '../helpers/marker_message.dart';
|
|
import '../helpers/snack_bar_builder.dart';
|
|
import '../helpers/utf8_length_limiter.dart';
|
|
import 'settings_screen.dart';
|
|
import 'line_of_sight_map_screen.dart';
|
|
import '../theme/theme_icons.dart';
|
|
|
|
class MapScreen extends StatefulWidget {
|
|
final LatLng? highlightPosition;
|
|
final String? highlightLabel;
|
|
final String? highlightMarkerKey;
|
|
final double highlightZoom;
|
|
final bool hideBackButton;
|
|
|
|
const MapScreen({
|
|
super.key,
|
|
this.highlightPosition,
|
|
this.highlightLabel,
|
|
this.highlightMarkerKey,
|
|
this.highlightZoom = 15.0,
|
|
this.hideBackButton = false,
|
|
});
|
|
|
|
@override
|
|
State<MapScreen> createState() => _MapScreenState();
|
|
}
|
|
|
|
class _MapScreenState extends State<MapScreen> with DisconnectNavigationMixin {
|
|
// Zoom level at which node labels start to appear
|
|
static const double _labelZoomThreshold = 14.0;
|
|
// Below this zoom, nearby nodes collapse into clusters.
|
|
static const double _clusterOffZoom = 12.5;
|
|
// Guessed (estimated) locations only render at closer zooms to avoid a
|
|
// carpet of approximate markers at city-wide scale.
|
|
static const double _guessedZoomThreshold = 12.0;
|
|
static const double _mapMinZoom = 2.0;
|
|
static const double _mapMaxZoom = 18.0;
|
|
|
|
final MapController _mapController = MapController();
|
|
final MapMarkerService _markerService = MapMarkerService();
|
|
final NetworkMapOnlineController _online = NetworkMapOnlineController();
|
|
final Set<String> _hiddenMarkerIds = {};
|
|
Set<String> _removedMarkerIds = {};
|
|
late final MapPathTraceDraft _traceDraft = context
|
|
.read<UiViewStateService>()
|
|
.mapPathTrace;
|
|
bool get _isBuildingPathTrace => _traceDraft.active;
|
|
set _isBuildingPathTrace(bool value) => _traceDraft.active = value;
|
|
bool _isSelectingPoi = false;
|
|
bool _hasInitializedMap = false;
|
|
bool _removedMarkersLoaded = false;
|
|
List<int> get _pathTrace => _traceDraft.pathBytes;
|
|
List<int> get _pathTraceHopWidths => _traceDraft.hopWidths;
|
|
List<Contact> get _pathTraceContacts => _traceDraft.contacts;
|
|
List<LatLng> get _points => _traceDraft.points;
|
|
final List<Polyline> _polylines = [];
|
|
bool _statsExpanded = false;
|
|
bool _showNodeLabels = true;
|
|
double _zoom = 10.0;
|
|
String? _selectedKey;
|
|
String? _locatingKey;
|
|
LatLng? _selectedGuessPos;
|
|
_Freshness _freshness = _Freshness.all;
|
|
final TextEditingController _searchController = TextEditingController();
|
|
final FocusNode _searchFocus = FocusNode();
|
|
String _searchQuery = '';
|
|
List<_GuessedLocation> _cachedGuessedLocations = [];
|
|
int? _guessedLocationsCacheKey;
|
|
static const Duration _guessMaxAge = Duration(days: 7);
|
|
({LatLng center, double zoom})? _cachedFallbackCamera;
|
|
bool _guessInFlight = false;
|
|
VoidCallback? _guessRerun;
|
|
// Saved paths for contacts outside the path-history cache, read once.
|
|
final Map<String, List<PathRecord>> _storedPaths = {};
|
|
int? _sharedMarkersCacheSignature;
|
|
Locale? _sharedMarkersCacheLocale;
|
|
List<_SharedMarker> _cachedSharedMarkers = const [];
|
|
_NodeMarkersCacheKey? _nodeMarkersCacheKey;
|
|
List<Marker> _cachedNodeMarkers = const [];
|
|
// Online/recent status is derived from DateTime.now(); rebuild periodically
|
|
// so markers age even when the connector stays quiet.
|
|
Timer? _ageTimer;
|
|
// Camera computed from the visible points; only needed until the map has
|
|
// been positioned once.
|
|
({LatLng center, double zoom})? _initialCamera;
|
|
|
|
static const String _lastCameraKey = 'map_last_camera';
|
|
|
|
({LatLng center, double zoom}) _fallbackCamera(MeshCoreConnector connector) {
|
|
final lat = connector.selfLatitude;
|
|
final lon = connector.selfLongitude;
|
|
if (lat != null && lon != null && isPlausibleLocation(lat, lon)) {
|
|
return (center: LatLng(lat, lon), zoom: 12.0);
|
|
}
|
|
final saved = PrefsManager.instance.getStringList(_lastCameraKey);
|
|
if (saved != null && saved.length == 3) {
|
|
final values = saved.map(double.tryParse).toList();
|
|
if (!values.contains(null)) {
|
|
return (center: LatLng(values[0]!, values[1]!), zoom: values[2]!);
|
|
}
|
|
}
|
|
return (center: const LatLng(20, 0), zoom: _mapMinZoom);
|
|
}
|
|
|
|
void _saveLastCamera() {
|
|
try {
|
|
final camera = _mapController.camera;
|
|
PrefsManager.instance.setStringList(_lastCameraKey, [
|
|
camera.center.latitude.toString(),
|
|
camera.center.longitude.toString(),
|
|
camera.zoom.toString(),
|
|
]);
|
|
} catch (_) {}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_ageTimer?.cancel();
|
|
_online.removeListener(_onOnlineChanged);
|
|
_online.dispose();
|
|
_saveLastCamera();
|
|
_searchController.dispose();
|
|
_searchFocus.dispose();
|
|
_mapController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
ColorScheme get _overlayScheme => Theme.of(context).colorScheme;
|
|
|
|
bool get _useDarkOverlay => Theme.of(context).brightness == Brightness.dark;
|
|
|
|
/// The stock dark theme keeps the map's fixed high-contrast panels; custom
|
|
/// themes (and light mode) draw panels in the theme's own colors.
|
|
bool get _usePaletteOverlay =>
|
|
_useDarkOverlay && !MeshMapTheme.of(context).followsTheme;
|
|
|
|
Color get _overlayPanelColor => _usePaletteOverlay
|
|
? MapPalette.panelDark
|
|
: _overlayScheme.surfaceContainerLow.withValues(alpha: 0.96);
|
|
|
|
Color get _overlayPrimaryTextColor =>
|
|
_usePaletteOverlay ? MapPalette.textPrimary : _overlayScheme.onSurface;
|
|
|
|
Color get _overlaySecondaryTextColor => _usePaletteOverlay
|
|
? MapPalette.textSecondary
|
|
: _overlayScheme.onSurfaceVariant;
|
|
|
|
Color get _overlayMutedTextColor => _usePaletteOverlay
|
|
? MapPalette.textMuted
|
|
: _overlayScheme.onSurfaceVariant;
|
|
|
|
Color get _overlayBorderColor =>
|
|
_usePaletteOverlay ? MapPalette.border : _overlayScheme.outlineVariant;
|
|
|
|
Color get _overlayShadowColor => _usePaletteOverlay
|
|
? MapPalette.markerShadow
|
|
: MapPalette.markerShadow.withValues(alpha: 0.18);
|
|
|
|
_NodeAge _ageOf(Contact contact) {
|
|
final d = DateTime.now().difference(contact.lastHeard);
|
|
if (d.inMinutes <= 60) return _NodeAge.online;
|
|
if (d.inHours <= 24) return _NodeAge.recent;
|
|
return _NodeAge.stale;
|
|
}
|
|
|
|
void _selectNode(Contact contact, {LatLng? guessedPosition}) {
|
|
HapticFeedback.selectionClick();
|
|
setState(() {
|
|
_selectedKey = contact.publicKeyHex;
|
|
_selectedGuessPos = guessedPosition;
|
|
_searchQuery = '';
|
|
_searchController.clear();
|
|
_searchFocus.unfocus();
|
|
});
|
|
}
|
|
|
|
void _clearSelection() {
|
|
setState(() {
|
|
_selectedKey = null;
|
|
_selectedGuessPos = null;
|
|
});
|
|
}
|
|
|
|
void _onOnlineChanged() {
|
|
if (mounted) setState(() {});
|
|
}
|
|
|
|
bool _showsOnline(MapSourceOption source) => source != MapSourceOption.local;
|
|
|
|
void _requestOnlineData() {
|
|
try {
|
|
_online.requestBounds(
|
|
_mapController.camera.visibleBounds,
|
|
fetchLinks: context
|
|
.read<AppSettingsService>()
|
|
.settings
|
|
.mapShowOnlineLinks,
|
|
);
|
|
} catch (_) {
|
|
// Camera not ready yet; onMapReady requests once it is.
|
|
}
|
|
}
|
|
|
|
void _setMapSource(MapSourceOption source) {
|
|
context.read<UiViewStateService>().setMapSource(source);
|
|
if (_showsOnline(source)) {
|
|
_requestOnlineData();
|
|
} else {
|
|
_online.cancel();
|
|
}
|
|
}
|
|
|
|
void _showOnlineRepeater(
|
|
BuildContext context,
|
|
MeshCoreConnector connector,
|
|
NetworkMapRepeater repeater,
|
|
) {
|
|
showNetworkMapRepeaterSheet(
|
|
context,
|
|
connector: connector,
|
|
repeater: repeater,
|
|
onManage: (contact) => contact.type == advTypeRoom
|
|
? showRoomLoginDialog(context, contact, manage: true)
|
|
: showRepeaterLoginDialog(context, contact),
|
|
);
|
|
}
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_loadRemovedMarkers();
|
|
_online.addListener(_onOnlineChanged);
|
|
_ageTimer = Timer.periodic(const Duration(seconds: 60), (_) {
|
|
if (mounted) setState(() {});
|
|
});
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (mounted) {
|
|
context.read<MeshCoreConnector>().getChannels();
|
|
if (widget.highlightPosition != null) {
|
|
_mapController.move(widget.highlightPosition!, widget.highlightZoom);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
Future<void> _loadRemovedMarkers() async {
|
|
final ids = await _markerService.loadRemovedIds();
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_removedMarkerIds = ids;
|
|
_removedMarkersLoaded = true;
|
|
});
|
|
// If this screen was opened to highlight a marker, and that marker
|
|
// was previously removed, re-enable it now that we've loaded the saved
|
|
// removed IDs.
|
|
if (widget.highlightMarkerKey != null &&
|
|
_removedMarkerIds.contains(widget.highlightMarkerKey)) {
|
|
final updated = Set<String>.from(_removedMarkerIds);
|
|
updated.remove(widget.highlightMarkerKey);
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_removedMarkerIds = updated;
|
|
});
|
|
await _markerService.saveRemovedIds(updated);
|
|
}
|
|
}
|
|
|
|
double _standardDeviation(List<double> values) {
|
|
if (values.length <= 1) {
|
|
return 0.0;
|
|
}
|
|
|
|
final mean = values.reduce((a, b) => a + b) / values.length;
|
|
|
|
double sumSquaredDiff = 0.0;
|
|
for (final value in values) {
|
|
final diff = value - mean;
|
|
sumSquaredDiff += diff * diff;
|
|
}
|
|
|
|
// Sample standard deviation (n-1) — most appropriate here
|
|
final variance = sumSquaredDiff / (values.length - 1);
|
|
|
|
return sqrt(variance);
|
|
}
|
|
|
|
// Calculate zoom level based on the spread of points (std deviation in degrees)
|
|
double _zoomFromStdDev(double latStdDev, double lonStdDev) {
|
|
final maxSpread = max(latStdDev, lonStdDev);
|
|
if (maxSpread <= 0) return 13.0;
|
|
// Approximate: each zoom level halves the visible area
|
|
// ~0.01 degrees spread -> zoom 13, ~0.1 -> zoom 10, ~1.0 -> zoom 7
|
|
final zoom = 10.0 - log(maxSpread * 10 + 1) / ln10 * 3;
|
|
return zoom.clamp(4.0, 15.0);
|
|
}
|
|
|
|
/// Centre and zoom that frame [allPoints], ignoring outliers more than two
|
|
/// standard deviations away. Returns null when there are no points.
|
|
({LatLng center, double zoom})? _cameraForPoints(List<LatLng> allPoints) {
|
|
if (allPoints.isEmpty) return null;
|
|
if (allPoints.length < 3) {
|
|
double avgLat = 0.0;
|
|
double avgLon = 0.0;
|
|
for (final point in allPoints) {
|
|
avgLat += point.latitude;
|
|
avgLon += point.longitude;
|
|
}
|
|
return (
|
|
center: LatLng(avgLat / allPoints.length, avgLon / allPoints.length),
|
|
zoom: 12.0,
|
|
);
|
|
}
|
|
final latValues = allPoints.map((p) => p.latitude).toList();
|
|
final lonValues = allPoints.map((p) => p.longitude).toList();
|
|
|
|
final meanLat = latValues.reduce((a, b) => a + b) / latValues.length;
|
|
final meanLon = lonValues.reduce((a, b) => a + b) / lonValues.length;
|
|
final latStdDev = _standardDeviation(latValues);
|
|
final lonStdDev = _standardDeviation(lonValues);
|
|
|
|
final filteredPoints = allPoints
|
|
.where(
|
|
(p) =>
|
|
(p.latitude - meanLat).abs() <= latStdDev * 2 &&
|
|
(p.longitude - meanLon).abs() <= lonStdDev * 2,
|
|
)
|
|
.toList();
|
|
|
|
if (filteredPoints.isEmpty) {
|
|
return (
|
|
center: LatLng(meanLat, meanLon),
|
|
zoom: _zoomFromStdDev(latStdDev, lonStdDev),
|
|
);
|
|
}
|
|
final filteredLatValues = filteredPoints.map((p) => p.latitude).toList();
|
|
final filteredLonValues = filteredPoints.map((p) => p.longitude).toList();
|
|
final avgLat = filteredLatValues.reduce((a, b) => a + b);
|
|
final avgLon = filteredLonValues.reduce((a, b) => a + b);
|
|
return (
|
|
center: LatLng(
|
|
avgLat / filteredPoints.length,
|
|
avgLon / filteredPoints.length,
|
|
),
|
|
// Use std deviation of filtered points for zoom
|
|
zoom: _zoomFromStdDev(
|
|
_standardDeviation(filteredLatValues),
|
|
_standardDeviation(filteredLonValues),
|
|
),
|
|
);
|
|
}
|
|
|
|
bool _isDesktopPlatform(TargetPlatform platform) {
|
|
return platform == TargetPlatform.linux ||
|
|
platform == TargetPlatform.windows ||
|
|
platform == TargetPlatform.macOS;
|
|
}
|
|
|
|
void _zoomMapBy(double delta) {
|
|
final camera = _mapController.camera;
|
|
final nextZoom = (camera.zoom + delta)
|
|
.clamp(_mapMinZoom, _mapMaxZoom)
|
|
.toDouble();
|
|
_mapController.move(camera.center, nextZoom);
|
|
}
|
|
|
|
Widget _buildControlRail(
|
|
BuildContext context, {
|
|
required ({LatLng center, double zoom}) Function() computeCamera,
|
|
required MeshCoreConnector connector,
|
|
}) {
|
|
final hasSelf =
|
|
connector.selfLatitude != null && connector.selfLongitude != null;
|
|
return Positioned(
|
|
left: 12,
|
|
bottom: 96,
|
|
child: DecoratedBox(
|
|
decoration: BoxDecoration(
|
|
color: _overlayPanelColor,
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
border: Border.all(color: _overlayBorderColor),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
],
|
|
),
|
|
child: ClipRRect(
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.add),
|
|
visualDensity: VisualDensity.standard,
|
|
tooltip: context.l10n.map_zoomIn,
|
|
onPressed: () => _zoomMapBy(1),
|
|
),
|
|
IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.remove),
|
|
tooltip: context.l10n.map_zoomOut,
|
|
onPressed: () => _zoomMapBy(-1),
|
|
),
|
|
IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.crop_free),
|
|
tooltip: context.l10n.map_centerMap,
|
|
onPressed: () {
|
|
final camera = computeCamera();
|
|
_mapController.move(camera.center, camera.zoom);
|
|
},
|
|
),
|
|
if (hasSelf)
|
|
IconButton(
|
|
color: MeshMapTheme.of(context).accent,
|
|
icon: const Icon(Icons.my_location),
|
|
tooltip: context.l10n.map_centerOnMe,
|
|
onPressed: () => _mapController.move(
|
|
LatLng(connector.selfLatitude!, connector.selfLongitude!),
|
|
max(_zoom, 14),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
void _handleMapContextPress(
|
|
BuildContext context,
|
|
MeshCoreConnector connector,
|
|
LatLng latLng,
|
|
) {
|
|
if (_isSelectingPoi) {
|
|
setState(() {
|
|
_isSelectingPoi = false;
|
|
});
|
|
_shareMarker(
|
|
context: context,
|
|
connector: connector,
|
|
position: latLng,
|
|
defaultLabel: context.l10n.map_pointOfInterest,
|
|
flags: 'poi',
|
|
);
|
|
return;
|
|
}
|
|
_showShareMarkerAtPositionSheet(
|
|
context: context,
|
|
connector: connector,
|
|
position: latLng,
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Builder(
|
|
builder: (context) {
|
|
final connectorSnapshot = context
|
|
.select<MeshCoreConnector, _MapConnectorSnapshot>(
|
|
_MapConnectorSnapshot.fromConnector,
|
|
);
|
|
final connector = connectorSnapshot.connector;
|
|
if (!checkConnectionAndNavigate(connector)) {
|
|
return const SizedBox.shrink();
|
|
}
|
|
final settings = context.select<AppSettingsService, AppSettings>(
|
|
(service) => service.settings,
|
|
);
|
|
final pathHistoryVersion = context.select<PathHistoryService, int>(
|
|
(service) => service.version,
|
|
);
|
|
final mapSource = context.select<UiViewStateService, MapSourceOption>(
|
|
(service) => service.mapSource,
|
|
);
|
|
final showLocal = mapSource != MapSourceOption.online;
|
|
final showOnline = _showsOnline(mapSource);
|
|
final settingsService = context.read<AppSettingsService>();
|
|
final pathHistory = context.read<PathHistoryService>();
|
|
final tileCache = context.read<MapTileCacheService>();
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final isDesktop = _isDesktopPlatform(defaultTargetPlatform);
|
|
final allContacts = connector.allContacts;
|
|
|
|
final contacts = settings.mapShowDiscoveryContacts
|
|
? allContacts
|
|
: allContacts.where((c) => c.isActive).toList();
|
|
|
|
final highlightPosition = widget.highlightPosition;
|
|
final sharedMarkers = settings.mapShowMarkers
|
|
? _collectSharedMarkers(
|
|
connector,
|
|
connectorSnapshot.markerSignature,
|
|
)
|
|
.where(
|
|
(marker) =>
|
|
!_hiddenMarkerIds.contains(marker.id) &&
|
|
!_removedMarkerIds.contains(marker.id),
|
|
)
|
|
.toList()
|
|
: <_SharedMarker>[];
|
|
|
|
// Filter by time
|
|
final now = DateTime.now();
|
|
final filteredByTime = settings.mapTimeFilterHours == 0
|
|
? contacts
|
|
: contacts.where((c) {
|
|
final hoursSinceLastSeen = now.difference(c.lastHeard).inHours;
|
|
return hoursSinceLastSeen <= settings.mapTimeFilterHours;
|
|
}).toList();
|
|
|
|
// Quick activity filter (search bar chips)
|
|
final filteredByFreshness = switch (_freshness) {
|
|
_Freshness.all => filteredByTime,
|
|
_Freshness.online =>
|
|
filteredByTime.where((c) => _ageOf(c) == _NodeAge.online).toList(),
|
|
_Freshness.recent =>
|
|
filteredByTime.where((c) => _ageOf(c) != _NodeAge.stale).toList(),
|
|
_Freshness.stale =>
|
|
filteredByTime.where((c) => _ageOf(c) == _NodeAge.stale).toList(),
|
|
};
|
|
|
|
// Filter by key prefix
|
|
final keyPrefix = settings.mapKeyPrefix.trim();
|
|
final filteredByKeyPrefix =
|
|
(settings.mapKeyPrefixEnabled && keyPrefix.isNotEmpty)
|
|
? filteredByFreshness.where((c) {
|
|
return c.publicKeyHex.toLowerCase().startsWith(
|
|
keyPrefix.toLowerCase(),
|
|
);
|
|
}).toList()
|
|
: filteredByFreshness;
|
|
|
|
// Filter by location
|
|
final contactsWithLocation = filteredByKeyPrefix.where((c) {
|
|
return c.hasLocation;
|
|
}).toList();
|
|
|
|
// All contacts with a known location — used as anchors regardless of
|
|
// time/key-prefix filters so that repeaters are always available.
|
|
final allContactsWithLocation = allContacts
|
|
.where((c) => c.hasLocation)
|
|
.toList();
|
|
|
|
// Guessed markers represent the same node types as known-location
|
|
// markers, so apply the node-type filters before estimating positions.
|
|
final guessCandidates = _filterContactsBySettings(
|
|
filteredByKeyPrefix,
|
|
settings,
|
|
noLocations: true,
|
|
);
|
|
|
|
// Guessed locations are computed in a background isolate; the last
|
|
// result stays on screen until the new one arrives.
|
|
final maxRangeKm = _estimateLoRaRangeKm(connector);
|
|
final cacheKey = Object.hash(
|
|
Object.hashAll(
|
|
guessCandidates.map(
|
|
(c) => Object.hash(c.publicKeyHex, _bytesSignature(c.path)),
|
|
),
|
|
),
|
|
Object.hashAll(
|
|
allContactsWithLocation.map(
|
|
(c) =>
|
|
Object.hash(c.publicKeyHex, c.latitude, c.longitude, c.type),
|
|
),
|
|
),
|
|
pathHistoryVersion,
|
|
maxRangeKm,
|
|
connector.selfLatitude,
|
|
connector.selfLongitude,
|
|
settings.mapShowGuessedLocations,
|
|
);
|
|
if (cacheKey != _guessedLocationsCacheKey) {
|
|
_guessedLocationsCacheKey = cacheKey;
|
|
if (settings.mapShowGuessedLocations) {
|
|
unawaited(
|
|
_startGuessedLocations(
|
|
cacheKey,
|
|
guessCandidates,
|
|
allContactsWithLocation,
|
|
pathHistory,
|
|
maxRangeKm,
|
|
),
|
|
);
|
|
} else {
|
|
_cachedGuessedLocations = [];
|
|
}
|
|
}
|
|
final guessedLocations = settings.mapShowGuessedLocations
|
|
? _cachedGuessedLocations
|
|
: <_GuessedLocation>[];
|
|
|
|
_polylines.clear();
|
|
_polylines.addAll(
|
|
_points.length > 1
|
|
? [
|
|
Polyline(
|
|
points: _points,
|
|
strokeWidth: 4,
|
|
color: MeshMapTheme.of(context).accent,
|
|
),
|
|
]
|
|
: <Polyline>[],
|
|
);
|
|
|
|
// Collect polylines for shared markers' history with dashed lines
|
|
final List<Polyline> sharedMarkerPolylines = [];
|
|
for (final marker in sharedMarkers) {
|
|
if (marker.history.isNotEmpty) {
|
|
final points = List<LatLng>.from(marker.history);
|
|
points.add(marker.position);
|
|
sharedMarkerPolylines.add(
|
|
Polyline(
|
|
points: points,
|
|
color: marker.isChannel
|
|
? (marker.isPublicChannel
|
|
? MapPalette.cluster
|
|
: MapPalette.router)
|
|
: MapPalette.shared,
|
|
strokeWidth: 3,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
// Only the first frame's camera matters; afterwards reuse it instead
|
|
// of re-reading prefs and re-running the spread statistics on every
|
|
// rebuild. The "center map" control recomputes on demand.
|
|
({LatLng center, double zoom}) computeCamera() {
|
|
final fallback = _hasInitializedMap
|
|
? (_cachedFallbackCamera ??= _fallbackCamera(connector))
|
|
: _fallbackCamera(connector);
|
|
if (highlightPosition != null) {
|
|
return (center: highlightPosition, zoom: widget.highlightZoom);
|
|
}
|
|
return _cameraForPoints([
|
|
...contactsWithLocation.map(
|
|
(c) => LatLng(c.latitude!, c.longitude!),
|
|
),
|
|
...sharedMarkers.map((m) => m.position),
|
|
]) ??
|
|
fallback;
|
|
}
|
|
|
|
final (center: center, zoom: initialZoom) = _hasInitializedMap
|
|
? (_initialCamera ??= computeCamera())
|
|
: computeCamera();
|
|
|
|
// Re center map after removed markers have loaded
|
|
if (!_hasInitializedMap && _removedMarkersLoaded) {
|
|
_hasInitializedMap = true;
|
|
_initialCamera = (center: center, zoom: initialZoom);
|
|
_showNodeLabels = initialZoom >= _labelZoomThreshold;
|
|
_zoom = initialZoom;
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (mounted) {
|
|
_mapController.move(center, initialZoom);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Opened as a detail screen (e.g. from a chat's location link): let the
|
|
// user go back. As a quick-switch root, keep the tab-like behaviour.
|
|
final isDetailScreen = !widget.hideBackButton;
|
|
final allowBack = isDetailScreen || !connector.isConnected;
|
|
|
|
final visibleContacts = _filterContactsBySettings(
|
|
contactsWithLocation,
|
|
settings,
|
|
);
|
|
final visibleOnlineRepeaters = _filterOnlineRepeatersBySettings(
|
|
_online.repeaters,
|
|
settings,
|
|
showGuessedLocations: settings.mapShowGuessedLocations,
|
|
);
|
|
Contact? selectedContact;
|
|
if (_selectedKey != null) {
|
|
for (final c in allContacts) {
|
|
if (c.publicKeyHex == _selectedKey) {
|
|
selectedContact = c;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
final locatedTotal = allContacts.where((c) => c.hasLocation).length;
|
|
final hiddenCount = max(0, locatedTotal - visibleContacts.length);
|
|
final onlineCount = visibleContacts
|
|
.where((c) => _ageOf(c) == _NodeAge.online)
|
|
.length;
|
|
final repeaterCount = visibleContacts
|
|
.where((c) => c.type == advTypeRepeater)
|
|
.length;
|
|
|
|
return PopScope(
|
|
canPop: allowBack && !_isBuildingPathTrace,
|
|
onPopInvokedWithResult: (didPop, _) {
|
|
if (!didPop && _isBuildingPathTrace) _closePathTrace();
|
|
},
|
|
child: Scaffold(
|
|
appBar: AppBar(
|
|
backgroundColor: scheme.surface,
|
|
foregroundColor: scheme.onSurface,
|
|
title: AppBarTitle(context.l10n.map_title),
|
|
centerTitle: true,
|
|
automaticallyImplyLeading: false,
|
|
leading: isDetailScreen && Navigator.canPop(context)
|
|
? BackButton(onPressed: () => Navigator.maybePop(context))
|
|
: null,
|
|
bottom: const SyncProgressAppBarBottom(),
|
|
actions: [
|
|
PopupMenuButton(
|
|
itemBuilder: (context) => [
|
|
if (!_isBuildingPathTrace &&
|
|
connector.selfLatitude != null &&
|
|
connector.selfLongitude != null)
|
|
PopupMenuItem(
|
|
child: Row(
|
|
children: [
|
|
const Icon(Icons.radar),
|
|
const SizedBox(width: 8),
|
|
Text(context.l10n.contacts_pathTrace),
|
|
],
|
|
),
|
|
onTap: () => _openPathTrace(
|
|
connector,
|
|
LatLng(
|
|
connector.selfLatitude!,
|
|
connector.selfLongitude!,
|
|
),
|
|
),
|
|
),
|
|
if (!_isBuildingPathTrace)
|
|
PopupMenuItem(
|
|
child: Row(
|
|
children: [
|
|
const Icon(Icons.radar),
|
|
const SizedBox(width: 8),
|
|
Text(context.l10n.manualTrace_menuItem),
|
|
],
|
|
),
|
|
onTap: () => ManualPathTraceScreen.open(context),
|
|
),
|
|
if (!_isBuildingPathTrace)
|
|
PopupMenuItem(
|
|
child: Row(
|
|
children: [
|
|
const LosIcon(),
|
|
const SizedBox(width: 8),
|
|
Text(context.l10n.map_lineOfSight),
|
|
],
|
|
),
|
|
onTap: () {
|
|
final candidates = <LineOfSightEndpoint>[];
|
|
if (connector.selfLatitude != null &&
|
|
connector.selfLongitude != null) {
|
|
candidates.add(
|
|
LineOfSightEndpoint(
|
|
label: context.l10n.pathTrace_you,
|
|
point: LatLng(
|
|
connector.selfLatitude!,
|
|
connector.selfLongitude!,
|
|
),
|
|
color: MeshMapTheme.of(context).accent,
|
|
icon: Icons.person_pin_circle,
|
|
),
|
|
);
|
|
}
|
|
for (final c in contactsWithLocation) {
|
|
candidates.add(
|
|
LineOfSightEndpoint(
|
|
label: c.name,
|
|
point: LatLng(c.latitude!, c.longitude!),
|
|
color: mapNodeTypeColor(c.type),
|
|
icon: mapNodeTypeIcon(c.type),
|
|
),
|
|
);
|
|
}
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) => LineOfSightMapScreen(
|
|
title: context.l10n.map_losScreenTitle,
|
|
candidates: candidates,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
PopupMenuItem(
|
|
child: Row(
|
|
children: [
|
|
Icon(
|
|
Icons.logout,
|
|
color: Theme.of(context).colorScheme.error,
|
|
),
|
|
const SizedBox(width: 8),
|
|
Text(context.l10n.common_disconnect),
|
|
],
|
|
),
|
|
onTap: () => _disconnect(context, connector),
|
|
),
|
|
PopupMenuItem(
|
|
child: Row(
|
|
children: [
|
|
const ThemedIcon(ThemeIconSlot.settings),
|
|
const SizedBox(width: 8),
|
|
Text(context.l10n.settings_title),
|
|
],
|
|
),
|
|
onTap: () => Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) => const SettingsScreen(),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
icon: const Icon(Icons.more_vert),
|
|
),
|
|
],
|
|
),
|
|
body: Stack(
|
|
children: [
|
|
FlutterMap(
|
|
mapController: _mapController,
|
|
options: MapOptions(
|
|
initialCenter: center,
|
|
initialZoom: initialZoom,
|
|
minZoom: _mapMinZoom,
|
|
maxZoom: _mapMaxZoom,
|
|
interactionOptions: InteractionOptions(
|
|
flags: ~InteractiveFlag.rotate,
|
|
scrollWheelVelocity: isDesktop ? 0.012 : 0.005,
|
|
cursorKeyboardRotationOptions:
|
|
CursorKeyboardRotationOptions.disabled(),
|
|
keyboardOptions: isDesktop
|
|
? const KeyboardOptions(
|
|
enableArrowKeysPanning: true,
|
|
enableWASDPanning: true,
|
|
enableRFZooming: true,
|
|
)
|
|
: const KeyboardOptions.disabled(),
|
|
),
|
|
onTap: (_, latLng) {
|
|
if (_isSelectingPoi) {
|
|
setState(() {
|
|
_isSelectingPoi = false;
|
|
});
|
|
_shareMarker(
|
|
context: context,
|
|
connector: connector,
|
|
position: latLng,
|
|
defaultLabel: context.l10n.map_pointOfInterest,
|
|
flags: 'poi',
|
|
);
|
|
return;
|
|
}
|
|
// Tapping empty map dismisses selection + search.
|
|
if (_selectedKey != null || _searchQuery.isNotEmpty) {
|
|
setState(() {
|
|
_selectedKey = null;
|
|
_selectedGuessPos = null;
|
|
_searchQuery = '';
|
|
_searchController.clear();
|
|
_searchFocus.unfocus();
|
|
});
|
|
}
|
|
},
|
|
onLongPress: (_, latLng) {
|
|
_handleMapContextPress(context, connector, latLng);
|
|
},
|
|
onSecondaryTap: (_, latLng) {
|
|
_handleMapContextPress(context, connector, latLng);
|
|
},
|
|
onMapReady: () {
|
|
if (showOnline) _requestOnlineData();
|
|
},
|
|
onMapEvent: (event) {
|
|
if (event is MapEventMoveEnd ||
|
|
event is MapEventFlingAnimationEnd ||
|
|
event is MapEventScrollWheelZoom ||
|
|
event is MapEventDoubleTapZoomEnd) {
|
|
_saveLastCamera();
|
|
if (showOnline) _requestOnlineData();
|
|
}
|
|
},
|
|
onPositionChanged: (camera, hasGesture) {
|
|
// Track zoom in half-step buckets so cluster/marker
|
|
// detail levels update without rebuilding every frame.
|
|
final bucket = (camera.zoom * 2).roundToDouble() / 2;
|
|
final shouldShow = camera.zoom >= _labelZoomThreshold;
|
|
if ((bucket != _zoom || shouldShow != _showNodeLabels) &&
|
|
mounted) {
|
|
setState(() {
|
|
_zoom = bucket;
|
|
_showNodeLabels = shouldShow;
|
|
});
|
|
}
|
|
},
|
|
),
|
|
children: [
|
|
tileCache.buildTileLayer(context),
|
|
if (_polylines.isNotEmpty && _isBuildingPathTrace)
|
|
PolylineLayer(polylines: _polylines),
|
|
if (sharedMarkerPolylines.isNotEmpty)
|
|
PolylineLayer(polylines: sharedMarkerPolylines),
|
|
if (showOnline)
|
|
...buildNetworkMapOnlineLayers(
|
|
controller: _online,
|
|
repeaters: visibleOnlineRepeaters,
|
|
showLinks: settings.mapShowOnlineLinks,
|
|
localMarkerKeys: showLocal
|
|
? {for (final c in visibleContacts) c.publicKeyHex}
|
|
: const {},
|
|
onTap: (repeater) =>
|
|
_showOnlineRepeater(context, connector, repeater),
|
|
),
|
|
MarkerLayer(
|
|
markers: [
|
|
if (highlightPosition != null)
|
|
Marker(
|
|
point: highlightPosition,
|
|
width: 44,
|
|
height: 44,
|
|
child: IgnorePointer(
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: MapPalette.batteryLow,
|
|
border: Border.all(
|
|
color: MapPalette.markerOutline,
|
|
width: 3,
|
|
),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
],
|
|
),
|
|
child: const Icon(
|
|
Icons.location_on,
|
|
color: MapPalette.markerOutline,
|
|
size: 25,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
if (showLocal &&
|
|
!settings.mapShowOverlaps &&
|
|
(_zoom >= _guessedZoomThreshold ||
|
|
_isBuildingPathTrace))
|
|
..._buildGuessedMarker(
|
|
guessedLocations,
|
|
showLabels: _showNodeLabels,
|
|
),
|
|
if (showLocal)
|
|
..._buildNodeMarkersCached(
|
|
visibleContacts,
|
|
settings,
|
|
connectorSnapshot.contactsSignature,
|
|
connectorSnapshot.batterySignature,
|
|
_freshness,
|
|
settings.mapTimeFilterHours,
|
|
settings.mapKeyPrefixEnabled,
|
|
settings.mapKeyPrefix,
|
|
settings.mapShowDiscoveryContacts,
|
|
Object.hashAllUnordered(
|
|
settings.batteryChemistryByRepeaterId.entries.map(
|
|
(entry) => Object.hash(entry.key, entry.value),
|
|
),
|
|
),
|
|
showLabels: _showNodeLabels,
|
|
selectedContact: selectedContact,
|
|
),
|
|
..._buildPoiAndSelfMarkers(
|
|
sharedMarkers,
|
|
selfPosition:
|
|
connector.selfLatitude != null &&
|
|
connector.selfLongitude != null
|
|
? LatLng(
|
|
connector.selfLatitude!,
|
|
connector.selfLongitude!,
|
|
)
|
|
: null,
|
|
clusterPois:
|
|
!settings.mapShowOverlaps &&
|
|
!_isBuildingPathTrace,
|
|
),
|
|
if (_showNodeLabels &&
|
|
connector.selfLatitude != null &&
|
|
connector.selfLongitude != null)
|
|
_buildNodeLabelMarker(
|
|
point: LatLng(
|
|
connector.selfLatitude!,
|
|
connector.selfLongitude!,
|
|
),
|
|
label: context.l10n.pathTrace_you,
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
if (selectedContact == null)
|
|
_buildControlRail(
|
|
context,
|
|
computeCamera: computeCamera,
|
|
connector: connector,
|
|
),
|
|
if (!_isBuildingPathTrace)
|
|
_buildTopOverlay(
|
|
context,
|
|
mapSource: mapSource,
|
|
connector: connector,
|
|
settingsService: settingsService,
|
|
allContacts: allContacts,
|
|
guessedLocations: guessedLocations,
|
|
visibleCount:
|
|
visibleContacts.length +
|
|
((settings.mapShowGuessedLocations &&
|
|
_zoom >= _guessedZoomThreshold)
|
|
? guessedLocations.length
|
|
: 0),
|
|
onlineCount: onlineCount,
|
|
repeaterCount: repeaterCount,
|
|
hiddenCount: hiddenCount,
|
|
pinCount: sharedMarkers.length,
|
|
),
|
|
if (_isBuildingPathTrace) _buildPathTraceOverlay(),
|
|
if (showOnline &&
|
|
!_isBuildingPathTrace &&
|
|
selectedContact == null &&
|
|
(_online.state == NetworkMapLoadState.zoomIn ||
|
|
_online.state == NetworkMapLoadState.error))
|
|
_buildOnlineHint(context, _online.state)
|
|
else if (showLocal &&
|
|
contactsWithLocation.isEmpty &&
|
|
selectedContact == null &&
|
|
!_isBuildingPathTrace)
|
|
Positioned(
|
|
left: 16,
|
|
right: 88,
|
|
bottom: 16,
|
|
child: Card(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(12),
|
|
child: Text(context.l10n.map_noNodesLocationHint),
|
|
),
|
|
),
|
|
),
|
|
if (selectedContact != null && !_isBuildingPathTrace)
|
|
_buildSelectedNodeCard(context, selectedContact, connector),
|
|
],
|
|
),
|
|
bottomNavigationBar: SafeArea(
|
|
top: false,
|
|
child: QuickSwitchBar(
|
|
selectedIndex: 2,
|
|
onDestinationSelected: (index) =>
|
|
_handleQuickSwitch(index, context),
|
|
contactsUnreadCount: connector.getTotalContactsUnreadCount(),
|
|
channelsUnreadCount: connector.getTotalChannelsUnreadCount(),
|
|
highContrast: _usePaletteOverlay,
|
|
),
|
|
),
|
|
floatingActionButton:
|
|
(selectedContact == null && !_isBuildingPathTrace)
|
|
? FloatingActionButton(
|
|
onPressed: () => _showFilterSheet(context, settingsService),
|
|
tooltip: context.l10n.map_filterNodes,
|
|
child: Badge.count(
|
|
count: _activeFilterCount(settings),
|
|
isLabelVisible: _activeFilterCount(settings) > 0,
|
|
child: const Icon(Icons.filter_list),
|
|
),
|
|
)
|
|
: null,
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
List<Marker> _buildNodeMarkersCached(
|
|
List<Contact> contacts,
|
|
AppSettings settings,
|
|
int contactsSignature,
|
|
int batterySignature,
|
|
_Freshness freshness,
|
|
double timeFilterHours,
|
|
bool keyPrefixEnabled,
|
|
String keyPrefix,
|
|
bool showDiscoveryContacts,
|
|
int batteryChemistrySignature, {
|
|
required bool showLabels,
|
|
Contact? selectedContact,
|
|
}) {
|
|
final visibleContactsSignature = Object.hashAll(
|
|
contacts.map(
|
|
(contact) =>
|
|
Object.hash(_mapContactSignature(contact), _ageOf(contact)),
|
|
),
|
|
);
|
|
final key = _NodeMarkersCacheKey(
|
|
contactsSignature: contactsSignature,
|
|
visibleContactsSignature: visibleContactsSignature,
|
|
batterySignature: batterySignature,
|
|
freshness: freshness,
|
|
timeFilterHours: timeFilterHours,
|
|
keyPrefixEnabled: keyPrefixEnabled,
|
|
keyPrefix: keyPrefix,
|
|
showDiscoveryContacts: showDiscoveryContacts,
|
|
batteryChemistrySignature: batteryChemistrySignature,
|
|
showLabels: showLabels,
|
|
selectedKey: selectedContact?.publicKeyHex,
|
|
zoom: _zoom,
|
|
overlapsMode: settings.mapShowOverlaps,
|
|
showRepeaters: settings.mapShowRepeaters,
|
|
showChatNodes: settings.mapShowChatNodes,
|
|
showOtherNodes: settings.mapShowOtherNodes,
|
|
isBuildingPathTrace: _isBuildingPathTrace,
|
|
clusterNodes: settings.mapClusterNodes,
|
|
);
|
|
if (key != _nodeMarkersCacheKey) {
|
|
_nodeMarkersCacheKey = key;
|
|
_cachedNodeMarkers = List.unmodifiable(
|
|
_buildNodeMarkers(
|
|
contacts,
|
|
settings,
|
|
showLabels: showLabels,
|
|
selectedContact: selectedContact,
|
|
),
|
|
);
|
|
}
|
|
return _cachedNodeMarkers;
|
|
}
|
|
|
|
Future<void> _startGuessedLocations(
|
|
int cacheKey,
|
|
List<Contact> candidates,
|
|
List<Contact> withLocation,
|
|
PathHistoryService pathHistory,
|
|
double? maxRangeKm,
|
|
) async {
|
|
if (_guessInFlight) {
|
|
_guessRerun = () => _startGuessedLocations(
|
|
cacheKey,
|
|
candidates,
|
|
withLocation,
|
|
pathHistory,
|
|
maxRangeKm,
|
|
);
|
|
return;
|
|
}
|
|
_guessInFlight = true;
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final selfLat = connector.selfLatitude;
|
|
final selfLon = connector.selfLongitude;
|
|
// Old paths say little about where a node is now.
|
|
final cutoff = DateTime.now().subtract(_guessMaxAge);
|
|
final eligible = candidates
|
|
.where((c) => !c.hasLocation && c.lastSeen.isAfter(cutoff))
|
|
.toList();
|
|
final toLoad = <String>{
|
|
for (final c in eligible)
|
|
if (!pathHistory.isCached(c.publicKeyHex) &&
|
|
!_storedPaths.containsKey(c.publicKeyHex))
|
|
c.publicKeyHex,
|
|
}.toList();
|
|
if (toLoad.isNotEmpty) {
|
|
final loaded = await Future.wait(toLoad.map(pathHistory.readStoredPaths));
|
|
for (var i = 0; i < toLoad.length; i++) {
|
|
_storedPaths[toLoad[i]] = loaded[i];
|
|
}
|
|
}
|
|
if (!mounted) {
|
|
_guessInFlight = false;
|
|
return;
|
|
}
|
|
List<PathRecord> pathsFor(String key) => pathHistory.isCached(key)
|
|
? pathHistory.peekRecentPaths(key)
|
|
: _storedPaths[key] ?? const [];
|
|
final input = (
|
|
candidates: [
|
|
for (final c in eligible)
|
|
(
|
|
publicKey: c.publicKey,
|
|
paths: [
|
|
(c.path.toList(), c.pathHashWidth),
|
|
for (final r in pathsFor(c.publicKeyHex))
|
|
(
|
|
r.pathBytes,
|
|
Contact.inferPathHashWidth(r.hopCount, r.pathBytes.length),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
anchors: [
|
|
for (final r in withLocation)
|
|
if (r.type == advTypeRepeater || r.type == advTypeRoom)
|
|
(r.publicKey, r.latitude!, r.longitude!),
|
|
],
|
|
selfPosition:
|
|
selfLat != null &&
|
|
selfLon != null &&
|
|
isPlausibleLocation(selfLat, selfLon)
|
|
? (selfLat, selfLon)
|
|
: null,
|
|
maxRangeKm: maxRangeKm,
|
|
);
|
|
List<(int, double, double, bool)> placed;
|
|
try {
|
|
placed = await compute(estimateGuessedLocations, input);
|
|
} catch (e) {
|
|
debugPrint('Guessed location estimate failed: $e');
|
|
placed = const [];
|
|
} finally {
|
|
_guessInFlight = false;
|
|
}
|
|
final rerun = _guessRerun;
|
|
_guessRerun = null;
|
|
if (!mounted) return;
|
|
if (!context.read<AppSettingsService>().settings.mapShowGuessedLocations) {
|
|
return;
|
|
}
|
|
// Show this result even if inputs moved on; it is newer than what is on
|
|
// screen, and the queued rerun replaces it shortly.
|
|
rerun?.call();
|
|
setState(() {
|
|
_cachedGuessedLocations = [
|
|
for (final (index, lat, lon, highConfidence) in placed)
|
|
_GuessedLocation(
|
|
contact: eligible[index],
|
|
position: LatLng(lat, lon),
|
|
highConfidence: highConfidence,
|
|
),
|
|
];
|
|
});
|
|
}
|
|
|
|
/// Estimates the free-space maximum LoRa range in km from the connected
|
|
/// device's current radio parameters. Returns null if parameters are unknown.
|
|
double? _estimateLoRaRangeKm(MeshCoreConnector connector) {
|
|
final freqHz = connector.currentFreqHz;
|
|
final bwHz = connector.currentBwHz;
|
|
final sf = connector.currentSf;
|
|
final txPower = connector.currentTxPower;
|
|
if (freqHz == null || bwHz == null || sf == null || txPower == null) {
|
|
return null;
|
|
}
|
|
// LoRa receiver sensitivity = thermal noise + NF + required demod SNR
|
|
const noiseFigureDb = 6.0;
|
|
final thermalNoiseDbm = -174.0 + 10 * log(bwHz.toDouble()) / ln10;
|
|
final sensitivityDbm =
|
|
thermalNoiseDbm + noiseFigureDb + _sfToRequiredSnrDb(sf);
|
|
// FSPL at max range equals link budget:
|
|
// FSPL = 20*log10(d_m) + 20*log10(f_hz) - 147.55
|
|
final linkBudgetDb = txPower.toDouble() - sensitivityDbm;
|
|
final exponent =
|
|
(linkBudgetDb + 147.55 - 20 * log(freqHz.toDouble()) / ln10) / 20;
|
|
return pow(10, exponent) / 1000;
|
|
}
|
|
|
|
double _sfToRequiredSnrDb(int sf) {
|
|
switch (sf) {
|
|
case 5:
|
|
return -2.5;
|
|
case 6:
|
|
return -5.0;
|
|
case 7:
|
|
return -7.5;
|
|
case 8:
|
|
return -10.0;
|
|
case 9:
|
|
return -12.5;
|
|
case 10:
|
|
return -15.0;
|
|
case 11:
|
|
return -17.5;
|
|
case 12:
|
|
return -20.0;
|
|
default:
|
|
return -10.0;
|
|
}
|
|
}
|
|
|
|
List<Marker> _buildGuessedMarker(
|
|
List<_GuessedLocation> guessed, {
|
|
required bool showLabels,
|
|
}) {
|
|
final markers = <Marker>[];
|
|
|
|
for (final guess in guessed) {
|
|
if (guess.contact.type == advTypeChat && _isBuildingPathTrace) {
|
|
continue;
|
|
}
|
|
|
|
final color = mapNodeTypeColor(guess.contact.type);
|
|
final marker = Marker(
|
|
point: guess.position,
|
|
width: 48,
|
|
height: 48,
|
|
child: GestureDetector(
|
|
onLongPress: () {
|
|
if (_isBuildingPathTrace) showNodeInfoSheet(context, guess.contact);
|
|
},
|
|
onSecondaryTap: () {
|
|
if (_isBuildingPathTrace) showNodeInfoSheet(context, guess.contact);
|
|
},
|
|
onTap: () => _isBuildingPathTrace
|
|
? _addToPath(context, guess.contact, position: guess.position)
|
|
: _selectNode(guess.contact, guessedPosition: guess.position),
|
|
child: Center(
|
|
child: Container(
|
|
width: 36,
|
|
height: 36,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: _overlayPanelColor,
|
|
border: Border.all(
|
|
color: guess.highConfidence ? color : _overlayMutedTextColor,
|
|
width: guess.highConfidence ? 2.5 : 2,
|
|
),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 7,
|
|
offset: Offset(0, 2),
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Icon(
|
|
Icons.not_listed_location,
|
|
color: _overlayPrimaryTextColor,
|
|
size: 19,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
|
|
markers.add(marker);
|
|
|
|
if (showLabels) {
|
|
markers.add(
|
|
_buildNodeLabelMarker(
|
|
point: guess.position,
|
|
label: guess.contact.name,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
return markers;
|
|
}
|
|
|
|
List<Contact> _filterContactsBySettings(
|
|
List<Contact> contacts,
|
|
dynamic settings, {
|
|
bool noLocations = false,
|
|
}) {
|
|
List<Contact> filtered = [];
|
|
bool addContact = false;
|
|
|
|
for (final contact in contacts) {
|
|
addContact = false;
|
|
if (!contact.hasLocation && !noLocations) {
|
|
continue;
|
|
}
|
|
|
|
// Apply node type filters. The overlaps toggle is purely a visual
|
|
// highlight (applied in _buildNodeMarkers) and no longer affects which
|
|
// nodes are shown.
|
|
if (contact.type == advTypeRepeater &&
|
|
(settings.mapShowRepeaters || _isBuildingPathTrace)) {
|
|
addContact = true;
|
|
}
|
|
if (contact.type == advTypeChat &&
|
|
(settings.mapShowChatNodes || _isBuildingPathTrace)) {
|
|
addContact = true;
|
|
}
|
|
if (contact.type != advTypeChat &&
|
|
contact.type != advTypeRepeater &&
|
|
(settings.mapShowOtherNodes || _isBuildingPathTrace)) {
|
|
addContact = true;
|
|
}
|
|
|
|
if (contact.type == advTypeChat && _isBuildingPathTrace) {
|
|
addContact = false;
|
|
}
|
|
|
|
if (addContact) {
|
|
filtered.add(contact);
|
|
}
|
|
}
|
|
return filtered;
|
|
}
|
|
|
|
List<NetworkMapRepeater> _filterOnlineRepeatersBySettings(
|
|
List<NetworkMapRepeater> repeaters,
|
|
dynamic settings, {
|
|
required bool showGuessedLocations,
|
|
}) {
|
|
final keyPrefix = settings.mapKeyPrefix.trim().toLowerCase();
|
|
final now = DateTime.now();
|
|
|
|
return repeaters.where((repeater) {
|
|
if (repeater.isEstimated && !showGuessedLocations) return false;
|
|
|
|
final typeVisible = switch (repeater.type) {
|
|
advTypeRepeater => settings.mapShowRepeaters,
|
|
advTypeChat => settings.mapShowChatNodes,
|
|
_ => settings.mapShowOtherNodes,
|
|
};
|
|
if (!typeVisible) return false;
|
|
|
|
final freshnessVisible = switch (_freshness) {
|
|
_Freshness.all => true,
|
|
_Freshness.online => repeater.status == NetworkMapRepeaterStatus.active,
|
|
_Freshness.recent => repeater.status != NetworkMapRepeaterStatus.stale,
|
|
_Freshness.stale => repeater.status == NetworkMapRepeaterStatus.stale,
|
|
};
|
|
if (!freshnessVisible) return false;
|
|
|
|
if (settings.mapTimeFilterHours > 0 && repeater.lastSeen != null) {
|
|
final age = now.difference(repeater.lastSeen!).inHours;
|
|
if (age > settings.mapTimeFilterHours) return false;
|
|
}
|
|
|
|
return !settings.mapKeyPrefixEnabled ||
|
|
keyPrefix.isEmpty ||
|
|
repeater.key.toLowerCase().startsWith(keyPrefix);
|
|
}).toList();
|
|
}
|
|
|
|
List<Marker> _buildNodeMarkers(
|
|
List<Contact> contacts,
|
|
settings, {
|
|
required bool showLabels,
|
|
Contact? selectedContact,
|
|
}) {
|
|
final markers = <Marker>[];
|
|
final overlapsMode = settings.mapShowOverlaps && !_isBuildingPathTrace;
|
|
final selectedKey = selectedContact?.publicKeyHex;
|
|
final items = contacts.where((c) => c.publicKeyHex != selectedKey).toList();
|
|
|
|
// Key-prefix overlaps are a visual highlight only: flag the repeaters/rooms
|
|
// whose first key byte collides with another repeater/room on the map.
|
|
final overlapPrefixes = <String>{};
|
|
if (overlapsMode) {
|
|
final hopWidth = context
|
|
.read<MeshCoreConnector>()
|
|
.pathHashByteWidth
|
|
.clamp(1, pubKeySize)
|
|
.toInt();
|
|
final counts = <String, int>{};
|
|
for (final contact in contacts) {
|
|
if ((contact.type == advTypeRepeater || contact.type == advTypeRoom) &&
|
|
contact.publicKey.length >= hopWidth) {
|
|
final prefix = PathHelper.formatHopHex(
|
|
contact.publicKey.sublist(0, hopWidth),
|
|
);
|
|
counts[prefix] = (counts[prefix] ?? 0) + 1;
|
|
}
|
|
}
|
|
counts.forEach((prefix, count) {
|
|
if (count > 1) overlapPrefixes.add(prefix);
|
|
});
|
|
}
|
|
final overlapHopWidth = context
|
|
.read<MeshCoreConnector>()
|
|
.pathHashByteWidth
|
|
.clamp(1, pubKeySize)
|
|
.toInt();
|
|
bool isOverlap(Contact contact) =>
|
|
overlapsMode &&
|
|
(contact.type == advTypeRepeater || contact.type == advTypeRoom) &&
|
|
contact.publicKey.length >= overlapHopWidth &&
|
|
overlapPrefixes.contains(
|
|
PathHelper.formatHopHex(
|
|
contact.publicKey.sublist(0, overlapHopWidth),
|
|
),
|
|
);
|
|
|
|
void addNode(Contact contact, {bool dot = false}) {
|
|
final overlap = isOverlap(contact);
|
|
markers.add(_nodeMarker(contact, overlapsMode: overlap, dot: dot));
|
|
if (showLabels) {
|
|
markers.add(
|
|
_buildNodeLabelMarker(
|
|
point: LatLng(contact.latitude!, contact.longitude!),
|
|
label: overlap
|
|
? "${contact.publicKeyHex.substring(0, 2)}:${contact.name}"
|
|
: contact.name,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
if (!settings.mapClusterNodes ||
|
|
_zoom >= _clusterOffZoom ||
|
|
overlapsMode ||
|
|
_isBuildingPathTrace) {
|
|
for (final contact in items) {
|
|
addNode(contact);
|
|
}
|
|
} else {
|
|
// Grid clustering: bucket markers into ~64px screen cells at the
|
|
// current zoom; cells with 2+ nodes render as a numbered cluster.
|
|
final cellDeg = 360.0 / (256.0 * pow(2.0, _zoom)) * 64.0;
|
|
final cells = <String, List<Contact>>{};
|
|
for (final contact in items) {
|
|
final key =
|
|
'${(contact.latitude! / cellDeg).floor()}:${(contact.longitude! / cellDeg).floor()}';
|
|
(cells[key] ??= []).add(contact);
|
|
}
|
|
for (final cell in cells.values) {
|
|
if (cell.length == 1) {
|
|
addNode(cell.first, dot: true);
|
|
} else {
|
|
markers.add(_clusterMarker(cell));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Selected node always renders individually on top, even when its
|
|
// neighbors are clustered or it is filtered out.
|
|
if (selectedContact != null && selectedContact.hasLocation) {
|
|
markers.add(
|
|
_nodeMarker(
|
|
selectedContact,
|
|
overlapsMode: isOverlap(selectedContact),
|
|
selected: true,
|
|
),
|
|
);
|
|
markers.add(
|
|
_buildNodeLabelMarker(
|
|
point: LatLng(selectedContact.latitude!, selectedContact.longitude!),
|
|
label: selectedContact.name,
|
|
),
|
|
);
|
|
}
|
|
|
|
return markers;
|
|
}
|
|
|
|
Marker _nodeMarker(
|
|
Contact contact, {
|
|
bool overlapsMode = false,
|
|
bool dot = false,
|
|
bool selected = false,
|
|
}) {
|
|
final age = _ageOf(contact);
|
|
final baseColor = overlapsMode
|
|
? MapPalette.batteryLow
|
|
: _markerColor(contact);
|
|
final stale = age == _NodeAge.stale;
|
|
final online = age == _NodeAge.online;
|
|
final batteryLow = _isBatteryLow(contact);
|
|
final size = selected ? 46.0 : (dot ? 22.0 : 40.0);
|
|
return Marker(
|
|
point: LatLng(contact.latitude!, contact.longitude!),
|
|
width: size,
|
|
height: size,
|
|
child: Semantics(
|
|
button: true,
|
|
selected: selected,
|
|
label: context.l10n.map_nodeMarkerSemantics(
|
|
contact.name,
|
|
contact.typeLabel(context.l10n),
|
|
_ageLabel(age),
|
|
),
|
|
excludeSemantics: true,
|
|
child: GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onLongPress: () {
|
|
if (_isBuildingPathTrace) showNodeInfoSheet(context, contact);
|
|
},
|
|
onSecondaryTap: () {
|
|
if (_isBuildingPathTrace) showNodeInfoSheet(context, contact);
|
|
},
|
|
onTap: () => _isBuildingPathTrace
|
|
? _addToPath(context, contact)
|
|
: _selectNode(contact),
|
|
child: Center(
|
|
child: dot && !selected
|
|
? Container(
|
|
width: 15,
|
|
height: 15,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: baseColor,
|
|
border: Border.all(
|
|
color: MapPalette.markerOutline,
|
|
width: 2,
|
|
),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 6,
|
|
offset: Offset(0, 2),
|
|
),
|
|
],
|
|
),
|
|
)
|
|
: _buildNodeMarkerWidget(
|
|
color: baseColor,
|
|
icon: mapNodeTypeIcon(contact.type),
|
|
slot: mapMarkerSlotForNodeType(contact.type),
|
|
selected: selected,
|
|
stale: stale,
|
|
online: online,
|
|
batteryLow: batteryLow,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Marker _clusterMarker(List<Contact> members) {
|
|
final count = members.length;
|
|
double lat = 0, lon = 0;
|
|
var online = 0;
|
|
for (final m in members) {
|
|
lat += m.latitude!;
|
|
lon += m.longitude!;
|
|
if (_ageOf(m) == _NodeAge.online) online++;
|
|
}
|
|
final center = LatLng(lat / count, lon / count);
|
|
final size = count >= 50
|
|
? 54.0
|
|
: count >= 16
|
|
? 50.0
|
|
: count >= 6
|
|
? 46.0
|
|
: 42.0;
|
|
return Marker(
|
|
point: center,
|
|
width: size,
|
|
height: size,
|
|
child: GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onTap: () => _zoomToCluster(members),
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: MapPalette.cluster,
|
|
border: Border.all(color: MapPalette.markerOutline, width: 3),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
Text(
|
|
'$count',
|
|
style: MeshTheme.mono(
|
|
fontSize: count >= 100 ? 13 : 15,
|
|
fontWeight: FontWeight.w800,
|
|
color: MapPalette.markerOutline,
|
|
),
|
|
),
|
|
if (online > 0)
|
|
Container(
|
|
width: 7,
|
|
height: 7,
|
|
margin: const EdgeInsets.only(top: 1),
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: MapPalette.online,
|
|
border: Border.all(
|
|
color: MapPalette.markerOutline,
|
|
width: 1,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
void _zoomToCluster(List<Contact> members) {
|
|
HapticFeedback.selectionClick();
|
|
var minLat = double.infinity, maxLat = -double.infinity;
|
|
var minLon = double.infinity, maxLon = -double.infinity;
|
|
for (final m in members) {
|
|
minLat = min(minLat, m.latitude!);
|
|
maxLat = max(maxLat, m.latitude!);
|
|
minLon = min(minLon, m.longitude!);
|
|
maxLon = max(maxLon, m.longitude!);
|
|
}
|
|
_mapController.fitCamera(
|
|
CameraFit.bounds(
|
|
bounds: LatLngBounds(LatLng(minLat, minLon), LatLng(maxLat, maxLon)),
|
|
padding: const EdgeInsets.all(72),
|
|
maxZoom: 16,
|
|
),
|
|
);
|
|
}
|
|
|
|
Marker _buildNodeLabelMarker({required LatLng point, required String label}) {
|
|
return Marker(
|
|
point: point,
|
|
width: 140,
|
|
height: 26,
|
|
alignment: Alignment.topCenter,
|
|
child: IgnorePointer(
|
|
child: Transform.translate(
|
|
offset: const Offset(0, -20),
|
|
child: Center(
|
|
child: Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
|
decoration: BoxDecoration(
|
|
color: _overlayPanelColor,
|
|
borderRadius: BorderRadius.circular(MeshRadii.xs),
|
|
border: Border.all(color: _overlayBorderColor),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 4,
|
|
offset: Offset(0, 1),
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Text(
|
|
label,
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: MeshTheme.mono(
|
|
fontSize: 12,
|
|
fontWeight: FontWeight.w700,
|
|
color: _overlayPrimaryTextColor,
|
|
).copyWith(height: 1.15),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// A node type's icon as the theme shows it on the map.
|
|
Widget _nodeTypeIcon(int type, {required double size, Color? color}) {
|
|
final slot = mapMarkerSlotForNodeType(type);
|
|
return slot == null
|
|
? Icon(mapNodeTypeIcon(type), size: size, color: color)
|
|
: ThemedIcon(slot, size: size, color: color);
|
|
}
|
|
|
|
Color _markerColor(Contact contact) {
|
|
switch (contact.type) {
|
|
case advTypeRepeater:
|
|
return MapPalette.repeater;
|
|
case advTypeRoom:
|
|
return MapPalette.router;
|
|
case advTypeSensor:
|
|
return MapPalette.sensor;
|
|
default:
|
|
return _ageColor(_ageOf(contact));
|
|
}
|
|
}
|
|
|
|
bool _isBatteryLow(Contact contact) {
|
|
if (contact.type != advTypeRepeater) return false;
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final millivolts = connector.getRepeaterBatteryMillivolts(
|
|
contact.publicKeyHex,
|
|
);
|
|
if (millivolts == null) return false;
|
|
final chemistry = context
|
|
.read<AppSettingsService>()
|
|
.batteryChemistryForRepeater(contact.publicKeyHex);
|
|
return estimateBatteryPercentFromMillivolts(millivolts, chemistry) <= 20;
|
|
}
|
|
|
|
/// A theme's picture drawn as a whole round marker, with the usual
|
|
/// shadow and the accent ring when selected.
|
|
Widget _pictureMarker(
|
|
ImageProvider picture, {
|
|
required double size,
|
|
required bool selected,
|
|
required IconData fallback,
|
|
}) {
|
|
final accent = MeshMapTheme.of(context).accent;
|
|
return Container(
|
|
width: size,
|
|
height: size,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
border: selected ? Border.all(color: accent, width: 3) : null,
|
|
boxShadow: [
|
|
const BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
if (selected)
|
|
BoxShadow(
|
|
color: accent.withValues(alpha: 0.75),
|
|
blurRadius: 14,
|
|
spreadRadius: 3,
|
|
),
|
|
],
|
|
),
|
|
child: ClipOval(
|
|
child: Image(
|
|
image: picture,
|
|
fit: BoxFit.cover,
|
|
gaplessPlayback: true,
|
|
filterQuality: FilterQuality.medium,
|
|
errorBuilder: (_, _, _) =>
|
|
Icon(fallback, color: accent, size: size * 0.55),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildNodeMarkerWidget({
|
|
required Color color,
|
|
required IconData icon,
|
|
ThemeIconSlot? slot,
|
|
bool selected = false,
|
|
bool stale = false,
|
|
bool online = false,
|
|
bool batteryLow = false,
|
|
}) {
|
|
final statusColor = batteryLow
|
|
? MapPalette.batteryLow
|
|
: online
|
|
? MapPalette.online
|
|
: stale
|
|
? MapPalette.offline
|
|
: MapPalette.stale;
|
|
final override = slot == null ? null : MeshIconTheme.of(context)[slot];
|
|
final picture = themePictureOf(override);
|
|
final namedIcon = override?.icon == null
|
|
? null
|
|
: kThemeIconCatalog[override!.icon];
|
|
return Stack(
|
|
clipBehavior: Clip.none,
|
|
alignment: Alignment.center,
|
|
children: [
|
|
if (picture != null)
|
|
// Pictures carry more detail than a glyph, so they get more room.
|
|
_pictureMarker(
|
|
picture,
|
|
size: selected ? 50 : 42,
|
|
selected: selected,
|
|
fallback: icon,
|
|
)
|
|
else
|
|
Container(
|
|
width: selected ? 44 : 36,
|
|
height: selected ? 44 : 36,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: selected ? MeshMapTheme.of(context).accent : color,
|
|
border: Border.all(
|
|
color: MapPalette.markerOutline,
|
|
width: selected ? 3 : 2.5,
|
|
),
|
|
boxShadow: [
|
|
const BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
if (selected)
|
|
BoxShadow(
|
|
color: MeshMapTheme.of(
|
|
context,
|
|
).accent.withValues(alpha: 0.75),
|
|
blurRadius: 14,
|
|
spreadRadius: 3,
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Icon(
|
|
namedIcon ?? icon,
|
|
color: MapPalette.markerOutline,
|
|
size: selected ? 22 : 19,
|
|
),
|
|
),
|
|
Positioned(
|
|
right: selected ? -1 : -2,
|
|
bottom: selected ? 0 : -2,
|
|
child: Container(
|
|
width: batteryLow ? 16 : (selected ? 13 : 12),
|
|
height: batteryLow ? 16 : (selected ? 13 : 12),
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: statusColor,
|
|
border: Border.all(color: _overlayPanelColor, width: 2),
|
|
),
|
|
alignment: Alignment.center,
|
|
child: batteryLow
|
|
? const Icon(
|
|
Icons.battery_alert,
|
|
size: 12,
|
|
color: MapPalette.markerOutline,
|
|
)
|
|
: null,
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
Widget _buildLegendItem(
|
|
IconData icon,
|
|
String label,
|
|
Color color, {
|
|
ThemeIconSlot? slot,
|
|
}) {
|
|
return Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 1.5),
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (slot != null)
|
|
ThemedIcon(slot, size: 18, color: color)
|
|
else
|
|
Icon(icon, size: 18, color: color),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Text(
|
|
label,
|
|
style: TextStyle(
|
|
fontSize: 14,
|
|
fontWeight: FontWeight.w600,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Color _ageColor(_NodeAge age) {
|
|
switch (age) {
|
|
case _NodeAge.online:
|
|
return MapPalette.online;
|
|
case _NodeAge.recent:
|
|
return MapPalette.stale;
|
|
case _NodeAge.stale:
|
|
return MapPalette.textMuted;
|
|
}
|
|
}
|
|
|
|
String _ageLabel(_NodeAge age) {
|
|
switch (age) {
|
|
case _NodeAge.online:
|
|
return context.l10n.map_online;
|
|
case _NodeAge.recent:
|
|
return context.l10n.map_recent;
|
|
case _NodeAge.stale:
|
|
return context.l10n.map_stale;
|
|
}
|
|
}
|
|
|
|
Widget _buildTopOverlay(
|
|
BuildContext context, {
|
|
required MapSourceOption mapSource,
|
|
required MeshCoreConnector connector,
|
|
required AppSettingsService settingsService,
|
|
required List<Contact> allContacts,
|
|
required List<_GuessedLocation> guessedLocations,
|
|
required int visibleCount,
|
|
required int onlineCount,
|
|
required int repeaterCount,
|
|
required int hiddenCount,
|
|
required int pinCount,
|
|
}) {
|
|
final settings = settingsService.settings;
|
|
final hasQuery = _searchQuery.trim().isNotEmpty;
|
|
return Positioned(
|
|
top: 8,
|
|
left: 12,
|
|
right: 12,
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Row(
|
|
crossAxisAlignment: CrossAxisAlignment.center,
|
|
children: [
|
|
Expanded(
|
|
child: Material(
|
|
color: _overlayPanelColor,
|
|
shape: StadiumBorder(
|
|
side: BorderSide(color: _overlayBorderColor),
|
|
),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: TextField(
|
|
controller: _searchController,
|
|
focusNode: _searchFocus,
|
|
decoration: InputDecoration(
|
|
hintText: context.l10n.map_searchHint,
|
|
hintStyle: TextStyle(color: _overlaySecondaryTextColor),
|
|
prefixIcon: Icon(
|
|
Icons.search,
|
|
size: 20,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
suffixIcon: hasQuery
|
|
? IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.close, size: 18),
|
|
tooltip: context.l10n.common_clearSearch,
|
|
onPressed: () {
|
|
setState(() {
|
|
_searchQuery = '';
|
|
_searchController.clear();
|
|
});
|
|
},
|
|
)
|
|
: null,
|
|
filled: false,
|
|
border: InputBorder.none,
|
|
enabledBorder: InputBorder.none,
|
|
focusedBorder: InputBorder.none,
|
|
isDense: true,
|
|
contentPadding: const EdgeInsets.symmetric(
|
|
horizontal: 4,
|
|
vertical: 12,
|
|
),
|
|
),
|
|
style: TextStyle(
|
|
fontSize: 14,
|
|
color: _overlayPrimaryTextColor,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
cursorColor: MeshMapTheme.of(context).accent,
|
|
onChanged: (value) {
|
|
setState(() => _searchQuery = value);
|
|
},
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Material(
|
|
color: _overlayPanelColor,
|
|
shape: StadiumBorder(
|
|
side: BorderSide(color: _overlayBorderColor),
|
|
),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: InkWell(
|
|
onTap: () => setState(() => _statsExpanded = !_statsExpanded),
|
|
child: Container(
|
|
constraints: const BoxConstraints(minHeight: 46),
|
|
padding: const EdgeInsets.symmetric(horizontal: 12),
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Icon(
|
|
Icons.hub,
|
|
size: 18,
|
|
color: MeshMapTheme.of(context).accent,
|
|
),
|
|
const SizedBox(width: 6),
|
|
Text(
|
|
'$visibleCount',
|
|
style: MeshTheme.mono(
|
|
fontSize: 15,
|
|
fontWeight: FontWeight.w700,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
),
|
|
const SizedBox(width: 2),
|
|
AnimatedRotation(
|
|
turns: _statsExpanded ? 0.5 : 0,
|
|
duration: const Duration(milliseconds: 200),
|
|
child: Icon(
|
|
Icons.expand_more,
|
|
size: 16,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 6),
|
|
_buildMapSourceSwitch(context, mapSource),
|
|
if (hasQuery)
|
|
_buildSearchResults(context, allContacts, guessedLocations)
|
|
else if (_statsExpanded)
|
|
Align(
|
|
alignment: Alignment.centerRight,
|
|
child: _buildStatsCard(
|
|
context,
|
|
settings: settings,
|
|
visibleCount: visibleCount,
|
|
onlineCount: onlineCount,
|
|
repeaterCount: repeaterCount,
|
|
hiddenCount: hiddenCount,
|
|
pinCount: pinCount,
|
|
guessedCount: guessedLocations.length,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
int _activeFilterCount(AppSettings settings) => [
|
|
_freshness != _Freshness.all,
|
|
!settings.mapShowChatNodes,
|
|
!settings.mapShowRepeaters,
|
|
!settings.mapShowOtherNodes,
|
|
!settings.mapShowOnlineLinks,
|
|
settings.mapKeyPrefixEnabled,
|
|
].where((active) => active).length;
|
|
|
|
Widget _buildMapSourceSwitch(BuildContext context, MapSourceOption source) {
|
|
final l10n = context.l10n;
|
|
return Material(
|
|
color: _overlayPanelColor,
|
|
shape: StadiumBorder(side: BorderSide(color: _overlayBorderColor)),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: SegmentedButton<MapSourceOption>(
|
|
showSelectedIcon: false,
|
|
style: SegmentedButton.styleFrom(
|
|
minimumSize: const Size(0, 46),
|
|
side: BorderSide.none,
|
|
foregroundColor: _overlaySecondaryTextColor,
|
|
selectedForegroundColor: _overlayPrimaryTextColor,
|
|
selectedBackgroundColor: MeshMapTheme.of(
|
|
context,
|
|
).accent.withValues(alpha: 0.34),
|
|
textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700),
|
|
),
|
|
segments: [
|
|
ButtonSegment(
|
|
value: MapSourceOption.local,
|
|
icon: const Icon(Icons.radio, size: 20),
|
|
label: Text(l10n.networkMap_sourceLocal),
|
|
tooltip: l10n.networkMap_sourceLocalHint,
|
|
),
|
|
ButtonSegment(
|
|
value: MapSourceOption.online,
|
|
icon: const Icon(Icons.public, size: 20),
|
|
label: Text(l10n.networkMap_sourceOnline),
|
|
tooltip: l10n.networkMap_sourceOnlineHint,
|
|
),
|
|
ButtonSegment(
|
|
value: MapSourceOption.both,
|
|
icon: const Icon(Icons.layers, size: 20),
|
|
label: Text(l10n.networkMap_sourceBoth),
|
|
tooltip: l10n.networkMap_sourceBothHint,
|
|
),
|
|
],
|
|
selected: {source},
|
|
onSelectionChanged: (selection) {
|
|
HapticFeedback.selectionClick();
|
|
_setMapSource(selection.first);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildOnlineHint(BuildContext context, NetworkMapLoadState state) {
|
|
final zoomIn = state == NetworkMapLoadState.zoomIn;
|
|
return Positioned(
|
|
left: 16,
|
|
right: 88,
|
|
bottom: 16,
|
|
child: Card(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(14),
|
|
child: Row(
|
|
children: [
|
|
Icon(zoomIn ? Icons.zoom_in : Icons.cloud_off, size: 26),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Text(
|
|
zoomIn
|
|
? context.l10n.networkMap_zoomInHint
|
|
: context.l10n.networkMap_loadFailed,
|
|
style: Theme.of(context).textTheme.bodyLarge,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildSearchResults(
|
|
BuildContext context,
|
|
List<Contact> allContacts,
|
|
List<_GuessedLocation> guessedLocations,
|
|
) {
|
|
final query = _searchQuery.trim().toLowerCase();
|
|
final matches =
|
|
allContacts.where((c) => matchesContactQuery(c, query)).toList()
|
|
..sort((a, b) {
|
|
if (a.hasLocation != b.hasLocation) {
|
|
return a.hasLocation ? -1 : 1;
|
|
}
|
|
return b.lastHeard.compareTo(a.lastHeard);
|
|
});
|
|
final results = matches.take(8).toList();
|
|
return Container(
|
|
margin: const EdgeInsets.only(top: 6),
|
|
constraints: const BoxConstraints(maxHeight: 300),
|
|
decoration: BoxDecoration(
|
|
color: _overlayPanelColor,
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
border: Border.all(color: _overlayBorderColor),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 10,
|
|
offset: const Offset(0, 4),
|
|
),
|
|
],
|
|
),
|
|
child: results.isEmpty
|
|
? Padding(
|
|
padding: const EdgeInsets.all(16),
|
|
child: Text(
|
|
context.l10n.map_noResults,
|
|
style: TextStyle(
|
|
color: _overlaySecondaryTextColor,
|
|
fontSize: 13,
|
|
),
|
|
),
|
|
)
|
|
: ListView.separated(
|
|
shrinkWrap: true,
|
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
|
itemCount: results.length,
|
|
separatorBuilder: (_, _) =>
|
|
Divider(height: 1, color: _overlayBorderColor),
|
|
itemBuilder: (context, index) {
|
|
final c = results[index];
|
|
final color = mapNodeTypeColor(c.type);
|
|
return InkWell(
|
|
onTap: () => _onSearchResultTap(c, guessedLocations),
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 12,
|
|
vertical: 8,
|
|
),
|
|
child: Row(
|
|
children: [
|
|
_nodeTypeIcon(c.type, size: 18, color: color),
|
|
const SizedBox(width: 10),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
c.name,
|
|
style: TextStyle(
|
|
fontSize: 15,
|
|
fontWeight: FontWeight.w600,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
Text(
|
|
c.publicKeyHex.substring(0, 12),
|
|
style: MeshTheme.mono(
|
|
fontSize: 12,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
if (c.hasLocation)
|
|
Icon(
|
|
Icons.chevron_right,
|
|
size: 18,
|
|
color: _overlaySecondaryTextColor,
|
|
)
|
|
else
|
|
Text(
|
|
context.l10n.map_noGps.toUpperCase(),
|
|
style: MeshTheme.accentLabel(
|
|
color: _overlayMutedTextColor,
|
|
fontSize: 12,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
void _onSearchResultTap(
|
|
Contact contact,
|
|
List<_GuessedLocation> guessedLocations,
|
|
) {
|
|
if (contact.hasLocation) {
|
|
_selectNode(contact);
|
|
_mapController.move(
|
|
LatLng(contact.latitude!, contact.longitude!),
|
|
max(_zoom, 14),
|
|
);
|
|
return;
|
|
}
|
|
_GuessedLocation? guess;
|
|
for (final g in guessedLocations) {
|
|
if (g.contact.publicKeyHex == contact.publicKeyHex) {
|
|
guess = g;
|
|
break;
|
|
}
|
|
}
|
|
if (guess != null) {
|
|
_selectNode(contact, guessedPosition: guess.position);
|
|
_mapController.move(guess.position, max(_zoom, 13));
|
|
} else {
|
|
setState(() {
|
|
_searchQuery = '';
|
|
_searchController.clear();
|
|
_searchFocus.unfocus();
|
|
});
|
|
showNodeInfoSheet(context, contact);
|
|
}
|
|
}
|
|
|
|
Widget _buildStatsCard(
|
|
BuildContext context, {
|
|
required dynamic settings,
|
|
required int visibleCount,
|
|
required int onlineCount,
|
|
required int repeaterCount,
|
|
required int hiddenCount,
|
|
required int pinCount,
|
|
required int guessedCount,
|
|
}) {
|
|
return Container(
|
|
margin: const EdgeInsets.only(top: 6),
|
|
width: 250,
|
|
padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
|
|
decoration: BoxDecoration(
|
|
color: _overlayPanelColor,
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
border: Border.all(color: _overlayBorderColor),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 10,
|
|
offset: const Offset(0, 4),
|
|
),
|
|
],
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
_statRow(
|
|
context.l10n.map_visible,
|
|
visibleCount,
|
|
MeshMapTheme.of(context).accent,
|
|
),
|
|
_statRow(context.l10n.map_online, onlineCount, MapPalette.online),
|
|
_statRow(
|
|
context.l10n.map_repeaters,
|
|
repeaterCount,
|
|
MapPalette.repeater,
|
|
),
|
|
_statRow(context.l10n.map_hidden, hiddenCount, MapPalette.offline),
|
|
_statRow(context.l10n.map_markers, pinCount, MapPalette.shared),
|
|
Divider(height: 16, color: _overlayBorderColor),
|
|
_buildLegendItem(
|
|
Icons.person,
|
|
context.l10n.map_chat,
|
|
MeshMapTheme.of(context).accent,
|
|
slot: ThemeIconSlot.mapChat,
|
|
),
|
|
_buildLegendItem(
|
|
Icons.router,
|
|
context.l10n.map_repeater,
|
|
MapPalette.repeater,
|
|
slot: ThemeIconSlot.mapRepeater,
|
|
),
|
|
_buildLegendItem(
|
|
Icons.meeting_room,
|
|
context.l10n.map_room,
|
|
MapPalette.router,
|
|
slot: ThemeIconSlot.mapRoom,
|
|
),
|
|
_buildLegendItem(
|
|
Icons.sensors,
|
|
context.l10n.map_sensor,
|
|
MapPalette.sensor,
|
|
slot: ThemeIconSlot.mapSensor,
|
|
),
|
|
_buildLegendItem(
|
|
Icons.flag,
|
|
context.l10n.map_pinDm,
|
|
MapPalette.shared,
|
|
),
|
|
if (settings.mapShowGuessedLocations && guessedCount > 0)
|
|
_buildLegendItem(
|
|
Icons.not_listed_location,
|
|
context.l10n.map_guessedLocation,
|
|
_overlayMutedTextColor,
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _statRow(String label, int value, Color color) {
|
|
return Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 2),
|
|
child: Row(
|
|
children: [
|
|
Container(
|
|
width: 7,
|
|
height: 7,
|
|
decoration: BoxDecoration(shape: BoxShape.circle, color: color),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Text(
|
|
label,
|
|
style: TextStyle(fontSize: 14, color: _overlaySecondaryTextColor),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
Text(
|
|
'$value',
|
|
style: MeshTheme.mono(
|
|
fontSize: 14,
|
|
fontWeight: FontWeight.w700,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildSelectedNodeCard(
|
|
BuildContext context,
|
|
Contact contact,
|
|
MeshCoreConnector connector,
|
|
) {
|
|
final color = _markerColor(contact);
|
|
final age = _ageOf(contact);
|
|
final pos = contact.hasLocation
|
|
? LatLng(contact.latitude!, contact.longitude!)
|
|
: _selectedGuessPos;
|
|
return Positioned(
|
|
left: 12,
|
|
right: 12,
|
|
bottom: 12,
|
|
child: TweenAnimationBuilder<double>(
|
|
tween: Tween(begin: 1, end: 0),
|
|
duration: const Duration(milliseconds: 220),
|
|
curve: Curves.easeOutCubic,
|
|
builder: (context, t, child) => Transform.translate(
|
|
offset: Offset(0, 32 * t),
|
|
child: Opacity(opacity: 1 - t, child: child),
|
|
),
|
|
child: MeshCard(
|
|
margin: EdgeInsets.zero,
|
|
padding: const EdgeInsets.fromLTRB(14, 12, 8, 12),
|
|
color: _overlayPanelColor,
|
|
borderColor: _overlayBorderColor,
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
AvatarCircle(
|
|
name: contact.name,
|
|
size: 38,
|
|
color: color,
|
|
icon: mapNodeTypeIcon(contact.type),
|
|
iconSlot: mapMarkerSlotForNodeType(contact.type),
|
|
),
|
|
const SizedBox(width: 10),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
Flexible(
|
|
child: Text(
|
|
contact.name,
|
|
style: TextStyle(
|
|
fontSize: 15,
|
|
fontWeight: FontWeight.w700,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
if (contact.isFavorite) ...[
|
|
const SizedBox(width: 4),
|
|
const Icon(
|
|
Icons.star,
|
|
size: 14,
|
|
color: MapPalette.stale,
|
|
),
|
|
],
|
|
],
|
|
),
|
|
const SizedBox(height: 3),
|
|
Row(
|
|
children: [
|
|
StatusChip(
|
|
label: _ageLabel(age),
|
|
color: _ageColor(age),
|
|
fontSize: 12,
|
|
pulse: age == _NodeAge.online,
|
|
),
|
|
const SizedBox(width: 6),
|
|
Flexible(
|
|
child: Text(
|
|
contact.typeLabel(context.l10n),
|
|
style: TextStyle(
|
|
fontSize: 13,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
if (pos != null)
|
|
IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.center_focus_strong, size: 20),
|
|
tooltip: context.l10n.map_centerOnNode,
|
|
onPressed: () => _mapController.move(pos, max(_zoom, 15)),
|
|
),
|
|
IconButton(
|
|
color: _overlayPrimaryTextColor,
|
|
icon: const Icon(Icons.close, size: 20),
|
|
tooltip: context.l10n.common_close,
|
|
onPressed: _clearSelection,
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 8),
|
|
Wrap(
|
|
spacing: 14,
|
|
runSpacing: 4,
|
|
children: [
|
|
_miniMeta(
|
|
context.l10n.map_lastSeen,
|
|
formatNodeLastSeen(context.l10n, contact.lastHeard),
|
|
),
|
|
_miniMeta(
|
|
context.l10n.map_path,
|
|
contact.pathLabel(
|
|
context.l10n,
|
|
pathHashByteWidth: connector.pathHashByteWidth,
|
|
),
|
|
),
|
|
_miniMeta(
|
|
context.l10n.map_nodeId,
|
|
contact.publicKeyHex.substring(0, 12),
|
|
),
|
|
if (pos != null)
|
|
_miniMeta(
|
|
context.l10n.map_location,
|
|
'${contact.hasLocation ? '' : '~'}${pos.latitude.toStringAsFixed(5)}, ${pos.longitude.toStringAsFixed(5)}',
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 10),
|
|
Wrap(
|
|
spacing: 8,
|
|
runSpacing: 6,
|
|
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: MeshMapTheme.of(context).accent,
|
|
),
|
|
onPressed: () => showNodeInfoSheet(
|
|
context,
|
|
contact,
|
|
guessedPosition: contact.hasLocation
|
|
? null
|
|
: _selectedGuessPos,
|
|
),
|
|
child: Text(
|
|
context.l10n.map_details,
|
|
style: const TextStyle(fontSize: 14),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Asks the node for telemetry; a GPS fix in the reply moves its marker.
|
|
Future<void> _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,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
label.toUpperCase(),
|
|
style: MeshTheme.accentLabel(
|
|
color: _overlayMutedTextColor,
|
|
fontSize: 12,
|
|
),
|
|
),
|
|
const SizedBox(height: 1),
|
|
Text(
|
|
value,
|
|
style: MeshTheme.mono(fontSize: 13, color: _overlayPrimaryTextColor),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
List<Widget> _selectedNodeActions(
|
|
BuildContext context,
|
|
Contact contact,
|
|
MeshCoreConnector connector,
|
|
) {
|
|
Widget action(String label, IconData icon, VoidCallback onPressed) {
|
|
return FilledButton.icon(
|
|
style: FilledButton.styleFrom(
|
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
|
|
minimumSize: const Size(0, 44),
|
|
),
|
|
onPressed: onPressed,
|
|
icon: Icon(icon, size: 18),
|
|
label: Text(label, style: const TextStyle(fontSize: 14)),
|
|
);
|
|
}
|
|
|
|
switch (contact.type) {
|
|
case advTypeChat:
|
|
return [
|
|
action(context.l10n.contacts_openChat, Icons.chat_bubble_outline, () {
|
|
if (!contact.isActive) {
|
|
connector.importDiscoveredContact(contact);
|
|
}
|
|
final unread = connector.getUnreadCountForContactKey(
|
|
contact.publicKeyHex,
|
|
);
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) =>
|
|
ChatScreen(contact: contact, initialUnreadCount: unread),
|
|
),
|
|
);
|
|
}),
|
|
];
|
|
case advTypeRepeater:
|
|
return [
|
|
action(context.l10n.map_manageRepeater, Icons.cell_tower, () {
|
|
if (!contact.isActive) {
|
|
connector.importDiscoveredContact(contact);
|
|
}
|
|
showRepeaterLoginDialog(context, contact);
|
|
}),
|
|
];
|
|
case advTypeRoom:
|
|
return [
|
|
action(context.l10n.map_joinRoom, Icons.meeting_room, () {
|
|
if (!contact.isActive) {
|
|
connector.importDiscoveredContact(contact);
|
|
}
|
|
showRoomLoginDialog(context, contact);
|
|
}),
|
|
action(context.l10n.map_manageServer, Icons.room_preferences, () {
|
|
if (!contact.isActive) {
|
|
connector.importDiscoveredContact(contact);
|
|
}
|
|
showRoomLoginDialog(context, contact, manage: true);
|
|
}),
|
|
];
|
|
default:
|
|
return const [];
|
|
}
|
|
}
|
|
|
|
List<_SharedMarker> _collectSharedMarkers(
|
|
MeshCoreConnector connector,
|
|
int markerSignature,
|
|
) {
|
|
final locale = Localizations.localeOf(context);
|
|
if (_sharedMarkersCacheSignature == markerSignature &&
|
|
_sharedMarkersCacheLocale == locale) {
|
|
return _cachedSharedMarkers;
|
|
}
|
|
|
|
// Build a _SharedMarker per message (history empty), grouped by dedupe key.
|
|
// Afterwards pick the latest per key and fill its history from older ones.
|
|
final updatesByKey = <String, List<_SharedMarker>>{};
|
|
final selfName = connector.selfName ?? context.l10n.chat_me;
|
|
|
|
void addUpdate(_SharedMarker update) {
|
|
(updatesByKey[update.id] ??= <_SharedMarker>[]).add(update);
|
|
}
|
|
|
|
for (final contact in connector.contacts) {
|
|
final messages = connector.getMessages(contact);
|
|
for (final message in messages) {
|
|
final payload = parseMarkerText(message.text);
|
|
if (payload == null) continue;
|
|
final fromName = message.isOutgoing ? selfName : contact.name;
|
|
final key = buildSharedMarkerKey(
|
|
sourceId: contact.publicKeyHex,
|
|
label: payload.label,
|
|
fromName: fromName,
|
|
flags: payload.flags,
|
|
isChannel: false,
|
|
);
|
|
addUpdate(
|
|
_SharedMarker(
|
|
id: key,
|
|
position: payload.position,
|
|
label: payload.label.isEmpty
|
|
? context.l10n.map_sharedPin
|
|
: payload.label,
|
|
flags: payload.flags,
|
|
fromName: fromName,
|
|
sourceLabel: contact.name,
|
|
timestamp: message.timestamp,
|
|
isChannel: false,
|
|
isPublicChannel: false,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
for (final channel in connector.channels.where((c) => !c.isEmpty)) {
|
|
final isPublic = _isPublicChannel(channel);
|
|
final messages = connector.getChannelMessages(channel);
|
|
for (final message in messages) {
|
|
final payload = parseMarkerText(message.text);
|
|
if (payload == null) continue;
|
|
final key = buildSharedMarkerKey(
|
|
sourceId: 'channel:${channel.index}',
|
|
label: payload.label,
|
|
fromName: message.senderName,
|
|
flags: payload.flags,
|
|
isChannel: true,
|
|
);
|
|
addUpdate(
|
|
_SharedMarker(
|
|
id: key,
|
|
position: payload.position,
|
|
label: payload.label.isEmpty
|
|
? context.l10n.map_sharedPin
|
|
: payload.label,
|
|
flags: payload.flags,
|
|
fromName: message.senderName,
|
|
sourceLabel: channel.name.isEmpty
|
|
? context.l10n.channels_channelIndex(channel.index)
|
|
: channel.name,
|
|
timestamp: message.timestamp,
|
|
isChannel: true,
|
|
isPublicChannel: isPublic,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
final markers = <_SharedMarker>[];
|
|
updatesByKey.forEach((_, updates) {
|
|
updates.sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
|
final latest = updates.last;
|
|
// History: older positions, drop consecutive duplicates at same position.
|
|
final history = <LatLng>[];
|
|
for (var i = 0; i < updates.length - 1; i++) {
|
|
final p = updates[i].position;
|
|
if (history.isEmpty ||
|
|
history.last.latitude != p.latitude ||
|
|
history.last.longitude != p.longitude) {
|
|
history.add(p);
|
|
}
|
|
}
|
|
markers.add(latest.copyWithHistory(history));
|
|
});
|
|
|
|
markers.sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
|
_sharedMarkersCacheSignature = markerSignature;
|
|
_sharedMarkersCacheLocale = locale;
|
|
_cachedSharedMarkers = List.unmodifiable(markers);
|
|
return _cachedSharedMarkers;
|
|
}
|
|
|
|
Color _sharedMarkerColor(_SharedMarker marker) => marker.isChannel
|
|
? (marker.isPublicChannel ? MapPalette.cluster : MapPalette.router)
|
|
: MapPalette.shared;
|
|
|
|
Marker _buildSharedMarker(_SharedMarker marker) {
|
|
// Square marker with the circle centred, so the pin sits exactly on its
|
|
// coordinate (the default Marker alignment is centre).
|
|
return Marker(
|
|
point: marker.position,
|
|
width: 44,
|
|
height: 44,
|
|
child: Semantics(
|
|
button: true,
|
|
label: context.l10n.map_sharedMarkerSemantics(marker.label),
|
|
excludeSemantics: true,
|
|
child: GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onTap: () => _showMarkerInfo(marker),
|
|
child: Center(
|
|
child: Container(
|
|
width: 36,
|
|
height: 36,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: _sharedMarkerColor(marker),
|
|
border: Border.all(color: MapPalette.markerOutline, width: 2.5),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 3),
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: const Icon(
|
|
Icons.flag,
|
|
color: MapPalette.markerOutline,
|
|
size: 19,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Marker _buildSelfMarker(LatLng position) {
|
|
final override = MeshIconTheme.of(context)[ThemeIconSlot.mapSelf];
|
|
final picture = themePictureOf(override);
|
|
final namedIcon = override?.icon == null
|
|
? null
|
|
: kThemeIconCatalog[override!.icon];
|
|
return Marker(
|
|
point: position,
|
|
width: picture != null ? 48 : 40,
|
|
height: picture != null ? 48 : 40,
|
|
child: IgnorePointer(
|
|
child: Semantics(
|
|
label: context.l10n.pathTrace_you,
|
|
child: picture != null
|
|
? _pictureMarker(
|
|
picture,
|
|
size: 46,
|
|
selected: false,
|
|
fallback: Icons.person_pin_circle,
|
|
)
|
|
: Container(
|
|
width: 36,
|
|
height: 36,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: MapPalette.panelDark,
|
|
border: Border.all(
|
|
color: MapPalette.markerOutline,
|
|
width: 2.5,
|
|
),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: MapPalette.markerShadow,
|
|
blurRadius: 8,
|
|
offset: Offset(0, 2),
|
|
),
|
|
],
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Icon(
|
|
namedIcon ?? Icons.person_pin_circle,
|
|
color: MeshMapTheme.of(context).accent,
|
|
size: 22,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Shared POI markers plus the "You" marker. Outside overlaps/path-trace
|
|
/// mode, POIs falling into the same ~64px grid cell at the current zoom
|
|
/// (the same grid the node clusters use) collapse into one numbered marker.
|
|
/// The self position joins its cell, so POIs placed at or near the user's
|
|
/// position are not hidden under the "You" marker.
|
|
List<Marker> _buildPoiAndSelfMarkers(
|
|
List<_SharedMarker> pois, {
|
|
required LatLng? selfPosition,
|
|
required bool clusterPois,
|
|
}) {
|
|
if (!clusterPois) {
|
|
return [
|
|
...pois.map(_buildSharedMarker),
|
|
if (selfPosition != null) _buildSelfMarker(selfPosition),
|
|
];
|
|
}
|
|
final cellDeg = mapGridCellDegrees(_zoom);
|
|
final cells = mapGridCluster(pois, (m) => m.position, cellDeg);
|
|
final selfCellKey = selfPosition == null
|
|
? null
|
|
: mapGridCellKey(selfPosition, cellDeg);
|
|
final markers = <Marker>[];
|
|
Marker? selfMarker;
|
|
cells.forEach((key, members) {
|
|
if (key == selfCellKey) {
|
|
selfMarker = _poiClusterMarker(members, selfPosition: selfPosition);
|
|
} else if (members.length == 1) {
|
|
markers.add(_buildSharedMarker(members.first));
|
|
} else {
|
|
markers.add(_poiClusterMarker(members));
|
|
}
|
|
});
|
|
// Self is drawn last so it stays on top of nearby node markers.
|
|
if (selfPosition != null) {
|
|
markers.add(selfMarker ?? _buildSelfMarker(selfPosition));
|
|
}
|
|
return markers;
|
|
}
|
|
|
|
Marker _poiClusterMarker(
|
|
List<_SharedMarker> members, {
|
|
LatLng? selfPosition,
|
|
}) {
|
|
final count = members.length;
|
|
LatLng point;
|
|
if (selfPosition != null) {
|
|
point = selfPosition;
|
|
} else {
|
|
double lat = 0, lon = 0;
|
|
for (final m in members) {
|
|
lat += m.position.latitude;
|
|
lon += m.position.longitude;
|
|
}
|
|
point = LatLng(lat / count, lon / count);
|
|
}
|
|
final l10n = context.l10n;
|
|
return Marker(
|
|
point: point,
|
|
width: 48,
|
|
height: 48,
|
|
child: GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onTap: () => _showPoiClusterSheet(members, selfPosition: selfPosition),
|
|
child: Center(
|
|
child: PoiClusterMarker(
|
|
count: count,
|
|
includesSelf: selfPosition != null,
|
|
semanticLabel: selfPosition != null
|
|
? l10n.map_youWithMarkers(count)
|
|
: l10n.map_poiClusterSemantics(count),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
void _showPoiClusterSheet(
|
|
List<_SharedMarker> members, {
|
|
LatLng? selfPosition,
|
|
}) {
|
|
HapticFeedback.selectionClick();
|
|
showMeshSheet(
|
|
context,
|
|
builder: (sheetContext) {
|
|
final l10n = sheetContext.l10n;
|
|
final scheme = Theme.of(sheetContext).colorScheme;
|
|
return SafeArea(
|
|
child: ConstrainedBox(
|
|
constraints: BoxConstraints(
|
|
maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.7,
|
|
),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
BottomSheetHeader(
|
|
title: selfPosition != null
|
|
? l10n.map_youWithMarkers(members.length)
|
|
: l10n.map_poiClusterTitle(members.length),
|
|
),
|
|
Flexible(
|
|
child: ListView(
|
|
shrinkWrap: true,
|
|
children: [
|
|
if (selfPosition != null)
|
|
ListTile(
|
|
leading: Icon(
|
|
Icons.person_pin_circle,
|
|
color: MeshMapTheme.of(context).accent,
|
|
),
|
|
title: Text(l10n.pathTrace_you),
|
|
subtitle: Text(
|
|
'${selfPosition.latitude.toStringAsFixed(5)}, ${selfPosition.longitude.toStringAsFixed(5)}',
|
|
style: MeshTheme.mono(
|
|
fontSize: 13,
|
|
color: scheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_mapController.move(selfPosition, max(_zoom, 16));
|
|
},
|
|
),
|
|
for (final marker in members)
|
|
ListTile(
|
|
leading: Icon(
|
|
Icons.flag,
|
|
color: _sharedMarkerColor(marker),
|
|
),
|
|
title: Text(
|
|
marker.label,
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
subtitle: Text(
|
|
'${marker.fromName} · ${formatNodeLastSeen(context.l10n, marker.timestamp)}',
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
trailing: const Icon(Icons.chevron_right),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_showMarkerInfo(marker);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
void _handleQuickSwitch(int index, BuildContext context) {
|
|
FocusManager.instance.primaryFocus?.unfocus();
|
|
if (index == 2) return;
|
|
switch (index) {
|
|
case 0:
|
|
Navigator.pushReplacement(
|
|
context,
|
|
buildQuickSwitchRoute(const ContactsScreen(hideBackButton: true)),
|
|
);
|
|
break;
|
|
case 1:
|
|
Navigator.pushReplacement(
|
|
context,
|
|
buildQuickSwitchRoute(const ChannelsScreen(hideBackButton: true)),
|
|
);
|
|
break;
|
|
}
|
|
}
|
|
|
|
Future<void> _disconnect(
|
|
BuildContext context,
|
|
MeshCoreConnector connector,
|
|
) async {
|
|
final confirmed = await showDialog<bool>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
title: Text(context.l10n.common_disconnect),
|
|
content: Text(context.l10n.map_disconnectConfirm),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext, false),
|
|
child: Text(context.l10n.common_cancel),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext, true),
|
|
child: Text(context.l10n.common_disconnect),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
|
|
if (confirmed == true) {
|
|
await connector.disconnect();
|
|
}
|
|
}
|
|
|
|
void _showMarkerInfo(_SharedMarker marker) {
|
|
showDialog(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
scrollable: true,
|
|
title: Text(
|
|
marker.label.isEmpty ? context.l10n.map_sharedPin : marker.label,
|
|
),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
NodeInfoRow(label: context.l10n.map_from, value: marker.fromName),
|
|
NodeInfoRow(
|
|
label: context.l10n.map_source,
|
|
value: marker.sourceLabel,
|
|
),
|
|
NodeInfoRow(
|
|
label: context.l10n.map_sharedAt,
|
|
value: formatNodeLastSeen(context.l10n, marker.timestamp),
|
|
),
|
|
NodeInfoRow(
|
|
label: context.l10n.map_location,
|
|
value:
|
|
'${marker.position.latitude.toStringAsFixed(6)}, ${marker.position.longitude.toStringAsFixed(6)}',
|
|
),
|
|
if (marker.flags.isNotEmpty)
|
|
NodeInfoRow(label: context.l10n.map_flags, value: marker.flags),
|
|
const SizedBox(height: 12),
|
|
Text(
|
|
context.l10n.map_markerHideHint,
|
|
style: TextStyle(
|
|
fontSize: 13,
|
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
context.l10n.map_markerRemoveHint,
|
|
style: TextStyle(
|
|
fontSize: 13,
|
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () {
|
|
setState(() {
|
|
_hiddenMarkerIds.add(marker.id);
|
|
});
|
|
Navigator.pop(dialogContext);
|
|
},
|
|
child: Text(context.l10n.common_hide),
|
|
),
|
|
TextButton(
|
|
style: TextButton.styleFrom(
|
|
foregroundColor: Theme.of(context).colorScheme.error,
|
|
),
|
|
onPressed: () async {
|
|
Navigator.pop(dialogContext);
|
|
await _removeMarkerWithUndo(marker);
|
|
},
|
|
child: Text(context.l10n.common_remove),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext),
|
|
child: Text(context.l10n.common_close),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _removeMarkerWithUndo(_SharedMarker marker) async {
|
|
final previous = Set<String>.from(_removedMarkerIds);
|
|
final wasHidden = _hiddenMarkerIds.contains(marker.id);
|
|
setState(() {
|
|
_hiddenMarkerIds.add(marker.id);
|
|
_removedMarkerIds = {...previous, marker.id};
|
|
});
|
|
await _markerService.saveRemovedIds(_removedMarkerIds);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.map_markerRemoved),
|
|
action: SnackBarAction(
|
|
label: context.l10n.common_undo,
|
|
onPressed: () async {
|
|
if (!mounted) return;
|
|
setState(() {
|
|
if (!wasHidden) _hiddenMarkerIds.remove(marker.id);
|
|
_removedMarkerIds = Set<String>.from(previous);
|
|
});
|
|
await _markerService.saveRemovedIds(_removedMarkerIds);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _restoreRemovedMarkers() async {
|
|
final count = _removedMarkerIds.length;
|
|
if (count == 0) return;
|
|
setState(() {
|
|
_hiddenMarkerIds.removeAll(_removedMarkerIds);
|
|
_removedMarkerIds = <String>{};
|
|
});
|
|
await _markerService.saveRemovedIds(_removedMarkerIds);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.map_markersRestored(count)),
|
|
);
|
|
}
|
|
|
|
void _showShareMarkerAtPositionSheet({
|
|
required BuildContext context,
|
|
required MeshCoreConnector connector,
|
|
required LatLng position,
|
|
}) {
|
|
showModalBottomSheet(
|
|
context: context,
|
|
builder: (sheetContext) => SafeArea(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
ListTile(
|
|
leading: const Icon(Icons.place),
|
|
title: Text(context.l10n.map_shareMarkerHere),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_shareMarker(
|
|
context: context,
|
|
connector: connector,
|
|
position: position,
|
|
defaultLabel: context.l10n.map_pointOfInterest,
|
|
flags: 'poi',
|
|
);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.my_location),
|
|
title: Text(context.l10n.map_setAsMyLocation),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
confirmAndSetMyLocation(this.context, connector, position);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.close),
|
|
title: Text(context.l10n.common_cancel),
|
|
onTap: () => Navigator.pop(sheetContext),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _shareMarker({
|
|
required BuildContext context,
|
|
required MeshCoreConnector connector,
|
|
required LatLng position,
|
|
required String defaultLabel,
|
|
required String flags,
|
|
}) async {
|
|
if (!connector.isConnected) {
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.map_connectToShareMarkers),
|
|
);
|
|
return;
|
|
}
|
|
|
|
// A map point is not the user's own position, so it keeps the point's
|
|
// default label; reusing one label would move earlier shared points.
|
|
final label = await showMarkerLabelDialog(
|
|
context,
|
|
lat: position.latitude,
|
|
lon: position.longitude,
|
|
defaultLabel: defaultLabel,
|
|
flags: flags,
|
|
confirmText: context.l10n.common_continue,
|
|
);
|
|
if (label == null || !mounted) return;
|
|
|
|
final markerText = _formatMarkerMessage(position, label, flags);
|
|
if (!mounted) return;
|
|
|
|
await _showRecipientSheet(
|
|
// ignore: use_build_context_synchronously
|
|
context: context,
|
|
connector: connector,
|
|
markerText: markerText,
|
|
);
|
|
}
|
|
|
|
bool _markerFits(BuildContext context, String markerText, int maxBytes) {
|
|
if (utf8ByteLength(markerText) <= maxBytes) return true;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_messageTooLong(maxBytes)),
|
|
);
|
|
return false;
|
|
}
|
|
|
|
String _formatMarkerMessage(LatLng position, String label, String flags) =>
|
|
formatMarkerText(position.latitude, position.longitude, label, flags);
|
|
|
|
Future<void> _showRecipientSheet({
|
|
required BuildContext context,
|
|
required MeshCoreConnector connector,
|
|
required String markerText,
|
|
}) async {
|
|
if (!connector.isLoadingChannels && connector.channels.isEmpty) {
|
|
connector.getChannels();
|
|
}
|
|
String query = '';
|
|
|
|
await showModalBottomSheet(
|
|
context: context,
|
|
builder: (sheetContext) => StatefulBuilder(
|
|
builder: (sheetContext, setSheetState) {
|
|
return Consumer<MeshCoreConnector>(
|
|
builder: (consumerContext, liveConnector, child) {
|
|
final allContacts = liveConnector.contacts
|
|
.where(
|
|
(contact) =>
|
|
contact.type != advTypeRepeater &&
|
|
contact.type != advTypeRoom,
|
|
)
|
|
.toList();
|
|
return SafeArea(
|
|
child: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
|
child: Text(
|
|
context.l10n.map_sendToContact,
|
|
style: const TextStyle(fontWeight: FontWeight.bold),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
|
|
child: TextField(
|
|
decoration: InputDecoration(
|
|
hintText:
|
|
context.l10n.contacts_searchContactsNoNumber,
|
|
prefixIcon: const Icon(Icons.search),
|
|
border: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
contentPadding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
vertical: 12,
|
|
),
|
|
),
|
|
onChanged: (value) {
|
|
setSheetState(() {
|
|
query = value.toLowerCase();
|
|
});
|
|
},
|
|
),
|
|
),
|
|
...allContacts
|
|
.where(
|
|
(contact) =>
|
|
query.isEmpty ||
|
|
matchesContactQuery(contact, query),
|
|
)
|
|
.map((contact) {
|
|
return ListTile(
|
|
leading: const Icon(Icons.person),
|
|
title: Text(contact.name),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
if (!_markerFits(
|
|
context,
|
|
markerText,
|
|
maxContactMessageBytes(),
|
|
)) {
|
|
return;
|
|
}
|
|
liveConnector.sendMessage(contact, markerText);
|
|
},
|
|
);
|
|
}),
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
|
child: Text(
|
|
context.l10n.map_sendToChannel,
|
|
style: const TextStyle(fontWeight: FontWeight.bold),
|
|
),
|
|
),
|
|
if (liveConnector.isLoadingChannels)
|
|
const Padding(
|
|
padding: EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
vertical: 8,
|
|
),
|
|
child: LinearProgressIndicator(),
|
|
)
|
|
else if (liveConnector.channels
|
|
.where((c) => !c.isEmpty)
|
|
.isEmpty)
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
vertical: 8,
|
|
),
|
|
child: Text(context.l10n.map_noChannelsAvailable),
|
|
)
|
|
else
|
|
...liveConnector.channels.where((c) => !c.isEmpty).map((
|
|
channel,
|
|
) {
|
|
final isPublic = _isPublicChannel(channel);
|
|
final label = channel.name.isEmpty
|
|
? context.l10n.channels_channelIndex(
|
|
channel.index,
|
|
)
|
|
: channel.name;
|
|
return ListTile(
|
|
leading: Icon(
|
|
isPublic ? Icons.public : Icons.tag,
|
|
color: isPublic
|
|
? MapPalette.cluster
|
|
: MapPalette.repeater,
|
|
),
|
|
title: Text(label),
|
|
onTap: () async {
|
|
Navigator.pop(sheetContext);
|
|
final canSend = isPublic
|
|
? await _confirmPublicShare(context, label)
|
|
: true;
|
|
if (canSend &&
|
|
context.mounted &&
|
|
_markerFits(
|
|
context,
|
|
markerText,
|
|
maxChannelMessageBytes(
|
|
liveConnector.selfName,
|
|
),
|
|
)) {
|
|
liveConnector.sendChannelMessage(
|
|
channel,
|
|
markerText,
|
|
);
|
|
}
|
|
},
|
|
);
|
|
}),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
bool _isPublicChannel(Channel channel) {
|
|
return channel.isPublicChannel;
|
|
}
|
|
|
|
Future<bool> _confirmPublicShare(
|
|
BuildContext context,
|
|
String channelLabel,
|
|
) async {
|
|
final result = await showDialog<bool>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
title: Text(context.l10n.map_publicLocationShare),
|
|
content: Text(
|
|
context.l10n.map_publicLocationShareConfirm(channelLabel),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext, false),
|
|
child: Text(context.l10n.common_cancel),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext, true),
|
|
child: Text(context.l10n.common_share),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
return result ?? false;
|
|
}
|
|
|
|
void _showFilterSheet(
|
|
BuildContext context,
|
|
AppSettingsService settingsService,
|
|
) {
|
|
final showOnlineFilters =
|
|
context.read<UiViewStateService>().mapSource != MapSourceOption.local;
|
|
showMeshSheet(
|
|
context,
|
|
builder: (sheetContext) => StatefulBuilder(
|
|
builder: (sheetContext, setSheetState) {
|
|
return Consumer<AppSettingsService>(
|
|
builder: (consumerContext, service, child) {
|
|
final settings = service.settings;
|
|
final scheme = Theme.of(sheetContext).colorScheme;
|
|
|
|
Widget freshnessChip(_Freshness value, String label) {
|
|
final selected = _freshness == value;
|
|
final accent = switch (value) {
|
|
_Freshness.all => MeshMapTheme.of(context).accent,
|
|
_Freshness.online => MapPalette.online,
|
|
_Freshness.recent => MapPalette.stale,
|
|
_Freshness.stale => MapPalette.offline,
|
|
};
|
|
return FilterChip(
|
|
label: Text(label),
|
|
selected: selected,
|
|
showCheckmark: true,
|
|
checkmarkColor: accent,
|
|
backgroundColor: scheme.surfaceContainerLow,
|
|
selectedColor: Color.alphaBlend(
|
|
accent.withValues(alpha: 0.22),
|
|
scheme.surfaceContainerHigh,
|
|
),
|
|
side: BorderSide(
|
|
color: selected ? accent : scheme.outline,
|
|
width: selected ? 1.5 : 1,
|
|
),
|
|
labelStyle: TextStyle(
|
|
color: selected
|
|
? scheme.onSurface
|
|
: scheme.onSurfaceVariant,
|
|
fontWeight: selected ? FontWeight.w700 : FontWeight.w600,
|
|
),
|
|
onSelected: (_) {
|
|
setSheetState(() {});
|
|
setState(() => _freshness = value);
|
|
},
|
|
);
|
|
}
|
|
|
|
return SafeArea(
|
|
child: ConstrainedBox(
|
|
constraints: BoxConstraints(
|
|
maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.8,
|
|
),
|
|
child: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
BottomSheetHeader(
|
|
title: sheetContext.l10n.map_filterNodes,
|
|
),
|
|
SectionHeader(sheetContext.l10n.map_activity),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
child: Wrap(
|
|
spacing: 8,
|
|
runSpacing: 4,
|
|
children: [
|
|
freshnessChip(
|
|
_Freshness.all,
|
|
sheetContext.l10n.time_allTime,
|
|
),
|
|
freshnessChip(
|
|
_Freshness.online,
|
|
sheetContext.l10n.map_online,
|
|
),
|
|
freshnessChip(
|
|
_Freshness.recent,
|
|
sheetContext.l10n.map_recent,
|
|
),
|
|
freshnessChip(
|
|
_Freshness.stale,
|
|
sheetContext.l10n.map_stale,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
SectionHeader(
|
|
sheetContext.l10n.map_lastSeenTime,
|
|
trailing: Text(
|
|
_getTimeFilterLabel(settings.mapTimeFilterHours),
|
|
style: MeshTheme.mono(
|
|
fontSize: 13,
|
|
color: scheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
|
child: Slider(
|
|
value: _hoursToSliderValue(
|
|
settings.mapTimeFilterHours,
|
|
),
|
|
min: 0,
|
|
max: 100,
|
|
divisions: 100,
|
|
onChanged: (value) {
|
|
final hours = _sliderValueToHours(value);
|
|
service.setMapTimeFilterHours(hours);
|
|
},
|
|
),
|
|
),
|
|
SectionHeader(sheetContext.l10n.map_nodeTypes),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_chatNodes),
|
|
value: settings.mapShowChatNodes,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowChatNodes(value),
|
|
),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_repeaters),
|
|
value: settings.mapShowRepeaters,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowRepeaters(value),
|
|
),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_otherNodes),
|
|
value: settings.mapShowOtherNodes,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowOtherNodes(value),
|
|
),
|
|
if (showOnlineFilters)
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_showOnlineLinks),
|
|
value: settings.mapShowOnlineLinks,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowOnlineLinks(value),
|
|
),
|
|
SectionHeader(sheetContext.l10n.map_markers),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_showSharedMarkers),
|
|
value: settings.mapShowMarkers,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowMarkers(value),
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.restore),
|
|
title: Text(
|
|
sheetContext.l10n.map_restoreRemovedMarkers,
|
|
),
|
|
subtitle: Text(
|
|
sheetContext.l10n.map_restoreRemovedMarkersSubtitle(
|
|
_removedMarkerIds.length,
|
|
),
|
|
),
|
|
enabled: _removedMarkerIds.isNotEmpty,
|
|
onTap: () async {
|
|
await _restoreRemovedMarkers();
|
|
setSheetState(() {});
|
|
},
|
|
),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_clusterNodes),
|
|
subtitle: Text(
|
|
sheetContext.l10n.map_clusterNodesSubtitle,
|
|
),
|
|
value: settings.mapClusterNodes,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapClusterNodes(value),
|
|
),
|
|
SwitchListTile(
|
|
title: Text(
|
|
sheetContext.l10n.map_showGuessedLocations,
|
|
),
|
|
value: settings.mapShowGuessedLocations,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowGuessedLocations(value),
|
|
),
|
|
SwitchListTile(
|
|
title: Text(
|
|
sheetContext.l10n.map_showDiscoveryContacts,
|
|
),
|
|
value: settings.mapShowDiscoveryContacts,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowDiscoveryContacts(value),
|
|
),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_showOverlaps),
|
|
value: settings.mapShowOverlaps,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapShowOverlaps(value),
|
|
),
|
|
SectionHeader(sheetContext.l10n.map_keyPrefix),
|
|
SwitchListTile(
|
|
title: Text(sheetContext.l10n.map_filterByKeyPrefix),
|
|
value: settings.mapKeyPrefixEnabled,
|
|
dense: true,
|
|
onChanged: (value) =>
|
|
service.setMapKeyPrefixEnabled(value),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(16, 4, 16, 20),
|
|
child: TextFormField(
|
|
initialValue: settings.mapKeyPrefix,
|
|
enabled: settings.mapKeyPrefixEnabled,
|
|
decoration: InputDecoration(
|
|
labelText: sheetContext.l10n.map_publicKeyPrefix,
|
|
hintText:
|
|
sheetContext.l10n.map_publicKeyPrefixHint,
|
|
isDense: true,
|
|
),
|
|
style: MeshTheme.mono(fontSize: 13),
|
|
onChanged: (value) =>
|
|
service.setMapKeyPrefix(value),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
// Convert hours to slider value (0-100) with exponential scaling
|
|
double _hoursToSliderValue(double hours) {
|
|
if (hours == 0) return 100; // All time
|
|
|
|
// Map hours exponentially
|
|
// 0-24h: 0-40
|
|
// 24h-7d: 40-60
|
|
// 7d-30d: 60-80
|
|
// 30d-6mo: 80-99
|
|
// All time: 100
|
|
|
|
if (hours <= 24) {
|
|
return (hours / 24) * 40;
|
|
} else if (hours <= 168) {
|
|
// 7 days
|
|
return 40 + ((hours - 24) / (168 - 24)) * 20;
|
|
} else if (hours <= 720) {
|
|
// 30 days
|
|
return 60 + ((hours - 168) / (720 - 168)) * 20;
|
|
} else if (hours <= 4380) {
|
|
// 6 months
|
|
return 80 + ((hours - 720) / (4380 - 720)) * 19;
|
|
} else {
|
|
return 100;
|
|
}
|
|
}
|
|
|
|
// Convert slider value (0-100) to hours with exponential scaling
|
|
double _sliderValueToHours(double value) {
|
|
if (value >= 99.5) return 0; // All time
|
|
|
|
if (value <= 40) {
|
|
return (value / 40) * 24; // 0-24 hours
|
|
} else if (value <= 60) {
|
|
return 24 + ((value - 40) / 20) * (168 - 24); // 1-7 days
|
|
} else if (value <= 80) {
|
|
return 168 + ((value - 60) / 20) * (720 - 168); // 7-30 days
|
|
} else {
|
|
return 720 + ((value - 80) / 19) * (4380 - 720); // 30 days - 6 months
|
|
}
|
|
}
|
|
|
|
String _getTimeFilterLabel(double hours) {
|
|
if (hours == 0) return context.l10n.time_allTime;
|
|
|
|
if (hours < 1) {
|
|
return '${(hours * 60).round()} ${context.l10n.time_minutes}';
|
|
} else if (hours < 24) {
|
|
final h = hours.round();
|
|
return '$h ${h == 1 ? context.l10n.time_hour : context.l10n.time_hours}';
|
|
} else if (hours < 168) {
|
|
final days = (hours / 24).round();
|
|
return '$days ${days == 1 ? context.l10n.time_day : context.l10n.time_days}';
|
|
} else if (hours < 720) {
|
|
final weeks = (hours / 168).round();
|
|
return '$weeks ${weeks == 1 ? context.l10n.time_week : context.l10n.time_weeks}';
|
|
} else if (hours < 4380) {
|
|
final months = (hours / 730).round();
|
|
return '$months ${months == 1 ? context.l10n.time_month : context.l10n.time_months}';
|
|
} else {
|
|
return context.l10n.time_allTime;
|
|
}
|
|
}
|
|
|
|
void _addToPath(BuildContext context, Contact contact, {LatLng? position}) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final hopWidth = min(
|
|
connector.pathHashByteWidth.clamp(1, pubKeySize),
|
|
contact.publicKey.length,
|
|
).toInt();
|
|
final hopPrefix = contact.publicKey.sublist(0, hopWidth);
|
|
for (final existingHop in PathHelper.splitPathBytes(
|
|
_pathTrace,
|
|
connector.pathHashByteWidth,
|
|
)) {
|
|
if (listEquals(existingHop, hopPrefix)) {
|
|
return;
|
|
}
|
|
}
|
|
setState(() {
|
|
_pathTrace.addAll(hopPrefix); // Add the hop-width pubkey prefix.
|
|
_pathTraceHopWidths.add(hopWidth);
|
|
_pathTraceContacts.add(
|
|
contact.copyWith(
|
|
latitude: position?.latitude ?? contact.latitude,
|
|
longitude: position?.longitude ?? contact.longitude,
|
|
),
|
|
); // Add contact to path trace contacts
|
|
_points.add(position ?? LatLng(contact.latitude!, contact.longitude!));
|
|
_traceDraft.lastResultFrame = null;
|
|
});
|
|
}
|
|
|
|
/// Opens the path-trace builder, resuming hops picked earlier this session
|
|
/// on the same radio.
|
|
void _openPathTrace(MeshCoreConnector connector, LatLng position) {
|
|
setState(() {
|
|
final selfKey = connector.selfPublicKey;
|
|
if (!_traceDraft.belongsTo(selfKey) || !_traceDraft.hasHops) {
|
|
_traceDraft.clear();
|
|
}
|
|
_traceDraft.radioKey = selfKey;
|
|
if (_points.isEmpty) {
|
|
_points.add(position);
|
|
} else {
|
|
_points[0] = position;
|
|
}
|
|
_isBuildingPathTrace = true;
|
|
});
|
|
}
|
|
|
|
/// Hides the builder but keeps the picked hops and last result.
|
|
void _closePathTrace() {
|
|
setState(() {
|
|
_isBuildingPathTrace = false;
|
|
});
|
|
}
|
|
|
|
void _clearPath() {
|
|
setState(() {
|
|
final start = _points.isNotEmpty ? _points.first : null;
|
|
_traceDraft.clear();
|
|
if (start != null) _points.add(start);
|
|
});
|
|
}
|
|
|
|
void _removePath() {
|
|
setState(() {
|
|
final recordedHopWidth = _pathTraceHopWidths.isNotEmpty
|
|
? _pathTraceHopWidths.removeLast()
|
|
: context.read<MeshCoreConnector>().pathHashByteWidth.clamp(
|
|
1,
|
|
pubKeySize,
|
|
);
|
|
final hopByteCount = min(recordedHopWidth, _pathTrace.length).toInt();
|
|
_pathTraceContacts.removeLast();
|
|
// A path trace hop can be wider than one byte; remove the full hash prefix.
|
|
_pathTrace.removeRange(
|
|
_pathTrace.length - hopByteCount,
|
|
_pathTrace.length,
|
|
);
|
|
_points.removeLast();
|
|
_traceDraft.lastResultFrame = null;
|
|
});
|
|
}
|
|
|
|
void _setTraceReturnPath(bool returnPath) {
|
|
if (_traceDraft.returnPath == returnPath) return;
|
|
setState(() {
|
|
_traceDraft.returnPath = returnPath;
|
|
_traceDraft.lastResultFrame = null;
|
|
});
|
|
}
|
|
|
|
void _openManualEntry() {
|
|
final text = PathHelper.splitPathBytes(
|
|
_pathTrace,
|
|
context.read<MeshCoreConnector>().pathHashByteWidth,
|
|
).map(PathHelper.formatHopHex).join(',');
|
|
ManualPathTraceScreen.open(
|
|
context,
|
|
initialText: text,
|
|
initialReturnPath: _traceDraft.returnPath,
|
|
);
|
|
}
|
|
|
|
void _openTraceResult({required bool reuseLastResult}) {
|
|
final draft = _traceDraft;
|
|
final path = Uint8List.fromList(_pathTrace);
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) => PathTraceMapScreen(
|
|
title: context.l10n.contacts_pathTrace,
|
|
path: path,
|
|
flipPathAround: draft.returnPath,
|
|
pathHashByteWidth: context
|
|
.read<MeshCoreConnector>()
|
|
.pathHashByteWidth,
|
|
pathContacts: List.of(_pathTraceContacts),
|
|
initialTraceFrame: reuseLastResult ? draft.lastResultFrame : null,
|
|
onTraceFrame: (frame) {
|
|
// Ignore a reply for a selection the user has since changed.
|
|
if (!listEquals(draft.pathBytes, path)) return;
|
|
draft.lastResultFrame = frame;
|
|
if (mounted) setState(() {});
|
|
},
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildPathTraceOverlay() {
|
|
final l10n = context.l10n;
|
|
final theme = Theme.of(context);
|
|
final isImperial =
|
|
context.read<AppSettingsService>().settings.unitSystem ==
|
|
UnitSystem.imperial;
|
|
final hasHops = _pathTrace.isNotEmpty;
|
|
final returnPath = _traceDraft.returnPath;
|
|
const buttonSize = Size(48, 48);
|
|
final hopNames = _pathTraceContacts.map((c) => c.name).join(' → ');
|
|
return Positioned(
|
|
top: 16,
|
|
left: 16,
|
|
right: 16,
|
|
child: DecoratedBox(
|
|
decoration: BoxDecoration(
|
|
color: _overlayPanelColor,
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
border: Border.all(color: _overlayBorderColor),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: _overlayShadowColor,
|
|
blurRadius: 10,
|
|
offset: const Offset(0, 4),
|
|
),
|
|
],
|
|
),
|
|
child: ClipRRect(
|
|
borderRadius: BorderRadius.circular(MeshRadii.md),
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(12.0),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
Expanded(
|
|
child: Text(
|
|
l10n.contacts_pathTrace,
|
|
style: theme.textTheme.titleMedium?.copyWith(
|
|
fontWeight: FontWeight.bold,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
),
|
|
),
|
|
TextButton.icon(
|
|
onPressed: _closePathTrace,
|
|
style: TextButton.styleFrom(minimumSize: buttonSize),
|
|
icon: const Icon(Icons.close),
|
|
label: Text(l10n.common_close),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
hasHops ? l10n.map_pathTraceAddMoreHint : l10n.map_tapToAdd,
|
|
style: TextStyle(
|
|
fontSize: 15,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
),
|
|
if (hasHops) ...[
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
hopNames,
|
|
style: TextStyle(
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.w600,
|
|
color: _overlayPrimaryTextColor,
|
|
),
|
|
),
|
|
SelectableText(
|
|
PathHelper.splitPathBytes(
|
|
_pathTrace,
|
|
context.read<MeshCoreConnector>().pathHashByteWidth,
|
|
).map(PathHelper.formatHopHex).join(','),
|
|
style: MeshTheme.mono(
|
|
fontSize: 18,
|
|
fontWeight: FontWeight.w700,
|
|
color: MeshMapTheme.of(context).accent,
|
|
),
|
|
),
|
|
Text(
|
|
"${l10n.path_currentPathLabel} ${formatDistance(getPathDistanceMeters(_points), isImperial: isImperial)}",
|
|
style: MeshTheme.mono(
|
|
fontSize: 14,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Wrap(
|
|
spacing: 8,
|
|
children: [
|
|
TextButton.icon(
|
|
onPressed: _removePath,
|
|
style: TextButton.styleFrom(minimumSize: buttonSize),
|
|
icon: const Icon(Icons.undo),
|
|
label: Text(l10n.map_removeLast),
|
|
),
|
|
TextButton.icon(
|
|
onPressed: _openManualEntry,
|
|
style: TextButton.styleFrom(minimumSize: buttonSize),
|
|
icon: const Icon(Icons.keyboard),
|
|
label: Text(l10n.manualTrace_enterHashes),
|
|
),
|
|
TextButton.icon(
|
|
onPressed: _clearPath,
|
|
style: TextButton.styleFrom(minimumSize: buttonSize),
|
|
icon: const Icon(Icons.delete_outline),
|
|
label: Text(l10n.common_clear),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 4),
|
|
SegmentedButton<bool>(
|
|
segments: [
|
|
ButtonSegment(
|
|
value: true,
|
|
icon: const Icon(Icons.sync_alt),
|
|
label: Text(l10n.map_pathTraceModeRoundTrip),
|
|
),
|
|
ButtonSegment(
|
|
value: false,
|
|
icon: const Icon(Icons.arrow_forward),
|
|
label: Text(l10n.map_pathTraceModeAsEntered),
|
|
),
|
|
],
|
|
selected: {returnPath},
|
|
onSelectionChanged: (selection) =>
|
|
_setTraceReturnPath(selection.first),
|
|
style: SegmentedButton.styleFrom(minimumSize: buttonSize),
|
|
),
|
|
const SizedBox(height: 6),
|
|
Text(
|
|
returnPath
|
|
? l10n.map_pathTraceModeRoundTripHint
|
|
: l10n.map_pathTraceModeAsEnteredHint,
|
|
style: TextStyle(
|
|
fontSize: 14,
|
|
color: _overlaySecondaryTextColor,
|
|
),
|
|
),
|
|
const SizedBox(height: 10),
|
|
Wrap(
|
|
spacing: 8,
|
|
runSpacing: 8,
|
|
alignment: WrapAlignment.end,
|
|
children: [
|
|
if (_traceDraft.lastResultFrame != null)
|
|
OutlinedButton.icon(
|
|
onPressed: () =>
|
|
_openTraceResult(reuseLastResult: true),
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: buttonSize,
|
|
),
|
|
icon: const Icon(Icons.history),
|
|
label: Text(l10n.map_pathTraceViewLast),
|
|
),
|
|
FilledButton.icon(
|
|
onPressed: () =>
|
|
_openTraceResult(reuseLastResult: false),
|
|
style: FilledButton.styleFrom(minimumSize: buttonSize),
|
|
icon: const Icon(Icons.radar),
|
|
label: Text(l10n.map_runTrace),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
enum _NodeAge { online, recent, stale }
|
|
|
|
enum _Freshness { all, online, recent, stale }
|
|
|
|
int _bytesSignature(Iterable<int>? bytes) {
|
|
if (bytes == null) return 0;
|
|
return Object.hashAll(bytes);
|
|
}
|
|
|
|
int _mapContactSignature(Contact contact) {
|
|
return Object.hash(
|
|
contact.publicKeyHex,
|
|
contact.name,
|
|
contact.type,
|
|
contact.flags,
|
|
contact.pathLength,
|
|
_bytesSignature(contact.path),
|
|
contact.pathHashWidth,
|
|
contact.pathOverride,
|
|
_bytesSignature(contact.pathOverrideBytes),
|
|
contact.latitude,
|
|
contact.longitude,
|
|
contact.lastHeard.millisecondsSinceEpoch,
|
|
contact.lastMessageAt.millisecondsSinceEpoch,
|
|
contact.isActive,
|
|
);
|
|
}
|
|
|
|
class _MapConnectorSnapshot {
|
|
final MeshCoreConnector connector;
|
|
final int contactsSignature;
|
|
final int markerSignature;
|
|
final int batterySignature;
|
|
final int uiSignature;
|
|
|
|
const _MapConnectorSnapshot({
|
|
required this.connector,
|
|
required this.contactsSignature,
|
|
required this.markerSignature,
|
|
required this.batterySignature,
|
|
required this.uiSignature,
|
|
});
|
|
|
|
factory _MapConnectorSnapshot.fromConnector(MeshCoreConnector connector) {
|
|
final allContacts = connector.allContacts;
|
|
final contactsSignature = Object.hashAll(
|
|
allContacts.map(_mapContactSignature),
|
|
);
|
|
final batterySignature = Object.hashAll(
|
|
allContacts
|
|
.where((contact) => contact.type == advTypeRepeater)
|
|
.map(
|
|
(contact) => Object.hash(
|
|
contact.publicKeyHex,
|
|
connector.getRepeaterBatteryMillivolts(contact.publicKeyHex),
|
|
),
|
|
),
|
|
);
|
|
|
|
// Only detect that a conversation changed; _collectSharedMarkers does the
|
|
// per-message scan when this signature moves.
|
|
final markerParts = <Object?>[connector.selfName];
|
|
for (final contact in connector.contacts) {
|
|
final messages = connector.getMessages(contact);
|
|
markerParts.add(
|
|
Object.hash(
|
|
contact.publicKeyHex,
|
|
contact.name,
|
|
messages.length,
|
|
messages.isEmpty ? null : messages.last.messageId,
|
|
),
|
|
);
|
|
}
|
|
for (final channel in connector.channels) {
|
|
final messages = connector.getChannelMessages(channel);
|
|
markerParts.add(
|
|
Object.hash(
|
|
channel.index,
|
|
channel.name,
|
|
channel.isPublicChannel,
|
|
channel.isEmpty,
|
|
messages.length,
|
|
messages.isEmpty ? null : messages.last.messageId,
|
|
),
|
|
);
|
|
}
|
|
|
|
return _MapConnectorSnapshot(
|
|
connector: connector,
|
|
contactsSignature: contactsSignature,
|
|
markerSignature: Object.hashAll(markerParts),
|
|
batterySignature: batterySignature,
|
|
uiSignature: Object.hash(
|
|
connector.isConnected,
|
|
connector.selfLatitude,
|
|
connector.selfLongitude,
|
|
connector.currentFreqHz,
|
|
connector.currentBwHz,
|
|
connector.currentSf,
|
|
connector.currentTxPower,
|
|
connector.getTotalContactsUnreadCount(),
|
|
connector.getTotalChannelsUnreadCount(),
|
|
),
|
|
);
|
|
}
|
|
|
|
@override
|
|
bool operator ==(Object other) {
|
|
return other is _MapConnectorSnapshot &&
|
|
contactsSignature == other.contactsSignature &&
|
|
markerSignature == other.markerSignature &&
|
|
batterySignature == other.batterySignature &&
|
|
uiSignature == other.uiSignature;
|
|
}
|
|
|
|
@override
|
|
int get hashCode => Object.hash(
|
|
contactsSignature,
|
|
markerSignature,
|
|
batterySignature,
|
|
uiSignature,
|
|
);
|
|
}
|
|
|
|
class _NodeMarkersCacheKey {
|
|
final int contactsSignature;
|
|
final int visibleContactsSignature;
|
|
final int batterySignature;
|
|
final _Freshness freshness;
|
|
final double timeFilterHours;
|
|
final bool keyPrefixEnabled;
|
|
final String keyPrefix;
|
|
final bool showDiscoveryContacts;
|
|
final int batteryChemistrySignature;
|
|
final bool showLabels;
|
|
final String? selectedKey;
|
|
final double zoom;
|
|
final bool overlapsMode;
|
|
final bool showRepeaters;
|
|
final bool showChatNodes;
|
|
final bool showOtherNodes;
|
|
final bool isBuildingPathTrace;
|
|
final bool clusterNodes;
|
|
|
|
const _NodeMarkersCacheKey({
|
|
required this.contactsSignature,
|
|
required this.visibleContactsSignature,
|
|
required this.batterySignature,
|
|
required this.freshness,
|
|
required this.timeFilterHours,
|
|
required this.keyPrefixEnabled,
|
|
required this.keyPrefix,
|
|
required this.showDiscoveryContacts,
|
|
required this.batteryChemistrySignature,
|
|
required this.showLabels,
|
|
required this.selectedKey,
|
|
required this.zoom,
|
|
required this.overlapsMode,
|
|
required this.showRepeaters,
|
|
required this.showChatNodes,
|
|
required this.showOtherNodes,
|
|
required this.isBuildingPathTrace,
|
|
required this.clusterNodes,
|
|
});
|
|
|
|
@override
|
|
bool operator ==(Object other) {
|
|
return other is _NodeMarkersCacheKey &&
|
|
contactsSignature == other.contactsSignature &&
|
|
visibleContactsSignature == other.visibleContactsSignature &&
|
|
batterySignature == other.batterySignature &&
|
|
freshness == other.freshness &&
|
|
timeFilterHours == other.timeFilterHours &&
|
|
keyPrefixEnabled == other.keyPrefixEnabled &&
|
|
keyPrefix == other.keyPrefix &&
|
|
showDiscoveryContacts == other.showDiscoveryContacts &&
|
|
batteryChemistrySignature == other.batteryChemistrySignature &&
|
|
showLabels == other.showLabels &&
|
|
selectedKey == other.selectedKey &&
|
|
zoom == other.zoom &&
|
|
overlapsMode == other.overlapsMode &&
|
|
showRepeaters == other.showRepeaters &&
|
|
showChatNodes == other.showChatNodes &&
|
|
showOtherNodes == other.showOtherNodes &&
|
|
isBuildingPathTrace == other.isBuildingPathTrace &&
|
|
clusterNodes == other.clusterNodes;
|
|
}
|
|
|
|
@override
|
|
int get hashCode => Object.hash(
|
|
contactsSignature,
|
|
visibleContactsSignature,
|
|
batterySignature,
|
|
freshness,
|
|
timeFilterHours,
|
|
keyPrefixEnabled,
|
|
keyPrefix,
|
|
showDiscoveryContacts,
|
|
batteryChemistrySignature,
|
|
showLabels,
|
|
selectedKey,
|
|
zoom,
|
|
overlapsMode,
|
|
showRepeaters,
|
|
showChatNodes,
|
|
showOtherNodes,
|
|
isBuildingPathTrace,
|
|
clusterNodes,
|
|
);
|
|
}
|
|
|
|
class _GuessedLocation {
|
|
final Contact contact;
|
|
final LatLng position;
|
|
final bool highConfidence;
|
|
|
|
_GuessedLocation({
|
|
required this.contact,
|
|
required this.position,
|
|
required this.highConfidence,
|
|
});
|
|
}
|
|
|
|
/// Build a normalized dedupe key for shared markers.
|
|
/// Keeps the same algorithm previously present in both chat and map screens.
|
|
String buildSharedMarkerKey({
|
|
required String sourceId,
|
|
required String label,
|
|
required String fromName,
|
|
required String flags,
|
|
required bool isChannel,
|
|
}) {
|
|
final normalizedLabel = label.trim().toLowerCase();
|
|
final normalizedFrom = fromName.trim().toLowerCase();
|
|
final normalizedFlags = flags.trim().toLowerCase();
|
|
final scope = isChannel ? 'ch' : 'dm';
|
|
return '$scope|$sourceId|$normalizedFrom|$normalizedLabel|$normalizedFlags';
|
|
}
|
|
|
|
class _SharedMarker {
|
|
final String id;
|
|
final LatLng position;
|
|
final String label;
|
|
final String flags;
|
|
final String fromName;
|
|
final String sourceLabel;
|
|
final DateTime timestamp;
|
|
final bool isChannel;
|
|
final bool isPublicChannel;
|
|
final List<LatLng> history;
|
|
|
|
_SharedMarker({
|
|
required this.id,
|
|
required this.position,
|
|
required this.label,
|
|
required this.flags,
|
|
required this.fromName,
|
|
required this.sourceLabel,
|
|
required this.timestamp,
|
|
required this.isChannel,
|
|
required this.isPublicChannel,
|
|
this.history = const [],
|
|
});
|
|
|
|
_SharedMarker copyWithHistory(List<LatLng> newHistory) {
|
|
return _SharedMarker(
|
|
id: id,
|
|
position: position,
|
|
label: label,
|
|
flags: flags,
|
|
fromName: fromName,
|
|
sourceLabel: sourceLabel,
|
|
timestamp: timestamp,
|
|
isChannel: isChannel,
|
|
isPublicChannel: isPublicChannel,
|
|
history: newHistory,
|
|
);
|
|
}
|
|
}
|