Merge upstream/dev (86 commits) into tth
build / ci-image (push) Successful in 10s
build / build (push) Failing after 4m27s

Upstream redesigned the chat composer (bubble, round +/send button,
ChatComposerQuote for the reply preview); our terminal theme had tweaked
the old layout. Took upstream's structure and re-applied the terminal
look to the new widgets: compact panel padding, square bubble, square
button, square and one-line-low reply quote. The terminal reply padding
in channel_chat_screen now lives in ChatComposerQuote, so DMs get it too.

Also fixed for the merge:
- mesh_ui: AvatarCircle uses upstream's avatarInitials() (nullable); the
  terminal glyph falls back to the person icon like upstream does;
- chat_screen: upstream split maxMessageRetries into direct/flood limits,
  the terminal line now shows the bubble's maxSendAttempts;
- test/screens/copy_messages_test.dart: the 1x1 PNG had a bad IDAT CRC.
  Its async decode failure leaked into the next test; upstream's real
  flutter_langdetect hides that by timing, our stub (instant init) does
  not, so the DM test failed ~3 of 5 runs. Replaced with a valid PNG.

Checked in the CI image (Flutter 3.47.9): flutter analyze lib test clean;
flutter test all green except settings_reveal_test "hides Image Messages
sub-options", which fails the same way on plain upstream/dev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-23 12:43:57 +01:00
commit 63907cb17d
210 files changed
+47623 -4900

No files matched your search

+53 -26
View File
@@ -62,6 +62,14 @@ class ByteCountedTextField extends StatelessWidget {
final int? softLimitBytes;
final String? softLimitNote;
/// Lines the field grows to before it scrolls internally. Null (the
/// default) grows without limit.
final int? maxLines;
/// Show the counter row only once usage passes [warningThreshold], and give
/// it no space until then. By default the row keeps its height while hidden.
final bool counterOnlyNearLimit;
const ByteCountedTextField({
super.key,
required this.maxBytes,
@@ -80,6 +88,8 @@ class ByteCountedTextField extends StatelessWidget {
this.encoder,
this.softLimitBytes,
this.softLimitNote,
this.maxLines,
this.counterOnlyNearLimit = false,
});
@override
@@ -92,7 +102,9 @@ class ByteCountedTextField extends StatelessWidget {
: value.text;
final usedBytes = utf8.encode(effectiveText).length;
final ratio = maxBytes > 0 ? usedBytes / maxBytes : 0.0;
final showCounter = !(hideCounterWhenEmpty && value.text.isEmpty);
final showCounter = counterOnlyNearLimit
? ratio > warningThreshold
: !(hideCounterWhenEmpty && value.text.isEmpty);
final showSoftLimitNote =
softLimitNote != null &&
softLimitBytes != null &&
@@ -104,12 +116,27 @@ class ByteCountedTextField extends StatelessWidget {
? Theme.of(context).colorScheme.tertiary
: Theme.of(context).colorScheme.onSurfaceVariant;
final softNote = showSoftLimitNote
? Text(
softLimitNote!,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).colorScheme.tertiary,
),
)
: null;
final counter = Text(
'$usedBytes / $maxBytes',
style: TextStyle(fontSize: 12, color: counterColor),
);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
maxLines: null,
minLines: maxLines == null ? null : 1,
maxLines: maxLines,
controller: controller,
focusNode: focusNode,
autofocus: autofocus,
@@ -134,32 +161,32 @@ class ByteCountedTextField extends StatelessWidget {
textInputAction: textInputAction,
onSubmitted: onSubmitted,
),
Opacity(
opacity: showCounter ? 1 : 0,
child: Padding(
padding: const EdgeInsets.only(top: 4, right: 4),
child: Row(
children: [
Expanded(
child: showSoftLimitNote
? Text(
softLimitNote!,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).colorScheme.tertiary,
),
)
: const SizedBox.shrink(),
),
const SizedBox(width: 8),
Text(
'$usedBytes / $maxBytes',
style: TextStyle(fontSize: 12, color: counterColor),
),
],
if (counterOnlyNearLimit && showCounter)
// Right-aligned, and wraps rather than overflowing at large
// text sizes in a narrow field.
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 12, 8),
child: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
children: [?softNote, counter],
),
)
else if (!counterOnlyNearLimit)
Opacity(
opacity: showCounter ? 1 : 0,
child: Padding(
padding: const EdgeInsets.only(top: 4, right: 4),
child: Row(
children: [
Expanded(child: softNote ?? const SizedBox.shrink()),
const SizedBox(width: 8),
counter,
],
),
),
),
),
],
);
},
+57 -4
View File
@@ -42,26 +42,79 @@ ChatBackgroundService? _maybeService(
}
/// Draws [chatKey]'s background (its own, or the theme's) behind [child].
///
/// A [footer] (the chat composer) sits below [child] over the same
/// background and can ask [ChatBackdrop.hasBackgroundOf] whether one is
/// drawn. [contentKey] marks the message area above the footer.
class ChatBackdrop extends StatelessWidget {
final String chatKey;
final Widget child;
final Widget? footer;
final Key? contentKey;
const ChatBackdrop({super.key, required this.chatKey, required this.child});
const ChatBackdrop({
super.key,
required this.chatKey,
required this.child,
this.footer,
this.contentKey,
});
/// Whether the nearest [ChatBackdrop] draws a background behind its footer.
static bool hasBackgroundOf(BuildContext context) =>
context
.dependOnInheritedWidgetOfExactType<_ChatBackdropScope>()
?.hasBackground ??
false;
@override
Widget build(BuildContext context) {
final background = _maybeService(context)?.resolve(chatKey);
if (background == null) return child;
final footer = this.footer;
if (footer == null) {
if (background == null) return child;
return Stack(
fit: StackFit.expand,
children: [
Positioned.fill(child: ChatBackgroundLayer(background: background)),
child,
],
);
}
return Stack(
fit: StackFit.expand,
children: [
Positioned.fill(child: ChatBackgroundLayer(background: background)),
child,
Positioned.fill(
child: background == null
? const SizedBox.shrink()
: ChatBackgroundLayer(background: background),
),
Column(
children: [
Expanded(
child: KeyedSubtree(key: contentKey, child: child),
),
_ChatBackdropScope(
hasBackground: background != null,
child: footer,
),
],
),
],
);
}
}
class _ChatBackdropScope extends InheritedWidget {
final bool hasBackground;
const _ChatBackdropScope({required this.hasBackground, required super.child});
@override
bool updateShouldNotify(_ChatBackdropScope oldWidget) =>
hasBackground != oldWidget.hasBackground;
}
/// Paints one [ChatBackground], faded toward the theme's surface color.
class ChatBackgroundLayer extends StatelessWidget {
final ChatBackground background;
+619 -183
View File
@@ -1,3 +1,5 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
@@ -9,10 +11,12 @@ import '../theme/mesh_theme.dart';
import '../theme/terminal_theme.dart';
import '../utils/radio_guard.dart';
import 'byte_count_input.dart';
import 'chat_background.dart';
import 'connect_sheet.dart';
import 'gif_message.dart';
import 'gif_picker.dart';
import 'mesh_ui.dart';
import 'message_bubble_frame.dart';
import 'message_translation_button.dart';
import '../theme/theme_icons.dart';
@@ -55,10 +59,63 @@ Future<void> showComposerTranslationOptions(BuildContext context) async {
);
}
/// 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.
/// Corner radius of the compose bubble and the offline bar.
const double kComposerBubbleRadius = 20;
/// Lines the compose field grows to before it scrolls.
const int kComposerMaxLines = 5;
/// Fill of the compose bubble: the incoming-bubble colour over a chat
/// background so it stays readable, otherwise a raised surface.
Color composerBubbleColor(BuildContext context) {
return ChatBackdrop.hasBackgroundOf(context)
? MessageBubbleColors.of(context, isOutgoing: false).background
: Theme.of(context).colorScheme.surfaceContainerHigh;
}
/// The bottom panel holding the compose bubble: transparent over a chat
/// background, solid surface otherwise. 12dp side and 8dp vertical margins
/// (8dp on the trailing side, where the round button's touch target adds 2).
class _ComposerPanel extends StatelessWidget {
final List<Widget> header;
final Widget child;
const _ComposerPanel({this.header = const [], required this.child});
@override
Widget build(BuildContext context) {
final content = SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
...header,
Padding(
// tth fork, terminal theme: compact, edge to edge.
padding: MeshStyle.of(context).terminal
? const EdgeInsets.all(2)
: const EdgeInsetsDirectional.fromSTEB(12, 8, 10, 8),
child: child,
),
],
),
);
if (ChatBackdrop.hasBackgroundOf(context)) return content;
return ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: content,
);
}
}
/// The message composer shared by the direct and channel chat screens.
///
/// A rounded compose bubble (optional [replyPreview], then the byte-counted
/// text field or a GIF preview, with the translation toggle on its right)
/// and one round button beside it: "+" (the [actionsBuilder] menu) while the
/// field is empty, Send once there is text. [header] widgets (e.g. image
/// send progress) are stacked full-width above the bubble.
class ChatComposer extends StatelessWidget {
final TextEditingController controller;
final FocusNode focusNode;
@@ -75,6 +132,15 @@ class ChatComposer extends StatelessWidget {
final ValueChanged<String> onAction;
final List<Widget> header;
/// Shown inside the top of the bubble, usually a [ChatComposerQuote].
final Widget? replyPreview;
/// Marks the compose bubble (and the offline bar's bubble).
static const bubbleKey = ValueKey('chat-composer-bubble');
/// Marks the surface of the open "+" menu.
static const actionMenuKey = ValueKey('chat-composer-action-menu');
const ChatComposer({
super.key,
required this.controller,
@@ -88,40 +154,33 @@ class ChatComposer extends StatelessWidget {
this.softLimitNote,
this.encoder,
this.header = const [],
this.replyPreview,
});
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: MeshMenuItemRow(icon: action.icon, label: action.label),
),
],
final navigator = Navigator.of(buttonContext);
final overlay = navigator.overlay!.context.findRenderObject() as RenderBox;
final anchor =
button.localToGlobal(Offset.zero, ancestor: overlay) & button.size;
// The menu route never requests focus: if it took focus from the text
// field the keyboard would close, the composer would drop down and the
// menu would be left floating where the keyboard used to be.
final selected = await navigator.push<String>(
_ComposerActionMenuRoute(
actions: actions,
anchor: anchor,
button: button,
overlay: overlay,
capturedThemes: InheritedTheme.capture(
from: buttonContext,
to: navigator.context,
),
barrierLabel: MaterialLocalizations.of(buttonContext).menuDismissLabel,
animate: !MediaQuery.disableAnimationsOf(buttonContext),
),
);
if (selected == null || !buttonContext.mounted) return;
onAction(selected);
@@ -129,7 +188,6 @@ class ChatComposer extends StatelessWidget {
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
// Offline the chat is read-only. The draft stays in [controller] (owned
// by the screen) and is back when the radio reconnects.
if (context.radioReadOnly) return const OfflineComposerBar();
@@ -141,28 +199,42 @@ class ChatComposer extends StatelessWidget {
s.settings.translationTargetLanguageCode,
),
);
return Container(
final scheme = Theme.of(context).colorScheme;
final replyPreview = this.replyPreview;
final bubble = DecoratedBox(
key: ChatComposer.bubbleKey,
decoration: BoxDecoration(
color: scheme.surface,
border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)),
color: composerBubbleColor(context),
borderRadius: MeshStyle.of(context).terminal
? BorderRadius.zero
: BorderRadius.circular(kComposerBubbleRadius),
),
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...header,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (replyPreview != null)
Padding(
padding: MeshStyle.of(context).terminal
? const EdgeInsets.symmetric(horizontal: 2, vertical: 2)
: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
child: replyPreview,
),
ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) {
final gifId = GifHelper.parseGif(value.text);
if (gifId != null) {
return _buildGifPreview(context, gifId, scheme);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Builder(
builder: (buttonContext) => IconButton(
icon: const Icon(Icons.add_circle_outline),
tooltip: context.l10n.chat_selectSendAction,
onPressed: () => _openActionMenu(buttonContext),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) => _buildTextField(
context,
scheme,
constraints.maxHeight,
),
),
),
if (translation.$1)
@@ -171,52 +243,34 @@ class ChatComposer extends StatelessWidget {
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 ThemedIcon(ThemeIconSlot.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: MeshStyle.of(context).terminal
? const RoundedRectangleBorder()
: const CircleBorder(),
),
onPressed: hasText
? () {
HapticFeedback.lightImpact();
onSend();
}
: null,
);
},
),
],
),
);
},
),
],
),
);
return _ComposerPanel(
header: header,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(child: bubble),
const SizedBox(width: 4),
ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) => _ComposerRoundButton(
hasText: value.text.trim().isNotEmpty,
sendTooltip: sendTooltip,
actionsTooltip: context.l10n.chat_selectSendAction,
onSend: () {
HapticFeedback.lightImpact();
onSend();
},
onOpenActions: _openActionMenu,
),
],
),
),
],
),
);
}
@@ -237,41 +291,57 @@ class ChatComposer extends StatelessWidget {
}
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,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 8, 0, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ClipRRect(
borderRadius: BorderRadius.circular(MeshRadii.md),
child: GifMessage(
url: 'https://media.giphy.com/media/$gifId/giphy.gif',
backgroundColor: scheme.surfaceContainerHighest,
fallbackTextColor: scheme.onSurfaceVariant,
maxSize: 160,
),
),
),
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.close),
tooltip: context.l10n.chat_removeGif,
onPressed: () {
controller.clear();
focusNode.requestFocus();
},
),
],
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: MeshStyle.of(context).terminal
? BorderRadius.zero
: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(color: color, width: width),
);
/// [maxHeight] is the room the chat leaves the composer: above the
/// keyboard, since the screen's body resizes for it.
Widget _buildTextField(
BuildContext context,
ColorScheme scheme,
double maxHeight,
) {
// Five lines, or fewer when large text and a short window leave little
// room, so the field takes no more than about a quarter of the chat.
// Never one line: that stops wrapping and the keyboard's newline key.
final room = maxHeight.isFinite
? maxHeight
: MediaQuery.sizeOf(context).height;
final lineHeight = MediaQuery.textScalerOf(context).scale(16) * 1.5;
final maxLines = (room / 4 / lineHeight).floor().clamp(
2,
kComposerMaxLines,
);
return ByteCountedTextField(
maxBytes: maxBytes,
softLimitBytes: softLimitBytes,
@@ -281,85 +351,451 @@ class ChatComposer extends StatelessWidget {
hintText: context.l10n.chat_typeMessage,
onSubmitted: (_) => onSend(),
encoder: encoder,
maxLines: maxLines,
counterOnlyNearLimit: true,
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,
),
hintStyle: TextStyle(color: scheme.onSurfaceVariant),
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
filled: false,
isDense: true,
// A 24dp line plus 12 above and below: 48dp on one line, level with
// the round button beside the bubble.
contentPadding: const EdgeInsetsDirectional.fromSTEB(16, 12, 8, 12),
),
);
}
}
/// Stands in for the composer while no radio is connected.
class OfflineComposerBar extends StatelessWidget {
const OfflineComposerBar({super.key});
/// The round button beside the compose bubble: "+" while the field is
/// empty, Send once there is text. Drawn at 44dp in a 48dp touch target.
class _ComposerRoundButton extends StatelessWidget {
final bool hasText;
final String sendTooltip;
final String actionsTooltip;
final VoidCallback onSend;
final ValueChanged<BuildContext> onOpenActions;
const _ComposerRoundButton({
required this.hasText,
required this.sendTooltip,
required this.actionsTooltip,
required this.onSend,
required this.onOpenActions,
});
static const _visualSize = Size(44, 44);
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Container(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)),
ButtonStyle style(Color background, Color foreground) =>
IconButton.styleFrom(
backgroundColor: background,
foregroundColor: foreground,
fixedSize: _visualSize,
minimumSize: _visualSize,
padding: EdgeInsets.zero,
tapTargetSize: MaterialTapTargetSize.padded,
shape: MeshStyle.of(context).terminal
? const RoundedRectangleBorder()
: const CircleBorder(),
);
final Widget button = hasText
? IconButton.filled(
key: const ValueKey('composer-send'),
icon: const ThemedIcon(ThemeIconSlot.send, size: 22),
tooltip: sendTooltip,
style: style(scheme.primary, scheme.onPrimary),
onPressed: onSend,
)
: Builder(
key: const ValueKey('composer-actions'),
builder: (buttonContext) => IconButton.filled(
icon: const Icon(Icons.add, size: 28),
tooltip: actionsTooltip,
style: style(composerBubbleColor(context), scheme.onSurface),
onPressed: () => onOpenActions(buttonContext),
),
);
return SizedBox.square(
dimension: kMinInteractiveDimension,
child: AnimatedSwitcher(
duration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: const Duration(milliseconds: 150),
transitionBuilder: (child, animation) => FadeTransition(
opacity: animation,
child: ScaleTransition(
scale: Tween<double>(begin: 0.6, end: 1).animate(animation),
child: child,
),
),
child: button,
),
child: SafeArea(
);
}
}
/// A quoted message inside the top of the compose bubble ("Replying to
/// Bob"): a coloured bar on the leading edge, [title], [content], optional
/// [trailing] controls and a dismiss button.
class ChatComposerQuote extends StatelessWidget {
final String title;
final Widget content;
final Widget? trailing;
final VoidCallback onDismiss;
final String dismissTooltip;
const ChatComposerQuote({
super.key,
required this.title,
required this.content,
required this.onDismiss,
required this.dismissTooltip,
this.trailing,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final background = scheme.surfaceContainerHighest;
final accent = readableAccent(scheme.primary, background);
final trailing = this.trailing;
// tth fork, terminal theme: square and as low as one line allows.
final terminal = MeshStyle.of(context).terminal;
return ClipRRect(
borderRadius: terminal
? BorderRadius.zero
: BorderRadius.circular(MeshRadii.md),
child: DecoratedBox(
decoration: BoxDecoration(
color: background,
border: BorderDirectional(start: BorderSide(color: accent, width: 4)),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 12, 10),
padding: terminal
? const EdgeInsetsDirectional.fromSTEB(6, 0, 0, 0)
: const EdgeInsetsDirectional.fromSTEB(10, 6, 0, 6),
child: LayoutBuilder(
builder: (context, constraints) {
final message = Row(
children: [
Icon(
Icons.cloud_off,
color: scheme.onSurfaceVariant,
size: 24,
builder: (context, constraints) => Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w700,
color: accent,
),
),
content,
],
),
const SizedBox(width: 12),
Expanded(
child: Text(
context.l10n.chat_composerOffline,
style: Theme.of(
context,
).textTheme.bodyLarge?.copyWith(color: scheme.onSurface),
),
// The quote shares its row with Send, so a long trailing
// control (a region chip) must not squeeze out the message
// or the dismiss button.
if (trailing != null)
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth * 0.4,
),
child: trailing,
),
],
);
// Side by side when there is room; otherwise the button goes
// under the message so large text never squeezes it.
final roomy =
constraints.maxWidth /
MediaQuery.textScalerOf(context).scale(1) >=
420;
if (roomy) {
return Row(
children: [
Expanded(child: message),
const SizedBox(width: 8),
const ConnectButton(),
],
);
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
message,
const SizedBox(height: 8),
const ConnectButton(),
],
);
},
IconButton(
icon: const Icon(Icons.close),
tooltip: dismissTooltip,
color: scheme.onSurfaceVariant,
onPressed: onDismiss,
),
],
),
),
),
),
);
}
}
/// Stands in for the composer while no radio is connected, in the same
/// bubble and margins so the chat doesn't jump on connect or disconnect.
class OfflineComposerBar extends StatelessWidget {
const OfflineComposerBar({super.key});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final message = ConstrainedBox(
constraints: const BoxConstraints(minHeight: kMinInteractiveDimension),
child: DecoratedBox(
key: ChatComposer.bubbleKey,
decoration: BoxDecoration(
color: composerBubbleColor(context),
borderRadius: BorderRadius.circular(kComposerBubbleRadius),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(Icons.cloud_off, color: scheme.onSurfaceVariant, size: 24),
const SizedBox(width: 12),
Expanded(
child: Text(
context.l10n.chat_composerOffline,
style: Theme.of(
context,
).textTheme.bodyLarge?.copyWith(color: scheme.onSurface),
),
),
],
),
),
),
);
return _ComposerPanel(
child: LayoutBuilder(
builder: (context, constraints) {
// Side by side when there is room; otherwise the button goes
// under the message so large text never squeezes it.
final roomy =
constraints.maxWidth /
MediaQuery.textScalerOf(context).scale(1) >=
420;
if (roomy) {
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(child: message),
const SizedBox(width: 4),
const ConnectButton(),
],
);
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
message,
const SizedBox(height: 8),
const Align(
alignment: AlignmentDirectional.centerEnd,
child: ConnectButton(),
),
],
);
},
),
);
}
}
/// The "+" menu: a popup that grows upward from the bottom-trailing corner,
/// just above the "+" button, so it opens out of the button instead of
/// sliding down toward it.
class _ComposerActionMenuRoute extends PopupRoute<String> {
final List<ChatComposerAction> actions;
final Rect anchor;
final RenderBox button;
final RenderBox overlay;
final CapturedThemes capturedThemes;
final bool animate;
@override
final String barrierLabel;
_ComposerActionMenuRoute({
required this.actions,
required this.anchor,
required this.button,
required this.overlay,
required this.capturedThemes,
required this.barrierLabel,
required this.animate,
}) : super(requestFocus: false);
static const double _gap = 4;
static const double _margin = 8;
static const double _minWidth = 112;
@override
Color? get barrierColor => null;
@override
bool get barrierDismissible => true;
@override
Duration get transitionDuration =>
animate ? const Duration(milliseconds: 250) : Duration.zero;
@override
Duration get reverseTransitionDuration =>
animate ? const Duration(milliseconds: 150) : Duration.zero;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
final direction = Directionality.of(context);
final padding = MediaQuery.paddingOf(context);
return capturedThemes.wrap(
LayoutBuilder(
builder: (context, constraints) {
final viewport = constraints.biggest;
final rect = button.attached && overlay.attached
? button.localToGlobal(Offset.zero, ancestor: overlay) &
button.size
: anchor;
final rawEnd = direction == TextDirection.ltr
? viewport.width - rect.right
: rect.left;
final end = rawEnd
.clamp(
_margin,
math.max(_margin, viewport.width - _minWidth - _margin),
)
.toDouble();
final maxWidth = math.max(
_minWidth,
math.min(280.0, viewport.width - end - _margin),
);
final bottom = (viewport.height - rect.top + _gap)
.clamp(
_margin,
math.max(
_margin,
viewport.height -
padding.top -
_margin -
kMinInteractiveDimension,
),
)
.toDouble();
final maxHeight = math.max(
kMinInteractiveDimension,
viewport.height - bottom - padding.top - _margin,
);
return Stack(
children: [
Positioned.directional(
textDirection: direction,
end: end,
bottom: bottom,
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: _minWidth,
maxWidth: maxWidth,
maxHeight: maxHeight,
),
child: _ComposerActionMenu(
actions: actions,
animation: animation,
),
),
),
],
);
},
),
);
}
}
class _ComposerActionMenu extends StatelessWidget {
final List<ChatComposerAction> actions;
final Animation<double> animation;
const _ComposerActionMenu({required this.actions, required this.animation});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final menuTheme = PopupMenuTheme.of(context);
final items = IntrinsicWidth(
stepWidth: 56,
child: Semantics(
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: MaterialLocalizations.of(context).popupMenuLabel,
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: 8),
child: DefaultTextStyle(
style: (menuTheme.textStyle ?? theme.textTheme.labelLarge!)
.copyWith(color: scheme.onSurface),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final action in actions)
InkWell(
onTap: () => Navigator.of(context).pop(action.id),
child: ConstrainedBox(
constraints: const BoxConstraints(
minHeight: kMinInteractiveDimension,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: MeshMenuItemRow(
icon: action.icon,
label: action.label,
),
),
),
),
),
],
),
),
),
),
);
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
final t = animation.value;
final heightFactor =
(animation.status == AnimationStatus.reverse
? Curves.easeIn
: Curves.easeOutCubic)
.transform(t);
return Opacity(
opacity: const Interval(0, 0.4).transform(t),
child: Material(
key: ChatComposer.actionMenuKey,
type: MaterialType.card,
color: menuTheme.color ?? scheme.surfaceContainerHigh,
elevation: menuTheme.elevation ?? 3,
shadowColor: menuTheme.shadowColor,
surfaceTintColor: Colors.transparent,
shape:
menuTheme.shape ??
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(MeshRadii.md),
),
clipBehavior: Clip.antiAlias,
child: Align(
alignment: AlignmentDirectional.bottomEnd,
widthFactor: 1,
heightFactor: heightFactor,
child: child,
),
),
);
},
child: items,
);
}
}
+364
View File
@@ -0,0 +1,364 @@
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,
),
],
),
),
),
),
),
),
),
),
);
}
}
+27 -14
View File
@@ -44,21 +44,34 @@ class ChatDaySeparator extends StatelessWidget {
);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
children: [
line,
const SizedBox(width: 10),
Text(
formatChatDayLabel(context, day),
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
child: LayoutBuilder(
// Large text on a narrow phone wraps the label instead of overflowing;
// each rule keeps at least 16dp.
builder: (context, constraints) => Row(
children: [
line,
const SizedBox(width: 10),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth - 2 * (10 + 16)).clamp(
0.0,
double.infinity,
),
),
child: Text(
formatChatDayLabel(context, day),
textAlign: TextAlign.center,
style: MeshTheme.mono(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),
),
),
),
const SizedBox(width: 10),
line,
],
const SizedBox(width: 10),
line,
],
),
),
);
}
+35
View File
@@ -5,8 +5,10 @@ import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../screens/scanner_screen.dart';
import '../screens/settings_screen.dart';
import '../screens/usb_screen.dart';
import '../storage/last_radio_store.dart';
import '../theme/theme_icons.dart';
import '../utils/dialog_utils.dart';
import '../utils/platform_info.dart';
import 'mesh_ui.dart';
@@ -164,3 +166,36 @@ PopupMenuItem<T> connectionMenuItem<T>(
onTap: () => showConnectSheet(screenContext),
);
}
/// Overflow-menu entry that opens [SettingsScreen].
/// [screenContext] must outlive the menu, as onTap runs after it closes.
PopupMenuItem<T> settingsMenuItem<T>(
BuildContext screenContext,
BuildContext menuContext,
) {
return PopupMenuItem<T>(
child: MeshMenuItemRow(
leading: const ThemedIcon(ThemeIconSlot.settings, size: 20),
label: menuContext.l10n.settings_title,
),
onTap: () => Navigator.push(
screenContext,
MaterialPageRoute(builder: (_) => const SettingsScreen()),
),
);
}
/// Trailing app-level section shared by the main views' overflow menus:
/// an optional [PopupMenuDivider] (omitted when [hasPrecedingItems] is false)
/// followed by [connectionMenuItem] and [settingsMenuItem].
List<PopupMenuEntry<T>> mainOverflowTrailingItems<T>(
BuildContext screenContext,
BuildContext menuContext, {
bool hasPrecedingItems = true,
}) {
return <PopupMenuEntry<T>>[
if (hasPrecedingItems) const PopupMenuDivider(),
connectionMenuItem<T>(screenContext, menuContext),
settingsMenuItem<T>(screenContext, menuContext),
];
}
@@ -0,0 +1,223 @@
import 'package:flutter/material.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../models/contact_group.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_search.dart';
/// Create/edit dialog for a phone-side contact group. Current members are
/// listed first with a remove button each; the searchable "Add contacts"
/// list below shows only contacts that are not members yet.
///
/// Membership changes stay in the dialog until Save, which calls [onSave].
/// Nothing here touches the contacts stored on the radio.
class ContactGroupEditorDialog extends StatefulWidget {
const ContactGroupEditorDialog({
super.key,
required this.contacts,
required this.validateName,
required this.onSave,
this.group,
});
final List<Contact> contacts;
final ContactGroup? group;
/// Returns an error message for an invalid trimmed name, or null.
final String? Function(String name) validateName;
final Future<void> Function(ContactGroup group) onSave;
@override
State<ContactGroupEditorDialog> createState() =>
_ContactGroupEditorDialogState();
}
class _ContactGroupEditorDialogState extends State<ContactGroupEditorDialog> {
late final TextEditingController _nameController;
// Insertion-ordered; keeps keys of contacts no longer on the radio.
late final Set<String> _memberKeys;
late final List<Contact> _sortedContacts;
String _query = '';
@override
void initState() {
super.initState();
_nameController = TextEditingController(text: widget.group?.name ?? '');
_memberKeys = <String>{...?widget.group?.memberKeys};
_sortedContacts = List<Contact>.from(widget.contacts)
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
}
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
Future<void> _save() async {
final name = _nameController.text.trim();
final error = widget.validateName(name);
if (error != null) {
showDismissibleSnackBar(context, content: Text(error));
return;
}
await widget.onSave(
ContactGroup(name: name, memberKeys: _memberKeys.toList()),
);
if (mounted) Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final members = _sortedContacts
.where((c) => _memberKeys.contains(c.publicKeyHex))
.toList();
final candidates = _sortedContacts
.where(
(c) =>
!_memberKeys.contains(c.publicKeyHex) &&
matchesContactQuery(c, _query),
)
.toList();
if (_query.trim().isNotEmpty) {
candidates.sort((a, b) => compareContactQueryRank(a, b, _query));
}
Widget sectionLabel(String text) => Semantics(
header: true,
child: Padding(
padding: const EdgeInsets.fromLTRB(4, 16, 4, 4),
child: Text(
text.toUpperCase(),
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 13,
),
),
),
);
Widget contactTile(Contact contact, {required bool isMember}) {
return ListTile(
key: ValueKey(
'group-${isMember ? 'member' : 'candidate'}-'
'${contact.publicKeyHex}',
),
contentPadding: const EdgeInsetsDirectional.only(start: 4),
title: Text(
contact.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16),
),
subtitle: Text(contact.typeLabel(l10n)),
onTap: isMember
? null
: () => setState(() => _memberKeys.add(contact.publicKeyHex)),
trailing: isMember
? IconButton(
tooltip: l10n.contacts_groupRemoveMember(contact.name),
icon: Icon(Icons.remove_circle_outline, color: scheme.error),
onPressed: () =>
setState(() => _memberKeys.remove(contact.publicKeyHex)),
)
: IconButton(
tooltip: l10n.contacts_groupAddMember(contact.name),
icon: Icon(Icons.add_circle_outline, color: scheme.primary),
onPressed: () =>
setState(() => _memberKeys.add(contact.publicKeyHex)),
),
);
}
Widget emptyText(String text) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 12),
child: Text(
text,
style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant),
),
);
return AlertDialog(
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
contentPadding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
title: Text(
widget.group != null ? l10n.contacts_editGroup : l10n.contacts_newGroup,
),
content: SizedBox(
width: double.maxFinite,
height: MediaQuery.sizeOf(context).height * 0.7,
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: TextField(
controller: _nameController,
decoration: InputDecoration(
labelText: l10n.contacts_groupName,
border: const OutlineInputBorder(),
),
),
),
SliverToBoxAdapter(
child: sectionLabel(
l10n.contacts_groupCurrentMembers(members.length),
),
),
if (members.isEmpty)
SliverToBoxAdapter(child: emptyText(l10n.contacts_noMembers))
else
SliverList.builder(
itemCount: members.length,
itemBuilder: (context, index) =>
contactTile(members[index], isMember: true),
),
SliverToBoxAdapter(
child: sectionLabel(l10n.contacts_groupAddContacts),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: TextField(
decoration: InputDecoration(
hintText: l10n.contacts_filterContacts,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: true,
),
onChanged: (value) => setState(() => _query = value),
),
),
),
if (candidates.isEmpty)
SliverToBoxAdapter(
child: emptyText(l10n.contacts_noContactsMatchFilter),
)
else
SliverList.builder(
itemCount: candidates.length,
itemBuilder: (context, index) =>
contactTile(candidates[index], isMember: false),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: _save,
child: Text(
widget.group != null ? l10n.common_save : l10n.common_create,
),
),
],
);
}
}
+45 -2
View File
@@ -5,6 +5,7 @@ import '../l10n/app_localizations.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import '../theme/theme_icons.dart';
import '../utils/emoji_utils.dart';
/// Shared node-type visuals and last-seen formatting for contact lists
/// (contacts, discovery, nearby-node scan).
@@ -41,16 +42,58 @@ ThemeIconSlot? contactTypeIconSlot(int type) {
}
}
final RegExp _letterOrDigit = RegExp(r'^[\p{L}\p{N}]', unicode: true);
/// Avatar initials for a display name, or null when the name has nothing
/// usable so the caller can show an icon or key prefix instead.
///
/// Only letters and digits count: punctuation such as `-`, `(` or `[` splits
/// words but never becomes an initial, so "(Base) Node" gives "BN" and
/// "- Relay" gives "RE". Characters are whole grapheme clusters, so accented
/// letters and emoji are never cut in half. A name with no letters or digits
/// but an emoji shows that emoji.
String? avatarInitials(String name) {
final words = <String>[];
final current = StringBuffer();
String? emoji;
for (final cluster in name.characters) {
if (_letterOrDigit.hasMatch(cluster)) {
current.write(cluster);
continue;
}
if (current.isNotEmpty) {
words.add(current.toString());
current.clear();
}
emoji ??= firstEmoji(cluster);
}
if (current.isNotEmpty) words.add(current.toString());
if (words.isEmpty) return emoji;
if (words.length == 1) {
return words.first.characters.take(2).toString().toUpperCase();
}
return (words[0].characters.first + words[1].characters.first).toUpperCase();
}
/// The most recent activity for [contact]: for chat nodes this includes the
/// last message, for other node types only the last advert or telemetry fix.
DateTime resolveContactLastSeen(Contact contact) {
final heard = contact.lastHeard;
/// [addedAt] (the phone time the contact was added from a card) stands in
/// while the radio has no advert time for it.
DateTime resolveContactLastSeen(Contact contact, {DateTime? addedAt}) {
final heard =
addedAt != null &&
contact.lastSeen.millisecondsSinceEpoch == 0 &&
addedAt.isAfter(contact.lastHeard)
? addedAt
: contact.lastHeard;
if (contact.type != advTypeChat) return heard;
return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard;
}
/// Short relative "last seen" label ("now", "5 mins ago", "2 days ago").
String formatContactLastSeen(AppLocalizations l10n, DateTime lastSeen) {
if (lastSeen.millisecondsSinceEpoch == 0) return l10n.contacts_lastSeenNever;
final diff = DateTime.now().difference(lastSeen);
if (diff.isNegative || diff.inMinutes < 5) {
+298
View File
@@ -0,0 +1,298 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/image_codec_support.dart';
import '../services/image_codec_service.dart';
import '../theme/mesh_theme.dart';
import 'model_download_list.dart';
/// Image-codec registry: one [ModelDownloadList] row per model.
///
/// A preset and the files it installed are the same row. The friendly name is
/// the preset label, never the on-disk graph filename.
class ImageCodecModelsSection extends StatefulWidget {
const ImageCodecModelsSection({super.key});
@override
State<ImageCodecModelsSection> createState() =>
_ImageCodecModelsSectionState();
}
class _ImageCodecModelsSectionState extends State<ImageCodecModelsSection> {
String? _failedId;
String? _failedDetail;
@override
Widget build(BuildContext context) {
final codec = context.watch<ImageCodecService>();
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final reason = codec.unavailableReason;
final lastError = codec.lastError;
final showLastError =
lastError != null &&
lastError.isNotEmpty &&
lastError != 'Download stopped.' &&
lastError != _failedDetail;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text(
l10n.imageMessages_modelSectionTitle,
style: theme.textTheme.titleSmall,
),
),
if (reason != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: scheme.outlineVariant),
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Text(
reason,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
),
),
ModelDownloadList(items: _items(context, codec)),
if (showLastError)
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
child: Text(
lastError,
style: theme.textTheme.bodyMedium?.copyWith(color: scheme.error),
),
)
else
const SizedBox(height: 8),
],
);
}
List<ModelDownloadItem> _items(
BuildContext context,
ImageCodecService codec,
) {
final models = codec.availableModels;
final used = <ImageCodecModelRecord>{};
final items = <ModelDownloadItem>[];
for (final spec in imageCodecPresetModels) {
final belonging = [
for (final model in models)
if (_belongsToSpec(model, spec)) model,
];
used.addAll(belonging);
final record = _preferredRecord(belonging, spec);
items.add(_presetItem(context, codec, spec, record));
}
for (final model in models) {
if (used.contains(model)) continue;
items.add(_customItem(context, codec, model));
}
return items;
}
ModelDownloadItem _presetItem(
BuildContext context,
ImageCodecService codec,
ImageCodecModelSpec spec,
ImageCodecModelRecord? record,
) {
final l10n = context.l10n;
final blocked = spec.urlsArePlaceholders;
final installedId = record?.id;
final complete =
record != null && spec.hasCompleteInstalledRecord([record]);
final downloading = !blocked && _specIsDownloading(codec, spec);
final verifying = downloading && _isVerifying(codec);
final failed = !downloading && !complete && _failedId == spec.id;
final selectedId = codec.selectedModel?.id;
final selected =
complete && (selectedId == spec.id || selectedId == installedId);
final busy = codec.isBusy || codec.isDownloading;
final ModelDownloadStatus status;
String? statusLabel;
if (downloading) {
status = ModelDownloadStatus.downloading;
} else if (complete) {
status = ModelDownloadStatus.ready;
} else if (failed) {
status = ModelDownloadStatus.error;
} else {
status = ModelDownloadStatus.notDownloaded;
if (record != null && !blocked) {
statusLabel = l10n.modelDownload_incomplete;
}
}
final size = record != null && record.fileSizeBytes > 0
? record.fileSizeBytes
: spec.totalSizeBytes;
return ModelDownloadItem(
id: spec.id,
name: spec.label,
sizeBytes: size > 0 ? size : null,
status: status,
statusLabel: statusLabel,
selected: selected,
enabled: !blocked,
progress: verifying ? null : codec.downloadProgress,
downloadedBytes: downloading ? codec.downloadedBytes : 0,
totalBytes: downloading ? codec.downloadTotalBytes : null,
detail: blocked
? l10n.imageMessages_modelNotPublished
: verifying
? l10n.modelDownload_verifying
: failed
? _failedDetail
: null,
onDownload: !blocked && !complete && !codec.isDownloading
? () => _download(spec)
: null,
onCancel: downloading ? codec.cancelDownload : null,
onDelete: record != null && !busy ? () => _delete(record) : null,
onSelect: complete && !selected && !busy
? () => codec.setSelectedModelId(installedId ?? spec.id)
: null,
);
}
ModelDownloadItem _customItem(
BuildContext context,
ImageCodecService codec,
ImageCodecModelRecord model,
) {
final l10n = context.l10n;
final downloading = _recordIsDownloading(codec, model);
final verifying = downloading && _isVerifying(codec);
final ready = model.localPath.isNotEmpty && !downloading;
final busy = codec.isBusy || codec.isDownloading;
final selected = ready && codec.selectedModel?.id == model.id;
return ModelDownloadItem(
id: model.id,
name: imageCodecModelFriendlyName(model),
sizeBytes: model.fileSizeBytes > 0 ? model.fileSizeBytes : null,
status: downloading
? ModelDownloadStatus.downloading
: ready
? ModelDownloadStatus.ready
: ModelDownloadStatus.notDownloaded,
selected: selected,
progress: verifying ? null : codec.downloadProgress,
downloadedBytes: downloading ? codec.downloadedBytes : 0,
totalBytes: downloading ? codec.downloadTotalBytes : null,
detail: verifying ? l10n.modelDownload_verifying : null,
onCancel: downloading ? codec.cancelDownload : null,
onDelete: !busy ? () => _delete(model) : null,
onSelect: ready && !selected && !busy
? () => codec.setSelectedModelId(model.id)
: null,
);
}
bool _specIsDownloading(ImageCodecService codec, ImageCodecModelSpec spec) {
if (!codec.isDownloading) return false;
final name = _downloadFileName(codec);
if (name == null) return imageCodecPresetModels.length == 1;
return spec.assets.any((asset) => asset.fileName == name);
}
bool _recordIsDownloading(
ImageCodecService codec,
ImageCodecModelRecord model,
) {
if (!codec.isDownloading) return false;
final name = _downloadFileName(codec);
if (name == null) return false;
return model.name == name || model.assetFileNames.contains(name);
}
bool _isVerifying(ImageCodecService codec) =>
codec.downloadFileName?.startsWith('Verifying ') ?? false;
String? _downloadFileName(ImageCodecService codec) {
final raw = codec.downloadFileName;
if (raw == null || raw.isEmpty) return null;
const prefix = 'Verifying ';
return raw.startsWith(prefix) ? raw.substring(prefix.length) : raw;
}
Future<void> _download(ImageCodecModelSpec spec) async {
setState(() {
_failedId = null;
_failedDetail = null;
});
final l10n = context.l10n;
try {
await context.read<ImageCodecService>().downloadPresetModel(spec);
} on ImageCodecDownloadCancelled {
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.translation_downloadStopped),
);
} catch (error) {
if (!mounted) return;
final message = l10n.imageMessages_downloadFailedWithError('$error');
setState(() {
_failedId = spec.id;
_failedDetail = message;
});
showDismissibleSnackBar(context, content: Text(message));
}
}
Future<void> _delete(ImageCodecModelRecord model) async {
final l10n = context.l10n;
try {
await context.read<ImageCodecService>().removeModel(model);
} catch (error) {
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.modelDownload_removeFailed('$error')),
);
}
}
}
bool _belongsToSpec(ImageCodecModelRecord model, ImageCodecModelSpec spec) {
if (model.id == spec.id || model.name == spec.fileName) return true;
for (final asset in spec.assets) {
if (asset.fileName == model.name) return true;
}
return false;
}
ImageCodecModelRecord? _preferredRecord(
List<ImageCodecModelRecord> models,
ImageCodecModelSpec spec,
) {
for (final model in models) {
if (spec.hasCompleteInstalledRecord([model])) return model;
}
for (final model in models) {
if (model.id == spec.id) return model;
}
if (models.isEmpty) return null;
return models.first;
}
+21 -8
View File
@@ -136,14 +136,18 @@ class MeshNavTile extends StatelessWidget {
}
/// One radio-style option row inside a bottom sheet picker.
/// The selected row shows a filled radio icon and a bold title, so the
/// choice never depends on colour alone. A null [onTap] disables the row.
class MeshSheetOption extends StatelessWidget {
final String label;
final String? subtitle;
final bool selected;
final VoidCallback onTap;
final VoidCallback? onTap;
const MeshSheetOption({
super.key,
required this.label,
this.subtitle,
required this.selected,
required this.onTap,
});
@@ -151,14 +155,23 @@ class MeshSheetOption extends StatelessWidget {
@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,
return Semantics(
selected: selected,
inMutuallyExclusiveGroup: true,
child: ListTile(
leading: Icon(
selected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: selected ? scheme.primary : scheme.onSurfaceVariant,
),
title: Text(
label,
style: selected ? const TextStyle(fontWeight: FontWeight.w700) : null,
),
subtitle: subtitle == null ? null : Text(subtitle!),
enabled: onTap != null,
onTap: onTap,
),
title: Text(label),
onTap: onTap,
);
}
}
+43 -32
View File
@@ -8,6 +8,7 @@ import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import '../theme/terminal_theme.dart';
import '../theme/theme_icons.dart';
import 'contact_visuals.dart';
/// MeshCore shared design kit.
///
@@ -301,7 +302,8 @@ class StatTile extends StatelessWidget {
/// Initials avatar with a deterministic per-name hue, or a fixed [color]
/// for node-type coloring. Optional [icon] or themeable [iconSlot] replaces
/// initials.
/// initials. Initials come from [avatarInitials]; a name with no letters,
/// digits or emoji shows a generic person icon instead.
class AvatarCircle extends StatelessWidget {
final String name;
final double size;
@@ -338,7 +340,7 @@ class AvatarCircle extends StatelessWidget {
@override
Widget build(BuildContext context) {
final accent = color ?? _colorFor(name);
final initials = _initials(name);
final initials = avatarInitials(name);
if (MeshStyle.of(context).terminal) {
// Terminal theme: just the glyph, small enough for a one-line row.
final s = math.min(size, 20.0);
@@ -346,8 +348,12 @@ class AvatarCircle extends StatelessWidget {
width: s,
height: s,
child: Center(
child: (icon ?? iconSlot?.icon) != null
? Icon(icon ?? iconSlot!.icon, size: s * 0.85, color: accent)
child: (icon ?? iconSlot?.icon) != null || initials == null
? Icon(
icon ?? iconSlot?.icon ?? Icons.person_outline,
size: s * 0.85,
color: accent,
)
: Text(
initials,
style: MeshTheme.mono(
@@ -399,9 +405,9 @@ class AvatarCircle extends StatelessWidget {
size: size * 0.55,
color: readableAccent(accent, background, minContrast: 3),
)
: icon != null
: icon != null || initials == null
? Icon(
icon,
icon ?? Icons.person_outline,
size: size * 0.5,
color: readableAccent(accent, background, minContrast: 3),
)
@@ -415,21 +421,6 @@ class AvatarCircle extends StatelessWidget {
),
);
}
static String _initials(String name) {
final words = name
.trim()
.split(RegExp(r'\s+'))
.where((w) => w.isNotEmpty)
.toList();
if (words.isEmpty) return '?';
if (words.length == 1) {
return words.first.characters.take(2).toString().toUpperCase();
}
return (words.first.characters.take(1).toString() +
words[1].characters.take(1).toString())
.toUpperCase();
}
}
/// Four-bar signal strength indicator driven by an SNR value (dB), colored
@@ -738,6 +729,11 @@ class ErrorRetryCard extends StatelessWidget {
/// Staggered fade + slide entrance for list items. Wrap each item and pass
/// its [index]; animation only plays once per widget lifecycle.
///
/// Only rows built while their list is at rest at the top play it. Rows that
/// a scroll brings into view appear at once: a delayed fade there leaves
/// blank rows trailing the finger and adds a ticker and an opacity layer per
/// row during a fling.
class ListEntrance extends StatefulWidget {
final int index;
final Widget child;
@@ -750,41 +746,56 @@ class ListEntrance extends StatefulWidget {
class _ListEntranceState extends State<ListEntrance>
with SingleTickerProviderStateMixin {
// Created eagerly: a lazy `late final` initializer would run on first
// access — which can be dispose(), where ticker creation throws.
late final AnimationController _controller;
late final CurvedAnimation _curve;
// Created in initState, not lazily: a lazy initializer would run on first
// access — which can be dispose(), where ticker creation throws. Null when
// the row skips the entrance.
AnimationController? _controller;
CurvedAnimation? _curve;
/// Whether the enclosing list has scrolled away from the top or is moving,
/// i.e. this row is entering because of a scroll.
bool _enteredByScroll() {
final scrollable = context.findAncestorStateOfType<ScrollableState>();
if (scrollable == null) return false;
final position = scrollable.position;
return position.isScrollingNotifier.value ||
(position.hasPixels && position.pixels != 0);
}
@override
void initState() {
super.initState();
_controller = AnimationController(
// Decided once: changing the tree shape later would rebuild the row.
if (_enteredByScroll()) return;
final controller = _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 280),
);
_curve = CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic);
_curve = CurvedAnimation(parent: controller, curve: Curves.easeOutCubic);
final delay = Duration(milliseconds: 24 * widget.index.clamp(0, 12));
Future.delayed(delay, () {
if (mounted) _controller.forward();
if (mounted) controller.forward();
});
}
@override
void dispose() {
_curve.dispose();
_controller.dispose();
_curve?.dispose();
_controller?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final curve = _curve;
if (curve == null) return widget.child;
return FadeTransition(
opacity: _curve,
opacity: curve,
child: SlideTransition(
position: Tween(
begin: const Offset(0, 0.04),
end: Offset.zero,
).animate(_curve),
).animate(curve),
child: widget.child,
),
);
+23
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
/// Colours shared by the direct-message and channel chat bubbles.
@@ -149,3 +150,25 @@ class MessageBubbleFrame extends StatelessWidget {
);
}
}
/// Subtle indicator shown in a message bubble's metadata row when SMAZ
/// compression was applied to the message.
class CompressionIndicator extends StatelessWidget {
final double size;
final Color color;
const CompressionIndicator({super.key, this.size = 14, required this.color});
@override
Widget build(BuildContext context) {
final label = context.l10n.messageMeta_smazCompressed;
return Tooltip(
message: label,
triggerMode: TooltipTriggerMode.tap,
child: Semantics(
label: label,
child: Icon(Icons.compress, size: size, color: color),
),
);
}
}
+207 -88
View File
@@ -1,7 +1,10 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
import '../models/translation_support.dart';
import 'mesh_ui.dart';
class MessageTranslationButton extends StatelessWidget {
final bool enabled;
@@ -38,15 +41,58 @@ Future<void> showMessageTranslationSheet({
required ValueChanged<bool> onEnabledChanged,
required ValueChanged<String?> onLanguageSelected,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => _MessageTranslationSheet(
enabled: enabled,
selectedLanguageCode: selectedLanguageCode,
onEnabledChanged: onEnabledChanged,
onLanguageSelected: 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 screenHeight = math.min(
callerMedia.size.height,
sheetMedia.size.height,
);
final maxSheetHeight = math.max(
0.0,
math.min(
screenHeight * 0.82 - bottomSafeInset,
screenHeight - safeTop - math.max(callerBottom, navBottom),
),
);
return MediaQuery(
data: sheetMedia.copyWith(textScaler: callerMedia.textScaler),
child: Padding(
padding: EdgeInsets.only(bottom: extraBottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxSheetHeight),
child: _MessageTranslationSheet(
enabled: enabled,
selectedLanguageCode: selectedLanguageCode,
onEnabledChanged: onEnabledChanged,
onLanguageSelected: onLanguageSelected,
),
),
),
);
},
);
}
@@ -69,6 +115,8 @@ class _MessageTranslationSheet extends StatefulWidget {
}
class _MessageTranslationSheetState extends State<_MessageTranslationSheet> {
final GlobalKey _switchKey = GlobalKey();
final GlobalKey _searchKey = GlobalKey();
late final TextEditingController _searchController;
late bool _localEnabled;
late String? _localSelectedLanguageCode;
@@ -98,95 +146,166 @@ class _MessageTranslationSheetState extends State<_MessageTranslationSheet> {
});
}
Widget _buildSwitchTile(BuildContext context) {
return KeyedSubtree(
key: _switchKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(context.l10n.translation_translateBeforeSending),
subtitle: Text(
_localEnabled
? context.l10n.translation_composerEnabledHint
: context.l10n.translation_composerDisabledHint,
),
value: _localEnabled,
onChanged: (value) {
setState(() => _localEnabled = value);
widget.onEnabledChanged(value);
},
),
),
);
}
Widget _buildSearchField(BuildContext context) {
return KeyedSubtree(
key: _searchKey,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
child: TextField(
controller: _searchController,
onChanged: _updateFilter,
decoration: InputDecoration(
labelText: context.l10n.translation_targetLanguage,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
),
),
),
);
}
Widget _buildLanguageTile(BuildContext context, int index) {
if (index == 0) {
final selected = _localSelectedLanguageCode == null;
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
leading: Icon(
selected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
),
title: Text(context.l10n.translation_useAppLanguage),
onTap: () {
setState(() => _localSelectedLanguageCode = null);
widget.onLanguageSelected(null);
Navigator.pop(context);
},
);
}
final option = _filtered[index - 1];
final selected = option.code == _localSelectedLanguageCode;
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
leading: Icon(
selected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
),
title: Text(option.label),
subtitle: Text(option.code.toUpperCase()),
onTap: () {
setState(() => _localSelectedLanguageCode = option.code);
widget.onLanguageSelected(option.code);
Navigator.pop(context);
},
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16,
bottom: 16 + MediaQuery.of(context).viewInsets.bottom,
),
child: Column(
final header = BottomSheetHeader(
title: context.l10n.translation_messageTranslation,
);
final switchTile = _buildSwitchTile(context);
final searchField = _buildSearchField(context);
final itemCount = _filtered.length + 1;
return LayoutBuilder(
builder: (context, constraints) {
final scaler = MediaQuery.textScalerOf(context);
final narrow = constraints.maxWidth < 360;
final minPinnedHeight = scaler.scale(narrow ? 360 : 300);
if (constraints.maxHeight < scaler.scale(150)) {
return CustomScrollView(
shrinkWrap: true,
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
slivers: [
SliverToBoxAdapter(child: header),
SliverToBoxAdapter(child: switchTile),
SliverToBoxAdapter(child: searchField),
SliverPadding(
padding: const EdgeInsets.only(bottom: 12),
sliver: SliverList.list(
children: [
for (var i = 0; i < itemCount; i++)
_buildLanguageTile(context, i),
],
),
),
],
);
}
if (constraints.maxHeight < minPinnedHeight) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
header,
Flexible(
child: CustomScrollView(
shrinkWrap: true,
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
slivers: [
SliverToBoxAdapter(child: switchTile),
SliverToBoxAdapter(child: searchField),
SliverPadding(
padding: const EdgeInsets.only(bottom: 12),
sliver: SliverList.list(
children: [
for (var i = 0; i < itemCount; i++)
_buildLanguageTile(context, i),
],
),
),
],
),
),
],
);
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
context.l10n.translation_messageTranslation,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(context.l10n.translation_translateBeforeSending),
subtitle: Text(
_localEnabled
? context.l10n.translation_composerEnabledHint
: context.l10n.translation_composerDisabledHint,
),
value: _localEnabled,
onChanged: (value) {
setState(() => _localEnabled = value);
widget.onEnabledChanged(value);
},
),
const SizedBox(height: 8),
TextField(
controller: _searchController,
onChanged: _updateFilter,
decoration: InputDecoration(
labelText: context.l10n.translation_targetLanguage,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 12),
header,
switchTile,
searchField,
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: _filtered.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
final selected = _localSelectedLanguageCode == null;
return ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
selected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: Text(context.l10n.translation_useAppLanguage),
onTap: () {
setState(() => _localSelectedLanguageCode = null);
widget.onLanguageSelected(null);
Navigator.pop(context);
},
);
}
final option = _filtered[index - 1];
final selected = option.code == _localSelectedLanguageCode;
return ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
selected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: Text(option.label),
subtitle: Text(option.code.toUpperCase()),
onTap: () {
setState(() => _localSelectedLanguageCode = option.code);
widget.onLanguageSelected(option.code);
Navigator.pop(context);
},
);
},
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.only(bottom: 12),
itemCount: itemCount,
itemBuilder: _buildLanguageTile,
),
),
],
),
),
);
},
);
}
}
+337
View File
@@ -0,0 +1,337 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import 'mesh_nav_tile.dart';
/// Install state of one on-device model row.
enum ModelDownloadStatus { notDownloaded, downloading, ready, error }
/// One model in a [ModelDownloadList].
///
/// Callers own the download. This only describes what the row should show
/// and which action to offer.
class ModelDownloadItem {
final String id;
final String name;
/// Bytes on disk, or the expected download size before anything is fetched.
/// Zero and null both mean "size unknown" and are omitted.
final int? sizeBytes;
final ModelDownloadStatus status;
/// True when this installed model is the one the feature will use.
final bool selected;
/// False dims the row and drops its actions, same as a disabled settings tile.
final bool enabled;
/// 0–1 while [status] is [ModelDownloadStatus.downloading]. Null is an
/// indeterminate bar (size unknown, merging, or verifying).
final double? progress;
final int downloadedBytes;
final int? totalBytes;
/// Extra line under the status: a failure, a "not published" note, or
/// "merging" / "verifying" while a download finishes.
final String? detail;
/// Replaces the default status word. Used for an install that started but
/// did not finish ("Incomplete").
final String? statusLabel;
final VoidCallback? onDownload;
final VoidCallback? onCancel;
final VoidCallback? onDelete;
final VoidCallback? onSelect;
const ModelDownloadItem({
required this.id,
required this.name,
required this.status,
this.sizeBytes,
this.selected = false,
this.enabled = true,
this.progress,
this.downloadedBytes = 0,
this.totalBytes,
this.detail,
this.statusLabel,
this.onDownload,
this.onCancel,
this.onDelete,
this.onSelect,
});
bool get isActive => selected && status == ModelDownloadStatus.ready;
}
/// Shared list of on-device models: name, size, status, selection, and one
/// action (download, cancel, or remove).
///
/// Sits inside an existing card. It does not scroll; the page or dialog does.
class ModelDownloadList extends StatelessWidget {
final List<ModelDownloadItem> items;
/// When null, a row with an action keeps the button's own padding on the
/// right, and a row without one uses 16.
final EdgeInsets? rowPadding;
const ModelDownloadList({super.key, required this.items, this.rowPadding});
@override
Widget build(BuildContext context) {
return Column(
children: [
for (var i = 0; i < items.length; i++) ...[
if (i > 0) const Divider(height: 1, indent: 16),
_ModelDownloadRow(item: items[i], padding: rowPadding),
],
],
);
}
}
class _ModelDownloadRow extends StatelessWidget {
final ModelDownloadItem item;
final EdgeInsets? padding;
const _ModelDownloadRow({required this.item, required this.padding});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final onTap = _rowTap();
final actions = _actions(l10n);
final statusWord = _statusWord(l10n);
final sizeLabel = _sizeLabel(l10n);
final caption = _progressCaption(l10n);
final row = Padding(
padding:
padding ??
(actions.isEmpty
? const EdgeInsets.symmetric(horizontal: 16, vertical: 12)
: const EdgeInsets.fromLTRB(16, 12, 4, 12)),
child: Row(
children: [
_leading(scheme),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(item.name, style: meshTileTitleStyle(theme)),
const SizedBox(height: 2),
Text.rich(
TextSpan(
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
children: [
if (sizeLabel != null) ...[
TextSpan(
text: sizeLabel,
style: MeshTheme.mono(
fontSize: 14,
color: scheme.onSurfaceVariant,
),
),
const TextSpan(text: ' · '),
],
TextSpan(text: statusWord),
if (item.isActive) ...[
const TextSpan(text: ' · '),
TextSpan(
text: l10n.modelDownload_active,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurface,
fontWeight: FontWeight.w600,
),
),
],
],
),
),
if (item.detail != null && item.detail!.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
item.detail!,
style: theme.textTheme.bodyMedium?.copyWith(
color: item.status == ModelDownloadStatus.error
? scheme.error
: scheme.onSurfaceVariant,
),
),
],
if (item.status == ModelDownloadStatus.downloading) ...[
const SizedBox(height: 8),
LinearProgressIndicator(value: item.progress),
if (caption != null) ...[
const SizedBox(height: 4),
Text(
caption,
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
],
],
),
),
if (actions.isNotEmpty)
Row(mainAxisSize: MainAxisSize.min, children: actions),
],
),
);
return Opacity(
opacity: item.enabled ? 1 : 0.5,
child: Semantics(
button: onTap != null,
enabled: item.enabled,
selected: item.isActive,
hint: item.status == ModelDownloadStatus.ready && item.onSelect != null
? l10n.modelDownload_useModel
: null,
child: IgnorePointer(
ignoring: !item.enabled,
child: InkWell(
key: ValueKey('model-row-${item.id}'),
onTap: onTap,
child: row,
),
),
),
);
}
VoidCallback? _rowTap() {
if (!item.enabled) return null;
if (item.status == ModelDownloadStatus.ready) return item.onSelect;
if (item.status == ModelDownloadStatus.downloading) return null;
return item.onDownload;
}
Widget _leading(ColorScheme scheme) {
switch (item.status) {
case ModelDownloadStatus.downloading:
return const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
);
case ModelDownloadStatus.error:
return Icon(Icons.error_outline, size: 24, color: scheme.error);
case ModelDownloadStatus.ready:
return Icon(
item.isActive ? Icons.check_circle : Icons.check_circle_outline,
size: 24,
color: item.isActive ? scheme.primary : scheme.onSurfaceVariant,
);
case ModelDownloadStatus.notDownloaded:
return Icon(
Icons.memory_outlined,
size: 24,
color: scheme.onSurfaceVariant,
);
}
}
List<Widget> _actions(AppLocalizations l10n) {
if (!item.enabled) return const [];
if (item.status == ModelDownloadStatus.downloading) {
if (item.onCancel == null) return const [];
return [
IconButton(
key: ValueKey('model-cancel-${item.id}'),
tooltip: l10n.imageMessages_cancelDownload,
onPressed: item.onCancel,
iconSize: 24,
icon: const Icon(Icons.close),
),
];
}
final actions = <Widget>[];
if (item.status != ModelDownloadStatus.ready && item.onDownload != null) {
actions.add(
IconButton(
key: ValueKey('model-download-${item.id}'),
tooltip: l10n.imageMessages_downloadModel,
onPressed: item.onDownload,
iconSize: 24,
icon: const Icon(Icons.download_outlined),
),
);
}
if (item.onDelete != null) {
actions.add(
IconButton(
key: ValueKey('model-remove-${item.id}'),
tooltip: l10n.imageMessages_removeModel,
onPressed: item.onDelete,
iconSize: 24,
icon: const Icon(Icons.delete_outline),
),
);
}
return actions;
}
String _statusWord(AppLocalizations l10n) {
final override = item.statusLabel;
if (override != null && override.isNotEmpty) return override;
switch (item.status) {
case ModelDownloadStatus.notDownloaded:
return l10n.modelDownload_notDownloaded;
case ModelDownloadStatus.downloading:
return l10n.modelDownload_downloading;
case ModelDownloadStatus.ready:
return l10n.imageMessages_modelReady;
case ModelDownloadStatus.error:
return l10n.modelDownload_failed;
}
}
String? _sizeLabel(AppLocalizations l10n) {
final bytes = item.sizeBytes;
if (bytes == null || bytes <= 0) return null;
if (bytes >= 1024 * 1024 * 1024) {
return l10n.mapCache_sizeGigabytes(
(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2),
);
}
if (bytes >= 1024 * 1024) {
final mb = bytes / (1024 * 1024);
final digits = mb >= 100 ? 0 : 1;
return l10n.mapCache_sizeMegabytes(mb.toStringAsFixed(digits));
}
if (bytes >= 1024) {
return l10n.mapCache_sizeKilobytes((bytes / 1024).toStringAsFixed(0));
}
return l10n.mapCache_sizeBytes('$bytes');
}
String? _progressCaption(AppLocalizations l10n) {
if (item.status != ModelDownloadStatus.downloading) return null;
if (item.detail != null && item.detail!.isNotEmpty) return null;
final currentMb = item.downloadedBytes / (1024 * 1024);
final total = item.totalBytes;
if (total == null || total <= 0) {
return l10n.mapCache_sizeMegabytes(currentMb.toStringAsFixed(1));
}
final totalMb = total / (1024 * 1024);
final fraction = item.progress ?? (item.downloadedBytes / total);
final percent = (fraction * 100).clamp(0, 100).toStringAsFixed(0);
return l10n.modelDownload_progress(
currentMb.toStringAsFixed(1),
totalMb.toStringAsFixed(1),
percent,
);
}
}
+538 -171
View File
@@ -1,12 +1,17 @@
import 'dart:typed_data';
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/path_helper.dart';
import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_search.dart';
import 'mesh_ui.dart';
class PathEditorSheet extends StatefulWidget {
final List<Contact> availableContacts;
@@ -26,23 +31,28 @@ class PathEditorSheet extends StatefulWidget {
List<int> initialPath = const [],
int pathHashByteWidth = pathHashSize,
}) {
return showModalBottomSheet<Uint8List>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (context) => Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: FractionallySizedBox(
heightFactor: 0.9,
child: PathEditorSheet(
availableContacts: availableContacts,
initialPath: initialPath,
pathHashByteWidth: pathHashByteWidth,
),
),
),
// Same container as the other sheets: safe area on the top and sides,
// keyboard inset on the bottom, and the header at the top of the sheet.
// A fraction inside an expanding align left an empty band above the handle.
return showMeshSheet<Uint8List>(
context,
builder: (context) {
return LayoutBuilder(
builder: (context, constraints) {
final height = constraints.maxHeight.isFinite
? constraints.maxHeight
: MediaQuery.sizeOf(context).height;
return SizedBox(
height: height,
child: PathEditorSheet(
availableContacts: availableContacts,
initialPath: initialPath,
pathHashByteWidth: pathHashByteWidth,
),
);
},
);
},
);
}
@@ -62,10 +72,15 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final List<_Hop> _hops = [];
final _hexController = TextEditingController();
final _hexFocus = FocusNode();
final _searchFocus = FocusNode();
final _hopScroll = ScrollController();
String? _hexError;
bool _syncingHex = false;
String _search = '';
int _nextHopId = 0;
int? _highlightedHopId;
Timer? _highlightTimer;
@override
void initState() {
@@ -81,18 +96,27 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
@override
void dispose() {
_highlightTimer?.cancel();
_hopScroll.dispose();
_hexFocus.dispose();
_searchFocus.dispose();
_hexController.dispose();
super.dispose();
}
int get _hashChars {
final width = widget.pathHashByteWidth.clamp(1, pubKeySize).toInt();
return width * 2;
}
List<Contact> get _repeaters {
final query = _search.trim().toLowerCase();
final query = _search.trim();
return widget.availableContacts
.where((c) => c.type == advTypeRepeater || c.type == advTypeRoom)
.where((c) => c.publicKey.isNotEmpty)
.where((c) => query.isEmpty || c.name.toLowerCase().contains(query))
.where((c) => rankContactQuery(c, query) != null)
.toList()
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
..sort((a, b) => compareContactQueryRank(a, b, query));
}
void _syncHexFromHops() {
@@ -129,6 +153,7 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
return;
}
_hexError = null;
final previous = _hops.length;
_hops
..clear()
..addAll(
@@ -140,6 +165,9 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
return _Hop(_nextHopId++, Uint8List.fromList(bytes));
}),
);
if (_hops.length > previous && _hops.isNotEmpty) {
_markHopAdded(_hops.last.id);
}
});
}
@@ -148,14 +176,38 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final width = widget.pathHashByteWidth
.clamp(1, contact.publicKey.length)
.toInt();
HapticFeedback.selectionClick();
setState(() {
_hops.add(
_Hop(
_nextHopId++,
Uint8List.fromList(contact.publicKey.sublist(0, width)),
),
final hop = _Hop(
_nextHopId++,
Uint8List.fromList(contact.publicKey.sublist(0, width)),
);
_hops.add(hop);
_syncHexFromHops();
_markHopAdded(hop.id);
});
}
void _markHopAdded(int id) {
_highlightedHopId = id;
_highlightTimer?.cancel();
_highlightTimer = Timer(const Duration(milliseconds: 1400), () {
if (!mounted) return;
setState(() {
if (_highlightedHopId == id) _highlightedHopId = null;
});
});
_revealLatestHop();
}
void _revealLatestHop() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_hopScroll.hasClients) return;
_hopScroll.animateTo(
_hopScroll.position.maxScrollExtent,
duration: const Duration(milliseconds: 180),
curve: Curves.easeOut,
);
});
}
@@ -182,7 +234,14 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
Navigator.pop(context, Uint8List.fromList(bytes));
}
Widget _hopTile(BuildContext context, int index) {
String _contactHopHex(Contact contact) {
final width = widget.pathHashByteWidth
.clamp(1, contact.publicKey.length)
.toInt();
return PathHelper.formatHopHex(contact.publicKey.sublist(0, width));
}
Widget _hopTile(BuildContext context, int index, {required bool singleLine}) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final hop = _hops[index];
@@ -200,41 +259,61 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
: matches.length == 1
? matches.first.name
: matches.map((c) => c.name).join(' | ');
final highlighted = hop.id == _highlightedHopId;
return ListTile(
final label = name ?? l10n.pathEditor_unknownHop;
final hash = Text(hex, style: MeshTheme.mono(fontSize: 12));
return Material(
key: ValueKey(hop.id),
contentPadding: EdgeInsets.zero,
leading: CircleAvatar(
radius: 14,
backgroundColor: scheme.primaryContainer,
child: Text(
'${index + 1}',
style: TextStyle(fontSize: 12, color: scheme.onPrimaryContainer),
color: highlighted ? scheme.primaryContainer : scheme.surfaceContainerLow,
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
visualDensity: singleLine
? VisualDensity.compact
: VisualDensity.standard,
minVerticalPadding: singleLine ? 0 : 4,
leading: CircleAvatar(
radius: 16,
backgroundColor: scheme.primary,
child: Text(
'${index + 1}',
style: TextStyle(fontSize: 12, color: scheme.onPrimary),
),
),
),
title: Text(
name ?? l10n.pathEditor_unknownHop,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text(hex),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
tooltip: l10n.pathEditor_removeHop,
constraints: const BoxConstraints(minWidth: 44, minHeight: 44),
onPressed: () => _removeHop(index),
),
ReorderableDragStartListener(
index: index,
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12),
child: Icon(Icons.drag_handle),
title: singleLine
? Row(
children: [
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
hash,
],
)
: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: singleLine ? null : hash,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
tooltip: l10n.pathEditor_removeHop,
onPressed: () => _removeHop(index),
),
),
],
ReorderableDragStartListener(
index: index,
child: const SizedBox(
width: 48,
height: 48,
child: Icon(Icons.drag_handle),
),
),
],
),
),
);
}
@@ -246,16 +325,16 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final full = _hops.length >= _maxHops;
return ListTile(
contentPadding: EdgeInsets.zero,
contentPadding: const EdgeInsets.symmetric(vertical: 4),
enabled: !full,
leading: CircleAvatar(
radius: 16,
radius: 18,
backgroundColor: isRepeater
? scheme.primaryContainer
: scheme.secondaryContainer,
child: Icon(
isRepeater ? Icons.router : Icons.meeting_room,
size: 16,
size: 18,
color: isRepeater
? scheme.onPrimaryContainer
: scheme.onSecondaryContainer,
@@ -263,127 +342,372 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
),
title: Text(contact.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
'${contact.typeLabel(l10n)} • ${PathHelper.formatHopHex(contact.publicKey.sublist(0, widget.pathHashByteWidth.clamp(1, contact.publicKey.length).toInt()))}',
'${contact.typeLabel(l10n)} • ${_contactHopHex(contact)}',
style: MeshTheme.mono(fontSize: 12),
),
trailing: Icon(
Icons.add_circle_outline,
color: full ? scheme.outline : scheme.primary,
),
trailing: const Icon(Icons.add_circle_outline),
onTap: full ? null : () => _addHop(contact),
);
}
/// Heights for the hop list, hex field, and search field inside the
/// measured band between the title and the action buttons.
///
/// An invalid hex path grows the error text. That growth comes out of the
/// hop viewport first, keeping one row when it fits. When even one hop row,
/// the hex field with any active error, and the search field cannot fit,
/// [scroll] switches the middle band to a single scroll view so nothing is
/// crushed or overflows and all controls stay reachable.
({double hop, double hex, double search, bool scroll}) _middleBudget(
double space,
bool compact,
) {
final scaler = MediaQuery.textScalerOf(context);
final row = compact
? scaler.scale(56).clamp(56.0, 96.0)
: scaler.scale(76).clamp(72.0, 140.0);
final minRepeater = compact ? 56.0 : 80.0;
final searchH = scaler.scale(compact ? 48 : 56) + 20;
final baseHex = scaler.scale(compact ? 48 : 64) + (compact ? 16 : 44);
final errorExtra = _hexError == null
? 0.0
: scaler.scale(compact ? 56 : 52);
final wantedHop = _hops.isEmpty
? math.min(scaler.scale(compact ? 64 : 80), 140.0)
: math.min(_hops.length, compact ? 2 : 3) * row + 4;
final wantedHex = baseHex + errorExtra;
final minHop = _hops.isEmpty ? 0.0 : row;
final scroll = minHop + wantedHex + searchH > space;
var hopH = wantedHop;
if (!scroll) {
final targetMax = math.max(
minHop + wantedHex + searchH,
space - minRepeater,
);
final used = hopH + wantedHex + searchH;
if (used > targetMax) {
hopH -= math.min(used - targetMax, math.max(0.0, hopH - minHop));
}
}
return (hop: hopH, hex: wantedHex, search: searchH, scroll: scroll);
}
Widget _hopViewport(bool compact, double height) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return SizedBox(
height: height,
child: height < 8
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: scheme.outlineVariant),
),
child: _hops.isEmpty
? SingleChildScrollView(
padding: const EdgeInsets.all(12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
: ReorderableListView.builder(
scrollController: _hopScroll,
buildDefaultDragHandles: false,
padding: EdgeInsets.symmetric(
vertical: compact ? 0 : 4,
),
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: (context, index) =>
_hopTile(context, index, singleLine: compact),
),
),
),
);
}
Widget _hexViewport(bool compact, double height) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SizedBox(
height: height,
child: SingleChildScrollView(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!compact) ...[
Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
const SizedBox(height: 8),
],
TextField(
key: const Key('path-editor-hex-field'),
controller: _hexController,
focusNode: _hexFocus,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
style: MeshTheme.mono(fontSize: 14),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: compact || _hexError != null
? null
: l10n.pathEditor_hexHelper(_hashChars),
helperMaxLines: 3,
errorText: _hexError,
errorMaxLines: compact ? 4 : 3,
border: const OutlineInputBorder(),
isDense: compact,
),
),
],
),
),
);
}
Widget _searchViewport(bool compact, double height) {
final l10n = context.l10n;
return SizedBox(
height: height,
child: Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: TextField(
key: const Key('path-editor-search-field'),
focusNode: _searchFocus,
onChanged: (value) => setState(() => _search = value),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: compact,
),
),
),
);
}
Widget _repeaterViewport(List<Contact> repeaters) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
if (repeaters.isEmpty) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Align(
alignment: Alignment.topLeft,
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
);
}
return ListView.builder(
key: const Key('path-editor-repeater-list'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
itemCount: repeaters.length,
itemBuilder: (context, index) => _repeaterTile(context, repeaters[index]),
);
}
List<Widget> _middleSlivers({
required bool compact,
required List<Contact> repeaters,
}) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return [
SliverToBoxAdapter(child: _scrollHopBlock(compact)),
SliverToBoxAdapter(child: _scrollHexBlock(compact)),
SliverToBoxAdapter(child: _scrollSearchBlock(compact)),
if (repeaters.isEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
sliver: SliverList.builder(
key: const Key('path-editor-repeater-list'),
itemCount: repeaters.length,
itemBuilder: (context, index) =>
_repeaterTile(context, repeaters[index]),
),
),
];
}
/// One scrollable for the hop list, hex field, search field, and repeaters.
///
/// The blocks are intrinsic height with no nested scrolling, so a drag
/// anywhere in the band moves the search field and the repeater list into
/// view. The pinned layout keeps its own viewports.
Widget _scrollingMiddle({
required bool compact,
required List<Contact> repeaters,
}) {
return CustomScrollView(
key: const Key('path-editor-scroll-fallback'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
slivers: _middleSlivers(compact: compact, repeaters: repeaters),
);
}
Widget _scrollHopBlock(bool compact) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: scheme.outlineVariant),
),
child: _hops.isEmpty
? Padding(
padding: const EdgeInsets.all(12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
: ReorderableListView.builder(
scrollController: _hopScroll,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
padding: EdgeInsets.symmetric(vertical: compact ? 0 : 4),
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: (context, index) =>
_hopTile(context, index, singleLine: compact),
),
),
);
}
Widget _scrollHexBlock(bool compact) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!compact) ...[
Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
const SizedBox(height: 8),
],
TextField(
key: const Key('path-editor-hex-field'),
controller: _hexController,
focusNode: _hexFocus,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
style: MeshTheme.mono(fontSize: 14),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: compact || _hexError != null
? null
: l10n.pathEditor_hexHelper(_hashChars),
helperMaxLines: 3,
errorText: _hexError,
errorMaxLines: compact ? 4 : 3,
border: const OutlineInputBorder(),
isDense: compact,
),
),
],
),
);
}
Widget _scrollSearchBlock(bool compact) {
final l10n = context.l10n;
return Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: TextField(
key: const Key('path-editor-search-field'),
focusNode: _searchFocus,
onChanged: (value) => setState(() => _search = value),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: compact,
),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final repeaters = _repeaters;
return Column(
children: [
const SizedBox(height: 8),
Container(
width: 32,
height: 4,
decoration: BoxDecoration(
color: scheme.outlineVariant,
borderRadius: BorderRadius.circular(2),
return LayoutBuilder(
builder: (context, constraints) {
final maxHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: 640.0;
// Phone sheets and a keyboard-shrunk window use the shorter hop rows
// so the action buttons stay below the repeater list.
final compact = maxHeight < 680;
final scaler = MediaQuery.textScalerOf(context);
final header = Semantics(
liveRegion: true,
child: BottomSheetHeader(
title: l10n.pathEditor_title,
subtitle: l10n.pathEditor_hopCounter(_hops.length),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(l10n.pathEditor_title, style: theme.textTheme.titleLarge),
Text(
l10n.pathEditor_hopCounter(_hops.length),
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
children: [
if (_hops.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
else
ReorderableListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: _hopTile,
),
const Divider(),
const SizedBox(height: 8),
Text(l10n.pathEditor_addHops, style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
TextField(
onChanged: (value) => setState(() => _search = value),
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 4),
if (repeaters.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
else
...repeaters.map((c) => _repeaterTile(context, c)),
ExpansionTile(
tilePadding: EdgeInsets.zero,
title: Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextField(
controller: _hexController,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: _hexError == null
? l10n.pathEditor_hexHelper
: null,
errorText: _hexError,
border: const OutlineInputBorder(),
),
),
),
],
),
],
),
),
SafeArea(
);
final actions = SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
padding: EdgeInsets.fromLTRB(
16,
compact ? 4 : 8,
16,
compact ? 4 : 16,
),
child: Row(
children: [
Expanded(
@@ -408,8 +732,51 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
],
),
),
),
],
);
// When scaled header and action buttons leave less than one row for
// the middle band, scroll the whole sheet so nothing clips or crowds
// the viewport.
if (maxHeight < scaler.scale(150) + 28) {
return CustomScrollView(
key: const Key('path-editor-scroll-fallback'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
slivers: [
SliverToBoxAdapter(child: header),
..._middleSlivers(compact: compact, repeaters: repeaters),
SliverToBoxAdapter(child: actions),
],
);
}
return Column(
children: [
header,
Expanded(
child: LayoutBuilder(
builder: (context, inner) {
final budget = _middleBudget(inner.maxHeight, compact);
if (budget.scroll) {
return _scrollingMiddle(
compact: compact,
repeaters: repeaters,
);
}
return Column(
children: [
_hopViewport(compact, budget.hop),
_hexViewport(compact, budget.hex),
_searchViewport(compact, budget.search),
Expanded(child: _repeaterViewport(repeaters)),
],
);
},
),
),
actions,
],
);
},
);
}
}
+35 -23
View File
@@ -30,6 +30,16 @@ bool isDesktopMapPlatform([TargetPlatform? platform]) {
p == TargetPlatform.macOS;
}
/// Left edge of the [PathMapDesktopControls] column plus its 48px buttons
/// and a gap; overlays at the top of the map start here on desktop so they
/// don't cover the zoom buttons.
const double kPathMapDesktopControlsInset = 16 + 48 + 8;
/// Horizontal inset for overlays stacked at the top of a path map: clears
/// the desktop zoom controls, otherwise the usual 16px margin.
double pathMapTopOverlayInset([TargetPlatform? platform]) =>
isDesktopMapPlatform(platform) ? kPathMapDesktopControlsInset : 16;
/// 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) {
@@ -168,37 +178,38 @@ class PathMapDesktopControls extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
return Positioned(
top: 16,
left: 16,
child: DecoratedBox(
decoration: BoxDecoration(
color: MeshPalette.bg1.withValues(alpha: 0.90),
color: scheme.surfaceContainerLow.withValues(alpha: 0.94),
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MeshPalette.line2),
border: Border.all(color: scheme.outlineVariant),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(MeshRadii.md),
child: IconTheme(
data: const IconThemeData(color: MeshPalette.ink),
data: IconThemeData(color: scheme.onSurface),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.add),
color: MeshPalette.ink,
color: scheme.onSurface,
tooltip: l10n.map_zoomIn,
onPressed: onZoomIn,
),
IconButton(
icon: const Icon(Icons.remove),
color: MeshPalette.ink,
color: scheme.onSurface,
tooltip: l10n.map_zoomOut,
onPressed: onZoomOut,
),
IconButton(
icon: const Icon(Icons.my_location),
color: MeshPalette.ink,
color: scheme.onSurface,
tooltip: l10n.map_centerMap,
onPressed: onReset,
),
@@ -280,12 +291,12 @@ class PathSharedCountBadge extends StatelessWidget {
}
}
/// Dark, collapsible bottom panel shared by the path map screens: header
/// 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.
/// Uses the theme's card surface and sets text/icon/divider colours from the
/// [ColorScheme] so the panel matches light, dark and custom themes.
class PathMapBottomPanel extends StatelessWidget {
final Widget header;
final bool combined;
@@ -334,6 +345,7 @@ class PathMapBottomPanel extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final maxHeight =
MediaQuery.of(context).size.height * (combined ? 0.45 : 0.35);
const hopRowHeight = 60.0;
@@ -348,7 +360,7 @@ class PathMapBottomPanel extends StatelessWidget {
cardHeight = max(196.0, min(maxHeight, estimatedHeight));
}
final warnStyle = const TextStyle(fontSize: 12, color: MeshPalette.warn);
final warnStyle = TextStyle(fontSize: 12, color: scheme.tertiary);
final unresolved = selected?.unresolvedHops ?? 0;
return Positioned(
@@ -360,26 +372,26 @@ class PathMapBottomPanel extends StatelessWidget {
height: cardHeight,
child: Container(
decoration: BoxDecoration(
color: MeshPalette.bg1.withValues(alpha: 0.96),
color: scheme.surfaceContainerLow.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: MeshPalette.line2),
border: Border.all(color: scheme.outlineVariant),
),
clipBehavior: Clip.antiAlias,
child: DefaultTextStyle.merge(
style: const TextStyle(color: MeshPalette.ink),
style: TextStyle(color: scheme.onSurface),
child: IconTheme(
data: const IconThemeData(color: MeshPalette.ink),
data: IconThemeData(color: scheme.onSurface),
child: DividerTheme(
data: const DividerThemeData(color: MeshPalette.line),
data: DividerThemeData(color: scheme.outlineVariant),
child: ListTileTheme(
data: const ListTileThemeData(
iconColor: MeshPalette.ink2,
textColor: MeshPalette.ink,
data: ListTileThemeData(
iconColor: scheme.onSurfaceVariant,
textColor: scheme.onSurface,
),
child: TextButtonTheme(
data: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: MeshPalette.ink,
foregroundColor: scheme.onSurface,
),
),
child: LayoutBuilder(
@@ -445,7 +457,7 @@ class PathMapBottomPanel extends StatelessWidget {
? Icons.close_fullscreen
: Icons.open_in_full,
),
color: MeshPalette.ink,
color: scheme.onSurface,
tooltip: isExpanded
? l10n.pathMap_showMap
: l10n.pathMap_expandHopList,
@@ -457,7 +469,7 @@ class PathMapBottomPanel extends StatelessWidget {
? Icons.expand_less
: Icons.expand_more,
),
color: MeshPalette.ink,
color: scheme.onSurface,
tooltip: collapsed
? l10n.pathMap_expandPanel
: l10n.pathMap_collapsePanel,
@@ -489,10 +501,10 @@ class PathMapBottomPanel extends StatelessWidget {
),
child: Row(
children: [
const Icon(
Icon(
Icons.gps_off,
size: 16,
color: MeshPalette.warn,
color: scheme.tertiary,
),
const SizedBox(width: 6),
Expanded(
+61 -40
View File
@@ -8,6 +8,7 @@ import '../models/display_path.dart';
import '../models/path_playback.dart';
import '../theme/mesh_theme.dart';
import 'mesh_ui.dart';
import 'path_map_scaffold.dart';
/// Shared UI for the path map screens (live path trace and received-message
/// path map): packet-flow animation overlays, single/combined view toggle,
@@ -232,6 +233,7 @@ void showSharedNodeSheet(
required ValueChanged<DisplayPath> onSelect,
}) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
showModalBottomSheet(
context: context,
builder: (sheetContext) => SafeArea(
@@ -246,7 +248,7 @@ void showSharedNodeSheet(
style: MeshTheme.mono(
fontSize: 14,
fontWeight: FontWeight.w700,
color: MeshPalette.ink,
color: scheme.onSurface,
),
),
),
@@ -254,7 +256,7 @@ void showSharedNodeSheet(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
l10n.pathMap_sharedNodeCount(paths.length),
style: TextStyle(fontSize: 12, color: MeshPalette.ink3),
style: TextStyle(fontSize: 12, color: scheme.onSurfaceVariant),
),
),
const SizedBox(height: 8),
@@ -264,11 +266,14 @@ void showSharedNodeSheet(
leading: _colorDot(path.color),
title: Text(
path.label,
style: MeshTheme.mono(fontSize: 13, color: MeshPalette.ink),
style: MeshTheme.mono(fontSize: 13, color: scheme.onSurface),
),
trailing: Text(
l10n.pathMap_hopCount(path.totalTransmissions),
style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3),
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
onTap: () {
Navigator.pop(sheetContext);
@@ -302,33 +307,40 @@ class PathViewModeToggle extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
// Symmetric insets keep the toggle centred while clearing the desktop
// zoom controls in the top-left corner.
final inset = isDesktopMapPlatform() ? kPathMapDesktopControlsInset : 0.0;
return Positioned(
top: 12,
left: 0,
right: 0,
left: inset,
right: inset,
child: Center(
child: DecoratedBox(
decoration: BoxDecoration(
color: MeshPalette.bg1.withValues(alpha: 0.92),
borderRadius: BorderRadius.circular(MeshRadii.pill),
),
child: SegmentedButton<PathViewMode>(
style: const ButtonStyle(
visualDensity: VisualDensity(horizontal: -3, vertical: -3),
child: FittedBox(
fit: BoxFit.scaleDown,
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow.withValues(alpha: 0.94),
borderRadius: BorderRadius.circular(MeshRadii.pill),
),
showSelectedIcon: false,
segments: [
ButtonSegment(
value: PathViewMode.single,
label: MeshSegmentLabel(l10n.pathMap_viewSingle),
child: SegmentedButton<PathViewMode>(
style: const ButtonStyle(
visualDensity: VisualDensity(horizontal: -3, vertical: -3),
),
ButtonSegment(
value: PathViewMode.combined,
label: MeshSegmentLabel(l10n.pathMap_viewCombined),
),
],
selected: {mode},
onSelectionChanged: (selection) => onChanged(selection.first),
showSelectedIcon: false,
segments: [
ButtonSegment(
value: PathViewMode.single,
label: MeshSegmentLabel(l10n.pathMap_viewSingle),
),
ButtonSegment(
value: PathViewMode.combined,
label: MeshSegmentLabel(l10n.pathMap_viewCombined),
),
],
selected: {mode},
onSelectionChanged: (selection) => onChanged(selection.first),
),
),
),
),
@@ -363,6 +375,7 @@ class PathAnimationControls extends StatelessWidget {
animation: playback,
builder: (context, _) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final enabled = animationEnabled && playback.hasPath;
final path = selected;
String? hopLabel;
@@ -408,8 +421,8 @@ class PathAnimationControls extends StatelessWidget {
? l10n.pathMap_animationOff
: l10n.pathMap_animationOn,
color: animationEnabled
? MeshPalette.blue
: MeshPalette.ink4,
? scheme.primary
: scheme.onSurfaceVariant,
onPressed: onToggleAnimation,
),
controlButton(
@@ -441,7 +454,7 @@ class PathAnimationControls extends StatelessWidget {
tooltip: followEnabled
? l10n.pathMap_unfollowPacket
: l10n.pathMap_followPacket,
color: followEnabled ? MeshPalette.blue : null,
color: followEnabled ? scheme.primary : null,
onPressed: enabled ? onToggleFollow : null,
),
TextButton(
@@ -468,7 +481,7 @@ class PathAnimationControls extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: MeshTheme.mono(
fontSize: 12,
color: MeshPalette.ink2,
color: scheme.onSurfaceVariant,
),
),
),
@@ -494,16 +507,14 @@ class PathMiniLegend extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
Widget item(Widget swatch, String text) => Row(
mainAxisSize: MainAxisSize.min,
children: [
swatch,
const SizedBox(width: 4),
Flexible(
child: Text(
text,
style: TextStyle(fontSize: 12, color: MeshPalette.ink3),
),
child: Text(text, style: TextStyle(fontSize: 12, color: muted)),
),
],
);
@@ -515,7 +526,7 @@ class PathMiniLegend extends StatelessWidget {
width: 5,
height: 3,
margin: const EdgeInsets.only(right: 2),
color: MeshPalette.ink3,
color: muted,
),
],
);
@@ -571,6 +582,7 @@ class PathSummaryList extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -580,7 +592,10 @@ class PathSummaryList extends StatelessWidget {
children: [
Text(
l10n.pathMap_observedPaths(paths.length),
style: MeshTheme.accentLabel(color: MeshPalette.ink3),
style: MeshTheme.accentLabel(
color: scheme.onSurfaceVariant,
fontSize: 12,
),
),
const Spacer(),
if (hiddenIds.isNotEmpty)
@@ -607,6 +622,7 @@ class PathSummaryList extends StatelessWidget {
Widget _buildRow(BuildContext context, DisplayPath path) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final isSelected = path.id == selectedId;
final hidden = hiddenIds.contains(path.id);
final timestamp = path.record?.timestamp;
@@ -622,7 +638,9 @@ class PathSummaryList extends StatelessWidget {
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: isSelected ? MeshPalette.bg3 : Colors.transparent,
color: isSelected
? scheme.surfaceContainerHighest
: Colors.transparent,
borderRadius: BorderRadius.circular(MeshRadii.sm),
),
child: Row(
@@ -641,7 +659,7 @@ class PathSummaryList extends StatelessWidget {
fontWeight: isSelected
? FontWeight.w700
: FontWeight.w500,
color: MeshPalette.ink,
color: scheme.onSurface,
),
),
],
@@ -655,7 +673,10 @@ class PathSummaryList extends StatelessWidget {
parts.join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: MeshTheme.mono(fontSize: 12, color: MeshPalette.ink3),
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
),
),
@@ -663,7 +684,7 @@ class PathSummaryList extends StatelessWidget {
icon: Icon(
hidden ? Icons.visibility_off : Icons.visibility,
size: 20,
color: hidden ? MeshPalette.ink4 : MeshPalette.ink3,
color: scheme.onSurfaceVariant,
),
tooltip: hidden ? l10n.pathMap_showPath : l10n.pathMap_hidePath,
padding: EdgeInsets.zero,
+17 -6
View File
@@ -6,6 +6,7 @@ import 'package:provider/provider.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../l10n/contact_localization.dart';
import '../services/app_settings_service.dart';
import '../services/storage_service.dart';
import '../services/repeater_command_service.dart';
import '../connector/meshcore_connector.dart';
@@ -40,7 +41,9 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
String? _loginError;
late MeshCoreConnector _connector;
int _currentAttempt = 0;
static const int _maxAttempts = 5;
int get _maxAttempts =>
context.read<AppSettingsService>().settings.loginAttempts;
@override
void initState() {
@@ -195,10 +198,13 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
await _storage.removeRepeaterPassword(widget.repeater.publicKeyHex);
}
final autoClockSync = await _storage
.getRepeaterAutoClockSyncAfterLoginEnabled(
widget.repeater.publicKeyHex,
);
final globalClockSync = mounted
? context.read<AppSettingsService>().settings.clockSyncAfterLogin
: false;
final autoClockSync = await _storage.repeaterClockSyncAfterLogin(
widget.repeater.publicKeyHex,
globalDefault: globalClockSync,
);
if (autoClockSync) {
try {
final timestampSeconds =
@@ -390,7 +396,12 @@ class _RepeaterLoginDialogState extends State<RepeaterLoginDialog> {
}
},
onSubmitted: (_) => _handleLogin(),
autofocus: _passwordController.text.isEmpty,
autofocus:
context
.watch<AppSettingsService>()
.settings
.loginPasswordAutofocus &&
_passwordController.text.isEmpty,
),
const SizedBox(height: 12),
CheckboxListTile(
+8 -1
View File
@@ -7,6 +7,7 @@ import 'package:provider/provider.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../l10n/contact_localization.dart';
import '../services/app_settings_service.dart';
import '../services/storage_service.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
@@ -36,7 +37,9 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
bool _obscurePassword = true;
late MeshCoreConnector _connector;
int _currentAttempt = 0;
static const int _maxAttempts = 5;
int get _maxAttempts =>
context.read<AppSettingsService>().settings.loginAttempts;
@override
void initState() {
@@ -321,6 +324,10 @@ class _RoomLoginDialogState extends State<RoomLoginDialog> {
),
onSubmitted: (_) => _handleLogin(),
autofocus:
context
.watch<AppSettingsService>()
.settings
.loginPasswordAutofocus &&
!PlatformInfo.isMobile &&
_passwordController.text.isEmpty,
),
+115
View File
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
/// Shows or hides [child] by animating its height.
///
/// Use this wherever turning something on reveals more controls, and for any
/// other block that grows or collapses in place. Hidden controls are not in
/// the tree, so they are not announced. The duration and curve are fixed so
/// every reveal moves the same way. See documentation/design.md.
class RevealOnEnable extends StatelessWidget {
static const Duration duration = Duration(milliseconds: 200);
static const Curve curve = Curves.easeInOut;
final bool visible;
final Widget child;
final AlignmentGeometry alignment;
const RevealOnEnable({
super.key,
required this.visible,
required this.child,
this.alignment = Alignment.topCenter,
});
@override
Widget build(BuildContext context) {
return AnimatedSize(
duration: duration,
curve: curve,
alignment: alignment,
child: visible
? child
: const SizedBox(width: double.infinity, height: 0),
);
}
}
/// Nested controls under a settings switch: the shared reveal animation on a
/// tinted, indented panel.
class SettingsReveal extends StatelessWidget {
final bool visible;
final List<Widget> children;
const SettingsReveal({
super.key,
required this.visible,
required this.children,
});
@override
Widget build(BuildContext context) {
return RevealOnEnable(
visible: visible,
child: Material(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
),
),
),
);
}
}
/// A settings slider whose selected value stays visible in the title.
///
/// The drag bubble repeats the same number. Pass a [title] that already
/// includes [value], the way the channel-hop titles do, and an [icon] so the
/// row aligns with neighbouring [SwitchListTile] and [MeshNavTile] rows.
class SettingsValueSlider extends StatelessWidget {
final IconData icon;
final String title;
final String? subtitle;
final int value;
final int min;
final int max;
final ValueChanged<int> onChanged;
const SettingsValueSlider({
super.key,
required this.icon,
required this.title,
this.subtitle,
required this.value,
required this.min,
required this.max,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
final clamped = value.clamp(min, max);
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
leading: Icon(icon, size: 24),
title: Text(title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (subtitle != null) Text(subtitle!),
Slider(
value: clamped.toDouble(),
min: min.toDouble(),
max: max.toDouble(),
divisions: max > min ? max - min : null,
label: '$clamped',
onChanged: (next) => onChanged(next.round()),
),
],
),
);
}
}
+68 -43
View File
@@ -2,11 +2,13 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/contact_share_message.dart';
import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_search.dart';
import 'mesh_ui.dart';
/// Lets the user pick a saved contact (or themself) and appends the encoded
@@ -50,21 +52,19 @@ class _ShareContactSheetState extends State<_ShareContactSheet> {
final contacts =
connector.contacts
.where(
(c) =>
c.publicKey.length == 32 &&
(needle.isEmpty || c.name.toLowerCase().contains(needle)),
(c) => c.publicKey.length == 32 && matchesContactQuery(c, needle),
)
.toList()
..sort(
(a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
..sort((a, b) => compareContactQueryRank(a, b, needle));
final selfName = connector.selfName ?? '';
final showSelf =
selfKey != null &&
selfKey.length == 32 &&
(needle.isEmpty ||
selfName.toLowerCase().contains(needle) ||
l10n.contactShare_myContact.toLowerCase().contains(needle));
final selfRank = selfKey != null && selfKey.length == 32
? rankLabeledKeyQuery(
name: selfName.isEmpty ? l10n.contactShare_myContact : selfName,
publicKeyHex: pubKeyToHex(selfKey),
query: needle,
aliases: [l10n.contactShare_myContact],
)
: null;
return SafeArea(
child: ConstrainedBox(
@@ -86,43 +86,68 @@ class _ShareContactSheetState extends State<_ShareContactSheet> {
onChanged: (value) => setState(() => _query = value),
),
),
Flexible(
child: ListView(
shrinkWrap: true,
children: [
if (showSelf)
_tile(
context,
name: selfName.isEmpty
? l10n.contactShare_myContact
: selfName,
subtitle: l10n.contactShare_myContact,
token: encodeContactShare(
publicKey: selfKey,
type: 1,
name: selfName,
),
),
for (final c in contacts) _contactTile(context, c),
if (!showSelf && contacts.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(
l10n.contactShare_noContacts,
style: const TextStyle(fontSize: 14),
),
),
),
],
),
),
Flexible(child: _shareList(context, contacts, selfRank)),
],
),
),
);
}
Widget _shareList(
BuildContext context,
List<Contact> contacts,
ContactQueryRank? selfRank,
) {
final l10n = context.l10n;
final connector = widget.connector;
final selfKey = connector.selfPublicKey;
final selfName = connector.selfName ?? '';
final rows =
<({int rank, String name, Widget tile})>[
for (final contact in contacts)
(
rank: rankContactQuery(contact, _query)?.index ?? 3,
name: contact.name.toLowerCase(),
tile: _contactTile(context, contact),
),
if (selfRank != null && selfKey != null)
(
rank: selfRank.index,
name: (selfName.isEmpty ? l10n.contactShare_myContact : selfName)
.toLowerCase(),
tile: _tile(
context,
name: selfName.isEmpty ? l10n.contactShare_myContact : selfName,
subtitle: l10n.contactShare_myContact,
token: encodeContactShare(
publicKey: selfKey,
type: 1,
name: selfName,
),
),
),
]..sort((a, b) {
final byRank = a.rank.compareTo(b.rank);
if (byRank != 0) return byRank;
return a.name.compareTo(b.name);
});
if (rows.isEmpty) {
return Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(
l10n.contactShare_noContacts,
style: const TextStyle(fontSize: 14),
),
),
);
}
return ListView(
shrinkWrap: true,
children: [for (final row in rows) row.tile],
);
}
Widget _contactTile(BuildContext context, Contact c) {
return _tile(
context,
@@ -7,6 +7,7 @@ class TranslatedMessageContent extends StatelessWidget {
final String? originalText;
final TextStyle style;
final TextStyle? originalStyle;
final Color? backgroundColor;
final bool showOriginalFirst;
final VoidCallback? onSecondaryTap;
@@ -16,6 +17,7 @@ class TranslatedMessageContent extends StatelessWidget {
required this.style,
this.originalText,
this.originalStyle,
this.backgroundColor,
this.showOriginalFirst = true,
this.onSecondaryTap,
});
@@ -38,6 +40,7 @@ class TranslatedMessageContent extends StatelessWidget {
fontStyle: FontStyle.italic,
fontSize: style.fontSize,
),
backgroundColor: backgroundColor,
onSecondaryTap: onSecondaryTap,
)
: null;
@@ -45,6 +48,7 @@ class TranslatedMessageContent extends StatelessWidget {
context: context,
text: trimmedDisplay,
style: style,
backgroundColor: backgroundColor,
onSecondaryTap: onSecondaryTap,
);
+520 -370
View File
@@ -2,12 +2,15 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../models/app_settings.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';
import 'model_download_list.dart';
import 'settings_reveal.dart';
/// [TranslationService] publishes this as `downloadFileName` while it merges
/// downloaded chunks (see translation_service.dart). The service owns the
@@ -15,24 +18,21 @@ import 'mesh_nav_tile.dart';
/// 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.
/// On-device translation settings: feature toggles, target language, and the
/// shared model list.
///
/// Watches only [AppSettingsService] and [TranslationService], so download
/// progress ticks rebuild this card and nothing else on the settings screen.
/// [_TranslationModels] watches [TranslationService], so download progress
/// rebuilds the model rows and not the toggles above them.
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);
@@ -44,253 +44,74 @@ class TranslationSettingsSection extends StatelessWidget {
secondary: const Icon(Icons.translate, size: 24),
title: Text(l10n.translation_enableTitle),
subtitle: Text(l10n.translation_enableSubtitle),
value: settings.translationEnabled,
value: 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,
SettingsReveal(
visible: translationEnabled,
children: [
SwitchListTile(
contentPadding: tilePadding,
secondary: Icon(
Icons.auto_awesome_outlined,
size: 24,
color: disabledColor,
),
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),
),
],
],
),
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: translationEnabled
? () =>
_showTranslationLanguageDialog(context, settingsService)
: null,
),
const Divider(height: 1, indent: 16),
const _TranslationModels(),
],
),
],
);
}
static bool _isMerging(TranslationService service) =>
service.downloadFileName == _mergingChunksFileName;
void _showTranslationLanguageDialog(
BuildContext context,
AppSettingsService settingsService,
@@ -308,50 +129,6 @@ class TranslationSettingsSection extends StatelessWidget {
);
}
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;
@@ -363,45 +140,418 @@ class TranslationSettingsSection extends StatelessWidget {
}
return languageCode.toUpperCase();
}
}
String _downloadProgressLabel(
BuildContext context,
TranslationService translationService,
) {
class _PendingDownload {
final String id;
final String name;
final String sourceUrl;
final String? fileName;
final String? modelId;
const _PendingDownload({
required this.id,
required this.name,
required this.sourceUrl,
this.fileName,
this.modelId,
});
}
/// Preset rows, installed models, and the manual URL field.
class _TranslationModels extends StatefulWidget {
const _TranslationModels();
@override
State<_TranslationModels> createState() => _TranslationModelsState();
}
class _TranslationModelsState extends State<_TranslationModels> {
_PendingDownload? _pending;
String? _failedId;
String? _failedDetail;
@override
Widget build(BuildContext context) {
final settingsService = context.watch<AppSettingsService>();
final translationService = context.watch<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,
final settings = settingsService.settings;
final scheme = Theme.of(context).colorScheme;
final lastError = translationService.lastError;
final showLastError =
lastError != null &&
lastError.isNotEmpty &&
lastError != 'Download stopped.' &&
lastError != translationService.failedDownloadError &&
lastError != _failedDetail;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ModelDownloadList(
items: _items(l10n, settings, settingsService, translationService),
),
const Divider(height: 1, indent: 16),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: _TranslationUrlField(
initialValue: settings.translationModelSourceUrl ?? '',
onChanged: settingsService.setTranslationModelSourceUrl,
onDownload: translationService.isBusy
? null
: (url) => _download(sourceUrl: url),
labelText: l10n.translation_manualUrlLabel,
downloadTooltip: l10n.imageMessages_downloadModel,
),
),
if (showLastError)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Text(
lastError,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: scheme.error),
),
),
],
);
}
Future<void> _deleteTranslationModel(
BuildContext context,
List<ModelDownloadItem> _items(
AppLocalizations l10n,
AppSettings settings,
AppSettingsService settingsService,
TranslationService service,
) {
final downloaded = settings.translationDownloadedModels;
final selectedId = settings.translationSelectedModelId;
final pending = _pending;
final used = <TranslationModelRecord>{};
final items = <ModelDownloadItem>[];
var pendingShown = false;
final serviceFailedError = service.failedDownloadError;
bool targets(String id, String sourceUrl, String name) {
if (pending == null) return false;
if (pending.id == id || pending.modelId == id) return true;
if (sourceUrl.isNotEmpty && pending.sourceUrl == sourceUrl) return true;
if (name.isNotEmpty && pending.name == name) return true;
return false;
}
bool matchesServiceFailure(
String id,
String sourceUrl,
String? fileName,
String? installedName,
) {
if (serviceFailedError == null) return false;
if (service.failedDownloadModelId == id) return true;
if (sourceUrl.isNotEmpty &&
service.failedDownloadSourceUrl == sourceUrl) {
return true;
}
final failedFile = service.failedDownloadFileName;
if (failedFile != null &&
failedFile.isNotEmpty &&
(failedFile == fileName || failedFile == installedName)) {
return true;
}
return false;
}
ModelDownloadItem buildItem({
required String id,
required String name,
required String sourceUrl,
required String? fileName,
required String? modelId,
required TranslationModelRecord? installed,
}) {
if (installed != null) used.add(installed);
final downloading =
service.isDownloading &&
(targets(id, sourceUrl, name) ||
_fileNamesThisDownload(service, fileName, installed?.name));
final failed =
!downloading &&
(_failedId == id ||
(_failedId == null &&
matchesServiceFailure(
id,
sourceUrl,
fileName,
installed?.name,
)));
if (downloading || failed) pendingShown = true;
final merging = downloading && _isMerging(service);
final busy = service.isBusy;
final installedModel = installed;
final failureDetail = _failedId == id
? _failedDetail
: (serviceFailedError != null
? l10n.translation_downloadFailed(serviceFailedError)
: null);
return ModelDownloadItem(
id: id,
name: name,
sizeBytes: installedModel != null && installedModel.fileSizeBytes > 0
? installedModel.fileSizeBytes
: null,
status: downloading
? ModelDownloadStatus.downloading
: failed
? ModelDownloadStatus.error
: installedModel != null
? ModelDownloadStatus.ready
: ModelDownloadStatus.notDownloaded,
selected:
installedModel != null &&
!downloading &&
installedModel.id == selectedId,
detail: merging
? l10n.translation_mergingChunks
: failed
? failureDetail
: null,
progress: downloading && !merging ? service.downloadProgress : null,
downloadedBytes: downloading ? service.downloadedBytes : 0,
totalBytes: downloading ? service.downloadTotalBytes : null,
onDownload: !busy && installedModel == null
? () => _download(
sourceUrl: sourceUrl,
fileName: fileName,
id: modelId,
)
: null,
onCancel: downloading ? service.cancelDownload : null,
onDelete: installedModel != null && !busy
? () => _delete(service, installedModel)
: null,
onSelect:
installedModel != null &&
!downloading &&
installedModel.id != selectedId &&
!busy
? () => settingsService.setTranslationSelectedModelId(
installedModel.id,
)
: null,
);
}
for (final preset in translationPresetModels) {
TranslationModelRecord? installed;
for (final model in downloaded) {
if (model.id == preset.id ||
(preset.sourceUrl.isNotEmpty &&
model.sourceUrl == preset.sourceUrl) ||
(preset.name.isNotEmpty && model.name == preset.name)) {
installed = model;
break;
}
}
items.add(
buildItem(
id: preset.id,
name: translationModelFriendlyName(preset),
sourceUrl: preset.sourceUrl,
fileName: preset.name,
modelId: preset.id,
installed: installed,
),
);
}
for (final model in downloaded) {
if (used.contains(model)) continue;
items.add(
buildItem(
id: model.id,
name: translationModelFriendlyName(model),
sourceUrl: model.sourceUrl,
fileName: model.name,
modelId: model.id,
installed: model,
),
);
}
if (!pendingShown && service.isDownloading) {
items.add(_inProgressItem(l10n, service));
} else if (pending != null && !pendingShown && _failedId == pending.id) {
items.add(
ModelDownloadItem(
id: pending.id,
name: pending.name,
status: ModelDownloadStatus.error,
detail: _failedDetail,
onDownload: service.isBusy
? null
: () => _download(
sourceUrl: pending.sourceUrl,
fileName: pending.fileName,
id: pending.modelId,
),
),
);
} else if (!pendingShown &&
!service.isDownloading &&
serviceFailedError != null &&
service.failedDownloadSourceUrl != null) {
final failedUrl = service.failedDownloadSourceUrl!;
final failedFile = service.failedDownloadFileName;
final failedModelId = service.failedDownloadModelId;
final id = (failedModelId != null && failedModelId.isNotEmpty)
? failedModelId
: failedUrl.isNotEmpty
? failedUrl
: (failedFile ?? 'download');
items.add(
ModelDownloadItem(
id: id,
name: _displayName(failedUrl, failedFile, failedModelId),
status: ModelDownloadStatus.error,
detail: l10n.translation_downloadFailed(serviceFailedError),
onDownload: service.isBusy
? null
: () => _download(
sourceUrl: failedUrl,
fileName: failedFile,
id: failedModelId,
),
),
);
}
return items;
}
/// True when this row is the file [service] is fetching, including while
/// its displayed filename is the merge status.
bool _fileNamesThisDownload(
TranslationService service,
String? fileName,
String? installedName,
) {
bool matches(String? candidate) {
if (candidate == null || candidate.isEmpty) return false;
if (candidate == _mergingChunksFileName) return false;
return candidate == fileName || candidate == installedName;
}
return matches(service.downloadFileName) ||
matches(service.downloadTargetFileName);
}
/// Row for a download whose page state was discarded, or that has no
/// preset or installed row yet. The service keeps the URL and file name.
ModelDownloadItem _inProgressItem(
AppLocalizations l10n,
TranslationService service,
) {
final sourceUrl = service.downloadSourceUrl ?? '';
final rawName = service.downloadTargetFileName ?? service.downloadFileName;
final fileName = rawName == _mergingChunksFileName ? null : rawName;
final modelId = service.downloadModelId;
final id = (modelId != null && modelId.isNotEmpty)
? modelId
: sourceUrl.isNotEmpty
? sourceUrl
: (fileName ?? 'download');
final merging = _isMerging(service);
return ModelDownloadItem(
id: id,
name: _displayName(sourceUrl, fileName, modelId),
status: ModelDownloadStatus.downloading,
detail: merging ? l10n.translation_mergingChunks : null,
progress: merging ? null : service.downloadProgress,
downloadedBytes: service.downloadedBytes,
totalBytes: service.downloadTotalBytes,
onCancel: service.cancelDownload,
);
}
bool _isMerging(TranslationService service) =>
service.downloadFileName == _mergingChunksFileName;
Future<void> _download({
required String sourceUrl,
String? fileName,
String? id,
}) async {
final trimmed = sourceUrl.trim();
if (trimmed.isEmpty) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_enterUrlFirst),
);
return;
}
final pending = _PendingDownload(
id: id ?? trimmed,
name: _displayName(trimmed, fileName, id),
sourceUrl: trimmed,
fileName: fileName,
modelId: id,
);
setState(() {
_pending = pending;
_failedId = null;
_failedDetail = null;
});
final settingsService = context.read<AppSettingsService>();
final translationService = context.read<TranslationService>();
try {
await translationService.downloadModel(
sourceUrl: trimmed,
fileName: fileName,
id: id,
);
if (!mounted) return;
setState(() {
_pending = null;
_failedId = null;
_failedDetail = null;
});
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_modelDownloaded),
);
await settingsService.setTranslationEnabled(true);
} on TranslationDownloadCancelled {
if (!mounted) return;
setState(() {
_pending = null;
_failedId = null;
_failedDetail = null;
});
showDismissibleSnackBar(
context,
content: Text(context.l10n.translation_downloadStopped),
);
} catch (error) {
if (!mounted) return;
final message = context.l10n.translation_downloadFailed('$error');
setState(() {
_failedId = pending.id;
_failedDetail = message;
});
showDismissibleSnackBar(context, content: Text(message));
}
}
Future<void> _delete(
TranslationService translationService,
TranslationModelRecord model,
) async {
try {
await translationService.removeModel(model);
if (!context.mounted) return;
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(
@@ -411,7 +561,7 @@ class TranslationSettingsSection extends StatelessWidget {
),
);
} catch (error) {
if (!context.mounted) return;
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(
@@ -421,17 +571,36 @@ class TranslationSettingsSection extends StatelessWidget {
}
}
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,
String _displayName(String sourceUrl, String? fileName, String? id) {
for (final preset in translationPresetModels) {
if (preset.id == id || preset.sourceUrl == sourceUrl) {
return translationModelFriendlyName(preset);
}
}
final name = (fileName != null && fileName.isNotEmpty)
? fileName
: _fileNameFromUrl(sourceUrl);
return translationModelFriendlyName(
TranslationModelRecord(
id: id ?? name,
name: name,
sourceUrl: sourceUrl,
localPath: '',
downloadedAt: DateTime.fromMillisecondsSinceEpoch(0),
fileSizeBytes: 0,
),
);
}
String _fileNameFromUrl(String sourceUrl) {
final uri = Uri.tryParse(sourceUrl);
if (uri == null || uri.pathSegments.isEmpty) {
return context.l10n.translation_defaultModelName;
}
final last = uri.pathSegments.last.trim();
if (last.isEmpty) return context.l10n.translation_defaultModelName;
return last;
}
}
/// Owns the [TextEditingController] for the manual model URL field so it
@@ -441,21 +610,15 @@ class _TranslationUrlField extends StatefulWidget {
required this.initialValue,
required this.onChanged,
required this.onDownload,
required this.downloadLabel,
required this.isDownloading,
required this.onCancel,
required this.labelText,
required this.stopLabel,
required this.downloadTooltip,
});
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;
final String downloadTooltip;
@override
State<_TranslationUrlField> createState() => _TranslationUrlFieldState();
@@ -478,39 +641,26 @@ class _TranslationUrlFieldState extends State<_TranslationUrlField> {
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: widget.labelText,
border: const OutlineInputBorder(),
),
onChanged: widget.onChanged,
return TextField(
controller: _controller,
keyboardType: TextInputType.url,
autocorrect: false,
enableSuggestions: false,
decoration: InputDecoration(
labelText: widget.labelText,
border: const OutlineInputBorder(),
suffixIcon: IconButton(
tooltip: widget.downloadTooltip,
onPressed: widget.onDownload == null
? null
: () => widget.onDownload!(_controller.text.trim()),
icon: const Icon(Icons.download_outlined),
),
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),
),
],
],
),
],
),
onChanged: widget.onChanged,
onSubmitted: widget.onDownload == null
? null
: (value) => widget.onDownload!(value.trim()),
);
}
}