update to zjs81/dev 98f6cf3745

This commit is contained in:
ericz committed 2026-08-04 17:43:52 +02:00
commit 1fc6a9bf68
128 files changed
+11006 -1179

No files matched your search

+410 -91
View File
@@ -8,6 +8,7 @@ import '../l10n/l10n.dart';
import '../models/app_settings.dart';
import '../models/translation_support.dart';
import '../services/app_settings_service.dart';
import '../services/map_tile_cache_service.dart';
import '../services/notification_service.dart';
import '../services/translation_service.dart';
import '../theme/mesh_theme.dart';
@@ -699,52 +700,229 @@ class AppSettingsScreen extends StatelessWidget {
) {
final scheme = Theme.of(context).colorScheme;
final textTheme = Theme.of(context).textTheme;
return Column(
children: [
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
final children = <Widget>[
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
secondary: const Icon(Icons.router_outlined, size: 20),
title: Text(context.l10n.appSettings_showRepeaters),
subtitle: Text(context.l10n.appSettings_showRepeatersSubtitle),
value: settingsService.settings.mapShowRepeaters,
onChanged: (value) => settingsService.setMapShowRepeaters(value),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
secondary: const Icon(Icons.chat_outlined, size: 20),
title: Text(context.l10n.appSettings_showChatNodes),
subtitle: Text(context.l10n.appSettings_showChatNodesSubtitle),
value: settingsService.settings.mapShowChatNodes,
onChanged: (value) => settingsService.setMapShowChatNodes(value),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
secondary: const Icon(Icons.people_outline, size: 20),
title: Text(context.l10n.appSettings_showOtherNodes),
subtitle: Text(context.l10n.appSettings_showOtherNodesSubtitle),
value: settingsService.settings.mapShowOtherNodes,
onChanged: (value) => settingsService.setMapShowOtherNodes(value),
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () => _showTimeFilterSheet(context, settingsService),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.timer_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_timeFilter,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.mapTimeFilterHours == 0
? context.l10n.appSettings_timeFilterShowAll
: context.l10n.appSettings_timeFilterShowLast(
settingsService.settings.mapTimeFilterHours
.toInt(),
),
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.chevron_right,
color: scheme.onSurfaceVariant,
size: 16,
),
],
),
secondary: const Icon(Icons.router_outlined, size: 20),
title: Text(context.l10n.appSettings_showRepeaters),
subtitle: Text(context.l10n.appSettings_showRepeatersSubtitle),
value: settingsService.settings.mapShowRepeaters,
onChanged: (value) => settingsService.setMapShowRepeaters(value),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () => _showUnitsSheet(context, settingsService),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(Icons.straighten, size: 20, color: scheme.onSurfaceVariant),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_unitsTitle,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.unitSystem == UnitSystem.imperial
? context.l10n.appSettings_unitsImperial
: context.l10n.appSettings_unitsMetric,
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.chevron_right,
color: scheme.onSurfaceVariant,
size: 16,
),
],
),
secondary: const Icon(Icons.chat_outlined, size: 20),
title: Text(context.l10n.appSettings_showChatNodes),
subtitle: Text(context.l10n.appSettings_showChatNodesSubtitle),
value: settingsService.settings.mapShowChatNodes,
onChanged: (value) => settingsService.setMapShowChatNodes(value),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MapCacheScreen()),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.download_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_offlineMapCache,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.mapCacheBounds == null
? context.l10n.appSettings_noAreaSelected
: context.l10n.appSettings_areaSelectedZoom(
settingsService.settings.mapCacheMinZoom,
settingsService.settings.mapCacheMaxZoom,
),
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.chevron_right,
color: scheme.onSurfaceVariant,
size: 16,
),
],
),
secondary: const Icon(Icons.people_outline, size: 20),
title: Text(context.l10n.appSettings_showOtherNodes),
subtitle: Text(context.l10n.appSettings_showOtherNodesSubtitle),
value: settingsService.settings.mapShowOtherNodes,
onChanged: (value) => settingsService.setMapShowOtherNodes(value),
),
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () => _showMapRasterSourceDialog(context, settingsService),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.layers_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_rasterTileSource,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
_mapRasterSourceSummary(settingsService.settings),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.chevron_right,
color: scheme.onSurfaceVariant,
size: 16,
),
],
),
),
),
];
if (_isStadiaSource(settingsService.settings)) {
children.addAll([
const Divider(height: 1, indent: 16),
InkWell(
onTap: () => _showTimeFilterSheet(context, settingsService),
onTap: () => _showMapRasterEndpointDialog(context, settingsService),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.timer_outlined,
Icons.public_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
@@ -754,19 +932,14 @@ class AppSettingsScreen extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_timeFilter,
context.l10n.appSettings_stadiaEndpoint,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.mapTimeFilterHours == 0
? context.l10n.appSettings_timeFilterShowAll
: context.l10n.appSettings_timeFilterShowLast(
settingsService.settings.mapTimeFilterHours
.toInt(),
),
_mapRasterEndpointSummary(settingsService.settings),
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
@@ -785,13 +958,13 @@ class AppSettingsScreen extends StatelessWidget {
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () => _showUnitsSheet(context, settingsService),
onTap: () => _showMapApiKeyDialog(context, settingsService),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.straighten,
Icons.key_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
@@ -801,17 +974,14 @@ class AppSettingsScreen extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.l10n.appSettings_unitsTitle,
context.l10n.appSettings_stadiaApiKey,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.unitSystem ==
UnitSystem.imperial
? context.l10n.appSettings_unitsImperial
: context.l10n.appSettings_unitsMetric,
_mapApiKeySummary(context, settingsService.settings),
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
@@ -828,59 +998,208 @@ class AppSettingsScreen extends StatelessWidget {
),
),
),
const Divider(height: 1, indent: 16),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MapCacheScreen()),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(
Icons.download_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
]);
}
return Column(children: children);
}
String _mapRasterSourceSummary(AppSettings settings) {
final source = MapRasterSourceCatalog.fromSettings(settings);
return '${source.label} - ${source.description}';
}
bool _isStadiaSource(AppSettings settings) {
return MapRasterSourceCatalog.fromSettings(settings).isStadia;
}
String _mapRasterEndpointSummary(AppSettings settings) {
final endpoint = MapRasterEndpointCatalog.fromSettings(settings);
return '${endpoint.label} - ${endpoint.description}';
}
String _mapApiKeySummary(BuildContext context, AppSettings settings) {
return context.l10n.appSettings_stadiaApiKeyConfigured(
_maskApiKey(settings.effectiveMapTileApiKey),
);
}
String _maskApiKey(String value) {
if (value.length <= 8) return '********';
return '${value.substring(0, 4)}...${value.substring(value.length - 4)}';
}
void _showMapRasterSourceDialog(
BuildContext context,
AppSettingsService settingsService,
) {
String selectedId = settingsService.settings.mapRasterSourceId;
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setState) => AlertDialog(
title: Text(context.l10n.appSettings_rasterTileSource),
content: SizedBox(
width: 360,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(dialogContext).size.height * 0.6,
),
child: SingleChildScrollView(
child: RadioGroup<String>(
groupValue: selectedId,
onChanged: (value) {
if (value == null) return;
setState(() {
selectedId = value;
});
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.appSettings_offlineMapCache,
style: textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
for (final preset in MapRasterSourcePreset.values)
Builder(
builder: (context) {
final option = MapRasterSourceCatalog.fromPreset(
preset,
);
return RadioListTile<String>(
value: preset.id,
title: Text(option.label),
subtitle: Text(option.description),
);
},
),
),
const SizedBox(height: 2),
Text(
settingsService.settings.mapCacheBounds == null
? context.l10n.appSettings_noAreaSelected
: context.l10n.appSettings_areaSelectedZoom(
settingsService.settings.mapCacheMinZoom,
settingsService.settings.mapCacheMaxZoom,
),
style: textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.chevron_right,
color: scheme.onSurfaceVariant,
size: 16,
),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(context.l10n.common_cancel),
),
TextButton(
onPressed: () async {
await settingsService.setMapRasterSourceId(selectedId);
if (!dialogContext.mounted) return;
Navigator.pop(dialogContext);
},
child: Text(context.l10n.common_save),
),
],
),
],
),
);
}
void _showMapRasterEndpointDialog(
BuildContext context,
AppSettingsService settingsService,
) {
String selectedId = settingsService.settings.mapTileEndpointId;
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setState) => AlertDialog(
title: Text(context.l10n.appSettings_stadiaEndpoint),
content: SizedBox(
width: 360,
child: RadioGroup<String>(
groupValue: selectedId,
onChanged: (value) {
if (value == null) return;
setState(() {
selectedId = value;
});
},
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final option in MapRasterEndpointCatalog.presets)
RadioListTile<String>(
value: option.id,
title: Text(option.label),
subtitle: Text(option.description),
),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(context.l10n.common_cancel),
),
TextButton(
onPressed: () async {
await settingsService.setMapTileEndpointId(selectedId);
if (!dialogContext.mounted) return;
Navigator.pop(dialogContext);
},
child: Text(context.l10n.common_save),
),
],
),
),
);
}
void _showMapApiKeyDialog(
BuildContext context,
AppSettingsService settingsService,
) {
final currentApiKey = settingsService.settings.mapTileApiKey?.trim() ?? '';
final maskedApiKey = _maskApiKey(
currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey,
);
final controller = TextEditingController(text: maskedApiKey);
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(context.l10n.appSettings_stadiaApiKey),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(context.l10n.appSettings_stadiaApiKeyDialogDescription),
const SizedBox(height: 12),
TextField(
controller: controller,
autofocus: true,
autocorrect: false,
enableSuggestions: false,
autofillHints: const [AutofillHints.password],
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: '4e1bf343-3d91-4d9c-a8e1-1234567890ab',
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(context.l10n.common_cancel),
),
TextButton(
onPressed: () async {
final apiKey = controller.text.trim();
await settingsService.setMapTileApiKey(
apiKey == maskedApiKey ? currentApiKey : apiKey,
);
if (!dialogContext.mounted) return;
Navigator.pop(dialogContext);
},
child: Text(context.l10n.common_save),
),
],
),
);
}
+37 -17
View File
@@ -10,6 +10,13 @@ import '../helpers/snack_bar_builder.dart';
enum _BleLogView { frames, rawLogRx }
int _decodeRawPathByteLen(int pathLenRaw) {
if (pathLenRaw == 0xFF || pathLenRaw == 0) return 0;
final hashCount = pathLenRaw & 0x3F;
final hashWidth = ((pathLenRaw >> 6) & 0x03) + 1;
return hashCount * hashWidth;
}
class BleDebugLogScreen extends StatefulWidget {
const BleDebugLogScreen({super.key});
@@ -110,20 +117,32 @@ class _BleDebugLogScreenState extends State<BleDebugLogScreen> {
final entry = entries[index];
final time =
'${entry.timestamp.hour.toString().padLeft(2, '0')}:${entry.timestamp.minute.toString().padLeft(2, '0')}:${entry.timestamp.second.toString().padLeft(2, '0')}';
return GestureDetector(
onLongPress: () async {
await Clipboard.setData(
ClipboardData(
text: entry.payload
.map(
(b) => b
.toRadixString(16)
.padLeft(2, '0'),
)
.join(''),
Future<void> copyHex() async {
await Clipboard.setData(
ClipboardData(
text: entry.payload
.map(
(b) => b
.toRadixString(16)
.padLeft(2, '0'),
)
.join(''),
),
);
if (context.mounted) {
showDismissibleSnackBar(
context,
content: Text(
context.l10n.debugLog_bleCopied,
),
);
},
}
}
return GestureDetector(
onTap: copyHex,
onLongPress: copyHex,
onSecondaryTap: copyHex,
child: Container(
color: MeshPalette.bg,
padding: const EdgeInsets.symmetric(
@@ -302,16 +321,17 @@ class _BleDebugLogScreenState extends State<BleDebugLogScreen> {
rawHex: _bytesToHex(raw),
);
}
final pathLen = raw[index++];
if (raw.length < index + pathLen) {
final pathLenRaw = raw[index++];
final pathByteLen = _decodeRawPathByteLen(pathLenRaw);
if (raw.length < index + pathByteLen) {
return _RawPacketInfo(
title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}',
summary: 'Truncated path',
rawHex: _bytesToHex(raw),
);
}
final pathBytes = raw.sublist(index, index + pathLen);
index += pathLen;
final pathBytes = raw.sublist(index, index + pathByteLen);
index += pathByteLen;
if (raw.length <= index) {
return _RawPacketInfo(
title: 'RX RAW_LOG_RX_DATA • ${_payloadTypeLabel(payloadType)}',
@@ -324,7 +344,7 @@ class _BleDebugLogScreenState extends State<BleDebugLogScreen> {
final title =
'RX ${_payloadTypeLabel(payloadType)} • ${_routeLabel(routeType)} • v$payloadVer';
final summary = _decodePayloadSummary(payloadType, payload);
final pathSummary = pathLen > 0
final pathSummary = pathByteLen > 0
? 'Path=${_bytesToHex(pathBytes)}'
: 'Path=none';
final detail = '$summary • $pathSummary • len=${raw.length}';
+218 -80
View File
@@ -16,6 +16,7 @@ import '../helpers/chat_scroll_controller.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/gif_helper.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
@@ -42,6 +43,8 @@ import '../theme/mesh_theme.dart';
import '../widgets/mesh_ui.dart';
import 'channel_message_path_screen.dart';
import 'map_screen.dart';
import 'region_management_screen.dart';
import '../storage/region_store.dart';
class ChannelChatScreen extends StatefulWidget {
final Channel channel;
@@ -273,46 +276,63 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
children: [
_channelIcon(widget.channel),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.channel.name.isEmpty
? context.l10n.channels_channelIndex(
widget.channel.index,
)
: widget.channel.name,
style: const TextStyle(fontSize: 16),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Consumer<MeshCoreConnector>(
builder: (context, connector, _) {
final unreadCount = connector
.getUnreadCountForChannelIndex(widget.channel.index);
final privacy = widget.channel.isPublicChannel
? context.l10n.channels_public
: context.l10n.channels_private;
return Text(
'$privacy • ${context.l10n.chat_unread(unreadCount)}',
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 12),
);
},
),
],
title: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => openRegionSelectDialog(widget.channel),
child: Row(
children: [
_channelIcon(widget.channel),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.channel.name.isEmpty
? context.l10n.channels_channelIndex(
widget.channel.index,
)
: widget.channel.name,
style: const TextStyle(fontSize: 16),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Consumer<MeshCoreConnector>(
builder: (context, connector, _) {
final unreadCount = connector
.getUnreadCountForChannelIndex(
widget.channel.index,
);
final privacy = widget.channel.isPublicChannel
? context.l10n.channels_public
: context.l10n.channels_private;
final region = connector.getChannelRegion(
widget.channel.index,
);
final regionText = region.isNotEmpty
? ' • ${context.l10n.channels_regionSetTo(region)}'
: '';
return Text(
'$privacy • ${context.l10n.chat_unread(unreadCount)}$regionText',
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 12),
);
},
),
],
),
),
),
],
],
),
),
centerTitle: false,
bottom: const SyncProgressAppBarBottom(),
actions: [
IconButton(
tooltip: context.l10n.channels_regionSelect_Title,
icon: const Icon(Icons.landscape),
onPressed: () => openRegionSelectDialog(widget.channel),
),
const RadioStatsIconButton(),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
@@ -511,6 +531,14 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
: (message.pathVariants.isNotEmpty
? message.pathVariants.first
: Uint8List(0));
final displayPathHashWidth =
message.pathHashWidth ??
context.read<MeshCoreConnector>().pathHashByteWidth;
final displayHopCount = _displayHopCount(
displayPath,
displayPathHashWidth,
message.pathLength,
);
// Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk.
final bubbleColor = isOutgoing
@@ -550,10 +578,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
mainAxisAlignment: isOutgoing
? MainAxisAlignment.end
: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isOutgoing) ...[
_buildAvatar(message.senderName),
_buildAvatar(message.senderName, textScale),
const SizedBox(width: 6),
],
Flexible(
@@ -591,10 +619,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
: EdgeInsets.zero,
child: Text(
message.senderName,
style: MeshTheme.mono(
fontSize: 11,
style: TextStyle(
fontSize: 13 * textScale,
fontWeight: FontWeight.w700,
color: _colorForName(message.senderName),
color: textColor,
),
),
),
@@ -646,6 +674,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
fontStyle: FontStyle.italic,
color: textColor.withValues(alpha: 0.72),
),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showMessageActions(message)
: null,
),
),
],
@@ -658,21 +689,25 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
: EdgeInsets.zero,
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RouteChip(
isDirect: (message.pathLength ?? -1) >= 0,
hops: (message.pathLength ?? -1) >= 0
? message.pathLength
: null,
hops: displayHopCount,
),
const SizedBox(width: 4),
Text(
context.l10n.channels_via(
_formatPathPrefixes(displayPath),
),
style: MeshTheme.mono(
fontSize: 9.5 * textScale,
color: metaColor,
Flexible(
child: Text(
context.l10n.channels_via(
_formatPathPrefixes(
displayPath,
displayPathHashWidth,
),
),
style: MeshTheme.mono(
fontSize: 9.5 * textScale,
color: metaColor,
),
),
),
],
@@ -1012,8 +1047,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
Widget _buildAvatar(String senderName) {
return AvatarCircle(name: senderName, size: 32);
Widget _buildAvatar(String senderName, double textScale) {
return AvatarCircle(
name: senderName,
size: (32 * textScale).clamp(28.0, 56.0),
);
}
Widget _buildReplyBanner(double textScale) {
@@ -1176,25 +1214,19 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
decoration: InputDecoration(
hintText: context.l10n.chat_typeMessage,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.pill,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.outlineVariant,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.pill,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.outlineVariant,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.pill,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.primary,
width: 1.5,
@@ -1550,27 +1582,133 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
String _formatPathPrefixes(Uint8List pathBytes) {
return pathBytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(',');
String _formatPathPrefixes(Uint8List pathBytes, int pathHashByteWidth) {
return PathHelper.splitPathBytes(
pathBytes,
pathHashByteWidth,
).map(PathHelper.formatHopHex).join(',');
}
/// Deterministic name-to-hue mapping consistent with [AvatarCircle].
Color _colorForName(String name) {
const hues = [
MeshPalette.blue,
MeshPalette.magenta,
MeshPalette.signal,
MeshPalette.warn,
Color(0xFF8FA8F0),
Color(0xFF6FD9CE),
];
var h = 0;
for (final c in name.codeUnits) {
h = (h * 31 + c) & 0x7fffffff;
}
return hues[h % hues.length];
int? _displayHopCount(
Uint8List pathBytes,
int pathHashByteWidth,
int? fallbackPathLength,
) {
if ((fallbackPathLength ?? -1) < 0) return null;
if (pathBytes.isEmpty) return fallbackPathLength;
return PathHelper.splitPathBytes(pathBytes, pathHashByteWidth).length;
}
Future<void> openRegionSelectDialog(Channel channel) async {
// The AppBar subtitle reads the region from the connector inside a
// Consumer, so setChannelRegion's notifyListeners refreshes it directly —
// no post-dialog setState needed.
await showDialog(
context: context,
builder: (BuildContext context) => _RegionSelectDialog(channel: channel),
);
}
}
class _RegionSelectDialog extends StatefulWidget {
final Channel channel;
const _RegionSelectDialog({required this.channel});
@override
State<_RegionSelectDialog> createState() => _RegionSelectDialogState();
}
class _RegionSelectDialogState extends State<_RegionSelectDialog> {
final RegionStore regionStore = RegionStore();
List<Region> regions = [];
int selectedIndex = -1;
@override
void initState() {
super.initState();
loadRegions();
}
void loadRegions() {
setState(() {
regions = regionStore.loadRegions();
final channelRegion = context.read<MeshCoreConnector>().getChannelRegion(
widget.channel.index,
);
selectedIndex = regions.indexOf(channelRegion);
});
}
@override
Widget build(BuildContext context) {
return Dialog(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
AppBar(
backgroundColor: Colors.transparent,
title: Text(context.l10n.channels_regionSelect_Title),
centerTitle: true,
actions: [
IconButton(
tooltip: context.l10n.channels_clearRegion,
icon: const Icon(Icons.backspace_outlined),
onPressed: () {
context.read<MeshCoreConnector>().setChannelRegion(
widget.channel.index,
'',
);
Navigator.pop(context);
},
),
IconButton(
tooltip: context.l10n.settings_regionSettingsSubtitle,
icon: const Icon(Icons.settings),
onPressed: () async {
await pushRegionManagementScreen(context);
if (!mounted) return;
loadRegions();
},
),
],
),
const SizedBox(height: 15),
Expanded(
child: ListView.builder(
itemCount: regions.length,
itemBuilder: (context, index) {
final selected = selectedIndex == index;
return ListTile(
leading: Icon(
Icons.landscape,
color: selected ? MeshPalette.blue : null,
),
title: Text(regions[index]),
trailing: selected
? const Icon(Icons.check, color: MeshPalette.blue)
: null,
tileColor: selected ? MeshPalette.blueBg : null,
onTap: () {
// Tapping the already-selected region clears it.
context.read<MeshCoreConnector>().setChannelRegion(
widget.channel.index,
selected ? '' : regions[index],
);
Navigator.pop(context);
},
);
},
),
),
],
),
),
);
}
}
+135 -52
View File
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:meshcore_open/helpers/path_helper.dart';
import 'package:meshcore_open/screens/path_trace_map.dart';
import 'package:provider/provider.dart';
@@ -22,7 +23,6 @@ import '../theme/mesh_theme.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/path_map_ui.dart';
import '../widgets/themed_map_tile_layer.dart';
class ChannelMessagePathScreen extends StatelessWidget {
final ChannelMessage message;
@@ -43,19 +43,40 @@ class ChannelMessagePathScreen extends StatelessWidget {
message.pathVariants,
);
final primaryPath = !channelMessage && !message.isOutgoing
? Uint8List.fromList(primaryPathTmp.reversed.toList())
: primaryPathTmp;
final hashByteWidth =
(message.pathHashWidth ?? connector.pathHashByteWidth)
.clamp(1, 4)
.toInt();
final primaryPath = _orientPathBytes(
primaryPathTmp,
hashByteWidth,
reverse: !channelMessage && !message.isOutgoing,
);
final hops = _buildPathHops(
primaryPath,
connector,
l10n,
hashByteWidth,
resolveFromEnd: !message.isOutgoing,
);
final hasHopDetails = primaryPath.isNotEmpty;
final observedLabel = _formatObservedHops(
// Convert observed path byte length to hop count using the packet width.
// Legacy messages fall back to the current connector width.
// Reported path length (V3+) is already stored as a hop count; preserve
// the negative flood sentinel when present.
final observedHopCount = _hopCountFromBytes(
primaryPath.length,
message.pathLength,
hashByteWidth,
);
final reportedHopCount = message.pathLength;
final effectiveHopCount = observedHopCount > 0
? observedHopCount
: reportedHopCount;
final observedLabel = _formatObservedHops(
observedHopCount,
effectiveHopCount,
l10n,
);
final extraPaths = _otherPaths(primaryPath, message.pathVariants);
@@ -73,11 +94,8 @@ class ChannelMessagePathScreen extends StatelessWidget {
title: context.l10n.contacts_repeaterPathTrace,
path: primaryPath,
flipPathAround: true,
reversePathAround:
!(!channelMessage && !message.isOutgoing),
pathHashByteWidth: context
.read<MeshCoreConnector>()
.pathHashByteWidth,
reversePathAround: false,
pathHashByteWidth: hashByteWidth,
),
),
),
@@ -98,13 +116,20 @@ class ChannelMessagePathScreen extends StatelessWidget {
child: ListView(
padding: const EdgeInsets.symmetric(vertical: 8),
children: [
_buildSummaryCard(context, observedLabel: observedLabel),
_buildSummaryCard(
context,
observedLabel: observedLabel,
effectiveHopCount: effectiveHopCount,
),
const SizedBox(height: 16),
if (extraPaths.isNotEmpty) ...[
SectionHeader(
l10n.channelPath_otherObservedPaths,
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
),
_buildPathVariants(context, extraPaths),
const SizedBox(height: 8),
_buildPathVariants(context, extraPaths, hashByteWidth),
const SizedBox(height: 16),
],
SectionHeader(
l10n.channelPath_repeaterHops,
@@ -123,14 +148,18 @@ class ChannelMessagePathScreen extends StatelessWidget {
);
}
Widget _buildSummaryCard(BuildContext context, {String? observedLabel}) {
Widget _buildSummaryCard(
BuildContext context, {
String? observedLabel,
required int? effectiveHopCount,
}) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final routeChip = message.pathLength == null
final routeChip = effectiveHopCount == null
? null
: message.pathLength! < 0
: effectiveHopCount < 0
? const RouteChip(isDirect: false)
: RouteChip(isDirect: true, hops: message.pathLength);
: RouteChip(isDirect: true, hops: effectiveHopCount);
return MeshCard(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@@ -172,7 +201,7 @@ class ChannelMessagePathScreen extends StatelessWidget {
_buildDetailRow(
context,
l10n.channelPath_pathLabelTitle,
_formatPathLabel(message.pathLength, l10n),
_formatPathLabel(effectiveHopCount, l10n),
scheme: scheme,
),
if (observedLabel != null)
@@ -187,7 +216,11 @@ class ChannelMessagePathScreen extends StatelessWidget {
);
}
Widget _buildPathVariants(BuildContext context, List<Uint8List> variants) {
Widget _buildPathVariants(
BuildContext context,
List<Uint8List> variants,
int hashByteWidth,
) {
final l10n = context.l10n;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -210,7 +243,11 @@ class ChannelMessagePathScreen extends StatelessWidget {
Text(
l10n.channelPath_observedPathTitle(
i + 1,
_formatHopCount(variants[i].length, l10n),
_formatHopCount(
variants[i].length,
hashByteWidth,
l10n,
),
),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
@@ -218,7 +255,7 @@ class ChannelMessagePathScreen extends StatelessWidget {
),
const SizedBox(height: 2),
Text(
_formatPathPrefixes(variants[i]),
_formatPathPrefixes(variants[i], hashByteWidth),
style: MeshTheme.mono(
fontSize: 11,
color: Theme.of(context).colorScheme.onSurfaceVariant,
@@ -402,31 +439,31 @@ class ChannelMessagePathScreen extends StatelessWidget {
);
}
String _formatPathLabel(int? pathLength, AppLocalizations l10n) {
if (pathLength == null) return l10n.channelPath_unknownPath;
if (pathLength < 0) return l10n.channelPath_floodPath;
if (pathLength == 0) return l10n.channelPath_directPath;
return l10n.chat_hopsCount(pathLength);
String _formatPathLabel(int? hopCount, AppLocalizations l10n) {
if (hopCount == null) return l10n.channelPath_unknownPath;
if (hopCount < 0) return l10n.channelPath_floodPath;
if (hopCount == 0) return l10n.channelPath_directPath;
return l10n.chat_hopsCount(hopCount);
}
String? _formatObservedHops(
int observedCount,
int? pathLength,
int? targetHopCount,
AppLocalizations l10n,
) {
if (observedCount <= 0 && (pathLength == null || pathLength <= 0)) {
if (observedCount <= 0 && (targetHopCount == null || targetHopCount <= 0)) {
return null;
}
if (pathLength == null || pathLength < 0) {
if (targetHopCount == null || targetHopCount < 0) {
return observedCount > 0 ? l10n.chat_hopsCount(observedCount) : null;
}
if (observedCount == 0) {
return l10n.channelPath_observedZeroOf(pathLength);
return l10n.channelPath_observedZeroOf(targetHopCount);
}
if (observedCount == pathLength) {
if (observedCount == targetHopCount) {
return l10n.chat_hopsCount(observedCount);
}
return l10n.channelPath_observedSomeOf(observedCount, pathLength);
return l10n.channelPath_observedSomeOf(observedCount, targetHopCount);
}
Widget _buildDetailRow(
@@ -623,7 +660,10 @@ class _ChannelMessagePathMapScreenState
? kPrimaryPathColor
: kAlternatePathColors[(index - 1) % kAlternatePathColors.length],
isPrimary: isPrimary,
hopBytes: List<int>.from(orientedBytes),
hopBytes: [
for (final hop in hops)
if (hop.hopBytes != null) Uint8List.fromList(hop.hopBytes!),
],
points: points,
pointLabels: labels,
pointConfirmed: confirmed,
@@ -808,7 +848,11 @@ class _ChannelMessagePathMapScreenState
primaryPath,
);
final selectedPath = _orientPath(selectedPathTmp);
final width =
(widget.message.pathHashWidth ?? connector.pathHashByteWidth)
.clamp(1, 4)
.toInt();
final selectedPath = _orientPath(selectedPathTmp, width);
// Match on the unoriented bytes — observedPaths stores them as
// recorded, while selectedPath may be reversed for display.
@@ -817,19 +861,21 @@ class _ChannelMessagePathMapScreenState
selectedPath,
connector,
context.l10n,
width,
resolveFromEnd: !widget.message.isOutgoing,
);
// Renderable paths for the animation and combined view.
final entries = <_ObservedPathEntry>[];
for (var i = 0; i < observedPaths.length; i++) {
final oriented = _orientPath(observedPaths[i].pathBytes);
final oriented = _orientPath(observedPaths[i].pathBytes, width);
final pathHops = i == selectedIndex
? hops
: _buildPathHops(
oriented,
connector,
context.l10n,
width,
resolveFromEnd: !widget.message.isOutgoing,
);
final display = _buildDisplayPath(
@@ -908,7 +954,7 @@ class _ChannelMessagePathMapScreenState
? LatLngBounds.fromPoints(points)
: null;
final mapKey = ValueKey(
'${_formatPathPrefixes(selectedPath)},${context.l10n.pathTrace_you}',
'${_formatPathPrefixes(selectedPath, width)},${context.l10n.pathTrace_you}',
);
_pathDistance = _getPathDistance(points);
@@ -967,7 +1013,7 @@ class _ChannelMessagePathMapScreenState
},
),
children: [
ThemedMapTileLayer(tileCache: tileCache),
tileCache.buildTileLayer(context),
AnimatedBuilder(
animation: _playback,
builder: (context, _) {
@@ -1045,6 +1091,7 @@ class _ChannelMessagePathMapScreenState
context,
observedPaths,
selectedIndex,
width,
(index) {
setState(() {
_selectedPath = observedPaths[index].pathBytes;
@@ -1086,10 +1133,12 @@ class _ChannelMessagePathMapScreenState
BuildContext context,
List<_ObservedPath> paths,
int selectedIndex,
int hashByteWidth,
ValueChanged<int> onSelected, {
double topOffset = 16,
}) {
final l10n = context.l10n;
final width = hashByteWidth.clamp(1, 4).toInt();
final selectedPath = paths[selectedIndex];
final label = selectedPath.isPrimary
? l10n.channelPath_primaryPath(selectedIndex + 1)
@@ -1120,7 +1169,7 @@ class _ChannelMessagePathMapScreenState
value: i,
child: Text(
'${paths[i].isPrimary ? l10n.channelPath_primaryPath(i + 1) : l10n.channelPath_pathLabel(i + 1)}'
' • ${_formatHopCount(paths[i].pathBytes.length, l10n)}',
' • ${_formatHopCount(paths[i].pathBytes.length, width, l10n)}',
),
),
],
@@ -1134,7 +1183,7 @@ class _ChannelMessagePathMapScreenState
Text(
l10n.channelPath_selectedPathLabel(
label,
_formatPathPrefixes(selectedPath.pathBytes),
_formatPathPrefixes(selectedPath.pathBytes, width),
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
@@ -1378,11 +1427,11 @@ class _ChannelMessagePathMapScreenState
}
/// Orients recorded path bytes in the direction the packet traveled.
Uint8List _orientPath(Uint8List bytes) {
Uint8List _orientPath(Uint8List bytes, int hashByteWidth) {
final reverse =
(!widget.message.isOutgoing && !widget.channelMessage) ||
(widget.message.isOutgoing && widget.channelMessage);
return reverse ? Uint8List.fromList(bytes.reversed.toList()) : bytes;
return _orientPathBytes(bytes, hashByteWidth, reverse: reverse);
}
Marker _buildNodeLabelMarker({required LatLng point, required String label}) {
@@ -1738,6 +1787,7 @@ class _PathHop {
final Contact? contact;
final LatLng? position;
final AppLocalizations l10n;
final Uint8List? hopBytes;
const _PathHop({
required this.index,
@@ -1745,12 +1795,18 @@ class _PathHop {
required this.contact,
required this.position,
required this.l10n,
this.hopBytes,
});
bool get hasLocation => position != null;
String get displayLabel {
final prefixLabel = _formatPrefix(prefix);
final prefixLabel = hopBytes != null && hopBytes!.isNotEmpty
? hopBytes!
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join('')
.toUpperCase()
: _formatPrefix(prefix);
return '($prefixLabel) ${_resolveName(contact, l10n)}';
}
}
@@ -1765,10 +1821,12 @@ class _ObservedPath {
List<_PathHop> _buildPathHops(
Uint8List pathBytes,
MeshCoreConnector connector,
AppLocalizations l10n, {
AppLocalizations l10n,
int hashByteWidth, {
bool resolveFromEnd = false,
}) {
if (pathBytes.isEmpty) return const [];
final width = hashByteWidth.clamp(1, 4).toInt();
final endpoint =
(connector.selfLatitude != null && connector.selfLongitude != null)
? LatLng(connector.selfLatitude!, connector.selfLongitude!)
@@ -1778,19 +1836,23 @@ List<_PathHop> _buildPathHops(
contacts: connector.allContacts,
endpoint: endpoint,
resolveFromEnd: resolveFromEnd,
pathHashByteWidth: width,
);
final hopChunks = PathHelper.splitPathBytes(pathBytes, width);
final hops = <_PathHop>[];
for (var i = 0; i < pathBytes.length; i++) {
final contact = resolvedContacts[i];
for (var i = 0; i < hopChunks.length; i++) {
final hopBytes = hopChunks[i];
final contact = i < resolvedContacts.length ? resolvedContacts[i] : null;
final resolvedPosition = _resolvePosition(contact);
hops.add(
_PathHop(
index: i + 1,
prefix: pathBytes[i],
prefix: hopBytes.isNotEmpty ? hopBytes[0] : 0,
contact: contact,
position: resolvedPosition,
l10n: l10n,
hopBytes: hopBytes,
),
);
}
@@ -1810,14 +1872,35 @@ String _formatPrefix(int prefix) {
return prefix.toRadixString(16).padLeft(2, '0').toUpperCase();
}
String _formatPathPrefixes(Uint8List pathBytes) {
return pathBytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(',');
String _formatPathPrefixes(Uint8List pathBytes, int hashByteWidth) {
return PathHelper.splitPathBytes(
pathBytes,
hashByteWidth,
).map(PathHelper.formatHopHex).join(',');
}
String _formatHopCount(int count, AppLocalizations l10n) {
return l10n.chat_hopsCount(count);
Uint8List _orientPathBytes(
Uint8List pathBytes,
int hashByteWidth, {
required bool reverse,
}) {
if (!reverse || pathBytes.isEmpty) return pathBytes;
final hops = PathHelper.splitPathBytes(pathBytes, hashByteWidth);
return Uint8List.fromList([for (final hop in hops.reversed) ...hop]);
}
int _hopCountFromBytes(int byteCount, int hashByteWidth) {
if (byteCount <= 0) return 0;
final width = hashByteWidth.clamp(1, 4).toInt();
return (byteCount + width - 1) ~/ width;
}
String _formatHopCount(
int byteCount,
int hashByteWidth,
AppLocalizations l10n,
) {
return l10n.chat_hopsCount(_hopCountFromBytes(byteCount, hashByteWidth));
}
String _resolveName(Contact? contact, AppLocalizations l10n) {
+161 -132
View File
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/utils/keys.dart';
import 'package:meshcore_open/utils/platform_info.dart';
import 'package:meshcore_open/widgets/app_bar.dart';
import 'package:provider/provider.dart';
@@ -27,6 +27,7 @@ import '../widgets/qr_code_display.dart';
import '../widgets/quick_switch_bar.dart';
import '../widgets/sync_progress_overlay.dart';
import '../widgets/unread_badge.dart';
import '../helpers/gif_helper.dart';
import '../helpers/snack_bar_builder.dart';
import 'channel_chat_screen.dart';
import 'community_qr_scanner_screen.dart';
@@ -372,13 +373,30 @@ class _ChannelsScreenState extends State<ChannelsScreen>
_communityIndex,
);
final bool isCommunityChannel = Channel.isCommunityChannel(channelType);
final community = isCommunityChannel
? _communityIndex.getCommunityForChannel(channel)
: null;
// Only flood-routed channels carry a region; show it when one is set.
String subtitle = connector.hasChannelRegion(channel.index)
? context.l10n.channels_regionSetTo(
connector.getChannelRegion(channel.index),
)
: '';
switch (channelType) {
case ChannelType.communityPublic:
icon = Icons.groups;
iconColor = MeshPalette.magenta;
if (community != null) {
subtitle =
'${context.l10n.community_publicChannel} • ${community.name}';
}
case ChannelType.communityHashtag:
icon = Icons.groups;
iconColor = MeshPalette.magenta;
if (community != null) {
subtitle =
'${context.l10n.community_hashtagChannel} • ${community.name}';
}
case ChannelType.public:
icon = Icons.public;
iconColor = MeshPalette.signal;
@@ -393,7 +411,12 @@ class _ChannelsScreenState extends State<ChannelsScreen>
// Last message preview
final messages = connector.getChannelMessages(channel);
final lastMessage = messages.isNotEmpty ? messages.last : null;
final lastPreview = lastMessage?.text ?? '';
final lastMessageText = lastMessage?.text ?? '';
final lastPreview =
lastMessageText.isNotEmpty &&
GifHelper.parseGif(lastMessageText) != null
? context.l10n.chat_receivedGif
: lastMessageText;
final lastTime = lastMessage?.timestamp;
final channelLabel = channel.name.isEmpty
@@ -427,142 +450,156 @@ class _ChannelsScreenState extends State<ChannelsScreen>
channelMessageStore,
channel,
),
child: GestureDetector(
onSecondaryTapUp: PlatformInfo.isDesktop
? (_) => _showChannelActions(
this.context,
connector,
channelMessageStore,
channel,
)
: null,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Leading avatar with optional community badge
Stack(
clipBehavior: Clip.none,
children: [
AvatarCircle(
name: channelLabel,
size: 42,
color: iconColor,
icon: icon,
),
if (isCommunityChannel)
Positioned(
right: -2,
bottom: -2,
child: Container(
width: 16,
height: 16,
decoration: BoxDecoration(
color: MeshPalette.magenta,
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(
context,
).colorScheme.surfaceContainerLow,
width: 2,
),
),
child: const Icon(
Icons.people,
size: 8,
color: Colors.white,
),
),
),
],
),
const SizedBox(width: 12),
// Title + subtitle + ch chip
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
channelLabel,
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 6),
StatusChip(
label: 'CH ${channel.index}',
color: MeshPalette.blue,
fontSize: 10,
),
],
),
if (lastPreview.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
lastPreview,
style: MeshTheme.mono(
fontSize: 11.5,
color: scheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
onSecondaryTap: PlatformInfo.isDesktop
? () => _showChannelActions(
this.context,
connector,
channelMessageStore,
channel,
)
: null,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Leading avatar with optional community badge
Stack(
clipBehavior: Clip.none,
children: [
AvatarCircle(
name: channelLabel,
size: 42,
color: iconColor,
icon: icon,
),
),
const SizedBox(width: 8),
// Right side: time + unread badge + muted + drag handle
Column(
crossAxisAlignment: CrossAxisAlignment.end,
if (isCommunityChannel)
Positioned(
right: -2,
bottom: -2,
child: Container(
width: 16,
height: 16,
decoration: BoxDecoration(
color: MeshPalette.magenta,
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(
context,
).colorScheme.surfaceContainerLow,
width: 2,
),
),
child: const Icon(
Icons.people,
size: 8,
color: Colors.white,
),
),
),
],
),
const SizedBox(width: 12),
// Title + subtitle + ch chip
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (lastTime != null)
Text(
_relativeTime(lastTime),
style: MeshTheme.mono(
fontSize: 11,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (isMuted) ...[
Icon(
Icons.notifications_off,
size: 14,
color: scheme.onSurfaceVariant,
Expanded(
child: Text(
channelLabel,
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(width: 4),
],
if (unreadCount > 0) UnreadBadge(count: unreadCount),
),
const SizedBox(width: 6),
Text(
'CH ${channel.index}',
style: MeshTheme.mono(
fontSize: 11,
color: scheme.onSurfaceVariant.withValues(alpha: 0.7),
),
),
],
),
if (subtitle.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
subtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
if (lastPreview.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
lastPreview,
style: MeshTheme.mono(
fontSize: 11.5,
color: scheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
if (showDragHandle && dragIndex != null) ...[
const SizedBox(width: 4),
ReorderableDragStartListener(
index: dragIndex,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.drag_handle,
),
const SizedBox(width: 8),
// Right side: time + unread badge + muted + drag handle
Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
if (lastTime != null)
Text(
_relativeTime(lastTime),
style: MeshTheme.mono(
fontSize: 11,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isMuted) ...[
Icon(
Icons.notifications_off,
size: 14,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 4),
],
if (unreadCount > 0) UnreadBadge(count: unreadCount),
],
),
],
),
if (showDragHandle && dragIndex != null) ...[
const SizedBox(width: 4),
ReorderableDragStartListener(
index: dragIndex,
// Top-aligned with the "CH n" / time line. Bottom padding keeps
// a comfortable drag target without pushing the icon down.
child: Padding(
padding: const EdgeInsets.only(left: 8, right: 8, bottom: 16),
child: Icon(
Icons.drag_handle,
size: 18,
color: scheme.onSurfaceVariant,
),
),
),
],
),
],
),
),
);
@@ -910,11 +947,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
);
return;
}
final random = Random.secure();
final psk = Uint8List(16);
for (int i = 0; i < 16; i++) {
psk[i] = random.nextInt(256);
}
final psk = randomBytes(16);
Navigator.pop(sheetContext);
await connector.setChannel(
nextIndex,
@@ -1543,11 +1576,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
icon: const Icon(Icons.casino),
tooltip: sheetContext.l10n.channels_generateRandomPsk,
onPressed: () {
final random = Random.secure();
final bytes = Uint8List(16);
for (int i = 0; i < 16; i++) {
bytes[i] = random.nextInt(256);
}
final bytes = randomBytes(16);
pskController.text = Channel.formatPskHex(bytes);
},
),
+31 -6
View File
@@ -12,6 +12,7 @@ import '../utils/platform_info.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../widgets/message_status_icon.dart';
import '../widgets/empty_state.dart';
@@ -546,15 +547,15 @@ class _ChatScreenState extends State<ChatScreen> {
decoration: InputDecoration(
hintText: context.l10n.chat_typeMessage,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(MeshRadii.pill),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(color: scheme.outlineVariant),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(MeshRadii.pill),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(color: scheme.outlineVariant),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(MeshRadii.pill),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.primary,
width: 1.5,
@@ -776,17 +777,35 @@ class _ChatScreenState extends State<ChatScreen> {
}
String _currentPathLabel(Contact contact) {
final connector = context.read<MeshCoreConnector>();
// Check if user has set a path override
if (contact.pathOverride != null) {
if (contact.pathOverride! < 0) return context.l10n.chat_floodForced;
if (contact.pathOverride == 0) return context.l10n.chat_directForced;
return context.l10n.chat_hopsForced(contact.pathOverride!);
final bytes = contact.pathOverrideBytes ?? Uint8List(0);
final hopCount = _displayHopCount(
bytes,
contact.pathOverride!,
connector.pathHashByteWidth,
);
return context.l10n.chat_hopsForced(hopCount);
}
// Use device's path
if (contact.pathLength < 0) return context.l10n.chat_floodAuto;
if (contact.pathLength == 0) return context.l10n.chat_direct;
return context.l10n.chat_hopsCount(contact.pathLength);
final hopCount = _displayHopCount(
contact.path,
contact.pathLength,
connector.pathHashByteWidth,
);
return context.l10n.chat_hopsCount(hopCount);
}
int _displayHopCount(List<int> pathBytes, int storedHopCount, int hashWidth) {
if (pathBytes.isEmpty) return storedHopCount;
return PathHelper.splitPathBytes(pathBytes, hashWidth).length;
}
void _showContactInfo(BuildContext context) {
@@ -807,7 +826,10 @@ class _ChatScreenState extends State<ChatScreen> {
),
_buildInfoRow(
context.l10n.chat_path,
contact.pathLabel(context.l10n),
contact.pathLabel(
context.l10n,
pathHashByteWidth: connector.pathHashByteWidth,
),
),
_buildInfoRow(
context.l10n.contact_lastSeen,
@@ -1435,6 +1457,9 @@ class _MessageBubble extends StatelessWidget {
color: textColor.withValues(alpha: 0.72),
fontSize: bodyFontSize * textScale,
),
onSecondaryTap: PlatformInfo.isDesktop
? onLongPress
: null,
),
),
],
+26 -4
View File
@@ -915,6 +915,7 @@ class _ContactsScreenState extends State<ContactsScreen>
return _ContactTileEntrance(
index: index,
contact: contact,
pathHashByteWidth: connector.pathHashByteWidth,
lastSeen: _resolveLastSeen(contact),
unreadCount: unreadCount,
isFavorite: contact.isFavorite,
@@ -1371,7 +1372,10 @@ class _ContactsScreenState extends State<ContactsScreen>
MaterialPageRoute(
builder: (context) => PathTraceMapScreen(
title: context.l10n.contacts_repeaterPing,
path: Uint8List.fromList([contact.publicKey.first]),
path: contact.pathBytesForDisplay.isNotEmpty
? contact.pathBytesForDisplay
: _contactPathPrefix(contact, hw),
flipPathAround: true,
targetContact: contact,
pathHashByteWidth: hw,
),
@@ -1405,8 +1409,8 @@ class _ContactsScreenState extends State<ContactsScreen>
: context.l10n.contacts_roomPing,
path: contact.pathBytesForDisplay.isNotEmpty
? contact.pathBytesForDisplay
: Uint8List.fromList([contact.publicKey.first]),
flipPathAround: contact.pathBytesForDisplay.isNotEmpty,
: _contactPathPrefix(contact, hw),
flipPathAround: true,
targetContact: contact,
pathHashByteWidth: hw,
),
@@ -1516,6 +1520,16 @@ class _ContactsScreenState extends State<ContactsScreen>
);
}
Uint8List _contactPathPrefix(Contact contact, int hashByteWidth) {
if (contact.publicKey.isEmpty) return Uint8List(0);
final width = hashByteWidth
.clamp(1, pubKeySize)
.toInt()
.clamp(1, contact.publicKey.length)
.toInt();
return Uint8List.fromList(contact.publicKey.sublist(0, width));
}
void _confirmDelete(
BuildContext context,
MeshCoreConnector connector,
@@ -1549,6 +1563,7 @@ class _ContactsScreenState extends State<ContactsScreen>
class _ContactTile extends StatelessWidget {
final Contact contact;
final int pathHashByteWidth;
final DateTime lastSeen;
final int unreadCount;
final bool isFavorite;
@@ -1557,6 +1572,7 @@ class _ContactTile extends StatelessWidget {
const _ContactTile({
required this.contact,
required this.pathHashByteWidth,
required this.lastSeen,
required this.unreadCount,
required this.isFavorite,
@@ -1676,7 +1692,10 @@ class _ContactTile extends StatelessWidget {
children: [
Expanded(
child: Text(
contact.pathLabel(context.l10n),
contact.pathLabel(
context.l10n,
pathHashByteWidth: pathHashByteWidth,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
@@ -1763,6 +1782,7 @@ class _ContactTile extends StatelessWidget {
class _ContactTileEntrance extends StatelessWidget {
final int index;
final Contact contact;
final int pathHashByteWidth;
final DateTime lastSeen;
final int unreadCount;
final bool isFavorite;
@@ -1772,6 +1792,7 @@ class _ContactTileEntrance extends StatelessWidget {
const _ContactTileEntrance({
required this.index,
required this.contact,
required this.pathHashByteWidth,
required this.lastSeen,
required this.unreadCount,
required this.isFavorite,
@@ -1785,6 +1806,7 @@ class _ContactTileEntrance extends StatelessWidget {
index: index,
child: _ContactTile(
contact: contact,
pathHashByteWidth: pathHashByteWidth,
lastSeen: lastSeen,
unreadCount: unreadCount,
isFavorite: isFavorite,
+3 -7
View File
@@ -184,13 +184,6 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
connector,
index,
);
if (PlatformInfo.isDesktop) {
return GestureDetector(
onSecondaryTapUp: (_) =>
_showContactContextMenu(contact, connector),
child: tile,
);
}
return tile;
},
),
@@ -241,6 +234,9 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
}
},
onLongPress: () => _showContactContextMenu(contact, connector),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showContactContextMenu(contact, connector)
: null,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
child: Row(
children: [
+4 -4
View File
@@ -20,7 +20,6 @@ import '../widgets/app_bar.dart';
import '../widgets/quick_switch_bar.dart';
import '../icons/los_icon.dart';
import '../theme/mesh_theme.dart';
import '../widgets/themed_map_tile_layer.dart';
class LineOfSightEndpoint {
final String label;
@@ -357,7 +356,7 @@ class _LineOfSightMapScreenState extends State<LineOfSightMapScreen> {
Widget build(BuildContext context) {
final settings = context.watch<AppSettingsService>().settings;
final isImperial = settings.unitSystem == UnitSystem.imperial;
final tileCache = context.read<MapTileCacheService>();
final tileCache = context.watch<MapTileCacheService>();
final endpoints = _visibleEndpoints();
final mapPoints = [
if (_start != null) _start!.point,
@@ -430,6 +429,7 @@ class _LineOfSightMapScreenState extends State<LineOfSightMapScreen> {
minZoom: _mapMinZoom,
maxZoom: _mapMaxZoom,
onLongPress: (_, point) => _addCustomPoint(point),
onSecondaryTap: (_, point) => _addCustomPoint(point),
onPositionChanged: (camera, hasGesture) {
final shouldShow = camera.zoom >= _labelZoomThreshold;
if (!_didReceivePositionUpdate ||
@@ -442,8 +442,8 @@ class _LineOfSightMapScreenState extends State<LineOfSightMapScreen> {
},
),
children: [
ThemedMapTileLayer(
tileCache: tileCache,
tileCache.buildTileLayer(
context,
opacity: _showTerrainLayer ? 1 : 0.72,
),
if (_result != null && _result!.segments.isNotEmpty)
+130 -6
View File
@@ -12,7 +12,6 @@ import '../widgets/adaptive_app_bar_title.dart';
import '../helpers/snack_bar_builder.dart';
import '../theme/mesh_theme.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/themed_map_tile_layer.dart';
class MapCacheScreen extends StatefulWidget {
const MapCacheScreen({super.key});
@@ -34,6 +33,11 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
bool _isDownloading = false;
int _completedTiles = 0;
int _failedTiles = 0;
List<CachedTileInfo> _cachedTiles = const [];
int _cachedTileBytes = 0;
bool _isLoadingCachedTiles = false;
double _overlayZoom = 2.0;
LatLngBounds? _visibleBounds;
@override
void initState() {
@@ -123,8 +127,10 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
_minZoom = safeMin;
_maxZoom = safeMax;
_selectedBounds = bounds;
_visibleBounds = bounds;
});
_updateEstimate();
_refreshCachedTiles();
if (bounds != null) {
_mapController.fitCamera(
CameraFit.bounds(bounds: bounds, padding: const EdgeInsets.all(48)),
@@ -181,6 +187,7 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
Future<void> _startDownload() async {
final bounds = _selectedBounds;
final cacheService = context.read<MapTileCacheService>();
if (bounds == null) {
showDismissibleSnackBar(
context,
@@ -197,6 +204,18 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
return;
}
if (!cacheService.source.allowsBulkDownload) {
showDismissibleSnackBar(
context,
content: Text(
context.l10n.mapCache_bulkDownloadDisabledInConfig(
cacheService.source.label,
),
),
);
return;
}
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
@@ -219,8 +238,6 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
if (confirmed != true || !mounted) return;
final cacheService = context.read<MapTileCacheService>();
setState(() {
_isDownloading = true;
_completedTiles = 0;
@@ -254,6 +271,8 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
result.failed,
)
: context.l10n.mapCache_cachedTiles(result.downloaded);
await _refreshCachedTiles();
if (!mounted) return;
showDismissibleSnackBar(context, content: Text(message));
}
@@ -280,16 +299,61 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
final cacheService = context.read<MapTileCacheService>();
await cacheService.clearCache();
if (!mounted) return;
await _refreshCachedTiles();
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.mapCache_offlineCacheCleared),
);
}
Future<void> _refreshCachedTiles() async {
if (!mounted) return;
setState(() {
_isLoadingCachedTiles = true;
});
final cacheService = context.read<MapTileCacheService>();
final inventory = await cacheService.getCachedTileInventory();
if (!mounted) return;
setState(() {
_cachedTiles = inventory.tiles;
_cachedTileBytes = inventory.totalBytes;
_isLoadingCachedTiles = false;
});
}
String _formatBytes(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) {
return '${(bytes / 1024).toStringAsFixed(1)} KB';
}
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
@override
Widget build(BuildContext context) {
final tileCache = context.read<MapTileCacheService>();
final tileCache = context.watch<MapTileCacheService>();
final source = tileCache.source;
final selectedBounds = _selectedBounds;
final activeCachedTiles = tileCache.filterTilesForActiveSource(
_cachedTiles,
);
final cachedInSelection = tileCache.countTilesForBounds(
activeCachedTiles,
bounds: selectedBounds,
minZoom: _minZoom,
maxZoom: _maxZoom,
);
final overlayPolygons = tileCache.buildCachedTilePolygons(
activeCachedTiles,
zoom: _overlayZoom.round().clamp(0, 19).toInt(),
visibleBounds: _visibleBounds,
);
final cacheSummary =
'${context.l10n.mapCache_summarySource(source.label)}\n'
'${context.l10n.mapCache_summaryCachedTilesForSource(activeCachedTiles.length)}\n'
'${context.l10n.mapCache_summaryCachedInSelection(cachedInSelection)}\n'
'${context.l10n.mapCache_summaryApproxCacheSize(_formatBytes(_cachedTileBytes))}';
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final isDesktop = _isDesktopPlatform(defaultTargetPlatform);
@@ -327,9 +391,23 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
)
: const KeyboardOptions.disabled(),
),
onPositionChanged: (camera, hasGesture) {
final nextZoom = camera.zoom;
final nextBounds = camera.visibleBounds;
if (_overlayZoom != nextZoom ||
_visibleBounds?.north != nextBounds.north ||
_visibleBounds?.south != nextBounds.south ||
_visibleBounds?.east != nextBounds.east ||
_visibleBounds?.west != nextBounds.west) {
setState(() {
_overlayZoom = nextZoom;
_visibleBounds = nextBounds;
});
}
},
),
children: [
ThemedMapTileLayer(tileCache: tileCache),
tileCache.buildTileLayer(context),
if (selectedBounds != null)
PolygonLayer(
polygons: [
@@ -341,9 +419,24 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
),
],
),
if (overlayPolygons.isNotEmpty)
PolygonLayer(polygons: overlayPolygons),
],
),
if (isDesktop) _buildDesktopMapControls(),
Positioned(
top: 12,
left: isDesktop ? 84 : 12,
child: Card(
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(
'Z: ${_overlayZoom.round()}:',
style: const TextStyle(fontSize: 12),
),
),
),
),
Positioned(
top: 12,
right: 12,
@@ -445,6 +538,34 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 12),
TextFormField(
key: ValueKey(
'$cacheSummary|${activeCachedTiles.length}|$cachedInSelection|$_cachedTileBytes',
),
initialValue: cacheSummary,
readOnly: true,
minLines: 4,
maxLines: 4,
decoration: InputDecoration(
labelText: _isLoadingCachedTiles
? l10n.mapCache_cachedTilesLabel
: l10n.mapCache_cachedTileSummaryLabel,
border: const OutlineInputBorder(),
),
),
if (!source.allowsBulkDownload) ...[
const SizedBox(height: 8),
Text(
l10n.mapCache_bulkDownloadDisabledForSource(
source.label,
),
style: MeshTheme.mono(
fontSize: 12,
color: MeshPalette.alert,
),
),
],
if (_isDownloading) ...[
const SizedBox(height: 8),
LinearProgressIndicator(
@@ -471,7 +592,10 @@ class _MapCacheScreenState extends State<MapCacheScreen> {
child: ElevatedButton.icon(
icon: const Icon(Icons.download),
label: Text(l10n.mapCache_downloadTilesButton),
onPressed: _isDownloading || selectedBounds == null
onPressed:
_isDownloading ||
selectedBounds == null ||
!source.allowsBulkDownload
? null
: _startDownload,
),
+264 -152
View File
@@ -5,13 +5,14 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:meshcore_open/helpers/path_helper.dart';
import 'package:meshcore_open/screens/path_trace_map.dart';
import 'package:meshcore_open/widgets/app_bar.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/l10n.dart';
import '../models/app_settings.dart';
import '../models/channel.dart';
import '../models/contact.dart';
@@ -25,7 +26,6 @@ import '../utils/battery_utils.dart';
import '../utils/route_transitions.dart';
import '../widgets/quick_switch_bar.dart';
import '../widgets/sync_progress_overlay.dart';
import '../widgets/themed_map_tile_layer.dart';
import '../icons/los_icon.dart';
import 'channels_screen.dart';
import 'chat_screen.dart';
@@ -79,6 +79,7 @@ class _MapScreenState extends State<MapScreen> {
bool _hasInitializedMap = false;
bool _removedMarkersLoaded = false;
final List<int> _pathTrace = [];
final List<int> _pathTraceHopWidths = [];
final List<Contact> _pathTraceContacts = [];
final List<LatLng> _points = [];
final List<Polyline> _polylines = [];
@@ -107,6 +108,31 @@ class _MapScreenState extends State<MapScreen> {
super.dispose();
}
ColorScheme get _overlayScheme => Theme.of(context).colorScheme;
bool get _useDarkOverlay => Theme.of(context).brightness == Brightness.dark;
Color get _overlayPanelColor => _useDarkOverlay
? MapPalette.panelDark
: _overlayScheme.surfaceContainerLow.withValues(alpha: 0.96);
Color get _overlayPrimaryTextColor =>
_useDarkOverlay ? MapPalette.textPrimary : _overlayScheme.onSurface;
Color get _overlaySecondaryTextColor => _useDarkOverlay
? MapPalette.textSecondary
: _overlayScheme.onSurfaceVariant;
Color get _overlayMutedTextColor =>
_useDarkOverlay ? MapPalette.textMuted : _overlayScheme.onSurfaceVariant;
Color get _overlayBorderColor =>
_useDarkOverlay ? MapPalette.border : _overlayScheme.outlineVariant;
Color get _overlayShadowColor => _useDarkOverlay
? MapPalette.markerShadow
: Colors.black.withValues(alpha: 0.18);
_NodeAge _ageOf(Contact contact) {
final d = DateTime.now().difference(contact.lastSeen);
if (d.inMinutes <= 60) return _NodeAge.online;
@@ -233,12 +259,12 @@ class _MapScreenState extends State<MapScreen> {
bottom: 96,
child: DecoratedBox(
decoration: BoxDecoration(
color: MapPalette.panelDark,
color: _overlayPanelColor,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MapPalette.border),
boxShadow: const [
border: Border.all(color: _overlayBorderColor),
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 8,
offset: Offset(0, 3),
),
@@ -250,20 +276,20 @@ class _MapScreenState extends State<MapScreen> {
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.add),
visualDensity: VisualDensity.standard,
tooltip: context.l10n.map_zoomIn,
onPressed: () => _zoomMapBy(1),
),
IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.remove),
tooltip: context.l10n.map_zoomOut,
onPressed: () => _zoomMapBy(-1),
),
IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.crop_free),
tooltip: context.l10n.map_centerMap,
onPressed: () => _mapController.move(center, zoom),
@@ -285,6 +311,31 @@ class _MapScreenState extends State<MapScreen> {
);
}
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(
@@ -303,6 +354,7 @@ class _MapScreenState extends State<MapScreen> {
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;
@@ -376,17 +428,20 @@ class _MapScreenState extends State<MapScreen> {
// Compute guessed locations with caching
final maxRangeKm = _estimateLoRaRangeKm(connector);
final pathHashByteWidth = connector.pathHashByteWidth
.clamp(1, 4)
.toInt();
final filteredKeys = guessCandidates
.map((c) => '${c.publicKeyHex}:${c.path.join("-")}')
.join(',');
final anchorKeys = allContactsWithLocation
.map(
(c) =>
'${c.publicKeyHex}:${c.latitude}:${c.longitude}:${c.path.isNotEmpty ? c.path.last : ""}',
'${c.publicKeyHex}:${c.latitude}:${c.longitude}:${PathHelper.formatHopHex(c.path.isNotEmpty ? c.path.sublist(max(0, c.path.length - pathHashByteWidth)) : const [])}',
)
.join(',');
final cacheKey =
'$filteredKeys|$anchorKeys|$pathHistoryVersion:${connector.currentFreqHz}:${connector.currentSf}:${connector.currentBwHz}:${connector.currentTxPower}:${settings.mapShowGuessedLocations}';
'$filteredKeys|$anchorKeys|$pathHistoryVersion:$pathHashByteWidth:${connector.currentFreqHz}:${connector.currentSf}:${connector.currentBwHz}:${connector.currentTxPower}:${settings.mapShowGuessedLocations}';
if (cacheKey != _guessedLocationsCacheKey) {
_guessedLocationsCacheKey = cacheKey;
_cachedGuessedLocations = settings.mapShowGuessedLocations
@@ -395,6 +450,7 @@ class _MapScreenState extends State<MapScreen> {
allContactsWithLocation,
pathHistory,
maxRangeKm,
pathHashByteWidth,
)
: [];
}
@@ -554,8 +610,8 @@ class _MapScreenState extends State<MapScreen> {
canPop: allowBack,
child: Scaffold(
appBar: AppBar(
backgroundColor: MapPalette.panelDark,
foregroundColor: MapPalette.textPrimary,
backgroundColor: scheme.surface,
foregroundColor: scheme.onSurface,
title: AppBarTitle(context.l10n.map_title),
centerTitle: true,
automaticallyImplyLeading: false,
@@ -708,24 +764,10 @@ class _MapScreenState extends State<MapScreen> {
}
},
onLongPress: (_, 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,
);
_handleMapContextPress(context, connector, latLng);
},
onSecondaryTap: (_, latLng) {
_handleMapContextPress(context, connector, latLng);
},
onPositionChanged: (camera, hasGesture) {
// Track zoom in half-step buckets so cluster/marker
@@ -742,7 +784,7 @@ class _MapScreenState extends State<MapScreen> {
},
),
children: [
ThemedMapTileLayer(tileCache: tileCache),
tileCache.buildTileLayer(context),
if (_polylines.isNotEmpty && _isBuildingPathTrace)
PolylineLayer(polylines: _polylines),
if (sharedMarkerPolylines.isNotEmpty)
@@ -895,7 +937,7 @@ class _MapScreenState extends State<MapScreen> {
_handleQuickSwitch(index, context),
contactsUnreadCount: connector.getTotalContactsUnreadCount(),
channelsUnreadCount: connector.getTotalChannelsUnreadCount(),
highContrast: true,
highContrast: _useDarkOverlay,
),
),
floatingActionButton:
@@ -970,23 +1012,19 @@ class _MapScreenState extends State<MapScreen> {
List<Contact> withLocation,
PathHistoryService pathHistory,
double? maxRangeKm,
int pathHashByteWidth,
) {
// Index known-location repeaters by their 1-byte hash.
// null value = two repeaters share the same hash byte (ambiguous collision).
final repeaterByHash = <int, Contact?>{};
for (final c in withLocation) {
if (c.type == advTypeRepeater) {
if (repeaterByHash.containsKey(c.publicKey[0])) {
repeaterByHash[c.publicKey[0]] =
null; // collision: can't disambiguate
} else {
repeaterByHash[c.publicKey[0]] = c;
}
}
}
final result = <_GuessedLocation>[];
final hopWidth = pathHashByteWidth.clamp(1, 4).toInt();
final anchorsByPrefix = <String, List<Contact>>{};
for (final repeater in withLocation) {
if (repeater.type != advTypeRepeater) continue;
if (repeater.publicKey.length < hopWidth) continue;
final prefix = PathHelper.formatHopHex(
repeater.publicKey.sublist(0, hopWidth),
);
anchorsByPrefix.putIfAbsent(prefix, () => []).add(repeater);
}
for (final contact in allContacts) {
if (contact.hasLocation) continue;
@@ -1000,21 +1038,23 @@ class _MapScreenState extends State<MapScreen> {
// Collect the contact-side (last-hop) repeater from every known path.
// path = [device-side hop, ..., contact-side hop]
// Only path.last is actually within radio range of the contact — using
// earlier bytes would anchor against our own side of the network.
// Only the last hop chunk is actually within radio range of the contact.
final pathSets = <List<int>>[
contact.path.toList(),
...pathHistory
.getRecentPaths(contact.publicKeyHex)
.map((r) => r.pathBytes),
];
final lastHopBytes = <int>{};
for (final pathBytes in pathSets) {
if (pathBytes.isEmpty) continue;
final lastHop = pathBytes.last;
lastHopBytes.add(lastHop);
final r = repeaterByHash[lastHop];
if (r != null) anchorSet.add(LatLng(r.latitude!, r.longitude!));
final lastHop = pathBytes.sublist(max(0, pathBytes.length - hopWidth));
if (lastHop.isEmpty) continue;
final repeaters = anchorsByPrefix[PathHelper.formatHopHex(lastHop)];
if (repeaters != null && repeaters.isNotEmpty) {
final repeater = repeaters.first;
anchorSet.add(LatLng(repeater.latitude!, repeater.longitude!));
}
}
// Filter anchors that are geometrically inconsistent with radio range.
@@ -1181,9 +1221,12 @@ class _MapScreenState extends State<MapScreen> {
width: 48,
height: 48,
child: GestureDetector(
onLongPress: () => _isBuildingPathTrace
? _showNodeInfo(context, guess.contact)
: null,
onLongPress: () {
if (_isBuildingPathTrace) _showNodeInfo(context, guess.contact);
},
onSecondaryTap: () {
if (_isBuildingPathTrace) _showNodeInfo(context, guess.contact);
},
onTap: () => _isBuildingPathTrace
? _addToPath(context, guess.contact, position: guess.position)
: _selectNode(guess.contact, guessedPosition: guess.position),
@@ -1193,14 +1236,14 @@ class _MapScreenState extends State<MapScreen> {
height: 36,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: MapPalette.panelDark,
color: _overlayPanelColor,
border: Border.all(
color: guess.highConfidence ? color : MapPalette.textMuted,
color: guess.highConfidence ? color : _overlayMutedTextColor,
width: guess.highConfidence ? 2.5 : 2,
),
boxShadow: const [
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 7,
offset: Offset(0, 2),
),
@@ -1209,7 +1252,7 @@ class _MapScreenState extends State<MapScreen> {
alignment: Alignment.center,
child: Icon(
Icons.not_listed_location,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
size: 19,
),
),
@@ -1286,12 +1329,20 @@ class _MapScreenState extends State<MapScreen> {
// 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 = <int>{};
final overlapPrefixes = <String>{};
if (overlapsMode) {
final counts = <int, int>{};
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) {
final prefix = contact.publicKey.first;
if ((contact.type == advTypeRepeater || contact.type == advTypeRoom) &&
contact.publicKey.length >= hopWidth) {
final prefix = PathHelper.formatHopHex(
contact.publicKey.sublist(0, hopWidth),
);
counts[prefix] = (counts[prefix] ?? 0) + 1;
}
}
@@ -1299,10 +1350,20 @@ class _MapScreenState extends State<MapScreen> {
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) &&
overlapPrefixes.contains(contact.publicKey.first);
contact.publicKey.length >= overlapHopWidth &&
overlapPrefixes.contains(
PathHelper.formatHopHex(
contact.publicKey.sublist(0, overlapHopWidth),
),
);
void addNode(Contact contact, {bool dot = false}) {
final overlap = isOverlap(contact);
@@ -1383,8 +1444,12 @@ class _MapScreenState extends State<MapScreen> {
height: size,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onLongPress: () =>
_isBuildingPathTrace ? _showNodeInfo(context, contact) : null,
onLongPress: () {
if (_isBuildingPathTrace) _showNodeInfo(context, contact);
},
onSecondaryTap: () {
if (_isBuildingPathTrace) _showNodeInfo(context, contact);
},
onTap: () => _isBuildingPathTrace
? _addToPath(context, contact)
: _selectNode(contact),
@@ -1523,12 +1588,12 @@ class _MapScreenState extends State<MapScreen> {
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: MapPalette.panelDark,
color: _overlayPanelColor,
borderRadius: BorderRadius.circular(MeshRadii.xs),
border: Border.all(color: MapPalette.border),
boxShadow: const [
border: Border.all(color: _overlayBorderColor),
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 4,
offset: Offset(0, 1),
),
@@ -1542,7 +1607,7 @@ class _MapScreenState extends State<MapScreen> {
style: MeshTheme.mono(
fontSize: 10,
fontWeight: FontWeight.w700,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
),
),
@@ -1663,7 +1728,7 @@ class _MapScreenState extends State<MapScreen> {
decoration: BoxDecoration(
shape: BoxShape.circle,
color: statusColor,
border: Border.all(color: MapPalette.panelDark, width: 2),
border: Border.all(color: _overlayPanelColor, width: 2),
),
alignment: Alignment.center,
child: batteryLow
@@ -1686,10 +1751,10 @@ class _MapScreenState extends State<MapScreen> {
Expanded(
child: Text(
label,
style: const TextStyle(
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: MapPalette.textSecondary,
color: _overlaySecondaryTextColor,
),
overflow: TextOverflow.ellipsis,
),
@@ -1747,9 +1812,9 @@ class _MapScreenState extends State<MapScreen> {
children: [
Expanded(
child: Material(
color: MapPalette.panelDark,
color: _overlayPanelColor,
shape: StadiumBorder(
side: const BorderSide(color: MapPalette.border),
side: BorderSide(color: _overlayBorderColor),
),
clipBehavior: Clip.antiAlias,
child: TextField(
@@ -1757,17 +1822,15 @@ class _MapScreenState extends State<MapScreen> {
focusNode: _searchFocus,
decoration: InputDecoration(
hintText: context.l10n.map_searchHint,
hintStyle: const TextStyle(
color: MapPalette.textSecondary,
),
prefixIcon: const Icon(
hintStyle: TextStyle(color: _overlaySecondaryTextColor),
prefixIcon: Icon(
Icons.search,
size: 20,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
suffixIcon: hasQuery
? IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.close, size: 18),
onPressed: () {
setState(() {
@@ -1787,9 +1850,9 @@ class _MapScreenState extends State<MapScreen> {
vertical: 12,
),
),
style: const TextStyle(
style: TextStyle(
fontSize: 14,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
fontWeight: FontWeight.w600,
),
cursorColor: MapPalette.selected,
@@ -1801,9 +1864,9 @@ class _MapScreenState extends State<MapScreen> {
),
const SizedBox(width: 8),
Material(
color: MapPalette.panelDark,
color: _overlayPanelColor,
shape: StadiumBorder(
side: const BorderSide(color: MapPalette.border),
side: BorderSide(color: _overlayBorderColor),
),
clipBehavior: Clip.antiAlias,
child: InkWell(
@@ -1827,17 +1890,17 @@ class _MapScreenState extends State<MapScreen> {
style: MeshTheme.mono(
fontSize: 13,
fontWeight: FontWeight.w700,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
),
const SizedBox(width: 2),
AnimatedRotation(
turns: _statsExpanded ? 0.5 : 0,
duration: const Duration(milliseconds: 200),
child: const Icon(
child: Icon(
Icons.expand_more,
size: 16,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
),
],
@@ -1936,12 +1999,12 @@ class _MapScreenState extends State<MapScreen> {
color: selected
? Color.alphaBlend(
accent.withValues(alpha: 0.34),
MapPalette.panelDark,
_overlayPanelColor,
)
: MapPalette.panelDark,
: _overlayPanelColor,
shape: StadiumBorder(
side: BorderSide(
color: selected ? accent : MapPalette.border,
color: selected ? accent : _overlayBorderColor,
width: selected ? 1.5 : 1,
),
),
@@ -1957,11 +2020,7 @@ class _MapScreenState extends State<MapScreen> {
mainAxisSize: MainAxisSize.min,
children: [
if (selected) ...[
const Icon(
Icons.check,
size: 13,
color: MapPalette.textPrimary,
),
Icon(Icons.check, size: 13, color: _overlayPrimaryTextColor),
const SizedBox(width: 4),
],
Text(
@@ -1970,8 +2029,8 @@ class _MapScreenState extends State<MapScreen> {
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: selected
? MapPalette.textPrimary
: MapPalette.textSecondary,
? _overlayPrimaryTextColor
: _overlaySecondaryTextColor,
),
),
],
@@ -2001,14 +2060,14 @@ class _MapScreenState extends State<MapScreen> {
margin: const EdgeInsets.only(top: 6),
constraints: const BoxConstraints(maxHeight: 300),
decoration: BoxDecoration(
color: MapPalette.panelDark,
color: _overlayPanelColor,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MapPalette.border),
boxShadow: const [
border: Border.all(color: _overlayBorderColor),
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 10,
offset: Offset(0, 4),
offset: const Offset(0, 4),
),
],
),
@@ -2017,8 +2076,8 @@ class _MapScreenState extends State<MapScreen> {
padding: const EdgeInsets.all(16),
child: Text(
context.l10n.map_noResults,
style: const TextStyle(
color: MapPalette.textSecondary,
style: TextStyle(
color: _overlaySecondaryTextColor,
fontSize: 13,
),
),
@@ -2028,7 +2087,7 @@ class _MapScreenState extends State<MapScreen> {
padding: const EdgeInsets.symmetric(vertical: 4),
itemCount: results.length,
separatorBuilder: (_, _) =>
const Divider(height: 1, color: MapPalette.border),
Divider(height: 1, color: _overlayBorderColor),
itemBuilder: (context, index) {
final c = results[index];
final color = _getNodeColor(c.type);
@@ -2049,10 +2108,10 @@ class _MapScreenState extends State<MapScreen> {
children: [
Text(
c.name,
style: const TextStyle(
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w600,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
overflow: TextOverflow.ellipsis,
),
@@ -2060,7 +2119,7 @@ class _MapScreenState extends State<MapScreen> {
c.publicKeyHex.substring(0, 12),
style: MeshTheme.mono(
fontSize: 10.5,
color: MapPalette.textSecondary,
color: _overlaySecondaryTextColor,
),
),
],
@@ -2070,13 +2129,13 @@ class _MapScreenState extends State<MapScreen> {
Icon(
Icons.chevron_right,
size: 18,
color: MapPalette.textSecondary,
color: _overlaySecondaryTextColor,
)
else
Text(
context.l10n.map_noGps.toUpperCase(),
style: MeshTheme.accentLabel(
color: MapPalette.textMuted,
color: _overlayMutedTextColor,
fontSize: 8.5,
),
),
@@ -2136,14 +2195,14 @@ class _MapScreenState extends State<MapScreen> {
width: 230,
padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
decoration: BoxDecoration(
color: MapPalette.panelDark,
color: _overlayPanelColor,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MapPalette.border),
boxShadow: const [
border: Border.all(color: _overlayBorderColor),
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 10,
offset: Offset(0, 4),
offset: const Offset(0, 4),
),
],
),
@@ -2160,7 +2219,7 @@ class _MapScreenState extends State<MapScreen> {
),
_statRow(context.l10n.map_hidden, hiddenCount, MapPalette.offline),
_statRow(context.l10n.map_markers, pinCount, MapPalette.shared),
const Divider(height: 16, color: MapPalette.border),
Divider(height: 16, color: _overlayBorderColor),
_buildLegendItem(
Icons.person,
context.l10n.map_chat,
@@ -2190,7 +2249,7 @@ class _MapScreenState extends State<MapScreen> {
_buildLegendItem(
Icons.not_listed_location,
context.l10n.map_guessedLocation,
MapPalette.textMuted,
_overlayMutedTextColor,
),
],
),
@@ -2211,7 +2270,10 @@ class _MapScreenState extends State<MapScreen> {
Expanded(
child: Text(
label,
style: TextStyle(fontSize: 12.5, color: MapPalette.textSecondary),
style: TextStyle(
fontSize: 12.5,
color: _overlaySecondaryTextColor,
),
overflow: TextOverflow.ellipsis,
),
),
@@ -2220,7 +2282,7 @@ class _MapScreenState extends State<MapScreen> {
style: MeshTheme.mono(
fontSize: 13,
fontWeight: FontWeight.w700,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
),
],
@@ -2253,8 +2315,8 @@ class _MapScreenState extends State<MapScreen> {
child: MeshCard(
margin: EdgeInsets.zero,
padding: const EdgeInsets.fromLTRB(14, 12, 8, 12),
color: MapPalette.panelDark,
borderColor: MapPalette.border,
color: _overlayPanelColor,
borderColor: _overlayBorderColor,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -2277,10 +2339,10 @@ class _MapScreenState extends State<MapScreen> {
Flexible(
child: Text(
contact.name,
style: const TextStyle(
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
),
overflow: TextOverflow.ellipsis,
),
@@ -2308,9 +2370,9 @@ class _MapScreenState extends State<MapScreen> {
Flexible(
child: Text(
contact.typeLabel(context.l10n),
style: const TextStyle(
style: TextStyle(
fontSize: 11.5,
color: MapPalette.textSecondary,
color: _overlaySecondaryTextColor,
),
overflow: TextOverflow.ellipsis,
),
@@ -2322,13 +2384,13 @@ class _MapScreenState extends State<MapScreen> {
),
if (pos != null)
IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.center_focus_strong, size: 20),
tooltip: context.l10n.map_centerOnNode,
onPressed: () => _mapController.move(pos, max(_zoom, 15)),
),
IconButton(
color: MapPalette.textPrimary,
color: _overlayPrimaryTextColor,
icon: const Icon(Icons.close, size: 20),
onPressed: _clearSelection,
),
@@ -2345,7 +2407,10 @@ class _MapScreenState extends State<MapScreen> {
),
_miniMeta(
context.l10n.map_path,
contact.pathLabel(context.l10n),
contact.pathLabel(
context.l10n,
pathHashByteWidth: connector.pathHashByteWidth,
),
),
_miniMeta('ID', contact.publicKeyHex.substring(0, 12)),
if (pos != null)
@@ -2389,14 +2454,17 @@ class _MapScreenState extends State<MapScreen> {
Text(
label.toUpperCase(),
style: MeshTheme.accentLabel(
color: MapPalette.textMuted,
color: _overlayMutedTextColor,
fontSize: 8,
),
),
const SizedBox(height: 1),
Text(
value,
style: MeshTheme.mono(fontSize: 11.5, color: MapPalette.textPrimary),
style: MeshTheme.mono(
fontSize: 11.5,
color: _overlayPrimaryTextColor,
),
),
],
);
@@ -2746,7 +2814,10 @@ class _MapScreenState extends State<MapScreen> {
children: [
_buildInfoRow(
context.l10n.map_path,
contact.pathLabel(context.l10n),
contact.pathLabel(
context.l10n,
pathHashByteWidth: connector.pathHashByteWidth,
),
),
if (contact.hasLocation)
_buildInfoRow(
@@ -3492,10 +3563,23 @@ class _MapScreenState extends State<MapScreen> {
}
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.add(
contact.publicKey[0],
); // Add first 16 bytes of public key to path trace
_pathTrace.addAll(hopPrefix); // Add the hop-width pubkey prefix.
_pathTraceHopWidths.add(hopWidth);
_pathTraceContacts.add(
contact.copyWith(
latitude: position?.latitude ?? contact.latitude,
@@ -3510,6 +3594,7 @@ class _MapScreenState extends State<MapScreen> {
setState(() {
_isBuildingPathTrace = true;
_pathTrace.clear();
_pathTraceHopWidths.clear();
_pathTraceContacts.clear();
_points.clear();
_polylines.clear();
@@ -3519,8 +3604,19 @@ class _MapScreenState extends State<MapScreen> {
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();
_pathTrace.removeLast(); // Remove last node from path trace
// A path trace hop can be wider than one byte; remove the full hash prefix.
_pathTrace.removeRange(
_pathTrace.length - hopByteCount,
_pathTrace.length,
);
_points.removeLast(); // Remove last point from points list
_polylines.clear(); // Clear polylines
});
@@ -3537,14 +3633,14 @@ class _MapScreenState extends State<MapScreen> {
right: 16,
child: DecoratedBox(
decoration: BoxDecoration(
color: MapPalette.panelDark,
color: _overlayPanelColor,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MapPalette.border),
boxShadow: const [
border: Border.all(color: _overlayBorderColor),
boxShadow: [
BoxShadow(
color: MapPalette.markerShadow,
color: _overlayShadowColor,
blurRadius: 10,
offset: Offset(0, 4),
offset: const Offset(0, 4),
),
],
),
@@ -3557,24 +3653,34 @@ class _MapScreenState extends State<MapScreen> {
children: [
Text(
l10n.contacts_pathTrace,
style: TextStyle(fontWeight: FontWeight.bold),
style: TextStyle(
fontWeight: FontWeight.bold,
color: _overlayPrimaryTextColor,
),
),
if (_pathTrace.isEmpty) const SizedBox(height: 8),
if (_pathTrace.isEmpty)
Text(l10n.map_tapToAdd, style: TextStyle(fontSize: 12)),
Text(
l10n.map_tapToAdd,
style: TextStyle(
fontSize: 12,
color: _overlaySecondaryTextColor,
),
),
const SizedBox(height: 6),
if (_pathTrace.isNotEmpty)
Text(
"${l10n.path_currentPathLabel} ${formatDistance(getPathDistanceMeters(_points), isImperial: isImperial)}",
style: MeshTheme.mono(
fontSize: 12,
color: MapPalette.textSecondary,
color: _overlaySecondaryTextColor,
),
),
SelectableText(
_pathTrace
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join(','),
PathHelper.splitPathBytes(
_pathTrace,
context.read<MeshCoreConnector>().pathHashByteWidth,
).map(PathHelper.formatHopHex).join(','),
style: MeshTheme.mono(
fontSize: 18,
fontWeight: FontWeight.w700,
@@ -3599,6 +3705,7 @@ class _MapScreenState extends State<MapScreen> {
builder: (context) => PathTraceMapScreen(
title: l10n.contacts_pathTrace,
path: Uint8List.fromList(_pathTrace),
flipPathAround: false,
pathHashByteWidth: hashW,
pathContacts: _pathTraceContacts,
),
@@ -3621,6 +3728,10 @@ class _MapScreenState extends State<MapScreen> {
title: l10n.contacts_pathTrace,
path: Uint8List.fromList(_pathTrace),
flipPathAround: true,
pathHashByteWidth: context
.read<MeshCoreConnector>()
.pathHashByteWidth,
pathContacts: _pathTraceContacts,
),
),
);
@@ -3643,6 +3754,7 @@ class _MapScreenState extends State<MapScreen> {
setState(() {
_isBuildingPathTrace = false;
_pathTrace.clear();
_pathTraceHopWidths.clear();
_points.clear();
_polylines.clear();
});
+2 -2
View File
@@ -276,7 +276,7 @@ class _NeighborsScreenState extends State<NeighborsScreen> {
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
@@ -296,7 +296,7 @@ class _NeighborsScreenState extends State<NeighborsScreen> {
),
],
),
centerTitle: false,
centerTitle: true,
actions: [
IconButton(
icon: Icon(isFloodMode ? Icons.waves : Icons.route),
+340 -164
View File
@@ -7,6 +7,7 @@ import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/helpers/path_helper.dart';
import 'package:meshcore_open/l10n/l10n.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/contact.dart';
@@ -19,7 +20,6 @@ import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/utils/app_logger.dart';
import 'package:meshcore_open/widgets/path_map_ui.dart';
import 'package:meshcore_open/widgets/snr_indicator.dart';
import 'package:meshcore_open/widgets/themed_map_tile_layer.dart';
import 'package:provider/provider.dart';
import '../theme/mesh_theme.dart';
@@ -27,9 +27,9 @@ export 'package:meshcore_open/widgets/path_map_ui.dart'
show formatDistance, getPathDistanceMeters;
class PathTraceData {
final Uint8List pathData;
final List<Uint8List> pathData;
final List<double> snrData;
final Map<int, Contact> pathContacts;
final Map<String, Contact> pathContacts;
PathTraceData({
required this.pathData,
@@ -38,6 +38,20 @@ class PathTraceData {
});
}
String _hopKey(Uint8List hopBytes) => PathHelper.formatHopHex(hopBytes);
Uint8List _lastHopChunk(Uint8List path, int hopWidth) {
if (path.isEmpty) return Uint8List(0);
final width = hopWidth.clamp(1, path.length).toInt();
return Uint8List.fromList(path.sublist(path.length - width));
}
bool _matchesHopPrefix(Uint8List a, Uint8List b) {
if (a.isEmpty || b.isEmpty) return false;
final width = min(a.length, b.length);
return listEquals(a.sublist(0, width), b.sublist(0, width));
}
class PathTraceMapScreen extends StatefulWidget {
final String title;
final Uint8List path;
@@ -80,8 +94,8 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
bool _failed2Loaded = false;
bool _hasData = false;
PathTraceData? _traceData;
// Inferred positions for hops that have no GPS location, keyed by hop byte.
Map<int, LatLng> _inferredHopPositions = {};
// Inferred positions for hops that have no GPS location, keyed by hop prefix.
Map<String, LatLng> _inferredHopPositions = {};
// Endpoint position for the target contact (GPS or guessed).
LatLng? _targetContactPosition;
bool _targetContactIsGuessed = false;
@@ -94,6 +108,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
double _pathDistanceMeters = 0.0;
bool _showNodeLabels = true;
Contact? _targetContact;
Uint8List? _sentTagBytes;
// Live path resolved at trace time; used by the response handler for
// endpoint inference so it matches the path that was actually traced.
Uint8List _tracedPath = Uint8List(0);
@@ -103,17 +118,82 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
PathHistoryService? _pathHistory;
PathViewMode _viewMode = PathViewMode.single;
List<DisplayPath> _displayPaths = [];
List<int> _primaryOutboundHops = [];
List<Uint8List> _primaryOutboundHops = [];
String _selectedPathId = 'primary';
final Set<String> _hiddenPathIds = {};
bool _panelCollapsed = false;
bool _animationEnabled = true;
bool _followPacket = false;
String _formatPathPrefixes(Uint8List pathBytes) {
return pathBytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(',');
String _formatPathPrefixes(Uint8List pathBytes, [int? hashByteWidth]) {
return PathHelper.splitPathBytes(
pathBytes,
hashByteWidth ?? widget.pathHashByteWidth,
).map(PathHelper.formatHopHex).join(',');
}
int _traceHashByteWidth(int pathHashByteWidth) {
final width = pathHashByteWidth.clamp(1, pubKeySize).toInt();
if (width <= 1) return 1;
if (width == 2) return 2;
// Trace packets encode hash width as 1 << flags, so 3-byte path hashes
// must be traced with a 4-byte public-key prefix.
return 4;
}
int _traceFlagsForHashWidth(int traceHashByteWidth) {
if (traceHashByteWidth <= 1) return 0;
if (traceHashByteWidth == 2) return 1;
return 2;
}
Uint8List _reversePathByHop(Uint8List pathBytes, int hopWidth) {
final reversedHops = PathHelper.splitPathBytes(
pathBytes,
hopWidth,
).reversed;
final bytes = <int>[];
for (final hop in reversedHops) {
bytes.addAll(hop);
}
return Uint8List.fromList(bytes);
}
Uint8List? _expandHopForTrace(
Uint8List hop,
int traceHashByteWidth,
MeshCoreConnector connector,
) {
if (hop.length == traceHashByteWidth) return hop;
final candidates = <Contact>[
...?widget.pathContacts,
if (widget.targetContact != null) widget.targetContact!,
...connector.allContactsUnfiltered,
];
for (final contact in candidates) {
if (contact.publicKey.length < traceHashByteWidth) continue;
if (!listEquals(contact.publicKey.sublist(0, hop.length), hop)) continue;
return Uint8List.fromList(
contact.publicKey.sublist(0, traceHashByteWidth),
);
}
return null;
}
Uint8List? _tracePathFromBytes(
Uint8List pathBytes,
int traceHashByteWidth,
MeshCoreConnector connector,
) {
final hops = PathHelper.splitPathBytes(pathBytes, widget.pathHashByteWidth);
final traceBytes = <int>[];
for (final hop in hops) {
final traceHop = _expandHopForTrace(hop, traceHashByteWidth, connector);
if (traceHop == null) return null;
traceBytes.addAll(traceHop);
}
return Uint8List.fromList(traceBytes);
}
@override
@@ -233,45 +313,62 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
);
}
Uint8List buildPath(Uint8List pathBytes) {
Uint8List traceBytes;
Uint8List? buildPath(
Uint8List pathBytes,
int traceHashByteWidth,
MeshCoreConnector connector,
) {
final pathHops = PathHelper.splitPathBytes(
pathBytes,
widget.pathHashByteWidth,
);
final hopWidth = traceHashByteWidth.clamp(1, pubKeySize).toInt();
if (pathBytes.isEmpty) {
final pk = widget.targetContact?.publicKey;
final n = widget.pathHashByteWidth.clamp(1, pubKeySize);
if (pk != null && pk.length >= n) {
return Uint8List.fromList(pk.sublist(0, n));
// Compute targetPrefix if targetContact is provided
Uint8List? targetPrefix;
if (widget.targetContact != null) {
final pk = widget.targetContact!.publicKey;
if (pk.isNotEmpty) {
final len = pk.length >= hopWidth ? hopWidth : pk.length;
targetPrefix = Uint8List.fromList(pk.sublist(0, len));
}
traceBytes = Uint8List(1);
traceBytes[0] = pk?[0] ?? 0;
return traceBytes;
}
if (widget.targetContact?.type == advTypeRepeater ||
widget.targetContact?.type == advTypeRoom) {
final len = (pathBytes.length + pathBytes.length + 1);
traceBytes = Uint8List(len);
traceBytes[pathBytes.length] = widget.targetContact?.publicKey[0] ?? 0;
for (int i = 0; i < pathBytes.length; i++) {
traceBytes[i] = pathBytes[i];
if (i < pathBytes.length) {
traceBytes[len - 1 - i] = pathBytes[i];
final outboundHops = <Uint8List>[];
for (final hop in pathHops) {
final traceHop = _expandHopForTrace(hop, traceHashByteWidth, connector);
if (traceHop == null) return null;
outboundHops.add(traceHop);
}
if (targetPrefix != null) {
// Check if targetPrefix is already the last hop in pathHops to avoid duplication
bool alreadyEndedWithTarget = false;
if (outboundHops.isNotEmpty) {
if (listEquals(outboundHops.last, targetPrefix)) {
alreadyEndedWithTarget = true;
}
}
} else {
if (pathBytes.length < 2) {
return pathBytes[0] == 0 ? Uint8List(0) : pathBytes;
}
final len = (pathBytes.length + pathBytes.length - 1);
traceBytes = Uint8List(len);
for (int i = 0; i < pathBytes.length; i++) {
traceBytes[i] = pathBytes[i];
if (i < pathBytes.length - 1) {
traceBytes[len - 1 - i] = pathBytes[i];
}
if (!alreadyEndedWithTarget) {
outboundHops.add(targetPrefix);
}
}
return traceBytes;
if (outboundHops.isEmpty) {
return Uint8List(0);
}
final mirroredHops = <Uint8List>[...outboundHops];
if (outboundHops.length > 1) {
mirroredHops.addAll(
outboundHops.sublist(0, outboundHops.length - 1).reversed,
);
}
final traceBytes = <int>[];
for (final hop in mirroredHops) {
traceBytes.addAll(hop);
}
return Uint8List.fromList(traceBytes);
}
/// Resolves the path bytes to trace. When tracing a specific contact's
@@ -301,26 +398,49 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
final traceHashByteWidth = _traceHashByteWidth(widget.pathHashByteWidth);
final livePath = _resolveLivePath(connector);
_tracedPath = livePath;
final pathTmp = widget.reversePathAround
? Uint8List.fromList(livePath.reversed.toList())
? _reversePathByHop(livePath, widget.pathHashByteWidth)
: livePath;
final path = widget.flipPathAround ? buildPath(pathTmp) : pathTmp;
final path = widget.flipPathAround
? buildPath(pathTmp, traceHashByteWidth, connector)
: _tracePathFromBytes(pathTmp, traceHashByteWidth, connector);
if (path == null) {
if (!mounted) return;
setState(() {
_isLoading = false;
_failed2Loaded = true;
});
return;
}
appLogger.info(
'Initiating path trace with path: ${_formatPathPrefixes(path)}',
'Initiating path trace with path: '
'${_formatPathPrefixes(path, traceHashByteWidth)}',
tag: 'PathTraceMapScreen',
noNotify: !mounted,
);
final sentTag = DateTime.now().millisecondsSinceEpoch ~/ 1000;
_sentTagBytes = Uint8List(4)
..[0] = sentTag & 0xFF
..[1] = (sentTag >> 8) & 0xFF
..[2] = (sentTag >> 16) & 0xFF
..[3] = (sentTag >> 24) & 0xFF;
final flags = _traceFlagsForHashWidth(traceHashByteWidth);
final tracePayload = path.isEmpty ? Uint8List.fromList([0x00]) : path;
final frame = buildTraceReq(
DateTime.now().millisecondsSinceEpoch ~/ 1000,
0, //auth
0, //flag
payload: path,
sentTag,
0, // auth
flags, // flag
payload: tracePayload,
);
connector.sendFrame(frame);
}
@@ -364,15 +484,13 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
// Check if it's a binary response
if (frame.length > 8 &&
if (frame.length >= 12 &&
code == pushCodeTraceData &&
listEquals(frame.sublist(4, 8), tagData)) {
(listEquals(frame.sublist(4, 8), _sentTagBytes) ||
listEquals(frame.sublist(4, 8), tagData))) {
_timeoutTimer?.cancel();
if (!mounted) return;
frameBuffer.skipBytes(3); //reserved + path length + flag
if (listEquals(frameBuffer.readBytes(4), tagData)) {
_handleTraceResponse(frame);
}
_handleTraceResponse(frame);
}
} catch (e) {
_timeoutTimer?.cancel();
@@ -393,21 +511,30 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final buffer = BufferReader(frame);
try {
buffer.skipBytes(2); // Skip push code and reserved byte
int pathLength = buffer.readUInt8();
final int flags = buffer
.readUInt8(); // path_sz = flags & 0x03 (path-hash mode, fw v1.11+)
final pathLenByte = buffer.readUInt8();
final flags = buffer.readUInt8();
buffer.skipBytes(4); // Skip tag data
buffer.skipBytes(4); // Skip auth code
final int pathSz = flags & 0x03;
Uint8List pathData = buffer.readBytes(pathLength);
var width = _traceHashByteWidth(1 << (flags & 0x03));
var pathLength = pathLenByte == 0xFF ? 0 : pathLenByte;
if (pathLength > buffer.remaining && (pathLenByte & 0xC0) != 0) {
final packedWidth = ((pathLenByte & 0xC0) >> 6) + 1;
final packedLength = (pathLenByte & 0x3F) * packedWidth;
if (packedLength <= buffer.remaining) {
width = packedWidth;
pathLength = packedLength;
}
}
final pathBytes = buffer.readBytes(pathLength);
final pathData = PathHelper.splitPathBytes(pathBytes, width);
// Firmware emits (path_len >> path_sz) hop SNRs plus 1 final SNR (to this node).
final int snrCount = (pathLength >> pathSz) + 1;
final snrCount = (pathLength ~/ width) + 1;
List<double> snrData = buffer
.readBytes(snrCount)
.map((snr) => snr.toSigned(8).toDouble() / 4)
.toList();
Map<int, Contact> pathContacts = {};
Map<String, Contact> pathContacts = {};
Contact lastContact = Contact(
path: Uint8List(0),
pathLength: 0,
@@ -419,7 +546,12 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
lastSeen: DateTime.now(),
);
if (widget.pathContacts != null) {
pathContacts = {for (var c in widget.pathContacts!) c.publicKey[0]: c};
final hopWidth = width.clamp(1, pubKeySize).toInt();
pathContacts = {
for (var c in widget.pathContacts!)
if (c.publicKey.length >= hopWidth)
_hopKey(Uint8List.fromList(c.publicKey.sublist(0, hopWidth))): c,
};
} else {
final contacts = connector.allContactsUnfiltered;
contacts.where((c) => c.type != advTypeChat).forEach((repeater) {
@@ -434,12 +566,14 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
_maxRepeaterMatchDistanceMeters) {
return; //skip reapeaters that are far away from the last one with known GPS, to avoid false matches
}
for (var repeaterData in pathData) {
for (final repeaterData in pathData) {
final hopWidth = repeaterData.length;
if (repeater.publicKey.length < hopWidth) continue;
if (listEquals(
repeater.publicKey.sublist(0, 1),
Uint8List.fromList([repeaterData]),
repeater.publicKey.sublist(0, hopWidth),
repeaterData,
)) {
pathContacts[repeaterData] = repeater;
pathContacts[_hopKey(repeaterData)] = repeater;
lastContact = repeater;
}
}
@@ -448,13 +582,20 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
// For hops with no GPS contact, infer position from other contacts
// with known GPS that share the same last-hop byte.
final Map<int, LatLng> inferredPositions = {};
final Map<String, LatLng> inferredPositions = {};
for (final hop in pathData) {
final contact = pathContacts[hop];
final hopKey = _hopKey(hop);
final contact = pathContacts[hopKey];
if (contact != null && contact.hasLocation) continue;
final peers = connector.contacts
.where(
(c) => c.hasLocation && c.path.isNotEmpty && c.path.last == hop,
(c) =>
c.hasLocation &&
c.path.isNotEmpty &&
_matchesHopPrefix(
_lastHopChunk(c.path, widget.pathHashByteWidth),
hop,
),
)
.toList();
if (peers.isNotEmpty) {
@@ -464,7 +605,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final lon =
peers.map((c) => c.longitude!).reduce((a, b) => a + b) /
peers.length;
inferredPositions[hop] = LatLng(lat, lon);
inferredPositions[hopKey] = LatLng(lat, lon);
}
}
@@ -486,20 +627,31 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final tc = _targetContact!;
if (tc.hasLocation) {
targetPos = LatLng(tc.latitude!, tc.longitude!);
} else if (_tracedPath.length > 1) {
} else if (pathData.length > 1 || _tracedPath.isNotEmpty) {
// Infer from the last hop: average GPS contacts sharing that hop.
// For a round-trip path (flipPathAround/reversePathAround), the target-side hop
// sits in the middle of the symmetric sequence; .last is the local side.
final tracedHops = PathHelper.splitPathBytes(
_tracedPath,
widget.pathHashByteWidth,
);
final hopsForEndpoint = tracedHops.isNotEmpty
? tracedHops
: pathData;
final lastHop = widget.reversePathAround
? _tracedPath.first
: _tracedPath.last;
? hopsForEndpoint.first
: hopsForEndpoint.last;
final lastHopKey = _hopKey(lastHop);
final peers = connector.allContacts
.where(
(c) =>
c.hasLocation &&
c.path.isNotEmpty &&
c.path.last == lastHop,
_matchesHopPrefix(
_lastHopChunk(c.path, widget.pathHashByteWidth),
lastHop,
),
)
.toList();
if (peers.isNotEmpty) {
@@ -516,9 +668,9 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
lon + offsetDeg * sin(angle),
);
targetGuessed = true;
} else if (inferredPositions.containsKey(lastHop)) {
final lat = inferredPositions[lastHop]!.latitude;
final lon = inferredPositions[lastHop]!.longitude;
} else if (inferredPositions.containsKey(lastHopKey)) {
final lat = inferredPositions[lastHopKey]!.latitude;
final lon = inferredPositions[lastHopKey]!.longitude;
const offsetDeg = 0.003;
final angle = (tc.publicKey[1] / 255.0) * 2 * pi;
targetPos = LatLng(
@@ -528,7 +680,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
targetGuessed = true;
} else {
// As a last resort, just place it at the same position as the last hop.
final contact = pathContacts[lastHop];
final contact = pathContacts[lastHopKey];
if (contact != null && contact.hasLocation) {
const offsetDeg = 0.003;
final angle = (tc.publicKey[1] / 255.0) * 2 * pi;
@@ -546,21 +698,22 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
_points = <LatLng>[];
_points.add(LatLng(connector.selfLatitude!, connector.selfLongitude!));
int hopLast = 0;
int hopLastLast = 0;
String hopLast = '';
String hopLastLast = '';
for (final hop in _traceData!.pathData) {
if (hop == hopLastLast && widget.flipPathAround) {
final hopKey = _hopKey(hop);
if (hopKey == hopLastLast && widget.flipPathAround) {
break; //skip duplicate hops in round-trip paths
}
final contact = _traceData!.pathContacts[hop];
final contact = _traceData!.pathContacts[hopKey];
if (contact != null && contact.hasLocation) {
_points.add(LatLng(contact.latitude!, contact.longitude!));
} else {
final inferred = inferredPositions[hop];
final inferred = inferredPositions[hopKey];
if (inferred != null) _points.add(inferred);
}
hopLastLast = hopLast;
hopLast = hop;
hopLast = hopKey;
}
if (targetPos != null) {
if (_targetContact != null && _targetContact!.type == advTypeChat) {
@@ -583,7 +736,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
_initialZoom = _points.isNotEmpty ? 13.0 : 2.0;
_bounds = _points.length > 1 ? LatLngBounds.fromPoints(_points) : null;
_mapKey = ValueKey(
'${context.l10n.pathTrace_you},${_formatPathPrefixes(_traceData!.pathData)}',
'${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}',
);
_pathDistanceMeters = getPathDistanceMeters(_points);
_primaryOutboundHops = _outboundHops(pathData);
@@ -605,37 +758,47 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
/// Outbound hop bytes of the traced path, mirroring the round-trip
/// dedup logic used when building [_points].
List<int> _outboundHops(Uint8List pathData) {
final hops = <int>[];
int hopLast = 0;
int hopLastLast = 0;
List<Uint8List> _outboundHops(List<Uint8List> pathData) {
final hops = <Uint8List>[];
var hopLast = '';
var hopLastLast = '';
for (final hop in pathData) {
if (hop == hopLastLast && widget.flipPathAround) break;
final hopKey = _hopKey(hop);
if (hopKey == hopLastLast && widget.flipPathAround) break;
hops.add(hop);
hopLastLast = hopLast;
hopLast = hop;
hopLast = hopKey;
}
return hops;
}
Contact? _contactForHop(int hop, MeshCoreConnector connector) {
final traced = _traceData?.pathContacts[hop];
Contact? _contactForHop(Uint8List hop, MeshCoreConnector connector) {
final traced = _traceData?.pathContacts[_hopKey(hop)];
if (traced != null) return traced;
for (final c in connector.allContactsUnfiltered) {
if (c.type != advTypeChat &&
c.publicKey.isNotEmpty &&
c.publicKey[0] == hop) {
c.publicKey.length >= hop.length &&
listEquals(c.publicKey.sublist(0, hop.length), hop)) {
return c;
}
}
return null;
}
LatLng? _inferredPositionForHop(int hop, MeshCoreConnector connector) {
final cached = _inferredHopPositions[hop];
LatLng? _inferredPositionForHop(Uint8List hop, MeshCoreConnector connector) {
final hopKey = _hopKey(hop);
final cached = _inferredHopPositions[hopKey];
if (cached != null) return cached;
final peers = connector.contacts
.where((c) => c.hasLocation && c.path.isNotEmpty && c.path.last == hop)
.where(
(c) =>
c.hasLocation &&
c.path.isNotEmpty &&
_matchesHopPrefix(
_lastHopChunk(c.path, widget.pathHashByteWidth),
hop,
),
)
.toList();
if (peers.isEmpty) return null;
final lat =
@@ -643,10 +806,14 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final lon =
peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length;
final pos = LatLng(lat, lon);
_inferredHopPositions[hop] = pos;
_inferredHopPositions[hopKey] = pos;
return pos;
}
String _pathKeyForHops(List<Uint8List> hops) {
return hops.map(PathHelper.formatHopHex).join(',');
}
/// Rebuilds the renderable paths: the traced path as primary plus up to
/// four distinct alternates from the target contact's path history.
void _rebuildDisplayPaths(MeshCoreConnector connector) {
@@ -664,18 +831,22 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final target = widget.targetContact;
final history = _pathHistory;
if (target != null && history != null) {
final seen = <String>{_primaryOutboundHops.join(',')};
final seen = <String>{_pathKeyForHops(_primaryOutboundHops)};
var altIndex = 0;
for (final record in history.getRecentPaths(target.publicKeyHex)) {
if (record.pathBytes.isEmpty) continue;
if (!seen.add(record.pathBytes.join(','))) continue;
final recordHops = PathHelper.splitPathBytes(
record.pathBytes,
widget.pathHashByteWidth,
);
if (!seen.add(_pathKeyForHops(recordHops))) continue;
if (altIndex >= kAlternatePathColors.length) break;
final alt = _buildDisplayPath(
id: 'alt-${record.pathBytes.join('-')}',
id: 'alt-${_pathKeyForHops(recordHops)}',
label: context.l10n.pathMap_alternate(altIndex + 1),
color: kAlternatePathColors[altIndex],
isPrimary: false,
hops: record.pathBytes,
hops: recordHops,
record: record,
connector: connector,
);
@@ -700,7 +871,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
required String label,
required Color color,
required bool isPrimary,
required List<int> hops,
required List<Uint8List> hops,
required MeshCoreConnector connector,
PathRecord? record,
}) {
@@ -719,7 +890,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
for (var i = 0; i < hops.length; i++) {
final hop = hops[i];
final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase();
final hex = PathHelper.formatHopHex(hop);
final contact = _contactForHop(hop, connector);
LatLng? pos;
var isGps = false;
@@ -773,7 +944,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
label: label,
color: color,
isPrimary: isPrimary,
hopBytes: List<int>.from(hops),
hopBytes: List<Uint8List>.from(hops),
points: points,
pointLabels: labels,
pointConfirmed: confirmed,
@@ -934,29 +1105,34 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
List<Marker> _buildHopMarkers(
List<int> pathData, {
List<Uint8List> pathData, {
required bool showLabels,
required Contact? target,
}) {
final markers = <Marker>[];
int hopLast = 0;
int hopLastLast = 0;
String hopLast = '';
String hopLastLast = '';
for (final hop in pathData) {
final contact = _traceData!.pathContacts[hop];
final inferred = _inferredHopPositions[hop];
final hopKey = _hopKey(hop);
final contact = _traceData!.pathContacts[hopKey];
final inferred = _inferredHopPositions[hopKey];
final hasGps = contact != null && contact.hasLocation;
if (hop == hopLastLast && widget.flipPathAround) {
if (hopKey == hopLastLast && widget.flipPathAround) {
continue; //skip duplicate hops in round-trip paths
}
if (!hasGps && inferred == null) {
hopLastLast = hopLast;
hopLast = hop;
hopLast = hopKey;
continue; //skip hops with no GPS and no inferred position
}
final point = hasGps
? LatLng(contact.latitude!, contact.longitude!)
: inferred!;
final label = hop.toRadixString(16).padLeft(2, '0').toUpperCase();
final label = PathHelper.formatHopHex(hop);
final shortLabel = label.length > 2 ? label.substring(0, 2) : label;
final fullLabel = label.length > 2
? (contact?.name != null ? '$label: ${contact!.name}' : label)
: (contact?.name ?? label);
markers.add(
Marker(
@@ -989,9 +1165,9 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
),
alignment: Alignment.center,
child: Text(
hasGps ? label : '~$label',
shortLabel,
style: MeshTheme.mono(
fontSize: 10,
fontSize: 12,
fontWeight: FontWeight.w700,
color: hasGps ? MeshPalette.signal : MeshPalette.warn,
),
@@ -1001,15 +1177,10 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
),
);
if (showLabels) {
markers.add(
_buildNodeLabelMarker(
point: point,
label: contact?.name ?? '~$label',
),
);
markers.add(_buildNodeLabelMarker(point: point, label: fullLabel));
}
hopLastLast = hopLast;
hopLast = hop;
hopLast = hopKey;
}
_addEndpointMarkers(markers, showLabels: showLabels, target: target);
@@ -1137,17 +1308,22 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final connector = context.read<MeshCoreConnector>();
final markers = <Marker>[];
// Hop byte -> paths that use it, in display order.
final hopPaths = <int, List<DisplayPath>>{};
// Hop prefix -> paths that use it, in display order.
final hopPaths = <String, List<DisplayPath>>{};
final hopsByKey = <String, Uint8List>{};
for (final path in _visiblePaths) {
for (final hop in path.hopBytes) {
final list = hopPaths.putIfAbsent(hop, () => []);
final hopKey = _hopKey(hop);
hopsByKey[hopKey] = hop;
final list = hopPaths.putIfAbsent(hopKey, () => []);
if (!list.contains(path)) list.add(path);
}
}
for (final entry in hopPaths.entries) {
final hop = entry.key;
final hopKey = entry.key;
final hop = hopsByKey[hopKey];
if (hop == null) continue;
final paths = entry.value;
final contact = _contactForHop(hop, connector);
final hasGps = contact != null && contact.hasLocation;
@@ -1155,7 +1331,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
? LatLng(contact.latitude!, contact.longitude!)
: _inferredPositionForHop(hop, connector);
if (point == null) continue;
final label = hop.toRadixString(16).padLeft(2, '0').toUpperCase();
final label = PathHelper.formatHopHex(hop);
final baseColor = hasGps ? MeshPalette.signal : MeshPalette.warn;
final shared = paths.length > 1;
@@ -1240,11 +1416,11 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
void _showSharedNodeSheet(
int hop,
Uint8List hop,
Contact? contact,
List<DisplayPath> paths,
) {
final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase();
final hex = PathHelper.formatHopHex(hop);
showSharedNodeSheet(
context,
title:
@@ -1291,29 +1467,28 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
String formatDirectionText(PathTraceData pathTraceData, int index) {
if (index == 0 || index == pathTraceData.snrData.length - 1) {
if (pathTraceData.pathData.isEmpty) {
return context.l10n.pathTrace_you;
}
if (index < 0 || index > pathTraceData.pathData.length) {
return context.l10n.pathTrace_you;
}
if (index == 0 || index == pathTraceData.pathData.length) {
if (index == 0) {
return context.l10n.pathTrace_you;
} else {
final contactName = pathTraceData
.pathContacts[pathTraceData.pathData[pathTraceData.pathData.length -
1]]
?.name;
final hex = pathTraceData.pathData[pathTraceData.pathData.length - 1]
.toRadixString(16)
.padLeft(2, '0')
.toUpperCase();
final hop = pathTraceData.pathData.last;
final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name;
final hex = PathHelper.formatHopHex(hop);
return contactName != null
? "$hex: $contactName"
: "$hex: ${context.l10n.channelPath_unknownRepeater}";
}
} else {
final contactName =
pathTraceData.pathContacts[pathTraceData.pathData[index - 1]]?.name;
final hex = pathTraceData.pathData[index - 1]
.toRadixString(16)
.padLeft(2, '0')
.toUpperCase();
final hop = pathTraceData.pathData[index - 1];
final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name;
final hex = PathHelper.formatHopHex(hop);
return contactName != null
? "$hex: $contactName"
: "$hex: ${context.l10n.channelPath_unknownRepeater}";
@@ -1321,14 +1496,18 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
}
String formatDirectionSubText(PathTraceData pathTraceData, int index) {
if (index == 0 || index == pathTraceData.snrData.length - 1) {
if (pathTraceData.pathData.isEmpty) {
return context.l10n.pathTrace_you;
}
if (index < 0 || index > pathTraceData.pathData.length) {
return context.l10n.pathTrace_you;
}
if (index == 0 || index == pathTraceData.pathData.length) {
if (index == 0) {
final contactName =
pathTraceData.pathContacts[pathTraceData.pathData[0]]?.name;
final hex = pathTraceData.pathData[0]
.toRadixString(16)
.padLeft(2, '0')
.toUpperCase();
final hop = pathTraceData.pathData.first;
final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name;
final hex = PathHelper.formatHopHex(hop);
return contactName != null
? "$hex: $contactName"
: "$hex: ${context.l10n.channelPath_unknownRepeater}";
@@ -1336,12 +1515,9 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
return context.l10n.pathTrace_you;
}
} else {
final contactName =
pathTraceData.pathContacts[pathTraceData.pathData[index]]?.name;
final hex = pathTraceData.pathData[index]
.toRadixString(16)
.padLeft(2, '0')
.toUpperCase();
final hop = pathTraceData.pathData[index];
final contactName = pathTraceData.pathContacts[_hopKey(hop)]?.name;
final hex = PathHelper.formatHopHex(hop);
return contactName != null
? "$hex: $contactName"
: "$hex: ${context.l10n.channelPath_unknownRepeater}";
@@ -1399,7 +1575,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
},
),
children: [
ThemedMapTileLayer(tileCache: tileCache),
tileCache.buildTileLayer(context),
AnimatedBuilder(
animation: _playback,
builder: (context, _) {
@@ -1670,11 +1846,11 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
final connector = context.read<MeshCoreConnector>();
final l10n = context.l10n;
final hopUseCount = <int, int>{};
final hopUseCount = <String, int>{};
if (_viewMode == PathViewMode.combined) {
for (final p in _visiblePaths) {
for (final hop in p.hopBytes.toSet()) {
hopUseCount.update(hop, (v) => v + 1, ifAbsent: () => 1);
for (final hopKey in p.hopBytes.map(PathHelper.formatHopHex).toSet()) {
hopUseCount.update(hopKey, (v) => v + 1, ifAbsent: () => 1);
}
}
}
@@ -1690,7 +1866,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
Widget? trailing;
if (index < path.hopBytes.length) {
final hop = path.hopBytes[index];
final hex = hop.toRadixString(16).padLeft(2, '0').toUpperCase();
final hex = PathHelper.formatHopHex(hop);
final contact = _contactForHop(hop, connector);
title = contact != null
? '$hex: ${contact.name}'
@@ -1703,7 +1879,7 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen>
: inferred
? l10n.pathTrace_legendInferred
: l10n.pathMap_noLocation;
final sharedCount = hopUseCount[hop] ?? 0;
final sharedCount = hopUseCount[_hopKey(hop)] ?? 0;
subtitle = sharedCount > 1
? '$status · ${l10n.pathMap_sharedNodeCount(sharedCount)}'
: status;
+527
View File
@@ -0,0 +1,527 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/l10n.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/storage/region_store.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
import 'package:provider/provider.dart';
Future<void> pushRegionManagementScreen(BuildContext context) {
return Navigator.push(
context,
MaterialPageRoute<void>(
builder: (context) => const RegionManagementScreen(),
),
);
}
class RegionManagementScreen extends StatefulWidget {
const RegionManagementScreen({super.key});
@override
State<RegionManagementScreen> createState() => _RegionManagementScreenState();
}
class _RegionManagementScreenState extends State<RegionManagementScreen> {
static final RegExp _validFetchedRegion = RegExp(r'^[a-z0-9-]{1,30}$');
final RegionStore _regionStore = RegionStore();
List<Region> _regions = [];
bool _isFetchingRegions = false;
@override
void initState() {
super.initState();
final connector = context.read<MeshCoreConnector>();
_regionStore.setPublicKeyHex = connector.selfPublicKeyHex;
_loadRegions();
}
void _loadRegions() {
final regions = _regionStore.loadRegions();
if (mounted) {
setState(() {
_regions = regions;
});
}
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold(
appBar: AppBar(
title: Text(l10n.settings_regionManagement_screenTitle),
centerTitle: true,
actions: [
IconButton(
tooltip: l10n.settings_regionAddRegion,
icon: const Icon(Icons.add),
onPressed: () => _showAddRegionDialog(context),
),
IconButton(
tooltip: l10n.settings_regionFetchRegions,
icon: _isFetchingRegions
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.travel_explore),
onPressed: _isFetchingRegions ? null : _showFetchRegionsDialog,
),
],
),
body: ListView.builder(
padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 88),
itemCount: _regions.length,
itemBuilder: (context, index) {
final region = _regions[index];
return _buildRegionTile(context, region);
},
),
);
}
void _showAddRegionDialog(BuildContext context) {
final l10n = context.l10n;
final controller = TextEditingController();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(l10n.settings_regionName),
content: TextField(
controller: controller,
autofocus: true,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _handleAddRegion(controller.text, context),
decoration: InputDecoration(
hintText: l10n.settings_regionNameHint,
border: const OutlineInputBorder(),
),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[a-z0-9-]")),
],
maxLength: 30,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () => _handleAddRegion(controller.text, context),
child: Text(l10n.common_add),
),
],
),
);
}
Future<void> _showFetchRegionsDialog() async {
if (_isFetchingRegions) return;
setState(() {
_isFetchingRegions = true;
});
Set<Region> fetchedRegions = {};
try {
fetchedRegions = await _fetchRegionsFromRepeaters();
} finally {
if (mounted) {
setState(() {
_isFetchingRegions = false;
});
}
}
if (!mounted) return;
final l10n = context.l10n;
final sortedRegions = fetchedRegions.toList()..sort();
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(l10n.settings_regionFetchRegions),
content: sortedRegions.isEmpty
? Text(l10n.settings_regionFetchRegionsFail)
: StatefulBuilder(
builder: (context, setDialogState) {
return SizedBox(
width: double.maxFinite,
child: ListView.builder(
shrinkWrap: true,
itemCount: sortedRegions.length,
itemBuilder: (context, index) {
final fetchedRegion = sortedRegions[index];
final alreadyExists = _regions.contains(fetchedRegion);
return MeshCard(
margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.only(left: 14, right: 4),
child: Row(
children: [
const Icon(
Icons.landscape,
color: MeshPalette.blue,
),
const SizedBox(width: 12),
Expanded(
child: Text(
fetchedRegion,
style: Theme.of(context).textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
TextButton(
style: alreadyExists
? TextButton.styleFrom(
foregroundColor: Theme.of(
context,
).disabledColor,
)
: null,
onPressed: () {
if (alreadyExists) {
_showDialogSnackBar(
context,
l10n.settings_regionFetchRegionsAlreadyExists,
);
return;
}
_regionStore.addRegion(fetchedRegion);
_loadRegions();
setDialogState(() {});
},
child: Text(l10n.common_add),
),
],
),
);
},
),
);
},
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_close),
),
],
),
);
}
void _showDialogSnackBar(BuildContext context, String message) {
final overlay = Overlay.maybeOf(context);
if (overlay == null) return;
final theme = Theme.of(context);
final entry = OverlayEntry(
builder: (context) => Positioned(
left: 16,
right: 16,
bottom: 32,
child: SafeArea(
child: Material(
color: theme.colorScheme.inverseSurface,
elevation: 6,
borderRadius: BorderRadius.circular(4),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Text(
message,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onInverseSurface,
),
),
),
),
),
),
);
overlay.insert(entry);
Timer(const Duration(seconds: 3), entry.remove);
}
Future<Set<Region>> _fetchRegionsFromRepeaters() async {
final connector = context.read<MeshCoreConnector>();
final repeaters = await _discoverNearbyRepeaters(connector);
final regions = <Region>{};
for (final repeater in repeaters) {
if (!mounted || !connector.isConnected) break;
regions.addAll(await _requestRegionsFromRepeater(connector, repeater));
}
return regions;
}
Future<List<Contact>> _discoverNearbyRepeaters(
MeshCoreConnector connector,
) async {
final repeaters = connector.contacts
.where((contact) => contact.type == advTypeRepeater)
.toList();
if (repeaters.isEmpty || !connector.isConnected) return <Contact>[];
StreamSubscription<Uint8List>? subscription;
Timer? timeout;
final completer = Completer<Set<String>>();
final respondingPrefixes = <String>{};
final tag = DateTime.now().microsecondsSinceEpoch & 0xFFFFFFFF;
void complete() {
if (completer.isCompleted) return;
timeout?.cancel();
subscription?.cancel();
completer.complete(respondingPrefixes);
}
subscription = connector.receivedFrames.listen((frame) {
if (frame.isEmpty || completer.isCompleted) return;
final reader = BufferReader(frame);
try {
if (reader.readByte() != pushCodeControlData) return;
if (reader.remaining < 9) return;
reader.skipBytes(3); // SNR, RSSI, path_len from companion firmware.
final payloadType = reader.readByte();
if (((payloadType >> 4) & 0x0F) != controlSubtypeDiscoverResp ||
(payloadType & 0x0F) != advTypeRepeater) {
return;
}
reader.skipBytes(1); // Inbound SNR reported by the responding repeater.
if (reader.readUInt32LE() != tag) return;
final publicKeyPrefix = reader.readRemainingBytes();
if (publicKeyPrefix.isEmpty) return;
respondingPrefixes.add(pubKeyToHex(publicKeyPrefix));
} catch (_) {
// Ignore malformed discovery frames; another response may still arrive.
}
});
try {
final payload = buildDiscoveryRequestPayload(tag, prefixOnly: true);
await connector.sendFrame(buildSendControlDataFrame(payload));
timeout = Timer(const Duration(seconds: 10), complete);
final prefixes = await completer.future;
return repeaters.where((contact) {
final contactKey = contact.publicKeyHex.toLowerCase();
return prefixes.any((prefix) => contactKey.startsWith(prefix));
}).toList();
} catch (_) {
timeout?.cancel();
await subscription.cancel();
return <Contact>[];
}
}
Future<Set<Region>> _requestRegionsFromRepeater(
MeshCoreConnector connector,
Contact repeater,
) async {
StreamSubscription<Uint8List>? subscription;
Timer? timeout;
final completer = Completer<Set<Region>>();
int? expectedTag;
final originalPath = Uint8List.fromList(repeater.path);
final originalPathLength = repeater.pathLength;
var pathChangedForRequest = false;
void complete(Set<Region> regions) {
if (completer.isCompleted) return;
timeout?.cancel();
subscription?.cancel();
completer.complete(regions);
}
void restartTimeout(Duration duration) {
timeout?.cancel();
timeout = Timer(duration, () => complete(<Region>{}));
}
try {
final replyPath = Uint8List(0);
const replyHopCount = 0;
await connector.setContactPath(repeater, replyPath, replyHopCount);
pathChangedForRequest = true;
subscription = connector.receivedFrames.listen((frame) {
if (frame.isEmpty || completer.isCompleted) return;
final reader = BufferReader(frame);
try {
final cmd = reader.readByte();
if (cmd == respCodeSent) {
reader.skipBytes(1);
expectedTag = reader.readUInt32LE();
final estimatedTimeoutMs = reader.readUInt32LE();
restartTimeout(
Duration(
milliseconds: estimatedTimeoutMs > 0
? estimatedTimeoutMs + 2000
: 10000,
),
);
return;
}
if (cmd == respCodeErr) {
complete(<Region>{});
return;
}
if (cmd != pushCodeBinaryResponse || expectedTag == null) return;
reader.skipBytes(1);
final tag = reader.readUInt32LE();
if (tag != expectedTag) return;
complete(_parseRegionsResponse(reader.readRemainingBytes()));
} catch (_) {
complete(<Region>{});
}
});
restartTimeout(const Duration(seconds: 10));
final frame = buildSendAnonReqFrame(
repeater.publicKey,
requestType: anonReqTypeRegions,
replyPath: replyPath,
replyHopCount: replyHopCount,
pathHashWidth: connector.pathHashByteWidth,
);
await connector.sendFrame(frame);
final regions = await completer.future;
if (pathChangedForRequest && connector.isConnected) {
await _restoreRepeaterPath(
connector,
repeater,
originalPathLength,
originalPath,
);
}
return regions;
} catch (_) {
timeout?.cancel();
subscription?.cancel();
if (pathChangedForRequest && connector.isConnected) {
await _restoreRepeaterPath(
connector,
repeater,
originalPathLength,
originalPath,
);
}
return <Region>{};
}
}
Future<void> _restoreRepeaterPath(
MeshCoreConnector connector,
Contact repeater,
int originalPathLength,
Uint8List originalPath,
) async {
if (originalPathLength < 0) {
await connector.clearContactPath(repeater);
return;
}
await connector.setContactPath(repeater, originalPath, originalPathLength);
}
Set<Region> _parseRegionsResponse(Uint8List frame) {
if (frame.length <= 4) return <Region>{};
final names = utf8
.decode(frame.sublist(4), allowMalformed: true)
.replaceAll('\x00', '')
.split(',');
return names
.map((name) => name.trim())
.where((name) => _validFetchedRegion.hasMatch(name))
.toSet();
}
void _handleAddRegion(Region region, BuildContext context) {
Navigator.pop(context);
_regionStore.addRegion(region);
_loadRegions();
}
Widget _buildRegionTile(BuildContext context, Region region) {
final scheme = Theme.of(context).colorScheme;
return MeshCard(
key: ValueKey(region),
padding: const EdgeInsets.only(left: 14, right: 4),
child: Row(
children: [
const Icon(Icons.landscape, color: MeshPalette.blue),
const SizedBox(width: 12),
Expanded(
child: Text(
region,
style: Theme.of(context).textTheme.bodyMedium,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
IconButton(
tooltip: context.l10n.settings_deleteRegion,
icon: Icon(Icons.delete_outline, color: scheme.error),
onPressed: () => _confirmDelete(context, region),
),
],
),
);
}
void _confirmDelete(BuildContext context, Region region) {
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(context.l10n.settings_deleteRegion),
content: Text(context.l10n.settings_deleteRegionConfirm(region)),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(context.l10n.common_cancel),
),
TextButton(
onPressed: () async {
final connector = context.read<MeshCoreConnector>();
Navigator.pop(dialogContext);
await _regionStore.removeRegion(region);
// Deleting a region clears it from any channels that used it;
// refresh the connector's in-memory channel regions to match.
await connector.loadChannelSettings();
_loadRegions();
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.l10n.settings_regionDeleted)),
);
},
child: Text(
context.l10n.common_delete,
style: TextStyle(
color: Theme.of(dialogContext).colorScheme.error,
),
),
),
],
),
);
}
}
+6 -1
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:provider/provider.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
@@ -31,6 +32,7 @@ class RepeaterHubScreen extends StatelessWidget {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final settingsService = context.watch<AppSettingsService>();
final connector = context.watch<MeshCoreConnector>();
final chemistry = settingsService.batteryChemistryForRepeater(
repeater.publicKeyHex,
);
@@ -85,7 +87,10 @@ class RepeaterHubScreen extends StatelessWidget {
),
const SizedBox(height: 4),
Text(
repeater.pathLabel(l10n),
repeater.pathLabel(
l10n,
pathHashByteWidth: connector.pathHashByteWidth,
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: scheme.onSurfaceVariant),
),
+173 -1
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:typed_data';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
@@ -11,6 +12,7 @@ import '../services/storage_service.dart';
import '../theme/mesh_theme.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/routing_sheet.dart';
import '../utils/keys.dart';
import '../helpers/snack_bar_builder.dart';
class RepeaterSettingsScreen extends StatefulWidget {
@@ -44,6 +46,7 @@ enum _SettingField {
advertInterval,
floodAdvertInterval,
pathHashMode,
prvKey,
txDelay,
directTxDelay,
intThresh,
@@ -109,6 +112,8 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
bool _refreshingIntThresh = false;
bool _refreshingAgcResetInterval = false;
bool _runningAction = false;
bool _searchingForKeyPair = false;
bool _stopSearchingForKeyPair = false;
StreamSubscription<Uint8List>? _frameSubscription;
RepeaterCommandService? _commandService;
@@ -154,6 +159,11 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
// Advanced
int _pathHashMode = 0; // 0-2
final TextEditingController _prvKeyController = TextEditingController();
final TextEditingController _pubKeyController = TextEditingController();
final TextEditingController _prvKeyPrefixController = TextEditingController();
final KeyPairSearcher _keyPairSearcher = KeyPairSearcher();
final int _searchChunkTime = 30; // time in ms to search before yielding
final TextEditingController _txDelayController = TextEditingController();
final TextEditingController _directTxDelayController =
TextEditingController();
@@ -206,6 +216,10 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
_txDelayController.dispose();
_directTxDelayController.dispose();
_intThreshController.dispose();
_prvKeyController.dispose();
_pubKeyController.dispose();
_prvKeyPrefixController.dispose();
_stopSearchingForKeyPair = true;
super.dispose();
}
@@ -860,6 +874,12 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
command: 'set path.hash.mode $_pathHashMode',
));
}
if (_dirtyFields.contains(_SettingField.prvKey)) {
final v = _prvKeyController.text.trim();
if (v != "") {
pending.add((field: _SettingField.prvKey, command: 'set prv.key $v'));
}
}
if (_dirtyFields.contains(_SettingField.txDelay) &&
_txDelayController.text.isNotEmpty) {
final v = double.tryParse(_txDelayController.text.trim());
@@ -1005,6 +1025,36 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
}
}
void _startSearchingForKeyPair() async {
if (_searchingForKeyPair) return;
setState(() {
_searchingForKeyPair = true;
_stopSearchingForKeyPair = false;
});
_searchForKeyPair();
}
void _searchForKeyPair() async {
if (_stopSearchingForKeyPair) {
if (mounted) setState(() => _searchingForKeyPair = false);
return;
}
final String prefix = _prvKeyPrefixController.text.trim();
MCKeyPair? keys = await _keyPairSearcher.findMatchingKeyPair(
prefix,
_searchChunkTime,
);
if (keys == null) {
// Ran out of time; schedule another attempt.
Timer.run(_searchForKeyPair);
} else {
setState(() => _searchingForKeyPair = false);
_prvKeyController.text = pubKeyToHex(keys.private);
_pubKeyController.text = pubKeyToHex(keys.public);
_markChanged(_SettingField.prvKey);
}
}
Widget _buildInlineRefreshButton({
required bool isRefreshing,
required VoidCallback onRefresh,
@@ -1069,6 +1119,7 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
_buildOwnerInfoCard(),
_buildActionsCard(),
_buildAdvancedCard(),
_buildKeysCard(),
const SizedBox(height: 16),
_buildDangerZoneCard(),
],
@@ -1984,6 +2035,127 @@ class _RepeaterSettingsScreenState extends State<RepeaterSettingsScreen> {
);
}
Widget _buildKeysCard() {
final l10n = context.l10n;
return MeshCard(
child: ExpansionTile(
leading: const Icon(Icons.vpn_key),
title: Text(
l10n.repeater_keySettings,
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
),
subtitle: Text(l10n.repeater_keySettingsSubtitle),
childrenPadding: const EdgeInsets.fromLTRB(0, 8, 0, 4),
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: TextField(
controller: _prvKeyController,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp("[0-9a-fA-F]")),
],
decoration: InputDecoration(
labelText: l10n.repeater_prvKey,
helperText: l10n.repeater_prvKeyHelper,
helperMaxLines: 3,
border: const OutlineInputBorder(),
),
onChanged: (_) {
_pubKeyController.text = "";
if (_prvKeyController.text.isNotEmpty) {
_markChanged(_SettingField.prvKey);
}
},
),
),
const SizedBox(width: 8),
Padding(
padding: const EdgeInsets.only(top: 8),
child: _searchingForKeyPair
? IconButton(
icon: const Icon(Icons.cancel, size: 24),
onPressed: (() => _stopSearchingForKeyPair = true),
tooltip: l10n.repeater_stopGeneratingPrvKey,
visualDensity: VisualDensity.compact,
)
: IconButton(
icon: const Icon(Icons.casino_rounded, size: 24),
onPressed: () {
_startSearchingForKeyPair();
},
tooltip: l10n.repeater_generatePrvKey,
visualDensity: VisualDensity.compact,
),
),
],
),
const SizedBox(height: 16),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: TextField(
readOnly: true,
controller: _pubKeyController,
style: TextStyle(
color: Theme.of(
context,
).textTheme.headlineSmall?.color?.withValues(alpha: 0.6),
),
decoration: InputDecoration(
labelText: l10n.repeater_pubKey,
helperText: l10n.repeater_pubKeyHelper,
helperMaxLines: 3,
border: const OutlineInputBorder(),
),
),
),
const SizedBox(width: 16),
Padding(
padding: const EdgeInsets.only(top: 12),
child: SizedBox(
width: 24,
height: 24,
child: _searchingForKeyPair
? CircularProgressIndicator(strokeWidth: 2)
: null,
),
),
const SizedBox(width: 8),
],
),
const SizedBox(height: 16),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: TextField(
controller: _prvKeyPrefixController,
maxLength: 4,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp("[0-9a-fA-F]")),
],
onChanged: (_) => setState(() => {}), // updates helper text
decoration: InputDecoration(
labelText: l10n.repeater_pubKeyPrefix,
helperText: l10n.repeater_pubKeyPrefixHelper(
pow(16, _prvKeyPrefixController.text.length).toInt(),
),
helperMaxLines: 3,
border: const OutlineInputBorder(),
),
),
),
const SizedBox(width: 48),
],
),
],
),
);
}
Widget _buildDangerZoneCard() {
final l10n = context.l10n;
return MeshCard(
+140 -4
View File
@@ -9,6 +9,7 @@ import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/l10n.dart';
import '../models/radio_settings.dart';
import '../services/app_settings_service.dart';
import '../services/app_debug_log_service.dart';
import '../theme/mesh_theme.dart';
import '../widgets/app_bar.dart';
@@ -19,6 +20,7 @@ import 'app_debug_log_screen.dart';
import 'ble_debug_log_screen.dart';
import '../widgets/radio_stats_entry.dart';
import '../widgets/sync_progress_overlay.dart';
import 'region_management_screen.dart';
/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others)
/// to the UI enum range (always 5-8).
@@ -449,6 +451,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
onTap: () => _showRadioSettings(context, connector),
),
const Divider(height: 1, indent: 16),
_tappableTile(
context,
icon: Icons.landscape,
title: l10n.settings_regionSettings,
subtitle: l10n.settings_regionSettingsSubtitle,
onTap: () => pushRegionManagementScreen(context),
),
const Divider(height: 1, indent: 16),
_tappableTile(
context,
icon: Icons.sensors_outlined,
@@ -458,10 +468,30 @@ class _SettingsScreenState extends State<SettingsScreen> {
? () => pushCompanionRadioStatsScreen(context)
: null,
),
const Divider(height: 1, indent: 16),
_tappableTile(
context,
icon: Icons.route_outlined,
title: l10n.repeater_pathHashMode,
subtitle: _pathHashModeSubtitle(context, connector.pathHashByteWidth),
onTap: connector.isConnected
? () => _editPathHashMode(context, connector)
: null,
),
],
);
}
String _pathHashModeSubtitle(BuildContext context, int pathHashByteWidth) {
final l10n = context.l10n;
return switch (pathHashByteWidth.clamp(1, 4).toInt()) {
1 => l10n.repeater_pathHashModeOption0,
2 => l10n.repeater_pathHashModeOption1,
3 => l10n.repeater_pathHashModeOption2,
_ => l10n.repeater_pathHashModeOption3,
};
}
Widget _buildLocationCardContent(
BuildContext context,
MeshCoreConnector connector,
@@ -750,8 +780,90 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
void _editPathHashMode(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
var selectedMode = (connector.pathHashByteWidth - 1).clamp(0, 3).toInt();
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: Text(l10n.repeater_pathHashMode),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButtonFormField<int>(
initialValue: selectedMode,
decoration: InputDecoration(
labelText: l10n.repeater_pathHashMode,
border: const OutlineInputBorder(),
),
items: [
DropdownMenuItem(
value: 0,
child: Text(l10n.repeater_pathHashModeOption0),
),
DropdownMenuItem(
value: 1,
child: Text(l10n.repeater_pathHashModeOption1),
),
DropdownMenuItem(
value: 2,
child: Text(l10n.repeater_pathHashModeOption2),
),
DropdownMenuItem(
value: 3,
child: Text(l10n.repeater_pathHashModeOption3),
),
],
onChanged: (value) {
if (value == null) return;
setDialogState(() => selectedMode = value);
},
),
const SizedBox(height: 12),
Text(
l10n.repeater_pathHashModeHelper,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
FilledButton(
onPressed: () async {
Navigator.pop(dialogContext);
try {
await connector.setPathHashMode(selectedMode);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.repeater_settingsSaved),
);
} catch (e) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
}
},
child: Text(l10n.common_save),
),
],
),
),
);
}
void _editLocation(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
final settingsService = context.read<AppSettingsService>();
final latController = TextEditingController();
final lonController = TextEditingController();
final intervalController = TextEditingController();
@@ -763,9 +875,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
final bool hasGPS = customVars.containsKey("gps");
bool isGPSEnabled = customVars["gps"] == "1";
// Read current interval or default to 900 (15 minutes)
final currentInterval =
int.tryParse(customVars["gps_interval"] ?? "") ?? 900;
final currentInterval = settingsService.resolvedGpsIntervalSeconds(
customVars,
);
intervalController.text = currentInterval.toString();
String? intervalError;
@@ -863,7 +975,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
Navigator.pop(context);
if (interval != null) {
await connector.setCustomVar("gps_interval:$interval");
await settingsService.setGpsIntervalSeconds(
interval,
writeToDevice: (value) =>
connector.setCustomVar("gps_interval:$value"),
);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
@@ -1163,12 +1279,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
void _privacySettings(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
final settingsService = context.read<AppSettingsService>();
int telemetryMode = connector.telemetryModeBase;
int telemetryLocMode = connector.telemetryModeLoc;
int telemetryEnvMode = connector.telemetryModeEnv;
bool advertLocPolicy = connector.advertLocationPolicy == 0 ? false : true;
int multiAcks = connector.multiAcks;
bool autoZeroHopAdvertOnGpsUpdate =
settingsService.settings.autoSendZeroHopAdvertOnGpsUpdate;
final telemModeBase = [
DropdownMenuItem(value: teleModeDeny, child: Text(l10n.settings_denyAll)),
@@ -1203,6 +1322,20 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) {
},
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.settings_autoZeroHopAdvertOnGpsUpdate,
subtitle: l10n.settings_autoZeroHopAdvertOnGpsUpdateSubtitle,
value: autoZeroHopAdvertOnGpsUpdate,
enabled: advertLocPolicy,
onChanged: advertLocPolicy
? (value) {
setDialogState(
() => autoZeroHopAdvertOnGpsUpdate = value,
);
}
: null,
),
const SizedBox(height: 8),
SwitchListTile(
title: Text(l10n.settings_multiAck),
value: multiAcks == 1,
@@ -1271,6 +1404,9 @@ void _privacySettings(BuildContext context, MeshCoreConnector connector) {
advertLocPolicy ? 1 : 0,
multiAcks,
);
await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate(
autoZeroHopAdvertOnGpsUpdate,
);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
+2 -2
View File
@@ -334,7 +334,7 @@ class _TelemetryScreenState extends State<TelemetryScreen> {
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
@@ -350,7 +350,7 @@ class _TelemetryScreenState extends State<TelemetryScreen> {
),
],
),
centerTitle: false,
centerTitle: true,
bottom: const SyncProgressAppBarBottom(),
actions: [
IconButton(