Merge branch 'dev' of https://github.com/zjs81/meshcore-open into fold_path_size_into_radio_presets
This commit is contained in:
commit
f8a9922ba4
231 files changed
+45401
-9099
No files matched your search
@@ -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,
|
||||
),
|
||||
|
||||
@@ -22,6 +22,9 @@ class ByteCountedTextField extends StatelessWidget {
|
||||
/// Optional focus node forwarded to the inner [TextField].
|
||||
final FocusNode? focusNode;
|
||||
|
||||
/// Whether the inner [TextField] requests focus when first built.
|
||||
final bool autofocus;
|
||||
|
||||
/// Hint text shown when the field is empty.
|
||||
final String? hintText;
|
||||
|
||||
@@ -64,6 +67,7 @@ class ByteCountedTextField extends StatelessWidget {
|
||||
required this.maxBytes,
|
||||
required this.controller,
|
||||
this.focusNode,
|
||||
this.autofocus = false,
|
||||
this.hintText,
|
||||
this.textInputAction = TextInputAction.send,
|
||||
this.onSubmitted,
|
||||
@@ -108,6 +112,7 @@ class ByteCountedTextField extends StatelessWidget {
|
||||
maxLines: null,
|
||||
controller: controller,
|
||||
focusNode: focusNode,
|
||||
autofocus: autofocus,
|
||||
inputFormatters: [
|
||||
...extraFormatters,
|
||||
Utf8LengthLimitingTextInputFormatter(
|
||||
@@ -140,7 +145,7 @@ class ByteCountedTextField extends StatelessWidget {
|
||||
? Text(
|
||||
softLimitNote!,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontSize: 12,
|
||||
color: Theme.of(context).colorScheme.tertiary,
|
||||
),
|
||||
)
|
||||
@@ -149,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),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
|
||||
/// Small warning shown next to a message time when the sender's clock put
|
||||
/// the timestamp well into the future (#584). The message itself is ordered
|
||||
/// by when it arrived.
|
||||
class FutureTimestampIndicator extends StatelessWidget {
|
||||
final double size;
|
||||
|
||||
const FutureTimestampIndicator({super.key, this.size = 16});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final label = context.l10n.chat_futureTimestampWarning;
|
||||
return Tooltip(
|
||||
message: label,
|
||||
triggerMode: TooltipTriggerMode.tap,
|
||||
child: Semantics(
|
||||
label: label,
|
||||
child: Icon(Icons.update, size: size, color: MeshPalette.warn),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
|
||||
/// Affiliate link for the SenseCAP MeshTracker X1.
|
||||
const getNodeUrl =
|
||||
'https://www.seeedstudio.com/sensecap-meshtracker-x1-meshtastic-gps-tracker-p-6935.html'
|
||||
'?sensecap_affiliate=JFWID0g&referring_service=link';
|
||||
|
||||
/// Bottom banner on the connect screen pointing new users at a node to buy.
|
||||
class GetNodeBanner extends StatelessWidget {
|
||||
const GetNodeBanner({super.key});
|
||||
|
||||
void _open() =>
|
||||
launchUrl(Uri.parse(getNodeUrl), mode: LaunchMode.externalApplication);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
|
||||
return SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
|
||||
child: Material(
|
||||
color: scheme.primaryContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(MeshRadii.md),
|
||||
side: BorderSide(color: scheme.primary.withValues(alpha: 0.4)),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: _open,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.router_outlined,
|
||||
size: 28,
|
||||
color: scheme.onPrimaryContainer,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.scanner_getNodeTitle,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
color: scheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
l10n.scanner_getNodeBody,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onPrimaryContainer,
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _open,
|
||||
icon: const Icon(Icons.shopping_cart_outlined, size: 22),
|
||||
label: Text(l10n.scanner_getNodeAction),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Center(
|
||||
child: Text(
|
||||
l10n.scanner_getNodeDisclosure,
|
||||
textAlign: TextAlign.center,
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: scheme.onPrimaryContainer.withValues(alpha: 0.8),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
|
||||
class GifMessage extends StatefulWidget {
|
||||
final String url;
|
||||
final Color backgroundColor;
|
||||
@@ -147,7 +149,7 @@ class _GifMessageState extends State<GifMessage> {
|
||||
if (_error != null) {
|
||||
content = Center(
|
||||
child: Text(
|
||||
"Can't load GIF\nTap to retry",
|
||||
context.l10n.gif_loadFailedRetry,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 12, color: widget.fallbackTextColor),
|
||||
),
|
||||
@@ -163,7 +165,7 @@ class _GifMessageState extends State<GifMessage> {
|
||||
} else if (_image == null) {
|
||||
content = Center(
|
||||
child: Text(
|
||||
'Tap to load GIF',
|
||||
context.l10n.gif_tapToLoad,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 12, color: widget.fallbackTextColor),
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/guessed_location_estimator.dart';
|
||||
import '../helpers/utf8_length_limiter.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
import 'byte_count_input.dart';
|
||||
|
||||
/// Makes [label] safe for the `m:lat,lon|label|flags` marker format: a `|`
|
||||
/// would split the label into the flags field and a line break would end the
|
||||
/// message, so both are replaced.
|
||||
String sanitizeMarkerLabel(String label) =>
|
||||
label.replaceAll('|', '/').replaceAll(RegExp(r'[\r\n]+'), ' ').trim();
|
||||
|
||||
/// The shared-marker message text parsed by `parseMarkerText`.
|
||||
String formatMarkerText(double lat, double lon, String label, String flags) =>
|
||||
'm:${lat.toStringAsFixed(6)},${lon.toStringAsFixed(6)}|'
|
||||
'${sanitizeMarkerLabel(label)}|$flags';
|
||||
|
||||
/// Bytes left for the label once the marker's fixed parts are counted, using
|
||||
/// the smaller of the contact and (worst-case sender name) channel limits so
|
||||
/// the marker fits either destination.
|
||||
int markerLabelByteBudget(double lat, double lon, String flags) {
|
||||
final maxPayload = [
|
||||
maxContactMessageBytes(),
|
||||
maxChannelMessageBytes(null),
|
||||
].reduce((a, b) => a < b ? a : b);
|
||||
final overhead = utf8ByteLength(formatMarkerText(lat, lon, '', flags));
|
||||
final budget = maxPayload - overhead;
|
||||
return budget > 0 ? budget : 0;
|
||||
}
|
||||
|
||||
/// Whether the radio reports a usable position. Firmware sends 0,0 when no
|
||||
/// location is set, which must not be shared as a real marker.
|
||||
bool hasShareableLocation(double? lat, double? lon) =>
|
||||
lat != null && lon != null && isPlausibleLocation(lat, lon);
|
||||
|
||||
/// Asks for a marker label. Returns the sanitised label (or the sanitised
|
||||
/// [defaultLabel] when left empty), or null when cancelled.
|
||||
Future<String?> showMarkerLabelDialog(
|
||||
BuildContext context, {
|
||||
required double lat,
|
||||
required double lon,
|
||||
required String defaultLabel,
|
||||
required String flags,
|
||||
required String confirmText,
|
||||
}) {
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => MarkerLabelDialog(
|
||||
maxBytes: markerLabelByteBudget(lat, lon, flags),
|
||||
defaultLabel: defaultLabel,
|
||||
confirmText: confirmText,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Label prompt for a shared map marker. Owns its controller and focus node
|
||||
/// so they outlive the dialog's exit animation instead of being disposed
|
||||
/// while the field is still mounted.
|
||||
class MarkerLabelDialog extends StatefulWidget {
|
||||
const MarkerLabelDialog({
|
||||
super.key,
|
||||
required this.maxBytes,
|
||||
required this.defaultLabel,
|
||||
required this.confirmText,
|
||||
});
|
||||
|
||||
final int maxBytes;
|
||||
final String defaultLabel;
|
||||
final String confirmText;
|
||||
|
||||
@override
|
||||
State<MarkerLabelDialog> createState() => _MarkerLabelDialogState();
|
||||
}
|
||||
|
||||
class _MarkerLabelDialogState extends State<MarkerLabelDialog> {
|
||||
late final String _fittedDefault = truncateUtf8(
|
||||
sanitizeMarkerLabel(widget.defaultLabel),
|
||||
widget.maxBytes,
|
||||
);
|
||||
late final TextEditingController _controller =
|
||||
TextEditingController(text: _fittedDefault)
|
||||
..selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: _fittedDefault.length,
|
||||
);
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focusNode.dispose();
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
final label = sanitizeMarkerLabel(_controller.text);
|
||||
Navigator.pop(context, label.isEmpty ? _fittedDefault : label);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final border = OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(MeshRadii.md),
|
||||
borderSide: BorderSide(color: scheme.outlineVariant),
|
||||
);
|
||||
return AlertDialog(
|
||||
title: Text(l10n.map_pinLabel),
|
||||
content: ByteCountedTextField(
|
||||
autofocus: true,
|
||||
focusNode: _focusNode,
|
||||
maxBytes: widget.maxBytes,
|
||||
controller: _controller,
|
||||
decoration: InputDecoration(
|
||||
hintText: l10n.map_label,
|
||||
helperText: l10n.map_labelUpdateHint,
|
||||
helperMaxLines: 3,
|
||||
helperStyle: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12),
|
||||
border: border,
|
||||
enabledBorder: border,
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(MeshRadii.md),
|
||||
borderSide: BorderSide(color: scheme.primary, width: 1.5),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: scheme.surfaceContainerLow,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 18,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
FilledButton(onPressed: _submit, child: Text(widget.confirmText)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../services/network_map/network_map_api_client.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
import 'mesh_ui.dart';
|
||||
|
||||
enum NetworkMapLoadState { idle, loading, ready, zoomIn, error }
|
||||
|
||||
/// Fetches the online network map for the visible area.
|
||||
///
|
||||
/// Requests are debounced while the map moves; a response that arrives after
|
||||
/// a newer request started is dropped.
|
||||
class NetworkMapOnlineController extends ChangeNotifier {
|
||||
static const Duration _debounce = Duration(milliseconds: 600);
|
||||
|
||||
final NetworkMapApiClient _client;
|
||||
final LayerHitNotifier<NetworkMapRepeater> hitNotifier = ValueNotifier(null);
|
||||
|
||||
List<NetworkMapRepeater> _repeaters = const [];
|
||||
List<NetworkMapLink> _links = const [];
|
||||
NetworkMapLoadState _state = NetworkMapLoadState.idle;
|
||||
Timer? _timer;
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
NetworkMapOnlineController({NetworkMapApiClient? client})
|
||||
: _client = client ?? NetworkMapApiClient();
|
||||
|
||||
List<NetworkMapRepeater> get repeaters => _repeaters;
|
||||
List<NetworkMapLink> get links => _links;
|
||||
NetworkMapLoadState get state => _state;
|
||||
|
||||
void requestBounds(LatLngBounds bounds) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer(_debounce, () => _load(bounds));
|
||||
}
|
||||
|
||||
/// Drops any pending or in-flight request (the online layer was hidden).
|
||||
void cancel() {
|
||||
_timer?.cancel();
|
||||
_generation++;
|
||||
}
|
||||
|
||||
Future<void> _load(LatLngBounds bounds) async {
|
||||
final boxes = NetworkMapBbox.forVisibleArea(
|
||||
west: bounds.west,
|
||||
south: bounds.south,
|
||||
east: bounds.east,
|
||||
north: bounds.north,
|
||||
);
|
||||
final generation = ++_generation;
|
||||
if (boxes == null) {
|
||||
_setState(NetworkMapLoadState.zoomIn);
|
||||
return;
|
||||
}
|
||||
_setState(NetworkMapLoadState.loading);
|
||||
try {
|
||||
final results = await Future.wait([
|
||||
Future.wait(boxes.map(_client.fetchRepeaters)),
|
||||
Future.wait(boxes.map((b) => _client.fetchLinks(b))),
|
||||
]);
|
||||
if (_disposed || generation != _generation) return;
|
||||
// Two boxes (antimeridian) can both return items on the seam.
|
||||
_repeaters = {
|
||||
for (final r in results[0].expand((l) => l as List<NetworkMapRepeater>))
|
||||
r.key: r,
|
||||
}.values.toList();
|
||||
_links = {
|
||||
for (final l in results[1].expand((l) => l as List<NetworkMapLink>))
|
||||
'${l.a}:${l.b}': l,
|
||||
}.values.toList();
|
||||
_setState(NetworkMapLoadState.ready);
|
||||
} catch (_) {
|
||||
if (_disposed || generation != _generation) return;
|
||||
_setState(NetworkMapLoadState.error);
|
||||
}
|
||||
}
|
||||
|
||||
void _setState(NetworkMapLoadState value) {
|
||||
_state = value;
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_timer?.cancel();
|
||||
hitNotifier.dispose();
|
||||
_client.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Color networkMapStatusColor(NetworkMapRepeaterStatus status) {
|
||||
return switch (status) {
|
||||
NetworkMapRepeaterStatus.active => MapPalette.online,
|
||||
NetworkMapRepeaterStatus.recent => MapPalette.stale,
|
||||
NetworkMapRepeaterStatus.stale => MapPalette.offline,
|
||||
};
|
||||
}
|
||||
|
||||
/// Map layers for the online network: links, repeater hexagons and a
|
||||
/// tappable center marker so small cells stay visible when zoomed out.
|
||||
///
|
||||
/// Keys in [localMarkerKeys] are already drawn by the local layer, so only
|
||||
/// their hexagon outline is added.
|
||||
List<Widget> buildNetworkMapOnlineLayers({
|
||||
required NetworkMapOnlineController controller,
|
||||
required Set<String> localMarkerKeys,
|
||||
required ValueChanged<NetworkMapRepeater> onTap,
|
||||
}) {
|
||||
final repeaters = controller.repeaters;
|
||||
return [
|
||||
PolylineLayer(
|
||||
polylines: [
|
||||
for (final link in controller.links)
|
||||
Polyline(
|
||||
points: [link.aCell.center, link.bCell.center],
|
||||
strokeWidth: link.confirmed ? 3.5 : 2.5,
|
||||
color: MapPalette.router.withValues(
|
||||
alpha: link.confirmed ? 0.85 : 0.6,
|
||||
),
|
||||
borderStrokeWidth: 1,
|
||||
borderColor: MapPalette.markerOutline.withValues(alpha: 0.7),
|
||||
pattern: link.confirmed
|
||||
? const StrokePattern.solid()
|
||||
: StrokePattern.dashed(segments: const [10, 8]),
|
||||
),
|
||||
],
|
||||
),
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
final hits = controller.hitNotifier.value?.hitValues;
|
||||
if (hits != null && hits.isNotEmpty) onTap(hits.first);
|
||||
},
|
||||
child: PolygonLayer<NetworkMapRepeater>(
|
||||
hitNotifier: controller.hitNotifier,
|
||||
polygons: [
|
||||
for (final repeater in repeaters)
|
||||
if (repeater.cell.boundary.length >= 3)
|
||||
Polygon<NetworkMapRepeater>(
|
||||
points: repeater.cell.boundary,
|
||||
hitValue: repeater,
|
||||
color: localMarkerKeys.contains(repeater.key)
|
||||
? null
|
||||
: networkMapStatusColor(
|
||||
repeater.status,
|
||||
).withValues(alpha: 0.22),
|
||||
borderColor: networkMapStatusColor(repeater.status),
|
||||
borderStrokeWidth: 2.5,
|
||||
pattern: repeater.confirmed
|
||||
? const StrokePattern.solid()
|
||||
: StrokePattern.dashed(segments: const [8, 6]),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
MarkerLayer(
|
||||
markers: [
|
||||
for (final repeater in repeaters)
|
||||
if (!localMarkerKeys.contains(repeater.key))
|
||||
Marker(
|
||||
point: repeater.cell.center,
|
||||
width: 34,
|
||||
height: 34,
|
||||
child: GestureDetector(
|
||||
onTap: () => onTap(repeater),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: networkMapStatusColor(repeater.status),
|
||||
border: Border.all(
|
||||
color: MapPalette.markerOutline,
|
||||
width: 2.5,
|
||||
),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: MapPalette.markerShadow,
|
||||
blurRadius: 6,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
repeater.type == advTypeRoom
|
||||
? Icons.meeting_room
|
||||
: Icons.router,
|
||||
color: MapPalette.markerOutline,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
enum NetworkMapReach { heard, nearby, far }
|
||||
|
||||
/// Distance under which a repeater counts as "in your area".
|
||||
const double networkMapNearbyKm = 50;
|
||||
|
||||
NetworkMapReach networkMapReachFor({
|
||||
required bool heardByRadio,
|
||||
required LatLng? self,
|
||||
required LatLng cell,
|
||||
}) {
|
||||
if (heardByRadio) return NetworkMapReach.heard;
|
||||
if (self != null &&
|
||||
const Distance().as(LengthUnit.Kilometer, self, cell) <=
|
||||
networkMapNearbyKm) {
|
||||
return NetworkMapReach.nearby;
|
||||
}
|
||||
return NetworkMapReach.far;
|
||||
}
|
||||
|
||||
/// Details for a repeater from the online map, with "Add to contacts" and
|
||||
/// "Manage". [onManage] runs the regular login → repeater hub flow.
|
||||
Future<void> showNetworkMapRepeaterSheet(
|
||||
BuildContext context, {
|
||||
required MeshCoreConnector connector,
|
||||
required NetworkMapRepeater repeater,
|
||||
required void Function(Contact contact) onManage,
|
||||
}) {
|
||||
return showMeshSheet<void>(
|
||||
context,
|
||||
builder: (sheetContext) => _NetworkMapRepeaterSheet(
|
||||
connector: connector,
|
||||
repeater: repeater,
|
||||
onManage: (contact) {
|
||||
Navigator.pop(sheetContext);
|
||||
onManage(contact);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _NetworkMapRepeaterSheet extends StatefulWidget {
|
||||
final MeshCoreConnector connector;
|
||||
final NetworkMapRepeater repeater;
|
||||
final void Function(Contact contact) onManage;
|
||||
|
||||
const _NetworkMapRepeaterSheet({
|
||||
required this.connector,
|
||||
required this.repeater,
|
||||
required this.onManage,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_NetworkMapRepeaterSheet> createState() =>
|
||||
_NetworkMapRepeaterSheetState();
|
||||
}
|
||||
|
||||
class _NetworkMapRepeaterSheetState extends State<_NetworkMapRepeaterSheet> {
|
||||
static const Duration _recentlyHeard = Duration(hours: 24);
|
||||
bool _busy = false;
|
||||
|
||||
NetworkMapRepeater get _repeater => widget.repeater;
|
||||
|
||||
Contact? get _savedContact =>
|
||||
widget.connector.getContactByPubKeyHex(_repeater.key);
|
||||
|
||||
bool get _heardByRadio {
|
||||
if (_savedContact != null) return true;
|
||||
final cutoff = DateTime.now().subtract(_recentlyHeard);
|
||||
return widget.connector.discoveredContacts.any(
|
||||
(c) => c.publicKeyHex == _repeater.key && c.lastSeen.isAfter(cutoff),
|
||||
);
|
||||
}
|
||||
|
||||
/// The saved contact, adding it first if needed. Null (with a message) when
|
||||
/// it cannot be added.
|
||||
Future<Contact?> _ensureContact() async {
|
||||
final existing = _savedContact;
|
||||
if (existing != null) return existing;
|
||||
final connector = widget.connector;
|
||||
final l10n = context.l10n;
|
||||
if (!connector.isConnected) {
|
||||
_snack(l10n.settings_notConnectedError);
|
||||
return null;
|
||||
}
|
||||
if (connector.contactsStorageFull ||
|
||||
connector.contacts.length >= connector.maxContacts) {
|
||||
_snack(l10n.contacts_storageFull);
|
||||
return null;
|
||||
}
|
||||
// Flood route, no location (the cell is only an approximation) and an
|
||||
// unknown advert time so the firmware's replay guard accepts the next
|
||||
// real advert.
|
||||
final contact = Contact(
|
||||
publicKey: hexToPubKey(_repeater.key),
|
||||
name: _repeater.name ?? _repeater.key.substring(0, 8),
|
||||
type: _repeater.type,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0, isUtc: true),
|
||||
);
|
||||
setState(() => _busy = true);
|
||||
final ok = await connector.importDiscoveredContact(contact);
|
||||
if (!mounted) return null;
|
||||
setState(() => _busy = false);
|
||||
if (!ok) {
|
||||
_snack(l10n.networkMap_addFailed);
|
||||
return null;
|
||||
}
|
||||
return _savedContact ?? contact;
|
||||
}
|
||||
|
||||
void _snack(String message) {
|
||||
showDismissibleSnackBar(context, content: Text(message));
|
||||
}
|
||||
|
||||
Future<void> _add() async {
|
||||
final contact = await _ensureContact();
|
||||
if (contact != null && mounted) {
|
||||
_snack(context.l10n.networkMap_addedToContacts);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _manage() async {
|
||||
final contact = await _ensureContact();
|
||||
if (contact != null && mounted) widget.onManage(contact);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final repeater = _repeater;
|
||||
final inContacts = _savedContact != null;
|
||||
final statusColor = networkMapStatusColor(repeater.status);
|
||||
final selfLat = widget.connector.selfLatitude;
|
||||
final selfLon = widget.connector.selfLongitude;
|
||||
final reach = networkMapReachFor(
|
||||
heardByRadio: _heardByRadio,
|
||||
self: selfLat != null && selfLon != null && (selfLat != 0 || selfLon != 0)
|
||||
? LatLng(selfLat, selfLon)
|
||||
: null,
|
||||
cell: repeater.cell.center,
|
||||
);
|
||||
final (reachLabel, reachColor, reachIcon) = switch (reach) {
|
||||
NetworkMapReach.heard => (
|
||||
l10n.networkMap_heardByRadio,
|
||||
MapPalette.online,
|
||||
Icons.hearing,
|
||||
),
|
||||
NetworkMapReach.nearby => (
|
||||
l10n.networkMap_inYourArea,
|
||||
MapPalette.selected,
|
||||
Icons.near_me,
|
||||
),
|
||||
NetworkMapReach.far => (
|
||||
l10n.networkMap_farAway,
|
||||
MapPalette.stale,
|
||||
Icons.warning_amber_rounded,
|
||||
),
|
||||
};
|
||||
final statusLabel = switch (repeater.status) {
|
||||
NetworkMapRepeaterStatus.active => l10n.networkMap_statusActive,
|
||||
NetworkMapRepeaterStatus.recent => l10n.networkMap_statusRecent,
|
||||
NetworkMapRepeaterStatus.stale => l10n.networkMap_statusStale,
|
||||
};
|
||||
final lastSeen = repeater.lastSeen;
|
||||
|
||||
Widget row(String label, String value) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
value,
|
||||
style: textTheme.bodyLarge?.copyWith(color: scheme.onSurface),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
return SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
BottomSheetHeader(
|
||||
title: repeater.name ?? l10n.networkMap_unnamed,
|
||||
subtitle: repeater.type == advTypeRoom
|
||||
? l10n.contact_typeRoom
|
||||
: l10n.contact_typeRepeater,
|
||||
trailing: Icon(
|
||||
repeater.type == advTypeRoom
|
||||
? Icons.meeting_room
|
||||
: Icons.router,
|
||||
color: statusColor,
|
||||
size: 26,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
StatusChip(
|
||||
label: reachLabel,
|
||||
color: reachColor,
|
||||
icon: reachIcon,
|
||||
fontSize: 15,
|
||||
),
|
||||
if (inContacts)
|
||||
StatusChip(
|
||||
label: l10n.networkMap_inYourContacts,
|
||||
color: MapPalette.repeater,
|
||||
icon: Icons.check_circle,
|
||||
fontSize: 15,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
row(l10n.networkMap_status, statusLabel),
|
||||
row(
|
||||
l10n.networkMap_reports,
|
||||
repeater.confirmed
|
||||
? l10n.networkMap_confirmed
|
||||
: l10n.networkMap_singleSource,
|
||||
),
|
||||
if (lastSeen != null)
|
||||
row(
|
||||
l10n.map_lastSeen,
|
||||
networkMapTimeAgo(context, lastSeen),
|
||||
),
|
||||
row(
|
||||
l10n.map_location,
|
||||
repeater.isEstimated
|
||||
? l10n.networkMap_locationEstimated
|
||||
: l10n.networkMap_locationAdvertised,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (!inContacts) ...[
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.tonalIcon(
|
||||
onPressed: _busy ? null : _add,
|
||||
icon: const Icon(Icons.person_add_alt_1, size: 22),
|
||||
label: Text(l10n.networkMap_addToContacts),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
],
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _busy ? null : _manage,
|
||||
icon: const Icon(Icons.admin_panel_settings, size: 22),
|
||||
label: Text(l10n.networkMap_manage),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// "Just now", "5m ago", "3h ago", "2d ago".
|
||||
String networkMapTimeAgo(BuildContext context, DateTime time) {
|
||||
final l10n = context.l10n;
|
||||
final difference = DateTime.now().difference(time);
|
||||
if (difference.inSeconds < 60) return l10n.time_justNow;
|
||||
if (difference.inMinutes < 60) {
|
||||
return l10n.time_minutesAgo(difference.inMinutes);
|
||||
}
|
||||
if (difference.inHours < 24) return l10n.time_hoursAgo(difference.inHours);
|
||||
return l10n.time_daysAgo(difference.inDays);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/app_settings_service.dart';
|
||||
import '../services/network_map/network_map_api_client.dart';
|
||||
|
||||
/// Asks once whether to share what the radio hears with the network map.
|
||||
///
|
||||
/// Shows nothing when uploading is already on, the prompt was shown before,
|
||||
/// or the app is in review mode. The prompt counts as shown as soon as it
|
||||
/// opens, so dismissing it never brings it back.
|
||||
Future<void> maybeShowNetworkMapOptInDialog(BuildContext context) async {
|
||||
final settingsService = context.read<AppSettingsService>();
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
final settings = settingsService.settings;
|
||||
if (settings.networkMapPromptShown ||
|
||||
settings.networkMapUploadEnabled ||
|
||||
connector.isReviewMode ||
|
||||
!connector.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
await settingsService.setNetworkMapPromptShown(true);
|
||||
if (!context.mounted) return;
|
||||
|
||||
final accepted = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => const _NetworkMapOptInDialog(),
|
||||
);
|
||||
if (accepted == true) {
|
||||
await settingsService.setNetworkMapUploadEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
class _NetworkMapOptInDialog extends StatelessWidget {
|
||||
const _NetworkMapOptInDialog();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
|
||||
return AlertDialog(
|
||||
icon: Icon(Icons.public, size: 36, color: scheme.primary),
|
||||
title: Text(l10n.networkMap_promptTitle),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.networkMap_promptBody,
|
||||
style: textTheme.bodyLarge?.copyWith(height: 1.4),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
l10n.networkMap_promptSettingsHint,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: TextButton.icon(
|
||||
style: TextButton.styleFrom(padding: EdgeInsets.zero),
|
||||
icon: const Icon(Icons.open_in_new, size: 20),
|
||||
label: Text(l10n.networkMap_whatWeCollect),
|
||||
onPressed: () => launchUrl(
|
||||
Uri.parse('$networkMapBaseUrl/privacy'),
|
||||
mode: LaunchMode.externalApplication,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text(l10n.networkMap_promptDecline),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text(l10n.networkMap_promptAccept),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/network_map/network_map_api_client.dart';
|
||||
import '../services/network_map/network_map_upload_service.dart';
|
||||
import 'mesh_nav_tile.dart';
|
||||
import 'network_map_online_layer.dart';
|
||||
|
||||
/// Opt-in toggle, plain-language explanation and status for network map
|
||||
/// uploads.
|
||||
class NetworkMapSettingsSection extends StatelessWidget {
|
||||
const NetworkMapSettingsSection({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final service = context.watch<NetworkMapUploadService>();
|
||||
final l10n = context.l10n;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SwitchListTile(
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 4,
|
||||
),
|
||||
secondary: const Icon(Icons.public, size: 24),
|
||||
title: Text(l10n.networkMap_uploadTitle),
|
||||
subtitle: Text(_status(context, service)),
|
||||
value: service.enabled,
|
||||
onChanged: service.setEnabled,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
|
||||
child: Text(
|
||||
l10n.networkMap_uploadExplanation,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurface,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1, indent: 16),
|
||||
MeshNavTile(
|
||||
icon: Icons.privacy_tip_outlined,
|
||||
title: l10n.networkMap_whatWeCollect,
|
||||
trailing: const Icon(Icons.open_in_new, size: 22),
|
||||
showChevron: false,
|
||||
onTap: () => launchUrl(
|
||||
Uri.parse('$networkMapBaseUrl/privacy'),
|
||||
mode: LaunchMode.externalApplication,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _status(BuildContext context, NetworkMapUploadService service) {
|
||||
final l10n = context.l10n;
|
||||
if (!service.enabled) return l10n.networkMap_statusOff;
|
||||
final last = service.lastUploadAt;
|
||||
if (last != null) {
|
||||
return l10n.networkMap_statusLastSent(
|
||||
networkMapTimeAgo(context, last),
|
||||
service.packetsSentToday,
|
||||
);
|
||||
}
|
||||
if (!service.isActive) return l10n.networkMap_statusWaiting;
|
||||
return l10n.networkMap_statusNothingSent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
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
|
||||
/// are listed live and can be added as contacts.
|
||||
Future<void> showNodeScanSheet(
|
||||
BuildContext context,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
return showMeshSheet<void>(
|
||||
context,
|
||||
builder: (_) => NodeScanSheet(connector: connector),
|
||||
);
|
||||
}
|
||||
|
||||
class NodeScanSheet extends StatefulWidget {
|
||||
const NodeScanSheet({super.key, required this.connector});
|
||||
|
||||
final MeshCoreConnector connector;
|
||||
|
||||
@override
|
||||
State<NodeScanSheet> createState() => _NodeScanSheetState();
|
||||
}
|
||||
|
||||
class _NodeScanSheetState extends State<NodeScanSheet> {
|
||||
final List<NodeDiscoverResponse> _results = [];
|
||||
final Set<String> _adding = {};
|
||||
StreamSubscription<NodeDiscoverResponse>? _subscription;
|
||||
bool _scanning = false;
|
||||
bool _failed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_startScan();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subscription?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _startScan() {
|
||||
_subscription?.cancel();
|
||||
setState(() {
|
||||
_results.clear();
|
||||
_scanning = true;
|
||||
_failed = false;
|
||||
});
|
||||
_subscription = widget.connector.discoverNearbyNodes().listen(
|
||||
(response) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_results
|
||||
..add(response)
|
||||
..sort((a, b) => b.snr.compareTo(a.snr));
|
||||
});
|
||||
},
|
||||
onError: (Object _) {
|
||||
if (!mounted) return;
|
||||
setState(() => _failed = true);
|
||||
},
|
||||
onDone: () {
|
||||
if (!mounted) return;
|
||||
setState(() => _scanning = false);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
bool _isContact(NodeDiscoverResponse response) {
|
||||
final keyHex = response.publicKeyHex;
|
||||
return widget.connector.contacts.any(
|
||||
(contact) => contact.publicKeyHex.startsWith(keyHex),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _add(NodeDiscoverResponse response) async {
|
||||
final keyHex = response.publicKeyHex;
|
||||
setState(() => _adding.add(keyHex));
|
||||
final contact = widget.connector.contactForDiscoverResponse(response);
|
||||
var imported = false;
|
||||
try {
|
||||
imported = await widget.connector.importDiscoveredContact(contact);
|
||||
} catch (_) {
|
||||
imported = false;
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() => _adding.remove(keyHex));
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(
|
||||
imported
|
||||
? context.l10n.discoveredContacts_contactAdded
|
||||
: context.l10n.contacts_contactImportFailed,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final status = _failed
|
||||
? l10n.discoveredContacts_scanFailed
|
||||
: _scanning
|
||||
? l10n.discoveredContacts_scanning
|
||||
: l10n.discoveredContacts_scanFound(_results.length);
|
||||
|
||||
return ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
BottomSheetHeader(
|
||||
title: l10n.discoveredContacts_scanTitle,
|
||||
subtitle: status,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
|
||||
child: Text(
|
||||
l10n.discoveredContacts_scanExplanation,
|
||||
style: TextStyle(fontSize: 14, color: scheme.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
if (_scanning) const LinearProgressIndicator(minHeight: 3),
|
||||
Flexible(
|
||||
child: _results.isEmpty
|
||||
? Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: _scanning
|
||||
? const SizedBox.shrink()
|
||||
: Text(
|
||||
l10n.discoveredContacts_scanNoResults,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 15),
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
itemCount: _results.length,
|
||||
itemBuilder: (context, index) =>
|
||||
_buildResult(context, _results[index]),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
|
||||
child: FilledButton.icon(
|
||||
onPressed: _scanning ? null : _startScan,
|
||||
icon: const Icon(Icons.radar, size: 20),
|
||||
label: Text(l10n.discoveredContacts_scanAgain),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildResult(BuildContext context, NodeDiscoverResponse response) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final contact = widget.connector.contactForDiscoverResponse(response);
|
||||
final known = _isKnownNode(contact);
|
||||
final inContacts = _isContact(response);
|
||||
final adding = _adding.contains(response.publicKeyHex);
|
||||
final color = contactTypeColor(response.nodeType);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: MeshCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
AvatarCircle(
|
||||
name: contact.name,
|
||||
size: 42,
|
||||
color: color,
|
||||
icon: contactTypeIcon(response.nodeType),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
contact.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
StatusChip(
|
||||
label: contact.typeLabel(l10n).toUpperCase(),
|
||||
color: color,
|
||||
icon: contactTypeIcon(response.nodeType),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
SignalBars(snr: response.snr, height: 16),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.discoveredContacts_scanSignal(
|
||||
response.snr.toStringAsFixed(1),
|
||||
response.remoteSnr.toStringAsFixed(1),
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
inContacts
|
||||
? l10n.discoveredContacts_scanInContacts
|
||||
: known
|
||||
? contact.shortPubKeyHex
|
||||
: l10n.discoveredContacts_scanNameLater,
|
||||
style: MeshTheme.mono(
|
||||
fontSize: 12,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (inContacts)
|
||||
Icon(Icons.check_circle, size: 24, color: MeshPalette.signal)
|
||||
else if (adding)
|
||||
const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
tooltip: l10n.discoveredContacts_addContact,
|
||||
icon: const Icon(Icons.person_add_alt_1),
|
||||
onPressed: response.hasFullKey ? () => _add(response) : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool _isKnownNode(Contact contact) =>
|
||||
contact.isActive ||
|
||||
widget.connector.discoveredContacts.any(
|
||||
(c) => c.publicKeyHex == contact.publicKeyHex,
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,6 +1,38 @@
|
||||
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.
|
||||
///
|
||||
/// Features:
|
||||
@@ -30,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;
|
||||
|
||||
@@ -47,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),
|
||||
@@ -150,81 +188,110 @@ class _QrScannerWidgetState extends State<QrScannerWidget>
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
// Scanner view
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: _handleDetection,
|
||||
errorBuilder: (context, error) {
|
||||
return _buildErrorWidget(context, error);
|
||||
},
|
||||
),
|
||||
// The camera preview is dark, so keep the system bar icons light, and lift
|
||||
// the controls above the navigation bar the app draws behind.
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: SystemUiOverlayStyle.light,
|
||||
child: Stack(
|
||||
children: [
|
||||
// Scanner view
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: _handleDetection,
|
||||
errorBuilder: (context, error) {
|
||||
return _buildErrorWidget(context, error);
|
||||
},
|
||||
),
|
||||
|
||||
// Overlay
|
||||
widget.overlay ?? _buildDefaultOverlay(context),
|
||||
// Overlay
|
||||
widget.overlay ?? _buildDefaultOverlay(context),
|
||||
|
||||
// Control buttons
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: _buildControls(context),
|
||||
),
|
||||
],
|
||||
// Control buttons
|
||||
Positioned(
|
||||
bottom: 16 + MediaQuery.viewPaddingOf(context).bottom,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: _buildControls(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -243,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,
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -256,49 +320,57 @@ 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;
|
||||
|
||||
switch (error.errorCode) {
|
||||
case MobileScannerErrorCode.permissionDenied:
|
||||
message =
|
||||
'Camera permission denied.\nPlease enable camera access in settings.';
|
||||
message = context.l10n.qr_cameraPermissionDenied;
|
||||
icon = Icons.no_photography;
|
||||
break;
|
||||
case MobileScannerErrorCode.unsupported:
|
||||
message = 'Camera not supported on this device.';
|
||||
message = context.l10n.qr_cameraUnsupported;
|
||||
icon = Icons.videocam_off;
|
||||
break;
|
||||
default:
|
||||
message =
|
||||
'Failed to start camera.\n${error.errorDetails?.message ?? ''}';
|
||||
message = context.l10n.qr_cameraStartFailed(
|
||||
error.errorDetails?.message ?? '',
|
||||
);
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -315,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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,836 @@
|
||||
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;
|
||||
|
||||
/// Companion firmware version that added CMD_SET_PATH_HASH_MODE (v1.14.0).
|
||||
const int _minFirmwareVerCodeForPathHashMode = 10;
|
||||
|
||||
/// 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 _pathHashByteWidth = 1;
|
||||
int? _selectedPresetIndex;
|
||||
_RadioSettingsSnapshot? _lastNonRepeatSnapshot;
|
||||
String? _frequencyError;
|
||||
String? _txPowerError;
|
||||
|
||||
bool get _supportsPathHashMode =>
|
||||
(widget.connector.firmwareVerCode ?? 0) >=
|
||||
_minFirmwareVerCodeForPathHashMode;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
_pathHashByteWidth = widget.connector.pathHashByteWidth;
|
||||
_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();
|
||||
_pathHashByteWidth = preset.pathHashByteWidth;
|
||||
_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));
|
||||
if (_supportsPathHashMode &&
|
||||
_pathHashByteWidth != widget.connector.pathHashByteWidth) {
|
||||
await widget.connector.setPathHashMode(_pathHashByteWidth - 1);
|
||||
}
|
||||
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),
|
||||
if (_supportsPathHashMode) ...[
|
||||
DropdownButtonFormField<int>(
|
||||
initialValue: _pathHashByteWidth,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.repeater_pathHashMode,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
DropdownMenuItem(
|
||||
value: 1,
|
||||
child: Text(l10n.repeater_pathHashModeOption0),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 2,
|
||||
child: Text(l10n.repeater_pathHashModeOption1),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 3,
|
||||
child: Text(l10n.repeater_pathHashModeOption2),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setState(() => _pathHashByteWidth = value);
|
||||
},
|
||||
),
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,8 @@
|
||||
/// with whoever implements export, not here.
|
||||
library;
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../services/received_image_store.dart';
|
||||
@@ -458,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),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -527,6 +526,7 @@ class _ReceivedImageMessageState extends State<ReceivedImageMessage> {
|
||||
png: png,
|
||||
synthesized: entry.synthesized,
|
||||
bytes: entry.bitstreamByteCount,
|
||||
aspectRatio: entry.displayAspectRatio,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -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,
|
||||
@@ -610,44 +612,61 @@ class _ReceivedImageViewer extends StatelessWidget {
|
||||
/// the one in the transcript.
|
||||
final int bytes;
|
||||
|
||||
/// Source shape (w/h) to undo the sender's stretch, as in the bubble. Null
|
||||
/// means square or unknown.
|
||||
final double? aspectRatio;
|
||||
|
||||
const _ReceivedImageViewer({
|
||||
required this.png,
|
||||
required this.synthesized,
|
||||
required this.bytes,
|
||||
this.aspectRatio,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
appBar: AppBar(
|
||||
// Light system bar icons over the black viewer, whatever the app theme.
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: SystemUiOverlayStyle.light,
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: Stack(
|
||||
children: [
|
||||
InteractiveViewer(child: Image.memory(png)),
|
||||
if (synthesized)
|
||||
const Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: _SyntheticBanner(),
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
foregroundColor: Colors.white,
|
||||
systemOverlayStyle: SystemUiOverlayStyle.light,
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: Stack(
|
||||
children: [
|
||||
InteractiveViewer(
|
||||
// fill inside the original aspect box: the exact
|
||||
// inverse of the sender's stretch, as in the bubble.
|
||||
child: AspectRatio(
|
||||
aspectRatio: aspectRatio ?? 1,
|
||||
child: Image.memory(png, fit: BoxFit.fill),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (synthesized)
|
||||
const Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: _SyntheticBanner(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (synthesized)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: _SyntheticCaption(bytes: bytes, onDark: true),
|
||||
),
|
||||
],
|
||||
if (synthesized)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: _SyntheticCaption(bytes: bytes, onDark: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -52,6 +52,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
|
||||
final savedPassword = await _storage.getRepeaterPassword(
|
||||
widget.repeater.publicKeyHex,
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (savedPassword != null) {
|
||||
setState(() {
|
||||
_passwordController.text = savedPassword;
|
||||
@@ -357,7 +358,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
|
||||
obscureText: _obscurePassword,
|
||||
// Firmware stores at most 15 bytes (CommonCLI.h password[16]).
|
||||
inputFormatters: const [
|
||||
Utf8LengthLimitingTextInputFormatter(15),
|
||||
Utf8LengthLimitingTextInputFormatter(20),
|
||||
],
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.login_password,
|
||||
@@ -422,7 +423,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
|
||||
l10n.login_routing,
|
||||
style: MeshTheme.accentLabel(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 11,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
@@ -500,7 +501,7 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
|
||||
pathHashByteWidth: connector.pathHashByteWidth,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontSize: 13,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -48,6 +48,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
|
||||
final savedPassword = await _storage.getRepeaterPassword(
|
||||
widget.room.publicKeyHex,
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (savedPassword != null) {
|
||||
setState(() {
|
||||
_passwordController.text = savedPassword;
|
||||
@@ -294,7 +295,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
|
||||
obscureText: _obscurePassword,
|
||||
// Firmware stores at most 15 bytes (CommonCLI.h password[16]).
|
||||
inputFormatters: const [
|
||||
Utf8LengthLimitingTextInputFormatter(15),
|
||||
Utf8LengthLimitingTextInputFormatter(20),
|
||||
],
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.login_password,
|
||||
@@ -354,7 +355,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
|
||||
l10n.login_routing,
|
||||
style: MeshTheme.accentLabel(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 11,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
@@ -432,7 +433,7 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
|
||||
pathHashByteWidth: connector.pathHashByteWidth,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontSize: 12,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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(
|
||||
@@ -577,8 +577,7 @@ class _RoutingSheetBodyState extends State<_RoutingSheetBody> {
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onSecondaryTapUp: PlatformInfo.isDesktop && hasBytes
|
||||
? (_) =>
|
||||
_showPathDetail(context, connector, contact, record)
|
||||
? (_) => _showPathDetail(context, connector, contact, record)
|
||||
: null,
|
||||
child: Card(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
@@ -597,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(
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ class UnreadBadge extends StatelessWidget {
|
||||
child: Text(
|
||||
display,
|
||||
style: MeshTheme.mono(
|
||||
fontSize: 11,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.white,
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
Reference in new issue
Block a user