Merge origin/dev into cursor/routing-send-settings-ef15

This commit is contained in:
zjs81 committed 2026-11-21 08:33:50 -07:00
commit 4065d60a16
84 files changed
+7843 -1144

No files matched your search

+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;
}
+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),
),
);
}
}
+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,
],
);
},
);
}
}
+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,
+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: 16),
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()),
);
}
}