Merge upstream/dev (35 commits) into tth
Conflicts in lib/widgets/mesh_nav_tile.dart and lib/widgets/mesh_ui.dart: took upstream's iconSlot/ThemedIcon, busy spinner and SectionHeader description, and re-applied the terminal theme on top (18 dp icons, narrower gaps and padding, mono section labels). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ceab62428a
103 files changed
+13328
-5463
No files matched your search
@@ -1,364 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/app_settings.dart';
|
||||
import '../models/chat_compression_mode.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
import 'mesh_nav_tile.dart';
|
||||
import 'mesh_ui.dart';
|
||||
|
||||
export '../models/chat_compression_mode.dart';
|
||||
|
||||
/// Always-visible "Compression: Off / SMAZ / Cyr2Lat" strip for the top of a
|
||||
/// DM or channel chat. Tapping it opens one sheet with the three choices,
|
||||
/// what each does, and the Cyr2Lat profile picker.
|
||||
///
|
||||
/// The parent supplies the saved state and persists changes through the
|
||||
/// callbacks; this widget only shows a new mode once the parent rebuilds it
|
||||
/// with that mode. A callback that throws leaves the saved mode in place and
|
||||
/// shows an error in the sheet.
|
||||
class ChatCompressionSelector extends StatefulWidget {
|
||||
final ChatCompressionMode mode;
|
||||
|
||||
/// False disables the strip and the sheet; [disabledReason] says why.
|
||||
final bool enabled;
|
||||
final String? disabledReason;
|
||||
|
||||
final List<Cyr2LatProfile> profiles;
|
||||
|
||||
/// The Cyr2Lat profile saved for this chat, if any.
|
||||
final String? profileId;
|
||||
|
||||
/// The app-wide profile, which sending uses when [profileId] is unset or
|
||||
/// no longer exists.
|
||||
final String? defaultProfileId;
|
||||
|
||||
final Future<void> Function(ChatCompressionMode mode) onModeChanged;
|
||||
final Future<void> Function(String profileId) onProfileChanged;
|
||||
|
||||
const ChatCompressionSelector({
|
||||
super.key,
|
||||
required this.mode,
|
||||
required this.enabled,
|
||||
this.disabledReason,
|
||||
required this.profiles,
|
||||
required this.profileId,
|
||||
this.defaultProfileId,
|
||||
required this.onModeChanged,
|
||||
required this.onProfileChanged,
|
||||
});
|
||||
|
||||
/// The profile sending actually uses, matching the connector's fallback.
|
||||
String? get effectiveProfileId {
|
||||
bool known(String? id) => profiles.any((p) => p.id == id);
|
||||
if (known(profileId)) return profileId;
|
||||
if (known(defaultProfileId)) return defaultProfileId;
|
||||
return profiles.isEmpty ? null : profiles.first.id;
|
||||
}
|
||||
|
||||
@override
|
||||
State<ChatCompressionSelector> createState() =>
|
||||
_ChatCompressionSelectorState();
|
||||
}
|
||||
|
||||
String chatCompressionModeLabel(BuildContext context, ChatCompressionMode m) {
|
||||
final l10n = context.l10n;
|
||||
return switch (m) {
|
||||
ChatCompressionMode.off => l10n.chatCompression_off,
|
||||
ChatCompressionMode.smaz => l10n.chatCompression_smaz,
|
||||
ChatCompressionMode.cyr2lat => l10n.chatCompression_cyr2lat,
|
||||
};
|
||||
}
|
||||
|
||||
/// What the open sheet renders. The sheet is a separate route, so it listens
|
||||
/// to this instead of rebuilding with the strip.
|
||||
class _SelectorView {
|
||||
final ChatCompressionMode mode;
|
||||
final bool enabled;
|
||||
final List<Cyr2LatProfile> profiles;
|
||||
final String? profileId;
|
||||
final bool busy;
|
||||
final bool failed;
|
||||
|
||||
/// Counts failed saves, so the profile picker drops an unsaved choice.
|
||||
final int failures;
|
||||
|
||||
const _SelectorView({
|
||||
required this.mode,
|
||||
required this.enabled,
|
||||
required this.profiles,
|
||||
required this.profileId,
|
||||
required this.busy,
|
||||
required this.failed,
|
||||
required this.failures,
|
||||
});
|
||||
}
|
||||
|
||||
class _ChatCompressionSelectorState extends State<ChatCompressionSelector> {
|
||||
late final ValueNotifier<_SelectorView> _view = ValueNotifier(_snapshot());
|
||||
bool _busy = false;
|
||||
bool _failed = false;
|
||||
int _failures = 0;
|
||||
|
||||
_SelectorView _snapshot() => _SelectorView(
|
||||
mode: widget.mode,
|
||||
enabled: widget.enabled,
|
||||
profiles: widget.profiles,
|
||||
profileId: widget.effectiveProfileId,
|
||||
busy: _busy,
|
||||
failed: _failed,
|
||||
failures: _failures,
|
||||
);
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatCompressionSelector oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// The sheet route is not below this widget, so it can't be marked dirty
|
||||
// during this build.
|
||||
SchedulerBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _view.value = _snapshot();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_view.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _setBusy(bool busy, {required bool failed}) {
|
||||
setState(() {
|
||||
_busy = busy;
|
||||
_failed = failed;
|
||||
if (failed) _failures++;
|
||||
});
|
||||
_view.value = _snapshot();
|
||||
}
|
||||
|
||||
/// Runs one save; returns whether it succeeded.
|
||||
Future<bool> _save(Future<void> Function() write) async {
|
||||
if (_busy || !widget.enabled) return false;
|
||||
_setBusy(true, failed: false);
|
||||
var ok = false;
|
||||
try {
|
||||
await write();
|
||||
ok = true;
|
||||
} catch (e) {
|
||||
debugPrint('[ChatCompressionSelector] save failed: $e');
|
||||
}
|
||||
if (mounted) _setBusy(false, failed: !ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
Future<void> _openSheet() async {
|
||||
if (_failed) _setBusy(false, failed: false);
|
||||
await showMeshSheet<void>(
|
||||
context,
|
||||
builder: (sheetContext) => ValueListenableBuilder<_SelectorView>(
|
||||
valueListenable: _view,
|
||||
builder: (sheetContext, view, _) => _buildSheet(sheetContext, view),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSheet(BuildContext context, _SelectorView view) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final canChange = view.enabled && !view.busy;
|
||||
|
||||
MeshSheetOption option(ChatCompressionMode mode, String description) {
|
||||
return MeshSheetOption(
|
||||
label: chatCompressionModeLabel(context, mode),
|
||||
subtitle: description,
|
||||
selected: view.mode == mode,
|
||||
onTap: canChange
|
||||
? () async {
|
||||
final ok = await _save(() => widget.onModeChanged(mode));
|
||||
// Cyr2Lat stays open so its profile can be picked.
|
||||
if (ok && mode != ChatCompressionMode.cyr2lat) {
|
||||
if (context.mounted) Navigator.of(context).maybePop();
|
||||
}
|
||||
}
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
final profileValue = view.profileId;
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
BottomSheetHeader(
|
||||
title: l10n.chatCompression_title,
|
||||
subtitle: l10n.chatCompression_sheetSubtitle,
|
||||
trailing: view.busy
|
||||
? const Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (view.failed)
|
||||
Container(
|
||||
margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: scheme.errorContainer,
|
||||
borderRadius: BorderRadius.circular(MeshRadii.sm),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
color: scheme.onErrorContainer,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.chatCompression_saveFailed,
|
||||
style: Theme.of(context).textTheme.bodyMedium
|
||||
?.copyWith(color: scheme.onErrorContainer),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!view.enabled && widget.disabledReason != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
child: Text(
|
||||
widget.disabledReason!,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
option(
|
||||
ChatCompressionMode.off,
|
||||
l10n.chatCompression_offDescription,
|
||||
),
|
||||
option(
|
||||
ChatCompressionMode.smaz,
|
||||
l10n.chatCompression_smazDescription,
|
||||
),
|
||||
option(
|
||||
ChatCompressionMode.cyr2lat,
|
||||
l10n.chatCompression_cyr2latDescription,
|
||||
),
|
||||
if (view.mode == ChatCompressionMode.cyr2lat &&
|
||||
view.profiles.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||
child: DropdownButtonFormField<String>(
|
||||
// The field keeps a picked value internally, so rebuild
|
||||
// it with the saved value after a change or a failure.
|
||||
key: ValueKey('$profileValue#${view.failures}'),
|
||||
isExpanded: true,
|
||||
initialValue: profileValue,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.chatCompression_profile,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
for (final profile in view.profiles)
|
||||
DropdownMenuItem(
|
||||
value: profile.id,
|
||||
child: Text(
|
||||
profile.name,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
onChanged: canChange
|
||||
? (id) {
|
||||
if (id == null || id == profileValue) return;
|
||||
_save(() => widget.onProfileChanged(id));
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
final l10n = context.l10n;
|
||||
final label = l10n.chatCompression_label(
|
||||
chatCompressionModeLabel(context, widget.mode),
|
||||
);
|
||||
final reason = widget.enabled ? null : widget.disabledReason;
|
||||
|
||||
// One short row: the chat already leaves little room for messages at
|
||||
// large text sizes, so a disabled strip explains itself in the sheet.
|
||||
return Material(
|
||||
color: scheme.surfaceContainerLow,
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(bottom: BorderSide(color: scheme.outlineVariant)),
|
||||
),
|
||||
child: MergeSemantics(
|
||||
child: Semantics(
|
||||
button: true,
|
||||
enabled: !_busy,
|
||||
label: reason == null ? label : '$label. $reason',
|
||||
hint: l10n.chatCompression_changeHint,
|
||||
child: InkWell(
|
||||
onTap: _busy ? null : _openSheet,
|
||||
child: ExcludeSemantics(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(minHeight: 48),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: scheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
if (_busy)
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
Icon(
|
||||
widget.enabled
|
||||
? Icons.arrow_drop_down
|
||||
: Icons.lock_outline,
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import 'chat_day_separator.dart';
|
||||
import 'empty_state.dart';
|
||||
import 'sync_progress_overlay.dart';
|
||||
|
||||
/// Results list for "search in this chat". Loads the full history through
|
||||
/// [loadEntries] (once, cached) and re-filters on each debounced [query].
|
||||
@@ -86,10 +87,7 @@ class _ChatSearchResultsState extends State<ChatSearchResults> {
|
||||
final showEmpty = !_loading && _results.isEmpty;
|
||||
return Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 3,
|
||||
child: _loading ? const LinearProgressIndicator() : null,
|
||||
),
|
||||
MeshProgressBar(active: _loading),
|
||||
if (!_loading && _results.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 10, 16, 6),
|
||||
|
||||
@@ -219,3 +219,42 @@ Future<bool> confirmClearChat(
|
||||
);
|
||||
return confirmed == true;
|
||||
}
|
||||
|
||||
/// Asks before removing [count] bookmarked messages.
|
||||
Future<bool> confirmRemoveBookmarks(
|
||||
BuildContext context, {
|
||||
int count = 1,
|
||||
}) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
final l10n = dialogContext.l10n;
|
||||
return AlertDialog(
|
||||
title: Text(
|
||||
count == 1
|
||||
? l10n.bookmarks_removeConfirmTitle
|
||||
: l10n.bookmarks_removeSelectedConfirmTitle,
|
||||
),
|
||||
content: Text(
|
||||
count == 1
|
||||
? l10n.bookmarks_removeConfirmMessage
|
||||
: l10n.bookmarks_removeSelectedConfirmMessage(count),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(dialogContext).colorScheme.error,
|
||||
),
|
||||
child: Text(l10n.common_remove),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
return confirmed == true;
|
||||
}
|
||||
@@ -4,14 +4,27 @@ import 'package:provider/provider.dart';
|
||||
import '../services/chat_text_scale_service.dart';
|
||||
|
||||
/// Gesture wrapper that exposes two-finger pinch-to-zoom for chat scrollables.
|
||||
/// Double-tap resets the scale. Only the wrapper itself listens to gestures;
|
||||
/// child scrollables keep their normal touch handling.
|
||||
/// Double-tap resets the scale, but only while the text is zoomed (or the
|
||||
/// caller supplies [onDoubleTap]) and [enabled] is true: a double-tap
|
||||
/// recognizer in the gesture arena makes every single tap on the child wait
|
||||
/// 300 ms, so it is left out wherever taps must be instant. Only the wrapper
|
||||
/// itself listens to gestures; child scrollables keep their normal touch
|
||||
/// handling.
|
||||
class ChatZoomWrapper extends StatefulWidget {
|
||||
const ChatZoomWrapper({super.key, required this.child, this.onDoubleTap});
|
||||
const ChatZoomWrapper({
|
||||
super.key,
|
||||
required this.child,
|
||||
this.onDoubleTap,
|
||||
this.enabled = true,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final VoidCallback? onDoubleTap;
|
||||
|
||||
/// When false (e.g. while selecting messages) no double-tap is recognized,
|
||||
/// so taps on the child are never delayed or swallowed.
|
||||
final bool enabled;
|
||||
|
||||
@override
|
||||
State<ChatZoomWrapper> createState() => _ChatZoomWrapperState();
|
||||
}
|
||||
@@ -22,14 +35,21 @@ class _ChatZoomWrapperState extends State<ChatZoomWrapper> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final service = context.read<ChatTextScaleService>();
|
||||
final zoomed = context.select<ChatTextScaleService, bool>(
|
||||
(s) => s.scale != 1.0,
|
||||
);
|
||||
final allowDoubleTap =
|
||||
widget.enabled && (zoomed || widget.onDoubleTap != null);
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.translucent,
|
||||
onDoubleTap: () {
|
||||
service.reset();
|
||||
service.persist();
|
||||
widget.onDoubleTap?.call();
|
||||
},
|
||||
onDoubleTap: allowDoubleTap
|
||||
? () {
|
||||
service.reset();
|
||||
service.persist();
|
||||
widget.onDoubleTap?.call();
|
||||
}
|
||||
: null,
|
||||
onScaleStart: (details) {
|
||||
if (details.pointerCount != 2) return;
|
||||
_startScale = service.scale;
|
||||
|
||||
@@ -2,34 +2,40 @@ 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.
|
||||
/// Asks the user to confirm a destructive action (Clear by default). Resolves
|
||||
/// to true only when the user taps the confirm button. [warning] uses the
|
||||
/// amber warning colour instead of red.
|
||||
Future<bool> showConfirmClearDialog(
|
||||
BuildContext context, {
|
||||
required String title,
|
||||
required String message,
|
||||
String? confirmLabel,
|
||||
bool warning = false,
|
||||
}) 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,
|
||||
builder: (dialogContext) {
|
||||
final scheme = Theme.of(dialogContext).colorScheme;
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
content: Text(message),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
child: Text(l10n.common_clear),
|
||||
),
|
||||
],
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: warning ? scheme.tertiary : scheme.error,
|
||||
foregroundColor: warning ? scheme.onTertiary : scheme.onError,
|
||||
),
|
||||
child: Text(confirmLabel ?? l10n.common_clear),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
return confirmed == true;
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class FeatureToggleRow extends StatefulWidget {
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final bool value;
|
||||
final bool enabled;
|
||||
final bool hasRefreshing;
|
||||
final bool isRefreshing;
|
||||
final ValueChanged<bool>? onChanged;
|
||||
final VoidCallback? onRefresh;
|
||||
final String? refreshTooltip;
|
||||
|
||||
const FeatureToggleRow({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.value,
|
||||
this.enabled = true,
|
||||
this.hasRefreshing = false,
|
||||
this.isRefreshing = false,
|
||||
this.onChanged,
|
||||
this.onRefresh,
|
||||
this.refreshTooltip,
|
||||
});
|
||||
|
||||
@override
|
||||
State<FeatureToggleRow> createState() => _FeatureToggleRow();
|
||||
}
|
||||
|
||||
class _FeatureToggleRow extends State<FeatureToggleRow> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final isEnabled = widget.enabled;
|
||||
final titleColor = isEnabled
|
||||
? scheme.onSurface
|
||||
: scheme.onSurfaceVariant.withValues(alpha: 0.7);
|
||||
final subtitleColor = isEnabled
|
||||
? scheme.onSurfaceVariant
|
||||
: scheme.onSurfaceVariant.withValues(alpha: 0.55);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
widget.title,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: titleColor,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
widget.subtitle,
|
||||
style: textTheme.bodySmall?.copyWith(color: subtitleColor),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Switch(
|
||||
value: widget.value,
|
||||
onChanged: isEnabled ? widget.onChanged : null,
|
||||
thumbColor: !isEnabled
|
||||
? WidgetStatePropertyAll<Color?>(scheme.onSurfaceVariant)
|
||||
: null,
|
||||
trackColor: !isEnabled
|
||||
? WidgetStatePropertyAll<Color?>(
|
||||
scheme.onSurfaceVariant.withValues(alpha: 0.35),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
if (widget.hasRefreshing) ...[
|
||||
const SizedBox(width: 4),
|
||||
widget.isRefreshing
|
||||
? SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 1.8,
|
||||
color: scheme.primary,
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.refresh, size: 18),
|
||||
onPressed: isEnabled ? widget.onRefresh : null,
|
||||
tooltip: widget.refreshTooltip,
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 32,
|
||||
minHeight: 32,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/terminal_theme.dart';
|
||||
import '../theme/theme_icons.dart';
|
||||
|
||||
/// Title style of settings rows: [MeshNavTile] and, through
|
||||
/// [MeshSettingsTileTheme], stock [ListTile]s and [SwitchListTile]s.
|
||||
@@ -34,12 +35,20 @@ class MeshSettingsTileTheme extends StatelessWidget {
|
||||
/// looks identical to one that can.
|
||||
class MeshNavTile extends StatelessWidget {
|
||||
final IconData icon;
|
||||
|
||||
/// Theme icon to show instead of [icon], so the row follows the user's
|
||||
/// theme like the contact list does.
|
||||
final ThemeIconSlot? iconSlot;
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final VoidCallback? onTap;
|
||||
final Color? titleColor;
|
||||
final Color? iconColor;
|
||||
final bool showChevron;
|
||||
|
||||
/// Shows the 18px spinner in place of the chevron and ignores taps while
|
||||
/// the row's action runs (e.g. a radio command). The row isn't dimmed.
|
||||
final bool busy;
|
||||
final Widget? trailing;
|
||||
final int? subtitleMaxLines;
|
||||
final EdgeInsetsGeometry padding;
|
||||
@@ -47,12 +56,14 @@ class MeshNavTile extends StatelessWidget {
|
||||
const MeshNavTile({
|
||||
super.key,
|
||||
required this.icon,
|
||||
this.iconSlot,
|
||||
required this.title,
|
||||
this.subtitle,
|
||||
this.onTap,
|
||||
this.titleColor,
|
||||
this.iconColor,
|
||||
this.showChevron = true,
|
||||
this.busy = false,
|
||||
this.trailing,
|
||||
this.subtitleMaxLines,
|
||||
this.padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
@@ -70,7 +81,9 @@ class MeshNavTile extends StatelessWidget {
|
||||
|
||||
final row = Row(
|
||||
children: [
|
||||
Icon(icon, size: iconSize, color: effectiveIconColor),
|
||||
iconSlot == null
|
||||
? Icon(icon, size: iconSize, color: effectiveIconColor)
|
||||
: ThemedIcon(iconSlot!, size: iconSize, color: effectiveIconColor),
|
||||
SizedBox(width: terminal ? 10 : 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
@@ -106,7 +119,17 @@ class MeshNavTile extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
?trailing,
|
||||
if (showChevron && trailing == null)
|
||||
if (busy && trailing == null)
|
||||
SizedBox.square(
|
||||
dimension: iconSize,
|
||||
child: const Center(
|
||||
child: SizedBox.square(
|
||||
dimension: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (showChevron && trailing == null)
|
||||
Icon(
|
||||
Icons.chevron_right,
|
||||
color: scheme.onSurfaceVariant,
|
||||
@@ -118,9 +141,9 @@ class MeshNavTile extends StatelessWidget {
|
||||
return MergeSemantics(
|
||||
child: Semantics(
|
||||
button: true,
|
||||
enabled: enabled,
|
||||
enabled: enabled && !busy,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
onTap: busy ? null : onTap,
|
||||
child: Padding(
|
||||
padding: terminal
|
||||
? const EdgeInsets.symmetric(horizontal: 8, vertical: 5)
|
||||
|
||||
+77
-27
@@ -13,52 +13,71 @@ import 'contact_visuals.dart';
|
||||
/// MeshCore shared design kit.
|
||||
///
|
||||
/// Building blocks used across all screens so the app reads as one product:
|
||||
/// [SectionHeader], [MeshCard], [StatusChip], [StatTile], [AvatarCircle],
|
||||
/// [SectionHeader], [MeshCard], [MeshInfoCard], [StatusChip], [StatTile],
|
||||
/// [AvatarCircle],
|
||||
/// [SignalBars], [RouteChip], [PulseDot], [BottomSheetHeader] +
|
||||
/// [showMeshSheet], [ErrorRetryCard], [ListEntrance], [MeshSegmentLabel]
|
||||
/// and [MeshMenuItemRow].
|
||||
|
||||
/// Small-caps mono section label, optionally with a trailing widget.
|
||||
/// Small-caps mono section label, optionally with a trailing widget and a
|
||||
/// short [description] under it.
|
||||
class SectionHeader extends StatelessWidget {
|
||||
final String label;
|
||||
final Widget? trailing;
|
||||
final String? description;
|
||||
final EdgeInsetsGeometry padding;
|
||||
|
||||
const SectionHeader(
|
||||
this.label, {
|
||||
super.key,
|
||||
this.trailing,
|
||||
this.description,
|
||||
this.padding = const EdgeInsets.fromLTRB(16, 20, 16, 8),
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: MeshStyle.of(context).terminal
|
||||
? const EdgeInsets.fromLTRB(8, 10, 8, 2)
|
||||
: padding,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label.toUpperCase(),
|
||||
style: MeshStyle.of(context).terminal
|
||||
? MeshTheme.mono(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
)
|
||||
: MeshTheme.accentLabel(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 13,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
final terminal = MeshStyle.of(context).terminal;
|
||||
final row = Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label.toUpperCase(),
|
||||
style: terminal
|
||||
? MeshTheme.mono(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
)
|
||||
: MeshTheme.accentLabel(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontSize: 13,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
?trailing,
|
||||
],
|
||||
),
|
||||
),
|
||||
?trailing,
|
||||
],
|
||||
);
|
||||
return Padding(
|
||||
padding: terminal ? const EdgeInsets.fromLTRB(8, 10, 8, 2) : padding,
|
||||
child: description == null
|
||||
? row
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
row,
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
description!,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -127,6 +146,37 @@ class MeshCard extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// [MeshCard] with an info icon and a short note, for the top of a page.
|
||||
class MeshInfoCard extends StatelessWidget {
|
||||
final String text;
|
||||
|
||||
const MeshInfoCard(this.text, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
return MeshCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.info_outline, size: 24, color: scheme.onSurfaceVariant),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: scheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tinted pill chip for statuses: a dot or icon plus a short label.
|
||||
/// Contrast ratio between two opaque colors (WCAG definition).
|
||||
double meshContrastRatio(Color a, Color b) {
|
||||
|
||||
@@ -41,31 +41,33 @@ Future<void> showMessageTranslationSheet({
|
||||
required ValueChanged<bool> onEnabledChanged,
|
||||
required ValueChanged<String?> onLanguageSelected,
|
||||
}) {
|
||||
final callerMedia = MediaQuery.of(context);
|
||||
final navMedia =
|
||||
MediaQuery.maybeOf(Navigator.of(context).context) ?? callerMedia;
|
||||
final callerBottom = math.max(
|
||||
callerMedia.viewInsets.bottom,
|
||||
math.max(callerMedia.viewPadding.bottom, callerMedia.padding.bottom),
|
||||
);
|
||||
final navBottom = math.max(
|
||||
navMedia.viewInsets.bottom,
|
||||
math.max(navMedia.viewPadding.bottom, navMedia.padding.bottom),
|
||||
);
|
||||
final extraBottom = math.max(0.0, callerBottom - navBottom);
|
||||
final safeTop = math.max(
|
||||
math.max(callerMedia.viewPadding.top, callerMedia.padding.top),
|
||||
math.max(navMedia.viewPadding.top, navMedia.padding.top),
|
||||
);
|
||||
final bottomSafeInset = math.max(
|
||||
math.max(callerMedia.viewPadding.bottom, callerMedia.padding.bottom),
|
||||
math.max(navMedia.viewPadding.bottom, navMedia.padding.bottom),
|
||||
);
|
||||
|
||||
return showMeshSheet<void>(
|
||||
context,
|
||||
builder: (sheetContext) {
|
||||
final sheetMedia = MediaQuery.of(sheetContext);
|
||||
final callerMedia =
|
||||
(context.mounted ? MediaQuery.maybeOf(context) : null) ?? sheetMedia;
|
||||
final navContext = Navigator.maybeOf(sheetContext)?.context;
|
||||
final navMedia =
|
||||
(navContext != null ? MediaQuery.maybeOf(navContext) : null) ??
|
||||
callerMedia;
|
||||
final callerBottom = math.max(
|
||||
callerMedia.viewInsets.bottom,
|
||||
math.max(callerMedia.viewPadding.bottom, callerMedia.padding.bottom),
|
||||
);
|
||||
final navBottom = math.max(
|
||||
navMedia.viewInsets.bottom,
|
||||
math.max(navMedia.viewPadding.bottom, navMedia.padding.bottom),
|
||||
);
|
||||
final extraBottom = math.max(0.0, callerBottom - navBottom);
|
||||
final safeTop = math.max(
|
||||
math.max(callerMedia.viewPadding.top, callerMedia.padding.top),
|
||||
math.max(navMedia.viewPadding.top, navMedia.padding.top),
|
||||
);
|
||||
final bottomSafeInset = math.max(
|
||||
math.max(callerMedia.viewPadding.bottom, callerMedia.padding.bottom),
|
||||
math.max(navMedia.viewPadding.bottom, navMedia.padding.bottom),
|
||||
);
|
||||
final screenHeight = math.min(
|
||||
callerMedia.size.height,
|
||||
sheetMedia.size.height,
|
||||
|
||||
@@ -1,892 +0,0 @@
|
||||
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';
|
||||
import '../utils/radio_guard.dart';
|
||||
|
||||
/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others)
|
||||
/// to the UI enum range (always 5-8).
|
||||
int _toUiCodingRate(int deviceCr) {
|
||||
return deviceCr <= 4 ? deviceCr + 4 : deviceCr;
|
||||
}
|
||||
|
||||
const Set<int> _defaultRepeatFreqsKHz = {433000, 869495, 918000};
|
||||
|
||||
/// Whether the firmware accepts [freqKHz] for off-grid client repeat, using
|
||||
/// the ranges from CMD_GET_ALLOWED_REPEAT_FREQ when known.
|
||||
bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) {
|
||||
final ranges = connector.allowedRepeatFreqRanges;
|
||||
if (ranges == null || ranges.isEmpty) {
|
||||
return _defaultRepeatFreqsKHz.contains(freqKHz);
|
||||
}
|
||||
return ranges.any((r) => freqKHz >= r.lowKHz && freqKHz <= r.highKHz);
|
||||
}
|
||||
|
||||
/// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER).
|
||||
const int _minTxPowerDbm = -9;
|
||||
|
||||
/// Radio parameter editor (preset, frequency, bandwidth, SF, CR, TX power,
|
||||
/// path-hash size 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.supportsPathHashMode;
|
||||
|
||||
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();
|
||||
_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 {
|
||||
if (!ensureRadioConnected(context)) return;
|
||||
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));
|
||||
// setPathHashMode updates the local width optimistically; the refreshed
|
||||
// DEVICE_INFO below overwrites it with what the radio actually stored.
|
||||
final requestedPathHashWidth =
|
||||
_supportsPathHashMode &&
|
||||
_pathHashByteWidth != widget.connector.pathHashByteWidth
|
||||
? _pathHashByteWidth
|
||||
: null;
|
||||
if (requestedPathHashWidth != null) {
|
||||
await widget.connector.setPathHashMode(requestedPathHashWidth - 1);
|
||||
}
|
||||
final selfInfo = widget.connector.receivedFrames
|
||||
.firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo)
|
||||
.timeout(const Duration(seconds: 5));
|
||||
final deviceInfo = requestedPathHashWidth == null
|
||||
? null
|
||||
: widget.connector.receivedFrames
|
||||
.firstWhere((f) => f.isNotEmpty && f[0] == respCodeDeviceInfo)
|
||||
.timeout(const Duration(seconds: 5));
|
||||
await widget.connector.refreshDeviceInfo();
|
||||
// Without a refreshed DEVICE_INFO the path hash change is unconfirmed
|
||||
// (this also covers setPathHashMode skipping a disconnected radio).
|
||||
final pathHashApplied =
|
||||
deviceInfo == null ||
|
||||
await deviceInfo.then(
|
||||
(_) => widget.connector.pathHashByteWidth == requestedPathHashWidth,
|
||||
onError: (_) => false,
|
||||
);
|
||||
final radioApplied = await selfInfo.then(
|
||||
(_) => _deviceMatches(
|
||||
freqHz: freqHz,
|
||||
bwHz: bwHz,
|
||||
sf: sf,
|
||||
cr: cr,
|
||||
txPower: txPower,
|
||||
clientRepeat: knownRepeat ? _clientRepeat : null,
|
||||
),
|
||||
onError: (_) => true,
|
||||
);
|
||||
if (!radioApplied) {
|
||||
_logRadioSettingsState('Radio did not apply requested settings');
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_radioSettingsNotApplied),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!pathHashApplied) {
|
||||
// Radio params and TX power were already applied; only the path
|
||||
// hash size is outstanding, so say that rather than a generic error.
|
||||
_logRadioSettingsState('Radio did not apply requested path hash size');
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_pathHashModeNotApplied),
|
||||
);
|
||||
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 '
|
||||
'pathHash=${_pathHashByteWidth}B '
|
||||
'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>(
|
||||
isExpanded: true,
|
||||
initialValue: _bandwidth,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_bandwidth,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: LoRaBandwidth.values
|
||||
.map(
|
||||
(bw) => DropdownMenuItem(
|
||||
value: bw,
|
||||
child: Text(bw.label, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() {
|
||||
_bandwidth = value;
|
||||
_syncPresetSelection();
|
||||
});
|
||||
_logRadioSettingsState('Manual settings edit: bandwidth');
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<LoRaSpreadingFactor>(
|
||||
isExpanded: true,
|
||||
initialValue: _spreadingFactor,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_spreadingFactor,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: LoRaSpreadingFactor.values
|
||||
.map(
|
||||
(sf) => DropdownMenuItem(
|
||||
value: sf,
|
||||
child: Text(sf.label, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() {
|
||||
_spreadingFactor = value;
|
||||
_syncPresetSelection();
|
||||
});
|
||||
_logRadioSettingsState(
|
||||
'Manual settings edit: spreading factor',
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<LoRaCodingRate>(
|
||||
isExpanded: true,
|
||||
initialValue: _codingRate,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_codingRate,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: LoRaCodingRate.values
|
||||
.map(
|
||||
(cr) => DropdownMenuItem(
|
||||
value: cr,
|
||||
child: Text(cr.label, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() {
|
||||
_codingRate = value;
|
||||
_syncPresetSelection();
|
||||
});
|
||||
_logRadioSettingsState('Manual settings edit: coding rate');
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_supportsPathHashMode) ...[
|
||||
// Values are path hash modes (0-2, byte width - 1), matching
|
||||
// the selectors in settings_screen and repeater_settings_screen.
|
||||
DropdownButtonFormField<int>(
|
||||
isExpanded: true,
|
||||
initialValue: (_pathHashByteWidth - 1).clamp(0, 2).toInt(),
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.repeater_pathHashMode,
|
||||
helperText: l10n.settings_pathHashModeHelper,
|
||||
helperMaxLines: 5,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
DropdownMenuItem(
|
||||
value: 0,
|
||||
child: Text(
|
||||
l10n.repeater_pathHashModeOption0,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 1,
|
||||
child: Text(
|
||||
l10n.repeater_pathHashModeOption1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 2,
|
||||
child: Text(
|
||||
l10n.repeater_pathHashModeOption2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setState(() => _pathHashByteWidth = value + 1);
|
||||
_logRadioSettingsState(
|
||||
'Manual settings edit: path hash size',
|
||||
);
|
||||
},
|
||||
),
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -3,57 +3,87 @@ import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
|
||||
class SyncProgressAppBarBottom extends StatelessWidget
|
||||
implements PreferredSizeWidget {
|
||||
static const double height = 3;
|
||||
/// The thin progress bar at the top of a screen or list: 4px, in the theme's
|
||||
/// progress colour and track. Fills when [value] is known, moves when it is
|
||||
/// null. While inactive it keeps its height, so the content doesn't jump.
|
||||
class MeshProgressBar extends StatelessWidget {
|
||||
static const double height = 4;
|
||||
|
||||
const SyncProgressAppBarBottom({super.key});
|
||||
final bool active;
|
||||
final double? value;
|
||||
|
||||
const MeshProgressBar({super.key, this.active = true, this.value});
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size.fromHeight(height);
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: height,
|
||||
child: active
|
||||
? LinearProgressIndicator(value: value, minHeight: height)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// [MeshProgressBar] as an app bar's `bottom`, for a screen's own task.
|
||||
class MeshProgressAppBarBottom extends StatelessWidget
|
||||
implements PreferredSizeWidget {
|
||||
final bool active;
|
||||
final double? value;
|
||||
|
||||
const MeshProgressAppBarBottom({super.key, this.active = true, this.value});
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size.fromHeight(MeshProgressBar.height);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
MeshProgressBar(active: active, value: value);
|
||||
}
|
||||
|
||||
/// [MeshProgressBar] as an app bar's `bottom` for the app-wide syncs:
|
||||
/// contacts, channels and queued messages, one at a time.
|
||||
class SyncProgressAppBarBottom extends StatelessWidget
|
||||
implements PreferredSizeWidget {
|
||||
/// Also shows the bar, moving, while the screen waits for the radio and no
|
||||
/// sync is running.
|
||||
final bool busy;
|
||||
|
||||
const SyncProgressAppBarBottom({super.key, this.busy = false});
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size.fromHeight(MeshProgressBar.height);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<MeshCoreConnector>(
|
||||
builder: (context, connector, _) {
|
||||
final state = _SyncProgressState.fromConnector(connector);
|
||||
if (state == null) return const SizedBox(height: height);
|
||||
|
||||
return SizedBox(
|
||||
height: height,
|
||||
child: LinearProgressIndicator(
|
||||
value: state.value,
|
||||
minHeight: height,
|
||||
color: state.color,
|
||||
backgroundColor: state.color.withValues(alpha: 0.18),
|
||||
),
|
||||
);
|
||||
final state =
|
||||
_SyncProgressState.fromConnector(connector) ??
|
||||
(busy && connector.isConnected
|
||||
? const _SyncProgressState(value: null)
|
||||
: null);
|
||||
return MeshProgressBar(active: state != null, value: state?.value);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SyncProgressState {
|
||||
/// Null while the progress is unknown.
|
||||
final double? value;
|
||||
final Color color;
|
||||
|
||||
const _SyncProgressState({required this.value, required this.color});
|
||||
const _SyncProgressState({required this.value});
|
||||
|
||||
static _SyncProgressState? fromConnector(MeshCoreConnector connector) {
|
||||
if (connector.isLoadingContacts) {
|
||||
return _SyncProgressState(
|
||||
value: connector.contactSyncProgress,
|
||||
color: Colors.red,
|
||||
);
|
||||
return _SyncProgressState(value: connector.contactSyncProgress);
|
||||
}
|
||||
if (connector.isSyncingChannels) {
|
||||
return _SyncProgressState(
|
||||
value: connector.channelSyncProgress / 100,
|
||||
color: Colors.blue,
|
||||
);
|
||||
return _SyncProgressState(value: connector.channelSyncProgress / 100);
|
||||
}
|
||||
if (connector.isShowingQueuedMessageSyncProgress) {
|
||||
return const _SyncProgressState(value: null, color: Colors.green);
|
||||
return const _SyncProgressState(value: null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ class TranslatedMessageContent extends StatelessWidget {
|
||||
final Color? backgroundColor;
|
||||
final bool showOriginalFirst;
|
||||
final VoidCallback? onSecondaryTap;
|
||||
final bool selectable;
|
||||
|
||||
const TranslatedMessageContent({
|
||||
super.key,
|
||||
@@ -20,6 +21,7 @@ class TranslatedMessageContent extends StatelessWidget {
|
||||
this.backgroundColor,
|
||||
this.showOriginalFirst = true,
|
||||
this.onSecondaryTap,
|
||||
this.selectable = true,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -42,6 +44,7 @@ class TranslatedMessageContent extends StatelessWidget {
|
||||
),
|
||||
backgroundColor: backgroundColor,
|
||||
onSecondaryTap: onSecondaryTap,
|
||||
selectable: selectable,
|
||||
)
|
||||
: null;
|
||||
final translatedWidget = LinkHandler.buildLinkifyText(
|
||||
@@ -50,6 +53,7 @@ class TranslatedMessageContent extends StatelessWidget {
|
||||
style: style,
|
||||
backgroundColor: backgroundColor,
|
||||
onSecondaryTap: onSecondaryTap,
|
||||
selectable: selectable,
|
||||
);
|
||||
|
||||
if (!shouldShowOriginal) {
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../utils/radio_guard.dart';
|
||||
import 'adaptive_app_bar_title.dart';
|
||||
import 'mesh_nav_tile.dart';
|
||||
import 'radio_disconnected_banner.dart';
|
||||
|
||||
/// Asks before leaving with unsaved edits: Cancel, Discard or Save. A
|
||||
/// successful save closes the page.
|
||||
class UnsavedChangesGuard extends StatelessWidget {
|
||||
final bool hasChanges;
|
||||
|
||||
/// Whether the dialog offers Save.
|
||||
final bool canSave;
|
||||
|
||||
/// Returns whether the save succeeded.
|
||||
final Future<bool> Function() onSave;
|
||||
|
||||
/// Dialog body.
|
||||
final String message;
|
||||
|
||||
final Widget child;
|
||||
|
||||
const UnsavedChangesGuard({
|
||||
super.key,
|
||||
required this.hasChanges,
|
||||
required this.canSave,
|
||||
required this.onSave,
|
||||
required this.message,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return PopScope(
|
||||
canPop: !hasChanges,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _confirmLeave(context);
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmLeave(BuildContext context) async {
|
||||
final l10n = context.l10n;
|
||||
final save = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.repeater_unsavedChangesTitle),
|
||||
content: Text(message),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(dialogContext).colorScheme.error,
|
||||
),
|
||||
child: Text(l10n.repeater_discardChanges),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: canSave
|
||||
? () => Navigator.pop(dialogContext, true)
|
||||
: null,
|
||||
child: Text(l10n.common_save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (save == null || !context.mounted) return;
|
||||
if (save && !await onSave()) return;
|
||||
if (!context.mounted) return;
|
||||
// Navigator.pop skips the PopScope check.
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// App bar Save button: hidden without changes, a spinner while [saving].
|
||||
class SaveChangesAction extends StatelessWidget {
|
||||
final bool visible;
|
||||
final bool saving;
|
||||
final VoidCallback? onPressed;
|
||||
|
||||
const SaveChangesAction({
|
||||
super.key,
|
||||
required this.visible,
|
||||
this.saving = false,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!visible) return const SizedBox.shrink();
|
||||
return TextButton.icon(
|
||||
onPressed: saving ? null : onPressed,
|
||||
icon: saving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.save),
|
||||
label: Text(context.l10n.common_save),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Page for settings saved to the radio: app bar Save, disconnected banner
|
||||
/// and [UnsavedChangesGuard]. Errors thrown by [onSave] go to a snackbar.
|
||||
class SaveToRadioPage extends StatefulWidget {
|
||||
final String title;
|
||||
final bool hasChanges;
|
||||
|
||||
/// False while a field is invalid.
|
||||
final bool canSave;
|
||||
|
||||
/// Sends the edits. Returns false if nothing was sent (failed validation).
|
||||
final Future<bool> Function() onSave;
|
||||
|
||||
final List<Widget> children;
|
||||
|
||||
const SaveToRadioPage({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.hasChanges,
|
||||
this.canSave = true,
|
||||
required this.onSave,
|
||||
required this.children,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SaveToRadioPage> createState() => SaveToRadioPageState();
|
||||
}
|
||||
|
||||
class SaveToRadioPageState extends State<SaveToRadioPage> {
|
||||
bool _saving = false;
|
||||
|
||||
/// Saves valid, unsaved edits; returns whether it did.
|
||||
Future<bool> save() async {
|
||||
if (_saving || !widget.hasChanges || !widget.canSave) return false;
|
||||
if (!ensureRadioConnected(context)) return false;
|
||||
final l10n = context.l10n;
|
||||
setState(() => _saving = true);
|
||||
try {
|
||||
return await widget.onSave();
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_error(e.toString())),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final canSave = widget.canSave && !context.radioReadOnly && !_saving;
|
||||
return UnsavedChangesGuard(
|
||||
hasChanges: widget.hasChanges,
|
||||
canSave: canSave,
|
||||
message: context.l10n.settings_unsavedChangesMessage,
|
||||
onSave: save,
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: AdaptiveAppBarTitle(widget.title),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
SaveChangesAction(
|
||||
visible: widget.hasChanges,
|
||||
saving: _saving,
|
||||
onPressed: canSave ? save : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: MeshSettingsTileTheme(
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: 24),
|
||||
children: [const RadioDisconnectedBanner(), ...widget.children],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user