UI refresh: shared widgets, screen cleanups, and full translations

- Extract reusable widgets (chat composer/send pipeline, message bubble
  frame, reaction chips, path map scaffold, radio settings dialog,
  translation settings section, map POI clusters, nav tiles, etc.) and
  slim down the screens that used them
- Map: hide/remove markers with restore, confirm before setting node
  location, POI clustering, semantics labels
- Map cache: cancellable downloads and a bulk tile limit
- Repeater: unsaved-changes guard, CLI search/copy/share transcript,
  framed-command debug preview, disconnected banner
- Confirm before clearing chats and debug logs
- Keep cached unread totals in sync on per-contact/channel updates
- Move remaining hardcoded strings into l10n and translate the 98 new
  keys into all 17 non-English locales
This commit is contained in:
zjs81 committed 2026-10-11 15:17:01 -07:00
1 parent 9609a8231d
commit 88dcc5943f
100 files changed
+19778 -8167

No files matched your search

+1 -1
View File
@@ -78,7 +78,7 @@ class _BatteryIndicatorState extends State<BatteryIndicator> {
child: Text(
displayText,
style: MeshTheme.mono(
fontSize: 11,
fontSize: 12,
fontWeight: FontWeight.w600,
color: batteryUi.color,
),
+2 -2
View File
@@ -145,7 +145,7 @@ class ByteCountedTextField extends StatelessWidget {
? Text(
softLimitNote!,
style: TextStyle(
fontSize: 11,
fontSize: 12,
color: Theme.of(context).colorScheme.tertiary,
),
)
@@ -154,7 +154,7 @@ class ByteCountedTextField extends StatelessWidget {
const SizedBox(width: 8),
Text(
'$usedBytes / $maxBytes',
style: TextStyle(fontSize: 11, color: counterColor),
style: TextStyle(fontSize: 12, color: counterColor),
),
],
),
+291
View File
@@ -0,0 +1,291 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../helpers/gif_helper.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../theme/mesh_theme.dart';
import 'byte_count_input.dart';
import 'gif_message.dart';
import 'gif_picker.dart';
import 'message_translation_button.dart';
/// One entry of the composer's "+" menu.
@immutable
class ChatComposerAction {
final String id;
final IconData icon;
final String label;
const ChatComposerAction({
required this.id,
required this.icon,
required this.label,
});
}
/// Opens the GIF picker and puts the chosen GIF into [controller].
void showChatGifPicker(BuildContext context, TextEditingController controller) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => GifPicker(
onGifSelected: (gifId) {
controller.text = GifHelper.encodeGif(gifId);
},
),
);
}
/// Opens the outgoing-translation options sheet.
Future<void> showComposerTranslationOptions(BuildContext context) async {
final settingsService = context.read<AppSettingsService>();
final settings = settingsService.settings;
await showMessageTranslationSheet(
context: context,
enabled: settings.composerTranslationEnabled,
selectedLanguageCode: settings.translationTargetLanguageCode,
onEnabledChanged: settingsService.setComposerTranslationEnabled,
onLanguageSelected: settingsService.setTranslationTargetLanguageCode,
);
}
/// The message composer shared by the direct and channel chat screens:
/// "+" action menu, optional translation toggle, byte-counted text field (or
/// GIF preview) and send button. [header] widgets (reply banner, progress)
/// are stacked above the row.
class ChatComposer extends StatelessWidget {
final TextEditingController controller;
final FocusNode focusNode;
final int maxBytes;
final int? softLimitBytes;
final String? softLimitNote;
final String Function(String)? encoder;
final VoidCallback onSend;
final String sendTooltip;
/// Builds the "+" menu entries when it is opened, so they reflect the
/// current state (e.g. whether the radio has a position).
final List<ChatComposerAction> Function() actionsBuilder;
final ValueChanged<String> onAction;
final List<Widget> header;
const ChatComposer({
super.key,
required this.controller,
required this.focusNode,
required this.maxBytes,
required this.onSend,
required this.sendTooltip,
required this.actionsBuilder,
required this.onAction,
this.softLimitBytes,
this.softLimitNote,
this.encoder,
this.header = const [],
});
Future<void> _openActionMenu(BuildContext buttonContext) async {
final actions = actionsBuilder();
if (actions.isEmpty) return;
final button = buttonContext.findRenderObject() as RenderBox;
final overlay =
Overlay.of(buttonContext).context.findRenderObject() as RenderBox;
final buttonOffset = button.localToGlobal(Offset.zero, ancestor: overlay);
final menuHeight = actions.length * kMinInteractiveDimension + 16;
final menuTop = (buttonOffset.dy - menuHeight).clamp(
8.0,
overlay.size.height,
);
final position = RelativeRect.fromLTRB(
buttonOffset.dx,
menuTop,
overlay.size.width - buttonOffset.dx - button.size.width,
overlay.size.height - buttonOffset.dy,
);
final selected = await showMenu<String>(
context: buttonContext,
position: position,
// Keep focus on the text field: if the menu route took focus, the
// keyboard would close, the composer would drop down and the menu would
// be left floating where the keyboard used to be.
requestFocus: false,
items: [
for (final action in actions)
PopupMenuItem(
value: action.id,
child: Row(
children: [
Icon(action.icon),
const SizedBox(width: 12),
Flexible(child: Text(action.label)),
],
),
),
],
);
if (selected == null || !buttonContext.mounted) return;
onAction(selected);
}
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final translation = context
.select<AppSettingsService, (bool, bool, String?)>(
(s) => (
s.settings.translationEnabled,
s.settings.composerTranslationEnabled,
s.settings.translationTargetLanguageCode,
),
);
return Container(
decoration: BoxDecoration(
color: scheme.surface,
border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)),
),
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...header,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Builder(
builder: (buttonContext) => IconButton(
icon: const Icon(Icons.add_circle_outline),
tooltip: context.l10n.chat_selectSendAction,
onPressed: () => _openActionMenu(buttonContext),
),
),
if (translation.$1)
MessageTranslationButton(
enabled: translation.$2,
languageCode: translation.$3,
onPressed: () => showComposerTranslationOptions(context),
),
Expanded(
child: ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) {
final gifId = GifHelper.parseGif(value.text);
if (gifId != null) {
return _buildGifPreview(context, gifId, scheme);
}
return _buildTextField(context, scheme);
},
),
),
const SizedBox(width: 6),
ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) {
final hasText = value.text.trim().isNotEmpty;
return IconButton.filled(
icon: const Icon(Icons.send, size: 20),
tooltip: sendTooltip,
style: IconButton.styleFrom(
backgroundColor: hasText
? scheme.primary
: scheme.surfaceContainerHighest,
foregroundColor: hasText
? scheme.onPrimary
: scheme.onSurfaceVariant,
minimumSize: const Size(40, 40),
shape: const CircleBorder(),
),
onPressed: hasText
? () {
HapticFeedback.lightImpact();
onSend();
}
: null,
);
},
),
],
),
),
],
),
),
);
}
Widget _buildGifPreview(
BuildContext context,
String gifId,
ColorScheme scheme,
) {
return Focus(
autofocus: true,
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
(event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
onSend();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: GifMessage(
url: 'https://media.giphy.com/media/$gifId/giphy.gif',
backgroundColor: scheme.surfaceContainerHighest,
fallbackTextColor: scheme.onSurface.withValues(alpha: 0.6),
maxSize: 160,
),
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.close),
tooltip: context.l10n.chat_removeGif,
onPressed: () {
controller.clear();
focusNode.requestFocus();
},
),
],
),
);
}
Widget _buildTextField(BuildContext context, ColorScheme scheme) {
OutlineInputBorder border(Color color, [double width = 1]) =>
OutlineInputBorder(
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(color: color, width: width),
);
return ByteCountedTextField(
maxBytes: maxBytes,
softLimitBytes: softLimitBytes,
softLimitNote: softLimitNote,
controller: controller,
focusNode: focusNode,
hintText: context.l10n.chat_typeMessage,
onSubmitted: (_) => onSend(),
encoder: encoder,
decoration: InputDecoration(
hintText: context.l10n.chat_typeMessage,
border: border(scheme.outlineVariant),
enabledBorder: border(scheme.outlineVariant),
focusedBorder: border(scheme.primary, 1.5),
filled: true,
fillColor: scheme.surfaceContainerLow,
contentPadding: const EdgeInsets.symmetric(
horizontal: 18,
vertical: 12,
),
),
);
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ class ChatDaySeparator extends StatelessWidget {
Text(
formatChatDayLabel(context, day),
style: MeshTheme.mono(
fontSize: 10.5,
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),
+192
View File
@@ -0,0 +1,192 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/translation_support.dart';
import '../services/app_settings_service.dart';
import '../services/translation_service.dart';
import '../utils/app_logger.dart';
import '../utils/platform_info.dart';
import 'marker_label_dialog.dart';
/// Send guard and one-second cooldown shared by the chat composers.
///
/// The cooldown is only stamped by [markDispatched], i.e. once a send has
/// actually gone to the connector, so a rejected attempt (empty, too long,
/// translation aborted) never locks the user out.
class ChatSendGuard {
static const cooldown = Duration(seconds: 1);
DateTime? _lastDispatchAt;
bool _busy = false;
/// True while a send is awaiting outgoing translation, so a second tap
/// can't send the same text again.
bool get isBusy => _busy;
/// Runs [action] unless another send is already in flight.
Future<void> runExclusive(Future<void> Function() action) async {
if (_busy) return;
_busy = true;
try {
await action();
} finally {
_busy = false;
}
}
/// Returns false, and tells the user, if the last dispatch was under a
/// second ago.
bool checkCooldown(BuildContext context) {
final last = _lastDispatchAt;
if (last != null && DateTime.now().difference(last) < cooldown) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.chat_sendCooldown),
);
return false;
}
return true;
}
void markDispatched() => _lastDispatchAt = DateTime.now();
}
/// Outcome of the optional outgoing translation step.
@immutable
class OutgoingTranslation {
final String text;
final String? originalText;
final String? languageCode;
final String? modelId;
const OutgoingTranslation(
this.text, {
this.originalText,
this.languageCode,
this.modelId,
});
}
/// Translates [text] when composer translation is on and applies, returning
/// the text to send plus translation metadata. Returns null when [context]
/// was unmounted while the translation ran.
Future<OutgoingTranslation?> translateOutgoingText(
BuildContext context,
String text,
) async {
final settings = context.read<AppSettingsService>().settings;
if (!settings.translationEnabled) return OutgoingTranslation(text);
final translationService = context.read<TranslationService>();
final targetLanguageCode = translationService.resolvedTargetLanguageCode(
Localizations.localeOf(context).languageCode,
);
if (!translationService.shouldTranslateOutgoing(
text: text,
targetLanguageCode: targetLanguageCode,
)) {
return OutgoingTranslation(text);
}
final result = await translationService.translateOutgoingText(
text: text,
targetLanguageCode: targetLanguageCode,
);
if (!context.mounted) return null;
if (result != null &&
result.status == MessageTranslationStatus.completed &&
result.translatedText.isNotEmpty) {
return OutgoingTranslation(
result.translatedText,
originalText: text,
languageCode: result.targetLanguageCode,
modelId: result.modelId,
);
}
return OutgoingTranslation(text);
}
/// Shares the radio's own position as a map marker through [send]. Uses the
/// same [guard] as typed messages so it can't race or flood alongside them.
Future<void> shareMyLocationMarker({
required BuildContext context,
required MeshCoreConnector connector,
required ChatSendGuard guard,
required Future<void> Function(String markerText) send,
String logTag = 'Chat',
}) async {
final lat = connector.selfLatitude;
final lon = connector.selfLongitude;
if (!hasShareableLocation(lat, lon)) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.chat_noRadioLocation),
);
return;
}
final selfName = connector.selfName;
final label = await showMarkerLabelDialog(
context,
lat: lat!,
lon: lon!,
defaultLabel: selfName != null && selfName.isNotEmpty
? selfName
: context.l10n.map_sharedPin,
flags: 'poi',
confirmText: context.l10n.common_share,
);
if (label == null || label.isEmpty || !context.mounted) return;
await guard.runExclusive(() async {
if (!guard.checkCooldown(context)) return;
final pending = send(formatMarkerText(lat, lon, label, 'poi'));
guard.markDispatched();
try {
await pending;
} catch (e) {
// A failed send is already marked failed on the message itself.
appLogger.warn('Sharing location failed: $e', tag: logTag);
}
});
}
/// Copies a message to the clipboard and confirms it.
void copyChatMessageText(BuildContext context, String text) {
Clipboard.setData(ClipboardData(text: text));
// Android shows its own clipboard chip; the snackbar is redundant there
// and lingers over the input field after the chip dismisses.
if (PlatformInfo.isAndroid) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.chat_messageCopied),
);
}
/// Asks before clearing a transcript. [message] says what will be erased.
Future<bool> confirmClearChat(
BuildContext context, {
required String message,
}) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(dialogContext.l10n.contact_clearChat),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(dialogContext.l10n.common_cancel),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: TextButton.styleFrom(
foregroundColor: Theme.of(dialogContext).colorScheme.error,
),
child: Text(dialogContext.l10n.common_delete),
),
],
),
);
return confirmed == true;
}
+35
View File
@@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
/// Asks the user to confirm clearing a log or history. Resolves to true only
/// when the user taps Clear.
Future<bool> showConfirmClearDialog(
BuildContext context, {
required String title,
required String message,
}) async {
final l10n = context.l10n;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(title),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.common_cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
style: FilledButton.styleFrom(
backgroundColor: Theme.of(dialogContext).colorScheme.error,
foregroundColor: Theme.of(dialogContext).colorScheme.onError,
),
child: Text(l10n.common_clear),
),
],
),
);
return confirmed == true;
}
+123
View File
@@ -0,0 +1,123 @@
import 'package:flutter/material.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/app_localizations.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
/// Shared node-type visuals and last-seen formatting for contact lists
/// (contacts, discovery, nearby-node scan).
/// Accent used for sensor nodes.
const Color meshSensorTeal = Color(0xFF4ACCC4);
/// Node-type accent colour per design language.
Color contactTypeColor(int type) {
switch (type) {
case advTypeRepeater:
return MeshPalette.warn;
case advTypeRoom:
return MeshPalette.magenta;
case advTypeSensor:
return meshSensorTeal;
default:
return MeshPalette.blue;
}
}
/// Node-type avatar icon. Returns null for chat nodes so [AvatarCircle]
/// shows initials.
IconData? contactTypeIcon(int type) {
switch (type) {
case advTypeRepeater:
return Icons.cell_tower;
case advTypeRoom:
return Icons.meeting_room;
case advTypeSensor:
return Icons.sensors;
default:
return null;
}
}
/// The most recent activity for [contact]: for chat nodes this includes the
/// last message, for other node types only the last advert.
DateTime resolveContactLastSeen(Contact contact) {
if (contact.type != advTypeChat) return contact.lastSeen;
return contact.lastMessageAt.isAfter(contact.lastSeen)
? contact.lastMessageAt
: contact.lastSeen;
}
/// Short relative "last seen" label ("now", "5 mins ago", "2 days ago").
String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) {
final diff = DateTime.now().difference(lastSeen);
if (diff.isNegative || diff.inMinutes < 5) {
return l10n.contacts_lastSeenNow;
}
if (diff.inMinutes < 60) {
return l10n.contacts_lastSeenMinsAgo(diff.inMinutes);
}
if (diff.inHours < 24) {
final hours = diff.inHours;
return hours == 1
? l10n.contacts_lastSeenHourAgo
: l10n.contacts_lastSeenHoursAgo(hours);
}
final days = diff.inDays;
return days == 1
? l10n.contacts_lastSeenDayAgo
: l10n.contacts_lastSeenDaysAgo(days);
}
/// Memoizes a derived list (filtered/sorted contacts) so it is only
/// recomputed when the input elements or the filter key change. Contacts are
/// immutable, so element identity is a sufficient change check even though
/// the connector hands out a fresh list copy on every read.
class DerivedListCache<T> {
List<T>? _inputs;
List<Object?>? _key;
List<T>? _result;
List<T> get(List<T> inputs, List<Object?> key, List<T> Function() compute) {
final cached = _result;
if (cached != null &&
_sameElements(_inputs!, inputs) &&
_sameKey(_key!, key)) {
return cached;
}
final result = compute();
_inputs = List<T>.of(inputs);
_key = key;
_result = result;
return result;
}
void invalidate() => _result = null;
static bool _sameElements<E>(List<E> a, List<E> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (!identical(a[i], b[i])) return false;
}
return true;
}
static bool _sameKey(List<Object?> a, List<Object?> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
final x = a[i];
final y = b[i];
if (x is List && y is List) {
if (x.length != y.length) return false;
for (var j = 0; j < x.length; j++) {
if (x[j] != y[j]) return false;
}
} else if (x != y) {
return false;
}
}
return true;
}
}
+151
View File
@@ -0,0 +1,151 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/app_settings.dart';
import '../services/app_settings_service.dart';
/// Add or edit a Cyrillic-to-Latin transliteration profile.
///
/// Pass [profile] to edit it; leave it null to create a new profile seeded
/// with the default character map. Owns (and disposes) its controllers.
class Cyr2LatProfileDialog extends StatefulWidget {
final AppSettingsService settingsService;
final Cyr2LatProfile? profile;
const Cyr2LatProfileDialog({
super.key,
required this.settingsService,
this.profile,
});
@override
State<Cyr2LatProfileDialog> createState() => _Cyr2LatProfileDialogState();
}
class _Cyr2LatProfileDialogState extends State<Cyr2LatProfileDialog> {
late final TextEditingController _nameController = TextEditingController(
text: widget.profile?.name ?? '',
);
late final TextEditingController _jsonController = TextEditingController(
text: const JsonEncoder.withIndent(
' ',
).convert(widget.profile?.charMap ?? defaultCyr2LatCharMap),
);
bool _saving = false;
bool get _isEdit => widget.profile != null;
@override
void dispose() {
_nameController.dispose();
_jsonController.dispose();
super.dispose();
}
Future<void> _save() async {
final l10n = context.l10n;
final name = _nameController.text;
if (name.isEmpty) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_cyr2latProfileNameEmpty),
);
return;
}
final Map<String, String> map;
try {
final json = jsonDecode(_jsonController.text) as Map<String, dynamic>;
map = json.map((key, value) => MapEntry(key, value.toString()));
} catch (e) {
showDismissibleSnackBar(
context,
content: Text(l10n.channels_cyr2latSettingsDialogWrongJSON('$e')),
);
return;
}
setState(() => _saving = true);
try {
final existing = widget.profile;
if (existing != null) {
await widget.settingsService.updateCyr2LatProfile(
existing.copyWith(name: name, charMap: map),
);
} else {
await widget.settingsService.addCyr2LatProfile(
Cyr2LatProfile(
id: DateTime.now().millisecondsSinceEpoch.toString(),
name: name,
charMap: map,
),
);
}
if (!mounted) return;
Navigator.pop(context);
showDismissibleSnackBar(
context,
content: Text(
_isEdit
? l10n.settings_cyr2latProfileUpdated
: l10n.settings_cyr2latProfileAdded,
),
);
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error('$e')),
);
}
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog(
title: Text(
_isEdit
? l10n.settings_cyr2latProfileEdit
: l10n.settings_cyr2latProfileAdd,
),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _nameController,
decoration: InputDecoration(
labelText: l10n.settings_cyr2latProfileName,
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: _jsonController,
maxLines: 15,
decoration: InputDecoration(
labelText: l10n.channels_cyr2latSettingsDialogHint,
border: const OutlineInputBorder(),
hintText: l10n.channels_cyr2latSettingsDscr,
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: _saving ? null : _save,
child: Text(l10n.common_save),
),
],
);
}
}
+2 -2
View File
@@ -65,7 +65,7 @@ class DebugFrameViewer {
children: [
Text(
details.toString(),
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
),
const Divider(),
Text(
@@ -75,7 +75,7 @@ class DebugFrameViewer {
const SizedBox(height: 8),
Text(
hexString,
style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
),
],
),
+7 -3
View File
@@ -77,7 +77,7 @@ class DeviceTile extends StatelessWidget {
Text(
mac,
style: MeshTheme.mono(
fontSize: 11,
fontSize: 13,
color: scheme.onSurfaceVariant,
),
maxLines: 1,
@@ -101,11 +101,15 @@ class DeviceTile extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Icon(signalUi.icon, size: 16, color: signalUi.color),
Icon(signalUi.icon, size: 20, color: signalUi.color),
const SizedBox(height: 3),
Text(
'$rssi dBm',
style: MeshTheme.mono(fontSize: 10, color: signalUi.color),
style: MeshTheme.mono(
fontSize: 13,
fontWeight: FontWeight.w600,
color: signalUi.color,
),
),
],
),
+1 -1
View File
@@ -183,7 +183,7 @@ class _GifPickerState extends State<GifPicker> {
Text(
context.l10n.gifPicker_poweredBy,
style: TextStyle(
fontSize: 11,
fontSize: 12,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
+77
View File
@@ -0,0 +1,77 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import 'mesh_nav_tile.dart';
import 'mesh_ui.dart';
/// App UI languages offered in settings, in display order. A null code means
/// "follow the system language". Add a locale here (and only here) to make it
/// selectable and labelled.
final List<(String?, String Function(AppLocalizations))> appLanguageOptions = [
(null, (l) => l.appSettings_languageSystem),
('en', (l) => l.appSettings_languageEn),
('fr', (l) => l.appSettings_languageFr),
('es', (l) => l.appSettings_languageEs),
('de', (l) => l.appSettings_languageDe),
('pl', (l) => l.appSettings_languagePl),
('sl', (l) => l.appSettings_languageSl),
('pt', (l) => l.appSettings_languagePt),
('it', (l) => l.appSettings_languageIt),
('zh', (l) => l.appSettings_languageZh),
('sv', (l) => l.appSettings_languageSv),
('nl', (l) => l.appSettings_languageNl),
('sk', (l) => l.appSettings_languageSk),
('bg', (l) => l.appSettings_languageBg),
('ru', (l) => l.appSettings_languageRu),
('uk', (l) => l.appSettings_languageUk),
('hu', (l) => l.appSettings_languageHu),
('ja', (l) => l.appSettings_languageJa),
('ko', (l) => l.appSettings_languageKo),
];
/// Localized label for [languageCode]; unknown codes and null read as
/// "System".
String appLanguageLabel(BuildContext context, String? languageCode) {
final l10n = context.l10n;
for (final (code, label) in appLanguageOptions) {
if (code == languageCode) return label(l10n);
}
return l10n.appSettings_languageSystem;
}
/// Bottom sheet for choosing the app UI language override.
void showLanguagePickerSheet(
BuildContext context,
AppSettingsService settingsService,
) {
final l10n = context.l10n;
final current = settingsService.settings.languageOverride;
showMeshSheet(
context,
builder: (ctx) => Column(
mainAxisSize: MainAxisSize.min,
children: [
BottomSheetHeader(title: l10n.appSettings_language),
SizedBox(
height: 400,
child: ListView(
children: [
for (final (code, label) in appLanguageOptions)
MeshSheetOption(
label: label(l10n),
selected: current == code,
onTap: () {
settingsService.setLanguageOverride(code);
Navigator.pop(ctx);
},
),
SizedBox(height: MediaQuery.paddingOf(ctx).bottom + 8),
],
),
),
],
),
);
}
+121
View File
@@ -0,0 +1,121 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import '../theme/mesh_theme.dart';
/// Size in degrees of a square grid cell that covers roughly [cellPx]
/// screen pixels at [zoom] (Web Mercator, 256 px tiles).
double mapGridCellDegrees(double zoom, {double cellPx = 64}) =>
360.0 / (256.0 * pow(2.0, zoom)) * cellPx;
/// Key of the grid cell that [point] falls into for a cell size of [cellDeg].
String mapGridCellKey(LatLng point, double cellDeg) =>
'${(point.latitude / cellDeg).floor()}:${(point.longitude / cellDeg).floor()}';
/// Buckets [items] into grid cells of [cellDeg] degrees, keeping insertion
/// order inside each cell.
Map<String, List<T>> mapGridCluster<T>(
Iterable<T> items,
LatLng Function(T item) positionOf,
double cellDeg,
) {
final cells = <String, List<T>>{};
for (final item in items) {
(cells[mapGridCellKey(positionOf(item), cellDeg)] ??= <T>[]).add(item);
}
return cells;
}
/// Round marker that stands for several shared points of interest. When
/// [includesSelf] is set, it is drawn with the "You" ring and person icon so
/// the user's own position stays visible under the POIs placed there.
class PoiClusterMarker extends StatelessWidget {
final int count;
final bool includesSelf;
final String semanticLabel;
const PoiClusterMarker({
super.key,
required this.count,
required this.semanticLabel,
this.includesSelf = false,
});
@override
Widget build(BuildContext context) {
final circle = Container(
width: 40,
height: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: includesSelf ? MapPalette.panelDark : MapPalette.router,
border: Border.all(
color: includesSelf ? MapPalette.selected : MapPalette.markerOutline,
width: 3,
),
boxShadow: const [
BoxShadow(
color: MapPalette.markerShadow,
blurRadius: 8,
offset: Offset(0, 3),
),
],
),
alignment: Alignment.center,
child: includesSelf
? const Icon(
Icons.person_pin_circle,
color: MapPalette.selected,
size: 24,
)
: Text(
'$count',
style: MeshTheme.mono(
fontSize: count >= 100 ? 13 : 15,
fontWeight: FontWeight.w800,
color: MapPalette.markerOutline,
),
),
);
return Semantics(
button: true,
label: semanticLabel,
excludeSemantics: true,
child: Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: [
circle,
if (includesSelf)
Positioned(
right: -2,
top: -2,
child: Container(
constraints: const BoxConstraints(minWidth: 22, minHeight: 22),
padding: const EdgeInsets.symmetric(horizontal: 4),
decoration: BoxDecoration(
color: MapPalette.router,
borderRadius: BorderRadius.circular(MeshRadii.pill),
border: Border.all(
color: MapPalette.markerOutline,
width: 1.5,
),
),
alignment: Alignment.center,
child: Text(
'$count',
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w800,
color: MapPalette.markerOutline,
),
),
),
),
],
),
);
}
}
+127
View File
@@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
/// Settings-style navigation row: leading icon, bold title, secondary
/// subtitle and an optional trailing chevron.
///
/// Sized for readability (24px icons, `bodyLarge` titles, `bodyMedium`
/// subtitles). When [onTap] is null the row is rendered dimmed and reported
/// as disabled to accessibility services, so a tile that cannot be used never
/// looks identical to one that can.
class MeshNavTile extends StatelessWidget {
final IconData icon;
final String title;
final String? subtitle;
final VoidCallback? onTap;
final Color? titleColor;
final Color? iconColor;
final bool showChevron;
final Widget? trailing;
final int? subtitleMaxLines;
final EdgeInsetsGeometry padding;
const MeshNavTile({
super.key,
required this.icon,
required this.title,
this.subtitle,
this.onTap,
this.titleColor,
this.iconColor,
this.showChevron = true,
this.trailing,
this.subtitleMaxLines,
this.padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final textTheme = theme.textTheme;
final enabled = onTap != null;
final effectiveIconColor = iconColor ?? scheme.onSurfaceVariant;
final row = Row(
children: [
Icon(icon, size: 24, color: effectiveIconColor),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
color: titleColor,
),
),
if (subtitle != null) ...[
const SizedBox(height: 2),
Text(
subtitle!,
maxLines: subtitleMaxLines,
overflow: subtitleMaxLines == null
? null
: TextOverflow.ellipsis,
style: textTheme.bodyMedium?.copyWith(
color: titleColor != null
? titleColor!.withValues(alpha: 0.8)
: scheme.onSurfaceVariant,
),
),
],
],
),
),
?trailing,
if (showChevron && trailing == null)
Icon(Icons.chevron_right, color: scheme.onSurfaceVariant, size: 24),
],
);
return MergeSemantics(
child: Semantics(
button: true,
enabled: enabled,
child: InkWell(
onTap: onTap,
child: Padding(
padding: padding,
// Dimmed rather than recoloured so warn/alert tints still read as
// such while clearly unavailable.
child: Opacity(opacity: enabled ? 1 : 0.5, child: row),
),
),
),
);
}
}
/// One radio-style option row inside a bottom sheet picker.
class MeshSheetOption extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback onTap;
const MeshSheetOption({
super.key,
required this.label,
required this.selected,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return ListTile(
leading: Icon(
selected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: selected ? scheme.primary : scheme.onSurfaceVariant,
),
title: Text(label),
onTap: onTap,
);
}
}
+33 -10
View File
@@ -1,3 +1,5 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -34,7 +36,10 @@ class SectionHeader extends StatelessWidget {
Expanded(
child: Text(
label.toUpperCase(),
style: MeshTheme.accentLabel(color: scheme.onSurfaceVariant),
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 13,
),
overflow: TextOverflow.ellipsis,
),
),
@@ -114,7 +119,7 @@ class StatusChip extends StatelessWidget {
required this.color,
this.icon,
this.pulse = false,
this.fontSize = 11.5,
this.fontSize = 12.5,
});
@override
@@ -192,7 +197,7 @@ class StatTile extends StatelessWidget {
label.toUpperCase(),
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 11,
fontSize: 12,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -217,7 +222,7 @@ class StatTile extends StatelessWidget {
TextSpan(
text: ' $unit',
style: MeshTheme.mono(
fontSize: 11,
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
@@ -377,7 +382,7 @@ class RouteChip extends StatelessWidget {
children: [
Icon(
isDirect ? Icons.trending_flat : Icons.podcasts,
size: 11,
size: 14,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 3),
@@ -385,7 +390,7 @@ class RouteChip extends StatelessWidget {
label,
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 8.5,
fontSize: 12,
),
),
],
@@ -539,6 +544,11 @@ class BottomSheetHeader extends StatelessWidget {
/// Shows a modal bottom sheet with the app-standard shape, scroll behavior
/// and safe-area handling. Pair the content with [BottomSheetHeader].
///
/// `useSafeArea` only pads the top and sides, so the bottom is padded here by
/// whichever is larger: the keyboard inset or the system navigation bar
/// (edge-to-edge Android, iOS home indicator). Both are then removed from the
/// content's [MediaQuery] so nested [SafeArea]s don't apply them twice.
Future<T?> showMeshSheet<T>(
BuildContext context, {
required WidgetBuilder builder,
@@ -549,10 +559,23 @@ Future<T?> showMeshSheet<T>(
isScrollControlled: isScrollControlled,
useSafeArea: true,
showDragHandle: false,
builder: (context) => Padding(
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: builder(context),
),
builder: (sheetContext) {
final media = MediaQuery.of(sheetContext);
final bottom = math.max(
media.viewInsets.bottom,
media.viewPadding.bottom,
);
return Padding(
padding: EdgeInsets.only(bottom: bottom),
child: MediaQuery(
data: media
.removeViewInsets(removeBottom: true)
.removeViewPadding(removeBottom: true)
.removePadding(removeBottom: true),
child: Builder(builder: builder),
),
);
},
);
}
+129
View File
@@ -0,0 +1,129 @@
import 'package:flutter/material.dart';
import '../theme/mesh_theme.dart';
/// Colours shared by the direct-message and channel chat bubbles.
@immutable
class MessageBubbleColors {
final Color background;
final Color border;
final Color text;
final Color meta;
const MessageBubbleColors({
required this.background,
required this.border,
required this.text,
required this.meta,
});
/// Outgoing bubbles use [MeshPalette.me] / [MeshPalette.meBorder] /
/// [MeshPalette.meInk]; a failed send switches to the error container.
factory MessageBubbleColors.of(
ColorScheme scheme, {
required bool isOutgoing,
bool isFailed = false,
}) {
final text = isFailed
? scheme.onErrorContainer
: isOutgoing
? MeshPalette.meInk
: scheme.onSurface;
return MessageBubbleColors(
background: isFailed
? scheme.errorContainer
: isOutgoing
? MeshPalette.me
: scheme.surfaceContainerLow,
border: isFailed
? scheme.error
: isOutgoing
? MeshPalette.meBorder
: scheme.outlineVariant,
text: text,
meta: text.withValues(alpha: 0.65),
);
}
}
/// Asymmetric bubble radius: the corner nearest the sender is tight.
BorderRadius messageBubbleRadius({required bool isOutgoing}) {
return isOutgoing
? const BorderRadius.only(
topLeft: Radius.circular(MeshRadii.lg),
topRight: Radius.circular(MeshRadii.lg),
bottomLeft: Radius.circular(MeshRadii.lg),
bottomRight: Radius.circular(MeshRadii.xs),
)
: const BorderRadius.only(
topLeft: Radius.circular(MeshRadii.xs),
topRight: Radius.circular(MeshRadii.lg),
bottomLeft: Radius.circular(MeshRadii.lg),
bottomRight: Radius.circular(MeshRadii.lg),
);
}
/// Extra sender-name hues beyond the [MeshPalette] accents. They match the
/// two extra hues [AvatarCircle] uses, so a name and its avatar agree.
const Color kSenderHuePeriwinkle = Color(0xFF8FA8F0);
const Color kSenderHueAqua = Color(0xFF6FD9CE);
const List<Color> _senderHues = [
MeshPalette.blue,
MeshPalette.magenta,
MeshPalette.signal,
MeshPalette.warn,
kSenderHuePeriwinkle,
kSenderHueAqua,
];
/// Deterministic name-to-hue mapping consistent with [AvatarCircle].
Color senderNameColor(String name) {
var h = 0;
for (final c in name.codeUnits) {
h = (h * 31 + c) & 0x7fffffff;
}
return _senderHues[h % _senderHues.length];
}
/// The bubble container shared by both chat screens: colour, border,
/// asymmetric radius, padding and the 72% max width.
class MessageBubbleFrame extends StatelessWidget {
final bool isOutgoing;
final bool isFailed;
/// Tighter padding for media (GIF) content.
final bool compact;
final double maxWidth;
final Widget child;
const MessageBubbleFrame({
super.key,
required this.isOutgoing,
required this.maxWidth,
required this.child,
this.isFailed = false,
this.compact = false,
});
@override
Widget build(BuildContext context) {
final colors = MessageBubbleColors.of(
Theme.of(context).colorScheme,
isOutgoing: isOutgoing,
isFailed: isFailed,
);
return Container(
padding: compact
? const EdgeInsets.all(4)
: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
constraints: BoxConstraints(maxWidth: maxWidth * 0.72),
decoration: BoxDecoration(
color: colors.background,
borderRadius: messageBubbleRadius(isOutgoing: isOutgoing),
border: Border.all(color: colors.border, width: 1),
),
child: child,
);
}
}
+4 -29
View File
@@ -9,6 +9,7 @@ import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import 'contact_visuals.dart';
import 'mesh_ui.dart';
/// Opens the nearby-node scan (#570): a zero-hop DISCOVER_REQ whose answers
@@ -180,7 +181,7 @@ class _NodeScanSheetState extends State<NodeScanSheet> {
final known = _isKnownNode(contact);
final inContacts = _isContact(response);
final adding = _adding.contains(response.publicKeyHex);
final color = _typeColor(response.nodeType);
final color = contactTypeColor(response.nodeType);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
@@ -192,7 +193,7 @@ class _NodeScanSheetState extends State<NodeScanSheet> {
name: contact.name,
size: 42,
color: color,
icon: _typeIcon(response.nodeType),
icon: contactTypeIcon(response.nodeType),
),
const SizedBox(width: 12),
Expanded(
@@ -217,7 +218,7 @@ class _NodeScanSheetState extends State<NodeScanSheet> {
StatusChip(
label: contact.typeLabel(l10n).toUpperCase(),
color: color,
icon: _typeIcon(response.nodeType),
icon: contactTypeIcon(response.nodeType),
),
],
),
@@ -281,30 +282,4 @@ class _NodeScanSheetState extends State<NodeScanSheet> {
widget.connector.discoveredContacts.any(
(c) => c.publicKeyHex == contact.publicKeyHex,
);
static Color _typeColor(int type) {
switch (type) {
case advTypeRepeater:
return MeshPalette.warn;
case advTypeRoom:
return MeshPalette.magenta;
case advTypeSensor:
return const Color(0xFF4ACCC4); // teal, as in the discovery list
default:
return MeshPalette.blue;
}
}
static IconData? _typeIcon(int type) {
switch (type) {
case advTypeRepeater:
return Icons.cell_tower;
case advTypeRoom:
return Icons.meeting_room;
case advTypeSensor:
return Icons.sensors;
default:
return null;
}
}
}
+506
View File
@@ -0,0 +1,506 @@
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/guessed_location_estimator.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../models/display_path.dart';
import '../models/path_playback.dart';
import '../theme/mesh_theme.dart';
import 'path_map_ui.dart';
/// Shared map plumbing for the path map screens (live path trace and
/// received-message path map): camera helpers, map options, desktop zoom
/// controls, node labels, and the collapsible bottom panel shell.
const double kPathMapMinZoom = 2.0;
const double kPathMapMaxZoom = 18.0;
const double kPathMapLabelZoomThreshold = 8.5;
const EdgeInsets _fitPadding = EdgeInsets.all(64);
bool isDesktopMapPlatform([TargetPlatform? platform]) {
final p = platform ?? defaultTargetPlatform;
return p == TargetPlatform.linux ||
p == TargetPlatform.windows ||
p == TargetPlatform.macOS;
}
/// The connected radio's position, or null when it is unknown (disconnected)
/// or not a real fix (SELF_INFO reports 0,0 without GPS).
LatLng? plausibleSelfPoint(MeshCoreConnector connector) {
final lat = connector.selfLatitude;
final lon = connector.selfLongitude;
if (lat == null || lon == null || !isPlausibleLocation(lat, lon)) {
return null;
}
return LatLng(lat, lon);
}
/// Cheap fingerprint of the fields path resolution depends on, used to skip
/// re-resolving hops when the connector notifies for unrelated reasons.
int contactListSignature(List<Contact> contacts) {
return Object.hash(
contacts.length,
Object.hashAll(
contacts.map(
(c) => Object.hash(
Object.hashAll(c.publicKey.take(8)),
c.type,
c.name,
c.latitude,
c.longitude,
c.lastSeen,
c.path.length,
),
),
),
);
}
bool sameLatLngList(List<LatLng> a, List<LatLng> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
/// Updates the playback path only when its geometry actually changed, so
/// unrelated rebuilds don't reset a running animation.
void syncPlaybackPath(PathPlaybackController playback, List<LatLng> points) {
if (sameLatLngList(points, playback.points)) return;
playback.setPath(points);
}
/// Keeps the camera centered on the packet while the follow lock is on.
void followPacketCamera(
MapController controller,
PathPlaybackController playback, {
required bool enabled,
}) {
if (!enabled || !playback.started || !playback.hasPath) return;
controller.move(playback.position, controller.camera.zoom);
}
void zoomMapBy(
MapController controller,
double delta, {
double minZoom = kPathMapMinZoom,
double maxZoom = kPathMapMaxZoom,
}) {
final camera = controller.camera;
final nextZoom = (camera.zoom + delta).clamp(minZoom, maxZoom).toDouble();
controller.move(camera.center, nextZoom);
}
void resetMapView(
MapController controller, {
required LatLngBounds? bounds,
required LatLng? center,
required double zoom,
}) {
if (bounds != null) {
controller.fitCamera(
CameraFit.bounds(bounds: bounds, padding: _fitPadding, maxZoom: 16),
);
return;
}
if (center != null) controller.move(center, zoom);
}
/// Map options shared by the path and line-of-sight maps: no rotation,
/// desktop keyboard panning/zooming, and an initial fit to [bounds].
MapOptions buildPathMapOptions({
required LatLng initialCenter,
required double initialZoom,
required LatLngBounds? bounds,
double minZoom = kPathMapMinZoom,
double maxZoom = kPathMapMaxZoom,
PositionCallback? onPositionChanged,
TapCallback? onLongPress,
TapCallback? onSecondaryTap,
}) {
final isDesktop = isDesktopMapPlatform();
return MapOptions(
initialCenter: initialCenter,
initialZoom: initialZoom,
initialCameraFit: bounds == null
? null
: CameraFit.bounds(bounds: bounds, padding: _fitPadding, maxZoom: 16),
minZoom: minZoom,
maxZoom: maxZoom,
interactionOptions: InteractionOptions(
flags: ~InteractiveFlag.rotate,
scrollWheelVelocity: isDesktop ? 0.012 : 0.005,
cursorKeyboardRotationOptions: CursorKeyboardRotationOptions.disabled(),
keyboardOptions: isDesktop
? const KeyboardOptions(
enableArrowKeysPanning: true,
enableWASDPanning: true,
enableRFZooming: true,
)
: const KeyboardOptions.disabled(),
),
onPositionChanged: onPositionChanged,
onLongPress: onLongPress,
onSecondaryTap: onSecondaryTap,
);
}
/// Floating zoom in/out/recenter buttons for desktop platforms.
class PathMapDesktopControls extends StatelessWidget {
final VoidCallback onZoomIn;
final VoidCallback onZoomOut;
final VoidCallback onReset;
const PathMapDesktopControls({
super.key,
required this.onZoomIn,
required this.onZoomOut,
required this.onReset,
});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Positioned(
top: 16,
left: 16,
child: DecoratedBox(
decoration: BoxDecoration(
color: MeshPalette.bg1.withValues(alpha: 0.90),
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MeshPalette.line2),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(MeshRadii.md),
child: IconTheme(
data: const IconThemeData(color: MeshPalette.ink),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.add),
color: MeshPalette.ink,
tooltip: l10n.map_zoomIn,
onPressed: onZoomIn,
),
IconButton(
icon: const Icon(Icons.remove),
color: MeshPalette.ink,
tooltip: l10n.map_zoomOut,
onPressed: onZoomOut,
),
IconButton(
icon: const Icon(Icons.my_location),
color: MeshPalette.ink,
tooltip: l10n.map_centerMap,
onPressed: onReset,
),
],
),
),
),
),
);
}
}
/// Name label floating above a node marker.
Marker buildPathNodeLabelMarker({
required LatLng point,
required String label,
}) {
return Marker(
point: point,
width: 140,
height: 26,
alignment: Alignment.topCenter,
child: IgnorePointer(
child: Transform.translate(
offset: const Offset(0, -20),
child: FittedBox(
fit: BoxFit.contain,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: MeshPalette.bg.withValues(alpha: 0.85),
borderRadius: BorderRadius.circular(MeshRadii.xs),
border: Border.all(color: MeshPalette.line, width: 0.5),
),
alignment: Alignment.center,
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w600,
color: MeshPalette.ink,
),
),
),
),
),
),
);
}
/// Small count badge drawn on markers for repeaters shared by several paths.
class PathSharedCountBadge extends StatelessWidget {
final int count;
const PathSharedCountBadge({super.key, required this.count});
@override
Widget build(BuildContext context) {
return Container(
width: 20,
height: 20,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: MeshPalette.bg1,
border: Border.all(color: MeshPalette.line3),
),
alignment: Alignment.center,
child: Text(
'$count',
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w700,
color: MeshPalette.ink,
),
),
);
}
}
/// Dark, collapsible bottom panel shared by the path map screens: header
/// with distance and legend, playback controls, warnings, optional
/// multi-path summary, and the hop list.
///
/// Sets dark-panel text/icon/divider colours explicitly so content does not
/// inherit light-theme colours.
class PathMapBottomPanel extends StatelessWidget {
final Widget header;
final bool combined;
final bool showInferredLegend;
final bool collapsed;
final VoidCallback onToggleCollapsed;
final PathPlaybackController playback;
final DisplayPath? selected;
final bool animationEnabled;
final VoidCallback onToggleAnimation;
final bool followEnabled;
final VoidCallback onToggleFollow;
final bool showNoSelfGpsNote;
final int pathCount;
final int hopRowCount;
final Widget? summary;
final Widget hopList;
const PathMapBottomPanel({
super.key,
required this.header,
required this.combined,
required this.showInferredLegend,
required this.collapsed,
required this.onToggleCollapsed,
required this.playback,
required this.selected,
required this.animationEnabled,
required this.onToggleAnimation,
required this.followEnabled,
required this.onToggleFollow,
required this.showNoSelfGpsNote,
required this.pathCount,
required this.hopRowCount,
required this.summary,
required this.hopList,
});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final maxHeight =
MediaQuery.of(context).size.height * (combined ? 0.45 : 0.35);
const hopRowHeight = 60.0;
double? cardHeight;
if (!collapsed) {
final summaryHeight = combined ? 34.0 + pathCount * 40.0 : 0.0;
final noteHeight = showNoSelfGpsNote ? 22.0 : 0.0;
final estimatedHeight =
150.0 + summaryHeight + noteHeight + hopRowCount * hopRowHeight;
cardHeight = max(196.0, min(maxHeight, estimatedHeight));
}
final warnStyle = const TextStyle(fontSize: 12, color: MeshPalette.warn);
final unresolved = selected?.unresolvedHops ?? 0;
return Positioned(
left: 16,
right: 16,
bottom: 16,
child: SizedBox(
height: cardHeight,
child: Container(
decoration: BoxDecoration(
color: MeshPalette.bg1.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MeshPalette.line2),
),
clipBehavior: Clip.antiAlias,
child: DefaultTextStyle.merge(
style: const TextStyle(color: MeshPalette.ink),
child: IconTheme(
data: const IconThemeData(color: MeshPalette.ink),
child: DividerTheme(
data: const DividerThemeData(color: MeshPalette.line),
child: ListTileTheme(
data: const ListTileThemeData(
iconColor: MeshPalette.ink2,
textColor: MeshPalette.ink,
),
child: TextButtonTheme(
data: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: MeshPalette.ink,
),
),
child: LayoutBuilder(
builder: (context, constraints) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: max(
0.0,
constraints.maxHeight -
(collapsed ? 0.0 : hopRowHeight + 1.0),
),
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
12,
8,
4,
0,
),
child: Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
header,
const SizedBox(height: 4),
PathMiniLegend(
combined: combined,
showInferred:
showInferredLegend,
),
],
),
),
IconButton(
icon: Icon(
collapsed
? Icons.expand_less
: Icons.expand_more,
),
color: MeshPalette.ink,
tooltip: collapsed
? l10n.pathMap_expandPanel
: l10n.pathMap_collapsePanel,
onPressed: onToggleCollapsed,
),
],
),
),
PathAnimationControls(
playback: playback,
selected: selected,
animationEnabled: animationEnabled,
onToggleAnimation: onToggleAnimation,
followEnabled: followEnabled,
onToggleFollow: onToggleFollow,
),
if (!collapsed) ...[
if (showNoSelfGpsNote)
Padding(
padding: const EdgeInsets.fromLTRB(
12,
0,
12,
4,
),
child: Row(
children: [
const Icon(
Icons.gps_off,
size: 16,
color: MeshPalette.warn,
),
const SizedBox(width: 6),
Expanded(
child: Text(
l10n.pathMap_noSelfGpsFix,
style: warnStyle,
),
),
],
),
),
if (unresolved > 0)
Padding(
padding: const EdgeInsets.fromLTRB(
12,
0,
12,
4,
),
child: Text(
l10n.pathMap_partialAnimation(
unresolved,
),
style: warnStyle,
),
),
?summary,
],
],
),
),
),
if (!collapsed) ...[
const Divider(height: 1),
Expanded(child: hopList),
],
],
),
),
),
),
),
),
),
),
),
);
}
}
+100 -84
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../models/display_path.dart';
import '../models/path_playback.dart';
@@ -13,7 +14,7 @@ import '../theme/mesh_theme.dart';
enum PathViewMode { single, combined }
const Color kPrimaryPathColor = Colors.blueAccent;
const Color kPrimaryPathColor = MeshPalette.blue;
const List<Color> kAlternatePathColors = [
Color(0xFF8B5CF6), // purple
MeshPalette.signal, // green
@@ -34,11 +35,15 @@ double getPathDistanceMeters(List<LatLng> points) {
return distanceMeters;
}
String formatDistance(double distanceMeters, {required bool isImperial}) {
String formatDistance(
double distanceMeters, {
required bool isImperial,
AppLocalizations? l10n,
}) {
if (isImperial) {
return '(${(distanceMeters / 1609.34).toStringAsFixed(2)} mi)';
return '(${(distanceMeters / 1609.34).toStringAsFixed(2)} ${l10n?.units_mi ?? 'mi'})';
}
return '(${(distanceMeters / 1000).toStringAsFixed(2)} km)';
return '(${(distanceMeters / 1000).toStringAsFixed(2)} ${l10n?.units_km ?? 'km'})';
}
String formatLastObserved(BuildContext context, DateTime timestamp) {
@@ -87,7 +92,7 @@ List<Polyline> buildMultiPathPolylines({
Polyline(
points: [path.points[i], path.points[i + 1]],
strokeWidth: 11,
color: Colors.white.withValues(alpha: 0.22),
color: MapPalette.markerOutline.withValues(alpha: 0.22),
),
);
}
@@ -153,7 +158,7 @@ List<Polyline> buildPacketTrailPolylines(
Polyline(
points: [playback.points[seg], playback.position],
strokeWidth: 8,
color: Colors.white.withValues(alpha: 0.45),
color: MapPalette.markerOutline.withValues(alpha: 0.45),
),
Polyline(points: traversed, strokeWidth: 5, color: color),
];
@@ -201,7 +206,7 @@ List<Marker> buildPacketMarkers(PathPlaybackController playback, Color color) {
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
border: Border.all(color: Colors.white, width: 2),
border: Border.all(color: MapPalette.markerOutline, width: 2),
boxShadow: [
BoxShadow(
color: color.withValues(alpha: 0.7),
@@ -262,7 +267,7 @@ void showSharedNodeSheet(
),
trailing: Text(
l10n.pathMap_hopCount(path.totalTransmissions),
style: MeshTheme.mono(fontSize: 11, color: MeshPalette.ink3),
style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3),
),
onTap: () {
Navigator.pop(sheetContext);
@@ -380,82 +385,92 @@ class PathAnimationControls extends StatelessWidget {
VoidCallback? onPressed,
Color? color,
}) => IconButton(
icon: Icon(icon, size: 20, color: color),
icon: Icon(icon, size: 24, color: color),
tooltip: tooltip,
onPressed: onPressed,
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 34, minHeight: 34),
constraints: const BoxConstraints(minWidth: 48, minHeight: 48),
);
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 12, 2),
child: Row(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
controlButton(
icon: Icons.animation,
tooltip: animationEnabled
? l10n.pathMap_animationOff
: l10n.pathMap_animationOn,
color: animationEnabled ? MeshPalette.blue : MeshPalette.ink4,
onPressed: onToggleAnimation,
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
controlButton(
icon: Icons.animation,
tooltip: animationEnabled
? l10n.pathMap_animationOff
: l10n.pathMap_animationOn,
color: animationEnabled
? MeshPalette.blue
: MeshPalette.ink4,
onPressed: onToggleAnimation,
),
controlButton(
icon: Icons.skip_previous,
tooltip: l10n.pathMap_stepBack,
onPressed: enabled && playback.started
? playback.stepBack
: null,
),
controlButton(
icon: playback.playing ? Icons.pause : Icons.play_arrow,
tooltip: playback.playing
? l10n.pathMap_pause
: l10n.pathMap_play,
onPressed: enabled ? playback.togglePlay : null,
),
controlButton(
icon: Icons.skip_next,
tooltip: l10n.pathMap_stepForward,
onPressed: enabled ? playback.stepForward : null,
),
controlButton(
icon: Icons.replay,
tooltip: l10n.pathMap_replay,
onPressed: enabled ? playback.replay : null,
),
controlButton(
icon: followEnabled ? Icons.lock : Icons.lock_open,
tooltip: followEnabled
? l10n.pathMap_unfollowPacket
: l10n.pathMap_followPacket,
color: followEnabled ? MeshPalette.blue : null,
onPressed: enabled ? onToggleFollow : null,
),
TextButton(
onPressed: enabled ? playback.cycleSpeed : null,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(48, 48),
),
child: Text(
playback.speed == 0.5
? '0.5×'
: '${playback.speed.toInt()}×',
style: MeshTheme.mono(fontSize: 14),
),
),
],
),
controlButton(
icon: Icons.skip_previous,
tooltip: l10n.pathMap_stepBack,
onPressed: enabled && playback.started
? playback.stepBack
: null,
),
controlButton(
icon: playback.playing ? Icons.pause : Icons.play_arrow,
tooltip: playback.playing
? l10n.pathMap_pause
: l10n.pathMap_play,
onPressed: enabled ? playback.togglePlay : null,
),
controlButton(
icon: Icons.skip_next,
tooltip: l10n.pathMap_stepForward,
onPressed: enabled ? playback.stepForward : null,
),
controlButton(
icon: Icons.replay,
tooltip: l10n.pathMap_replay,
onPressed: enabled ? playback.replay : null,
),
controlButton(
icon: followEnabled ? Icons.lock : Icons.lock_open,
tooltip: followEnabled
? l10n.pathMap_unfollowPacket
: l10n.pathMap_followPacket,
color: followEnabled ? MeshPalette.blue : null,
onPressed: enabled ? onToggleFollow : null,
),
TextButton(
onPressed: enabled ? playback.cycleSpeed : null,
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 6),
minimumSize: const Size(36, 30),
),
child: Text(
playback.speed == 0.5 ? '0.5×' : '${playback.speed.toInt()}×',
style: MeshTheme.mono(fontSize: 12),
),
),
Expanded(
child: Text(
hopLabel ?? '',
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
style: MeshTheme.mono(
fontSize: 10.5,
color: MeshPalette.ink2,
if (hopLabel != null)
Padding(
padding: const EdgeInsets.only(left: 8),
child: Text(
hopLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: MeshTheme.mono(
fontSize: 12,
color: MeshPalette.ink2,
),
),
),
),
],
),
);
@@ -483,7 +498,12 @@ class PathMiniLegend extends StatelessWidget {
children: [
swatch,
const SizedBox(width: 4),
Text(text, style: TextStyle(fontSize: 11, color: MeshPalette.ink3)),
Flexible(
child: Text(
text,
style: TextStyle(fontSize: 12, color: MeshPalette.ink3),
),
),
],
);
Widget dashSample() => Row(
@@ -511,7 +531,7 @@ class PathMiniLegend extends StatelessWidget {
width: 14,
height: 6,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.35),
color: MapPalette.markerOutline.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(3),
),
),
@@ -572,7 +592,7 @@ class PathSummaryList extends StatelessWidget {
),
child: Text(
l10n.pathMap_showAllPaths,
style: const TextStyle(fontSize: 11),
style: const TextStyle(fontSize: 12),
),
),
],
@@ -590,7 +610,7 @@ class PathSummaryList extends StatelessWidget {
final hidden = hiddenIds.contains(path.id);
final timestamp = path.record?.timestamp;
final parts = <String>[
'${l10n.pathMap_hopCount(path.totalTransmissions)} ${formatDistance(path.distanceMeters, isImperial: isImperial)}',
'${l10n.pathMap_hopCount(path.totalTransmissions)} ${formatDistance(path.distanceMeters, isImperial: isImperial, l10n: l10n)}',
l10n.pathMap_gpsCount(path.gpsConfirmedHops, path.hopBytes.length),
if (timestamp != null) formatLastObserved(context, timestamp),
];
@@ -634,23 +654,19 @@ class PathSummaryList extends StatelessWidget {
parts.join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: MeshTheme.mono(
fontSize: 10.5,
color: MeshPalette.ink3,
),
style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3),
),
),
),
IconButton(
icon: Icon(
hidden ? Icons.visibility_off : Icons.visibility,
size: 16,
size: 20,
color: hidden ? MeshPalette.ink4 : MeshPalette.ink3,
),
tooltip: hidden ? l10n.pathMap_showPath : l10n.pathMap_hidePath,
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 30, minHeight: 30),
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
onPressed: () => onToggleVisibility(path),
),
],
+124 -60
View File
@@ -2,7 +2,36 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
/// Size of the square scan window cut out of the overlay.
const double _scanWindowSize = 250;
/// Full-screen spinner shown in place of the scanner while a scanned code is
/// being processed (stops the camera and prevents duplicate detections).
class QrScannerProcessingBody extends StatelessWidget {
const QrScannerProcessingBody({super.key});
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: const Center(child: CircularProgressIndicator()),
);
}
}
/// Short warning snackbar for a QR code that isn't the expected kind.
void showInvalidQrSnackBar(BuildContext context, String message) {
showDismissibleSnackBar(
context,
content: Text(message),
backgroundColor: MeshPalette.warn,
duration: const Duration(seconds: 2),
);
}
/// A reusable QR code scanner widget that can be embedded anywhere.
///
@@ -33,6 +62,11 @@ class QrScannerWidget extends StatefulWidget {
/// Custom overlay widget (defaults to scan window frame)
final Widget? overlay;
/// Use the app-themed overlay (accent corner brackets and a high-contrast
/// instructions pill) instead of the plain default. Ignored when [overlay]
/// is given.
final bool themed;
/// Instructions text shown below the scan window
final String? instructions;
@@ -50,6 +84,7 @@ class QrScannerWidget extends StatefulWidget {
this.showFlashButton = true,
this.showCameraSwitchButton = true,
this.overlay,
this.themed = false,
this.instructions,
this.continuousScanning = false,
this.debounceDuration = const Duration(milliseconds: 500),
@@ -184,55 +219,79 @@ class _QrScannerWidgetState extends State<QrScannerWidget>
}
Widget _buildDefaultOverlay(BuildContext context) {
return ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.black.withValues(alpha: 0.5),
BlendMode.srcOut,
),
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: const BoxDecoration(
color: Colors.black,
backgroundBlendMode: BlendMode.dstOut,
),
final instructions = widget.instructions;
return Stack(
fit: StackFit.expand,
children: [
// Dimmed background with a transparent cutout for the scan window.
ColorFiltered(
colorFilter: ColorFilter.mode(
MeshPalette.bg.withValues(alpha: 0.55),
BlendMode.srcOut,
),
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: const BoxDecoration(
color: MeshPalette.bg,
backgroundBlendMode: BlendMode.dstOut,
),
),
Center(
child: Container(
height: _scanWindowSize,
width: _scanWindowSize,
decoration: BoxDecoration(
// Any opaque colour: it only defines the cutout shape.
color: MeshPalette.ink,
borderRadius: BorderRadius.circular(16),
),
),
),
],
),
),
if (widget.themed)
const ScannerCornerOverlay(
scanWindowSize: _scanWindowSize,
borderColor: MeshPalette.blue,
borderWidth: 3,
cornerLength: 28,
),
// Instructions pill below the scan window.
if (instructions != null)
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: _scanWindowSize + 24),
Container(
height: 250,
width: 250,
margin: const EdgeInsets.symmetric(horizontal: 24),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 12,
),
decoration: BoxDecoration(
color: Colors.red, // This color is used for cutout
borderRadius: BorderRadius.circular(16),
color: MeshPalette.bg.withValues(alpha: 0.85),
borderRadius: BorderRadius.circular(
widget.themed ? MeshRadii.pill : 8,
),
),
child: Text(
instructions,
style: const TextStyle(
color: MeshPalette.ink,
fontSize: 16,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
),
if (widget.instructions != null) ...[
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(8),
),
child: Text(
widget.instructions!,
style: const TextStyle(color: Colors.white, fontSize: 14),
textAlign: TextAlign.center,
),
),
],
],
),
),
],
),
],
);
}
@@ -251,10 +310,7 @@ class _QrScannerWidgetState extends State<QrScannerWidget>
? Icons.flash_on
: Icons.flash_off,
),
style: IconButton.styleFrom(
backgroundColor: Colors.black54,
foregroundColor: Colors.white,
),
style: _controlStyle,
);
},
),
@@ -264,15 +320,19 @@ class _QrScannerWidgetState extends State<QrScannerWidget>
IconButton.filled(
onPressed: () => _controller.switchCamera(),
icon: const Icon(Icons.cameraswitch),
style: IconButton.styleFrom(
backgroundColor: Colors.black54,
foregroundColor: Colors.white,
),
style: _controlStyle,
),
],
);
}
static final ButtonStyle _controlStyle = IconButton.styleFrom(
backgroundColor: MeshPalette.bg.withValues(alpha: 0.7),
foregroundColor: MeshPalette.ink,
minimumSize: const Size(56, 56),
iconSize: 28,
);
Widget _buildErrorWidget(BuildContext context, MobileScannerException error) {
String message;
IconData icon;
@@ -293,20 +353,24 @@ class _QrScannerWidgetState extends State<QrScannerWidget>
icon = Icons.error_outline;
}
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
message,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey[600], fontSize: 16),
),
],
final scheme = Theme.of(context).colorScheme;
return ColoredBox(
color: scheme.surface,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 64, color: scheme.onSurfaceVariant),
const SizedBox(height: 16),
Text(
message,
textAlign: TextAlign.center,
style: TextStyle(color: scheme.onSurface, fontSize: 16),
),
],
),
),
),
);
@@ -323,7 +387,7 @@ class ScannerCornerOverlay extends StatelessWidget {
const ScannerCornerOverlay({
super.key,
this.scanWindowSize = 250,
this.borderColor = Colors.white,
this.borderColor = MeshPalette.ink,
this.borderWidth = 3,
this.cornerLength = 30,
});
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
/// Inline warning shown at the top of repeater screens while the companion
/// radio is disconnected. Renders nothing while connected.
class RadioDisconnectedBanner extends StatelessWidget {
const RadioDisconnectedBanner({super.key});
@override
Widget build(BuildContext context) {
final connected = context.select<MeshCoreConnector, bool>(
(c) => c.isConnected,
);
if (connected) return const SizedBox.shrink();
final scheme = Theme.of(context).colorScheme;
final textTheme = Theme.of(context).textTheme;
return Semantics(
liveRegion: true,
child: Material(
color: scheme.errorContainer,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(Icons.link_off, size: 24, color: scheme.onErrorContainer),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.repeater_radioDisconnected,
style: textTheme.titleSmall?.copyWith(
color: scheme.onErrorContainer,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
context.l10n.repeater_radioDisconnectedHint,
style: textTheme.bodyMedium?.copyWith(
color: scheme.onErrorContainer,
),
),
],
),
),
],
),
),
),
);
}
}
+794
View File
@@ -0,0 +1,794 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/radio_settings.dart';
import '../services/app_debug_log_service.dart';
/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others)
/// to the UI enum range (always 5-8).
int _toUiCodingRate(int deviceCr) {
return deviceCr <= 4 ? deviceCr + 4 : deviceCr;
}
const Set<int> _defaultRepeatFreqsKHz = {433000, 869495, 918000};
/// Whether the firmware accepts [freqKHz] for off-grid client repeat, using
/// the ranges from CMD_GET_ALLOWED_REPEAT_FREQ when known.
bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) {
final ranges = connector.allowedRepeatFreqRanges;
if (ranges == null || ranges.isEmpty) {
return _defaultRepeatFreqsKHz.contains(freqKHz);
}
return ranges.any((r) => freqKHz >= r.lowKHz && freqKHz <= r.highKHz);
}
/// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER).
const int _minTxPowerDbm = -9;
/// Radio parameter editor (preset, frequency, bandwidth, SF, CR, TX power and
/// off-grid client repeat). Stays open when the radio rejects or fails to
/// apply the settings so the user's edits are not lost.
class RadioSettingsDialog extends StatefulWidget {
final MeshCoreConnector connector;
const RadioSettingsDialog({super.key, required this.connector});
@override
State<RadioSettingsDialog> createState() => _RadioSettingsDialogState();
}
class _RadioSettingsDialogState extends State<RadioSettingsDialog> {
final _frequencyController = TextEditingController();
LoRaBandwidth _bandwidth = LoRaBandwidth.bw125;
LoRaSpreadingFactor _spreadingFactor = LoRaSpreadingFactor.sf7;
LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5;
final _txPowerController = TextEditingController(text: '20');
bool _clientRepeat = false;
int? _selectedPresetIndex;
_RadioSettingsSnapshot? _lastNonRepeatSnapshot;
String? _frequencyError;
String? _txPowerError;
AppDebugLogService get _appLog =>
Provider.of<AppDebugLogService>(context, listen: false);
@override
void initState() {
super.initState();
// Populate with current settings if available
if (widget.connector.currentFreqHz != null) {
_frequencyController.text = (widget.connector.currentFreqHz! / 1000.0)
.toStringAsFixed(3);
} else {
_frequencyController.text = '915.0';
}
if (widget.connector.currentBwHz != null) {
// Find matching bandwidth enum
final bwValue = widget.connector.currentBwHz!;
for (var bw in LoRaBandwidth.values) {
if (bw.hz == bwValue) {
_bandwidth = bw;
break;
}
}
}
if (widget.connector.currentSf != null) {
// Find matching spreading factor enum
final sfValue = widget.connector.currentSf!;
for (var sf in LoRaSpreadingFactor.values) {
if (sf.value == sfValue) {
_spreadingFactor = sf;
break;
}
}
}
if (widget.connector.currentCr != null) {
// Find matching coding rate enum
final crValue = _toUiCodingRate(widget.connector.currentCr!);
for (var cr in LoRaCodingRate.values) {
if (cr.value == crValue) {
_codingRate = cr;
break;
}
}
}
if (widget.connector.currentTxPower != null) {
_txPowerController.text = widget.connector.currentTxPower.toString();
}
_clientRepeat = widget.connector.clientRepeat ?? false;
_selectedPresetIndex = _findMatchingPresetIndex();
if (_clientRepeat) {
_lastNonRepeatSnapshot =
_sessionRememberedNonRepeatSnapshot() ??
_inferNonRepeatSnapshotForRepeatEnabled();
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot!,
);
} else {
_lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection();
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_logRadioSettingsState('Dialog initialized');
});
}
@override
void dispose() {
_frequencyController.dispose();
_txPowerController.dispose();
super.dispose();
}
void _applyPreset(int index) {
setState(() {
_applyPresetState(index);
});
_logRadioSettingsState(
'Applied preset ${RadioSettings.presets[index].$1} (#$index)',
);
}
int? _findMatchingPresetIndex() {
return _findMatchingPresetIndexForSnapshot(_currentSnapshot());
}
int? _findMatchingPresetIndexForSnapshot(_RadioSettingsSnapshot snapshot) {
for (final i in _visiblePresetIndexes()) {
final preset = RadioSettings.presets[i].$2;
if (preset.frequencyHz == snapshot.frequencyHz &&
preset.bandwidth == snapshot.bandwidth &&
preset.spreadingFactor == snapshot.spreadingFactor &&
preset.codingRate == snapshot.codingRate) {
return i;
}
}
return null;
}
Iterable<int> _visiblePresetIndexes() sync* {
for (var i = 0; i < RadioSettings.presets.length; i++) {
if (_isOffGridPresetIndex(i)) {
continue;
}
yield i;
}
}
_RadioSettingsSnapshot _currentSnapshot() {
final frequencyMHz = double.tryParse(_frequencyController.text) ?? 915.0;
final txPowerDbm = int.tryParse(_txPowerController.text) ?? 20;
return _RadioSettingsSnapshot(
frequencyMHz: frequencyMHz,
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: txPowerDbm,
);
}
bool _isOffGridPresetIndex(int? index) {
if (index == null) return false;
return RadioSettings.presets[index].$1.startsWith('Off-Grid ');
}
double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) {
final baseKHz = (baseFrequencyMHz * 1000).round();
final ranges = widget.connector.allowedRepeatFreqRanges;
final candidates = ranges == null || ranges.isEmpty
? _defaultRepeatFreqsKHz
: {for (final r in ranges) baseKHz.clamp(r.lowKHz, r.highKHz)};
final closestKHz = candidates.reduce(
(a, b) => (a - baseKHz).abs() <= (b - baseKHz).abs() ? a : b,
);
return closestKHz / 1000.0;
}
double _normalFrequencyForBand(double frequencyMHz) {
if (frequencyMHz < 500) return 433.650;
if (frequencyMHz < 900) return 869.432;
return 915.8;
}
_RadioSettingsSnapshot _fallbackNonRepeatSnapshot(
double currentFrequencyMHz,
) {
return _RadioSettingsSnapshot(
frequencyMHz: _normalFrequencyForBand(currentFrequencyMHz),
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: int.tryParse(_txPowerController.text) ?? 20,
);
}
_RadioSettingsSnapshot _nonRepeatSnapshotForCurrentSelection() {
final current = _currentSnapshot();
if (!_isOffGridPresetIndex(_selectedPresetIndex)) {
return current;
}
return _fallbackNonRepeatSnapshot(current.frequencyMHz);
}
_RadioSettingsSnapshot? _sessionRememberedNonRepeatSnapshot() {
final snapshot = widget.connector.rememberedNonRepeatRadioState;
if (snapshot == null) return null;
return _RadioSettingsSnapshot.fromMeshCoreSnapshot(snapshot);
}
_RadioSettingsSnapshot _inferNonRepeatSnapshotForRepeatEnabled() {
final current = _currentSnapshot();
for (final i in _visiblePresetIndexes()) {
final preset = RadioSettings.presets[i].$2;
final offGridFreqHz =
(_offGridFrequencyForBaseFrequency(preset.frequencyMHz) * 1000)
.round();
if (offGridFreqHz == current.frequencyHz &&
preset.bandwidth == current.bandwidth &&
preset.spreadingFactor == current.spreadingFactor &&
preset.codingRate == current.codingRate) {
return _RadioSettingsSnapshot(
frequencyMHz: preset.frequencyMHz,
bandwidth: preset.bandwidth,
spreadingFactor: preset.spreadingFactor,
codingRate: preset.codingRate,
txPowerDbm: current.txPowerDbm,
);
}
}
return _fallbackNonRepeatSnapshot(current.frequencyMHz);
}
void _applySnapshot(_RadioSettingsSnapshot snapshot) {
_frequencyController.text = snapshot.frequencyMHz.toStringAsFixed(3);
_bandwidth = snapshot.bandwidth;
_spreadingFactor = snapshot.spreadingFactor;
_codingRate = snapshot.codingRate;
_txPowerController.text = snapshot.txPowerDbm.toString();
}
void _applyPresetState(int index) {
final preset = RadioSettings.presets[index].$2;
final baseSnapshot = _RadioSettingsSnapshot(
frequencyMHz: preset.frequencyMHz,
bandwidth: preset.bandwidth,
spreadingFactor: preset.spreadingFactor,
codingRate: preset.codingRate,
txPowerDbm: preset.txPowerDbm,
);
final frequencyMHz = _clientRepeat
? _offGridFrequencyForBaseFrequency(baseSnapshot.frequencyMHz)
: baseSnapshot.frequencyMHz;
_frequencyController.text = frequencyMHz.toString();
_bandwidth = preset.bandwidth;
_spreadingFactor = preset.spreadingFactor;
_codingRate = preset.codingRate;
_txPowerController.text = preset.txPowerDbm.toString();
_selectedPresetIndex = index;
_lastNonRepeatSnapshot = baseSnapshot;
// Programmatic writes skip TextField.onChanged, so clear any stale
// frequency/TX errors here or Save stays disabled.
_validateFields();
}
void _syncPresetSelection() {
final previousPresetIndex = _selectedPresetIndex;
final previousLastNonRepeat = _lastNonRepeatSnapshot;
if (_clientRepeat) {
final baseSnapshot =
previousLastNonRepeat ?? _inferNonRepeatSnapshotForRepeatEnabled();
if (_bandwidth != baseSnapshot.bandwidth ||
_spreadingFactor != baseSnapshot.spreadingFactor ||
_codingRate != baseSnapshot.codingRate ||
(int.tryParse(_txPowerController.text) ?? 20) !=
baseSnapshot.txPowerDbm) {
_lastNonRepeatSnapshot = _RadioSettingsSnapshot(
frequencyMHz: baseSnapshot.frequencyMHz,
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: int.tryParse(_txPowerController.text) ?? 20,
);
}
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot ?? baseSnapshot,
);
if (previousPresetIndex != _selectedPresetIndex ||
previousLastNonRepeat != _lastNonRepeatSnapshot) {
_logRadioSettingsState(
'Preset match updated while repeat enabled: ${_presetLabel(previousPresetIndex)} -> ${_presetLabel(_selectedPresetIndex)}',
);
}
return;
}
_lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection();
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot!,
);
if (previousPresetIndex != _selectedPresetIndex ||
previousLastNonRepeat != _lastNonRepeatSnapshot) {
_logRadioSettingsState(
'Preset sync updated state from ${_presetLabel(previousPresetIndex)} to ${_presetLabel(_selectedPresetIndex)}',
);
}
}
void _handleManualSettingsChanged(String source) {
_logRadioSettingsState('Manual settings edit: $source');
setState(() {
_validateFields();
_syncPresetSelection();
});
}
void _validateFields() {
final l10n = context.l10n;
final freqMHz = double.tryParse(_frequencyController.text);
_frequencyError = (freqMHz == null || freqMHz < 150 || freqMHz > 2500)
? l10n.settings_frequencyInvalid
: null;
final maxTxPower = widget.connector.maxTxPower ?? 22;
final txPower = int.tryParse(_txPowerController.text);
_txPowerError =
(txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower)
? l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower)
: null;
}
void _handleClientRepeatChanged(bool enabled) {
_logRadioSettingsState(
'Off-grid repeat toggle requested: $_clientRepeat -> $enabled',
);
setState(() {
final currentSnapshot = _currentSnapshot();
if (enabled) {
if (!_clientRepeat) {
_syncPresetSelection();
}
final baseSnapshot = _lastNonRepeatSnapshot ?? currentSnapshot;
_clientRepeat = true;
_frequencyController.text = _offGridFrequencyForBaseFrequency(
baseSnapshot.frequencyMHz,
).toStringAsFixed(3);
_validateFields();
return;
}
_clientRepeat = false;
_applySnapshot(
_lastNonRepeatSnapshot ??
_fallbackNonRepeatSnapshot(currentSnapshot.frequencyMHz),
);
_validateFields();
_syncPresetSelection();
});
_logRadioSettingsState('Off-grid repeat toggle applied');
}
Future<void> _saveSettings() async {
final l10n = context.l10n;
final freqMHz = double.tryParse(_frequencyController.text);
final txPower = int.tryParse(_txPowerController.text);
if (freqMHz == null || freqMHz < 150 || freqMHz > 2500) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_frequencyInvalid),
);
return;
}
final maxTxPower = widget.connector.maxTxPower ?? 22;
if (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) {
showDismissibleSnackBar(
context,
content: Text(
l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower),
),
);
return;
}
final freqHz = (freqMHz * 1000).round();
final bwHz = _bandwidth.hz;
final sf = _spreadingFactor.value;
final cr = _codingRate.value;
// if the client repeat isnt null then we know its supported
//otherwise we leave it out of the frame to avoid accidentally enabling
final knownRepeat = widget.connector.clientRepeat != null;
if (knownRepeat) {
if (_clientRepeat && !_isAllowedRepeatFreqKHz(widget.connector, freqHz)) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_clientRepeatFreqWarning),
);
return;
}
}
try {
_logRadioSettingsState('Saving radio settings');
final accepted = await widget.connector.setRadioParams(
freqHz,
bwHz,
sf,
cr,
clientRepeat: knownRepeat ? _clientRepeat : null,
);
if (!accepted) {
_logRadioSettingsState('Radio rejected requested settings');
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsNotApplied),
);
return;
}
await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower));
final selfInfo = widget.connector.receivedFrames
.firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo)
.timeout(const Duration(seconds: 5));
await widget.connector.refreshDeviceInfo();
final applied = await selfInfo.then(
(_) => _deviceMatches(
freqHz: freqHz,
bwHz: bwHz,
sf: sf,
cr: cr,
txPower: txPower,
clientRepeat: knownRepeat ? _clientRepeat : null,
),
onError: (_) => true,
);
if (!applied) {
_logRadioSettingsState('Radio did not apply requested settings');
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsNotApplied),
);
return;
}
final rememberedSnapshot = _clientRepeat
? _lastNonRepeatSnapshot
: _currentSnapshot();
if (rememberedSnapshot != null) {
widget.connector.rememberNonRepeatRadioState(
rememberedSnapshot.toMeshCoreSnapshot(),
);
}
if (!mounted) return;
_logRadioSettingsState('Radio settings saved successfully');
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsUpdated),
);
Navigator.pop(context);
} catch (e) {
_appLog.warn('Radio settings save failed: $e', tag: 'RadioSettings');
if (!mounted) return;
// Keep the dialog open, like the rejected/not-applied paths, so the
// user's edits survive a transient failure and can be retried.
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
}
}
bool _deviceMatches({
required int freqHz,
required int bwHz,
required int sf,
required int cr,
required int txPower,
required bool? clientRepeat,
}) {
final c = widget.connector;
// Firmware stores freq/bw as float MHz/kHz, so allow 1 unit of rounding.
return c.currentFreqHz != null &&
(c.currentFreqHz! - freqHz).abs() <= 1 &&
c.currentBwHz != null &&
(c.currentBwHz! - bwHz).abs() <= 1 &&
c.currentSf == sf &&
c.currentCr != null &&
_toUiCodingRate(c.currentCr!) == cr &&
c.currentTxPower == txPower &&
(clientRepeat == null || c.clientRepeat == clientRepeat);
}
String _presetLabel(int? index) {
if (index == null) {
return 'custom';
}
return '${RadioSettings.presets[index].$1} (#$index)';
}
String _formatSnapshot(_RadioSettingsSnapshot? snapshot) {
if (snapshot == null) {
return 'null';
}
return '${snapshot.frequencyMHz.toStringAsFixed(3)}MHz/'
'${snapshot.bandwidth.label}/'
'${snapshot.spreadingFactor.label}/'
'${snapshot.codingRate.label}/'
'${snapshot.txPowerDbm}dBm';
}
void _logRadioSettingsState(String message) {
if (!kDebugMode) return;
_appLog.info(
'$message | '
'freq=${_frequencyController.text}MHz '
'bw=${_bandwidth.label} '
'sf=${_spreadingFactor.label} '
'cr=${_codingRate.label} '
'tx=${_txPowerController.text}dBm '
'repeat=$_clientRepeat '
'preset=${_presetLabel(_selectedPresetIndex)} '
'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}',
tag: 'RadioSettings',
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog(
title: Text(l10n.settings_radioSettings),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButtonFormField<int>(
key: ValueKey<int?>(_selectedPresetIndex),
initialValue: _selectedPresetIndex ?? -1,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.settings_presets,
border: const OutlineInputBorder(),
),
items: [
if (_selectedPresetIndex == null)
DropdownMenuItem(
value: -1,
child: Text(l10n.settings_presetCustom),
),
for (final i in _visiblePresetIndexes())
DropdownMenuItem(
value: i,
child: Text(
RadioSettings.presets[i].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: (index) {
if (index != null && index >= 0) {
_applyPreset(index);
}
},
),
const SizedBox(height: 16),
TextField(
controller: _frequencyController,
onChanged: (_) => _handleManualSettingsChanged('frequency'),
decoration: InputDecoration(
labelText: l10n.settings_frequency,
border: const OutlineInputBorder(),
helperText: _clientRepeat
? l10n.settings_clientRepeatFrequencyNote(
_frequencyController.text,
)
: l10n.settings_frequencyHelper,
errorText: _frequencyError,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaBandwidth>(
initialValue: _bandwidth,
decoration: InputDecoration(
labelText: l10n.settings_bandwidth,
border: const OutlineInputBorder(),
),
items: LoRaBandwidth.values
.map(
(bw) => DropdownMenuItem(value: bw, child: Text(bw.label)),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_bandwidth = value;
_syncPresetSelection();
});
_logRadioSettingsState('Manual settings edit: bandwidth');
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaSpreadingFactor>(
initialValue: _spreadingFactor,
decoration: InputDecoration(
labelText: l10n.settings_spreadingFactor,
border: const OutlineInputBorder(),
),
items: LoRaSpreadingFactor.values
.map(
(sf) => DropdownMenuItem(value: sf, child: Text(sf.label)),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_spreadingFactor = value;
_syncPresetSelection();
});
_logRadioSettingsState(
'Manual settings edit: spreading factor',
);
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaCodingRate>(
initialValue: _codingRate,
decoration: InputDecoration(
labelText: l10n.settings_codingRate,
border: const OutlineInputBorder(),
),
items: LoRaCodingRate.values
.map(
(cr) => DropdownMenuItem(value: cr, child: Text(cr.label)),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_codingRate = value;
_syncPresetSelection();
});
_logRadioSettingsState('Manual settings edit: coding rate');
}
},
),
const SizedBox(height: 16),
TextField(
controller: _txPowerController,
onChanged: (_) => _handleManualSettingsChanged('tx power'),
decoration: InputDecoration(
labelText: l10n.settings_txPower,
border: const OutlineInputBorder(),
helperText: l10n.settings_txPowerRangeHelper(
_minTxPowerDbm,
widget.connector.maxTxPower ?? 22,
),
errorText: _txPowerError,
),
keyboardType: TextInputType.number,
),
if (widget.connector.clientRepeat != null) ...[
const SizedBox(height: 16),
SwitchListTile(
title: Text(l10n.settings_clientRepeat),
subtitle: Text(l10n.settings_clientRepeatSubtitle),
value: _clientRepeat,
onChanged: _handleClientRepeatChanged,
contentPadding: EdgeInsets.zero,
),
],
const SizedBox(height: 16),
Text(
l10n.settings_radioMatchWarning,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
FilledButton(
onPressed: (_frequencyError != null || _txPowerError != null)
? null
: _saveSettings,
child: Text(l10n.common_save),
),
],
);
}
}
class _RadioSettingsSnapshot {
final double frequencyMHz;
final LoRaBandwidth bandwidth;
final LoRaSpreadingFactor spreadingFactor;
final LoRaCodingRate codingRate;
final int txPowerDbm;
const _RadioSettingsSnapshot({
required this.frequencyMHz,
required this.bandwidth,
required this.spreadingFactor,
required this.codingRate,
required this.txPowerDbm,
});
/// Frequency in integer Hz — avoids floating-point comparison issues.
int get frequencyHz => (frequencyMHz * 1000).round();
/// Convert from the connector's raw-int snapshot to UI-enum snapshot.
static _RadioSettingsSnapshot? fromMeshCoreSnapshot(
MeshCoreRadioStateSnapshot snapshot,
) {
final bw = LoRaBandwidth.values
.where((b) => b.hz == snapshot.bwHz)
.firstOrNull;
final sf = LoRaSpreadingFactor.values
.where((s) => s.value == snapshot.sf)
.firstOrNull;
final cr = LoRaCodingRate.values
.where((c) => c.value == _toUiCodingRate(snapshot.cr))
.firstOrNull;
if (bw == null || sf == null || cr == null) return null;
return _RadioSettingsSnapshot(
frequencyMHz: snapshot.freqHz / 1000.0,
bandwidth: bw,
spreadingFactor: sf,
codingRate: cr,
txPowerDbm: snapshot.txPowerDbm,
);
}
/// Convert back to the connector's raw-int snapshot.
MeshCoreRadioStateSnapshot toMeshCoreSnapshot() {
return MeshCoreRadioStateSnapshot(
freqHz: frequencyHz,
bwHz: bandwidth.hz,
sf: spreadingFactor.value,
cr: codingRate.value,
txPowerDbm: txPowerDbm,
);
}
@override
bool operator ==(Object other) {
return other is _RadioSettingsSnapshot &&
frequencyHz == other.frequencyHz &&
bandwidth == other.bandwidth &&
spreadingFactor == other.spreadingFactor &&
codingRate == other.codingRate &&
txPowerDbm == other.txPowerDbm;
}
@override
int get hashCode => Object.hash(
frequencyHz,
bandwidth,
spreadingFactor,
codingRate,
txPowerDbm,
);
}
+150
View File
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
import '../models/message.dart';
import '../theme/mesh_theme.dart';
/// The emoji reaction pills under a chat bubble, shared by the direct and
/// channel chat screens.
///
/// [statuses] carries per-emoji send state for reactions this device sent
/// (direct chats only): pending chips are dimmed with a spinner and failed
/// chips become a retry button with a full-size tap target.
class ReactionChips extends StatelessWidget {
final Map<String, List<String?>> reactions;
final Map<String, MessageStatus> statuses;
/// Called when a chip that is not in the failed state is tapped.
final ValueChanged<String>? onTap;
/// Called when a failed chip is tapped.
final ValueChanged<String>? onRetry;
const ReactionChips({
super.key,
required this.reactions,
this.statuses = const {},
this.onTap,
this.onRetry,
});
@override
Widget build(BuildContext context) {
return Wrap(
spacing: 6,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
for (final entry in reactions.entries)
_ReactionChip(
emoji: entry.key,
count: entry.value.length,
status: statuses[entry.key],
onTap: onTap,
onRetry: onRetry,
),
],
);
}
}
class _ReactionChip extends StatelessWidget {
final String emoji;
final int count;
final MessageStatus? status;
final ValueChanged<String>? onTap;
final ValueChanged<String>? onRetry;
const _ReactionChip({
required this.emoji,
required this.count,
required this.status,
required this.onTap,
required this.onRetry,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final isPending =
status == MessageStatus.pending || status == MessageStatus.sent;
final isFailed = status == MessageStatus.failed;
final VoidCallback? handler = isFailed
? (onRetry == null ? null : () => onRetry!(emoji))
: (onTap == null ? null : () => onTap!(emoji));
final shape = RoundedRectangleBorder(
borderRadius: BorderRadius.circular(MeshRadii.pill),
side: BorderSide(
color: isFailed ? scheme.error : scheme.outlineVariant,
width: 1,
),
);
Widget content = Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
emoji,
style: MeshTheme.emoji(fontSize: 16),
textHeightBehavior: const TextHeightBehavior(
applyHeightToFirstAscent: false,
applyHeightToLastDescent: false,
),
),
if (count > 1) ...[
const SizedBox(width: 4),
Text(
'$count',
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w700,
color: scheme.onSurface,
),
),
],
if (isPending) ...[
const SizedBox(width: 4),
SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 1.5,
color: scheme.primary,
),
),
],
if (isFailed) ...[
const SizedBox(width: 6),
Icon(Icons.replay, size: 18, color: scheme.error),
],
],
);
content = Padding(
padding: EdgeInsets.symmetric(horizontal: isFailed ? 12 : 8, vertical: 4),
child: content,
);
if (isFailed) {
// A failed reaction is a retry button: give it a full tap target.
content = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 40, minWidth: 40),
child: Center(widthFactor: 1, heightFactor: 1, child: content),
);
}
Widget chip = Material(
color: isFailed ? scheme.errorContainer : scheme.surfaceContainerHigh,
shape: shape,
clipBehavior: Clip.antiAlias,
child: InkWell(onTap: handler, child: content),
);
if (isFailed && onRetry != null) {
chip = Semantics(
button: true,
label: context.l10n.common_retry,
child: chip,
);
}
return Opacity(opacity: isPending ? 0.5 : 1.0, child: chip);
}
}
+11 -9
View File
@@ -457,7 +457,7 @@ class _ReceivedImageMessageState extends State<ReceivedImageMessage> {
textAlign: TextAlign.center,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: color ?? widget.fallbackTextColor),
style: TextStyle(fontSize: 12, color: color ?? widget.fallbackTextColor),
);
}
@@ -547,20 +547,22 @@ class _SyntheticBanner extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 18,
height: 20,
alignment: Alignment.center,
color: Colors.black.withValues(alpha: 0.62),
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.auto_awesome, size: 11, color: Colors.white),
const Icon(Icons.auto_awesome, size: 12, color: Colors.white),
const SizedBox(width: 4),
Text(
_kSyntheticBadge,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 10, color: Colors.white),
Flexible(
child: Text(
_kSyntheticBadge,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 12, color: Colors.white),
),
),
],
),
@@ -590,7 +592,7 @@ class _SyntheticCaption extends StatelessWidget {
// than none — it clips exactly where the warning was going.
softWrap: true,
style: TextStyle(
fontSize: 10,
fontSize: 12,
color: onDark
? Colors.white70
: Theme.of(context).colorScheme.onSurfaceVariant,
+2 -2
View File
@@ -423,7 +423,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
l10n.login_routing,
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 11,
fontSize: 13,
),
),
const Spacer(),
@@ -501,7 +501,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
pathHashByteWidth: connector.pathHashByteWidth,
),
style: TextStyle(
fontSize: 11,
fontSize: 13,
color: scheme.onSurfaceVariant,
),
),
+2 -2
View File
@@ -355,7 +355,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
l10n.login_routing,
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 11,
fontSize: 12,
),
),
const Spacer(),
@@ -433,7 +433,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
pathHashByteWidth: connector.pathHashByteWidth,
),
style: TextStyle(
fontSize: 11,
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
+2 -2
View File
@@ -492,7 +492,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> {
title: Text(l10n.routing_floodDelivery),
subtitle: Text(
_floodStatsLine(context, stats),
style: const TextStyle(fontSize: 11),
style: const TextStyle(fontSize: 12),
),
trailing: mode == _RoutingMode.flood
? Icon(
@@ -596,7 +596,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> {
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
'$line1\n${line2Parts.join(' • ')}',
style: const TextStyle(fontSize: 11),
style: const TextStyle(fontSize: 12),
),
isThreeLine: true,
trailing: Row(
+1 -1
View File
@@ -313,7 +313,7 @@ class _SNRIndicatorState extends State<SNRIndicator> {
Text(
'${repeater.snr.toStringAsFixed(1)} dB • ${_formatLastUpdated(repeater.lastUpdated)}',
style: MeshTheme.mono(
fontSize: 11,
fontSize: 12,
color: colorScheme.onSurfaceVariant,
),
),
+1 -1
View File
@@ -240,7 +240,7 @@ class _TelemetryLocationMapState extends State<TelemetryLocationMap> {
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 11,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
@@ -0,0 +1,611 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/translation_support.dart';
import '../services/app_settings_service.dart';
import '../services/translation_service.dart';
import '../theme/mesh_theme.dart';
import 'mesh_nav_tile.dart';
/// [TranslationService] publishes this as `downloadFileName` while it merges
/// downloaded chunks (see translation_service.dart). The service owns the
/// value and exposes no separate state flag, so it is matched here, in one
/// place, until the service grows a proper "merging" getter.
const String _mergingChunksFileName = 'Merging chunks...';
/// On-device translation settings: feature toggles, target language, model
/// selection, model downloads and the downloaded-model list.
///
/// Watches only [AppSettingsService] and [TranslationService], so download
/// progress ticks rebuild this card and nothing else on the settings screen.
class TranslationSettingsSection extends StatelessWidget {
const TranslationSettingsSection({super.key});
@override
Widget build(BuildContext context) {
final settingsService = context.watch<AppSettingsService>();
final translationService = context.watch<TranslationService>();
final l10n = context.l10n;
final settings = settingsService.settings;
final translationEnabled = settings.translationEnabled;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final textTheme = theme.textTheme;
final disabledColor = translationEnabled ? null : theme.disabledColor;
const tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
contentPadding: tilePadding,
secondary: const Icon(Icons.translate, size: 24),
title: Text(l10n.translation_enableTitle),
subtitle: Text(l10n.translation_enableSubtitle),
value: settings.translationEnabled,
onChanged: settingsService.setTranslationEnabled,
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: tilePadding,
secondary: Icon(
Icons.auto_awesome_outlined,
size: 24,
color: disabledColor,
),
title: Text(
l10n.translation_autoIncomingTitle,
style: TextStyle(color: disabledColor),
),
subtitle: Text(
l10n.translation_autoIncomingSubtitle,
style: TextStyle(color: disabledColor),
),
value: settings.autoTranslateIncomingMessages,
onChanged: translationEnabled
? settingsService.setAutoTranslateIncomingMessages
: null,
),
const Divider(height: 1, indent: 16),
SwitchListTile(
contentPadding: tilePadding,
secondary: Icon(Icons.outgoing_mail, size: 24, color: disabledColor),
title: Text(
l10n.translation_composerTitle,
style: TextStyle(color: disabledColor),
),
subtitle: Text(
l10n.translation_composerSubtitle,
style: TextStyle(color: disabledColor),
),
value: settings.composerTranslationEnabled,
onChanged: translationEnabled
? settingsService.setComposerTranslationEnabled
: null,
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.language,
title: l10n.translation_targetLanguage,
subtitle: _translationLanguageLabel(
context,
settings.translationTargetLanguageCode,
),
onTap: () => _showTranslationLanguageDialog(context, settingsService),
),
const Divider(height: 1, indent: 16),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: DropdownButtonFormField<String>(
initialValue: settings.translationSelectedModelId,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.translation_downloadedModelLabel,
border: const OutlineInputBorder(),
),
items: [
for (final model in settings.translationDownloadedModels)
DropdownMenuItem(
value: model.id,
child: Text(
translationModelFriendlyName(model),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: settings.translationDownloadedModels.isEmpty
? null
: (value) {
settingsService.setTranslationSelectedModelId(value);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: DropdownButtonFormField<String>(
initialValue: null,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.translation_presetModelLabel,
border: const OutlineInputBorder(),
),
items: [
for (final preset in translationPresetModels)
DropdownMenuItem(
value: preset.sourceUrl,
child: Text(
translationModelFriendlyName(preset),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: translationService.isBusy
? null
: (value) async {
if (value == null) return;
final preset = translationPresetModels.firstWhere(
(entry) => entry.sourceUrl == value,
);
await _downloadTranslationModel(
context,
translationService,
settingsService,
sourceUrl: preset.sourceUrl,
fileName: preset.name,
id: preset.id,
);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_TranslationUrlField(
initialValue: settings.translationModelSourceUrl ?? '',
onChanged: settingsService.setTranslationModelSourceUrl,
onDownload: translationService.isBusy
? null
: (url) => _downloadTranslationModel(
context,
translationService,
settingsService,
sourceUrl: url,
),
downloadLabel: translationService.isDownloading
? l10n.translation_downloading
: translationService.isBusy
? l10n.translation_working
: l10n.translation_downloadModel,
isDownloading: translationService.isDownloading,
onCancel: translationService.cancelDownload,
labelText: l10n.translation_manualUrlLabel,
stopLabel: l10n.translation_stop,
),
if (translationService.isDownloading) ...[
const SizedBox(height: 12),
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: _isMerging(translationService)
? null
: translationService.downloadProgress,
),
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: Text(
_downloadProgressLabel(context, translationService),
style: MeshTheme.mono(
fontSize: 14,
color: scheme.onSurfaceVariant,
),
),
),
],
if (settings.translationDownloadedModels.isNotEmpty) ...[
const SizedBox(height: 16),
Align(
alignment: Alignment.centerLeft,
child: Text(
l10n.translation_downloadedModels,
style: textTheme.titleSmall,
),
),
const SizedBox(height: 8),
for (final model in settings.translationDownloadedModels)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Icon(
model.id == settings.translationSelectedModelId
? Icons.check_circle
: Icons.memory_outlined,
size: 24,
color: model.id == settings.translationSelectedModelId
? scheme.primary
: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: InkWell(
borderRadius: BorderRadius.circular(MeshRadii.xs),
onTap: () => settingsService
.setTranslationSelectedModelId(model.id),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
translationModelFriendlyName(model),
style: textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
Text(
_downloadedModelLabel(context, model),
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
),
),
),
IconButton(
tooltip: l10n.translation_deleteModel,
onPressed: translationService.isBusy
? null
: () => _deleteTranslationModel(
context,
translationService,
model,
),
icon: const Icon(Icons.delete_outline),
),
],
),
),
],
if (translationService.lastError != null) ...[
const SizedBox(height: 8),
Text(
translationService.lastError!,
style: TextStyle(color: scheme.error),
),
],
],
),
),
],
);
}
static bool _isMerging(TranslationService service) =>
service.downloadFileName == _mergingChunksFileName;
void _showTranslationLanguageDialog(
BuildContext context,
AppSettingsService settingsService,
) {
showDialog(
context: context,
builder: (context) => _TranslationLanguageDialogContent(
currentLanguageCode:
settingsService.settings.translationTargetLanguageCode,
onLanguageSelected: (value) {
settingsService.setTranslationTargetLanguageCode(value);
Navigator.pop(context);
},
),
);
}
Future<void> _downloadTranslationModel(
BuildContext context,
TranslationService translationService,
AppSettingsService settingsService, {
required String sourceUrl,
String? fileName,
String? id,
}) async {
if (sourceUrl.isEmpty) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_enterUrlFirst),
);
return;
}
try {
await translationService.downloadModel(
sourceUrl: sourceUrl,
fileName: fileName,
id: id,
);
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_modelDownloaded),
);
await settingsService.setTranslationEnabled(true);
} on TranslationDownloadCancelled {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_downloadStopped),
);
} catch (error) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
context.l10n.translation_downloadFailed(error.toString()),
),
);
}
}
String _translationLanguageLabel(BuildContext context, String? languageCode) {
if (languageCode == null || languageCode.isEmpty) {
return context.l10n.translation_useAppLanguage;
}
for (final option in supportedTranslationLanguages) {
if (option.code == languageCode) {
return option.label;
}
}
return languageCode.toUpperCase();
}
String _downloadProgressLabel(
BuildContext context,
TranslationService translationService,
) {
final l10n = context.l10n;
if (_isMerging(translationService)) {
return l10n.translation_mergingChunks;
}
final fileName =
translationService.downloadFileName ??
l10n.translation_defaultModelName;
final currentMb = translationService.downloadedBytes / (1024 * 1024);
final totalBytes = translationService.downloadTotalBytes;
if (totalBytes == null || totalBytes <= 0) {
return l10n.translation_downloadProgressBytes(
fileName,
currentMb.toStringAsFixed(1),
);
}
final totalMb = totalBytes / (1024 * 1024);
final percent = ((translationService.downloadProgress ?? 0) * 100)
.toStringAsFixed(0);
return l10n.translation_downloadProgressTotal(
fileName,
currentMb.toStringAsFixed(1),
totalMb.toStringAsFixed(1),
percent,
);
}
Future<void> _deleteTranslationModel(
BuildContext context,
TranslationService translationService,
TranslationModelRecord model,
) async {
try {
await translationService.removeModel(model);
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
context.l10n.appSettings_translationModelDeleted(
translationModelFriendlyName(model),
),
),
);
} catch (error) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
context.l10n.appSettings_translationModelDeleteFailed('$error'),
),
);
}
}
String _downloadedModelLabel(
BuildContext context,
TranslationModelRecord model,
) {
final sizeMb = model.fileSizeBytes / (1024 * 1024);
final source = model.sourceUrl.isEmpty ? model.name : model.sourceUrl;
return context.l10n.translation_downloadedModelDetails(
sizeMb.toStringAsFixed(1),
source,
);
}
}
/// Owns the [TextEditingController] for the manual model URL field so it
/// survives rebuilds of the parent section.
class _TranslationUrlField extends StatefulWidget {
const _TranslationUrlField({
required this.initialValue,
required this.onChanged,
required this.onDownload,
required this.downloadLabel,
required this.isDownloading,
required this.onCancel,
required this.labelText,
required this.stopLabel,
});
final String initialValue;
final ValueChanged<String> onChanged;
final void Function(String url)? onDownload;
final String downloadLabel;
final bool isDownloading;
final VoidCallback onCancel;
final String labelText;
final String stopLabel;
@override
State<_TranslationUrlField> createState() => _TranslationUrlFieldState();
}
class _TranslationUrlFieldState extends State<_TranslationUrlField> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.initialValue);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: widget.labelText,
border: const OutlineInputBorder(),
),
onChanged: widget.onChanged,
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: FilledButton.icon(
onPressed: widget.onDownload == null
? null
: () => widget.onDownload!(_controller.text.trim()),
icon: const Icon(Icons.download),
label: Text(widget.downloadLabel),
),
),
if (widget.isDownloading) ...[
const SizedBox(width: 8),
OutlinedButton.icon(
onPressed: widget.onCancel,
icon: const Icon(Icons.stop_circle_outlined),
label: Text(widget.stopLabel),
),
],
],
),
],
);
}
}
/// Dialog content for choosing the translation target language.
/// Owns the search [TextEditingController] so it is properly disposed.
class _TranslationLanguageDialogContent extends StatefulWidget {
const _TranslationLanguageDialogContent({
required this.currentLanguageCode,
required this.onLanguageSelected,
});
final String? currentLanguageCode;
final ValueChanged<String?> onLanguageSelected;
@override
State<_TranslationLanguageDialogContent> createState() =>
_TranslationLanguageDialogContentState();
}
class _TranslationLanguageDialogContentState
extends State<_TranslationLanguageDialogContent> {
late final TextEditingController _searchController;
List<TranslationLanguageOption> _filtered = supportedTranslationLanguages;
@override
void initState() {
super.initState();
_searchController = TextEditingController();
}
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(context.l10n.translation_targetLanguage),
content: SizedBox(
width: 360,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _searchController,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
),
onChanged: (value) {
final normalized = value.trim().toLowerCase();
setState(() {
_filtered = supportedTranslationLanguages.where((option) {
return option.label.toLowerCase().contains(normalized) ||
option.code.toLowerCase().contains(normalized);
}).toList();
});
},
),
const SizedBox(height: 12),
Flexible(
child: RadioGroup<String?>(
groupValue: widget.currentLanguageCode,
onChanged: (value) {
widget.onLanguageSelected(value);
},
child: ListView(
shrinkWrap: true,
children: [
RadioListTile<String?>(
value: null,
title: Text(context.l10n.translation_useAppLanguage),
),
for (final option in _filtered)
RadioListTile<String?>(
value: option.code,
title: Text(option.label),
subtitle: Text(option.code.toUpperCase()),
),
],
),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(context.l10n.common_close),
),
],
);
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ class UnreadBadge extends StatelessWidget {
child: Text(
display,
style: MeshTheme.mono(
fontSize: 11,
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.white,
),
+1 -1
View File
@@ -28,7 +28,7 @@ class UnreadDivider extends StatelessWidget {
child: Text(
context.l10n.chat_newMessages,
style: MeshTheme.mono(
fontSize: 10.5,
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),