Use one model row for image and translation downloads

Image settings, translation settings, and the restore prompt each listed models differently. Share ModelDownloadList so every model shows the same name, size, status, selection, and download, cancel, or remove action.

Co-authored-by: zjs81 <zjs81@users.noreply.github.com>
This commit is contained in:
Cursor Agentandzjs81 committed 2026-11-21 00:05:39 +00:00
1 parent 34ea0cb7ca
commit 9ffdbaae09
50 files changed
+2524 -833

No files matched your search

+297
View File
@@ -0,0 +1,297 @@
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.surfaceContainerHighest,
borderRadius: BorderRadius.circular(MeshRadii.md),
),
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;
}
+338
View File
@@ -0,0 +1,338 @@
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.fromLTRB(16, 8, 16, 8)
: const EdgeInsets.fromLTRB(16, 8, 0, 8)),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 2),
child: _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.download_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,
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,
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,
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,
);
}
}
+366 -322
View File
@@ -2,12 +2,14 @@ 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';
/// [TranslationService] publishes this as `downloadFileName` while it merges
/// downloaded chunks (see translation_service.dart). The service owns the
@@ -15,24 +17,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);
@@ -96,201 +95,11 @@ class TranslationSettingsSection extends StatelessWidget {
onTap: () => _showTranslationLanguageDialog(context, settingsService),
),
const Divider(height: 1, indent: 16),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: DropdownButtonFormField<String>(
initialValue: settings.translationSelectedModelId,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.translation_downloadedModelLabel,
border: const OutlineInputBorder(),
),
items: [
for (final model in settings.translationDownloadedModels)
DropdownMenuItem(
value: model.id,
child: Text(
translationModelFriendlyName(model),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: settings.translationDownloadedModels.isEmpty
? null
: (value) {
settingsService.setTranslationSelectedModelId(value);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: DropdownButtonFormField<String>(
initialValue: null,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.translation_presetModelLabel,
border: const OutlineInputBorder(),
),
items: [
for (final preset in translationPresetModels)
DropdownMenuItem(
value: preset.sourceUrl,
child: Text(
translationModelFriendlyName(preset),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: translationService.isBusy
? null
: (value) async {
if (value == null) return;
final preset = translationPresetModels.firstWhere(
(entry) => entry.sourceUrl == value,
);
await _downloadTranslationModel(
context,
translationService,
settingsService,
sourceUrl: preset.sourceUrl,
fileName: preset.name,
id: preset.id,
);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_TranslationUrlField(
initialValue: settings.translationModelSourceUrl ?? '',
onChanged: settingsService.setTranslationModelSourceUrl,
onDownload: translationService.isBusy
? null
: (url) => _downloadTranslationModel(
context,
translationService,
settingsService,
sourceUrl: url,
),
downloadLabel: translationService.isDownloading
? l10n.translation_downloading
: translationService.isBusy
? l10n.translation_working
: l10n.translation_downloadModel,
isDownloading: translationService.isDownloading,
onCancel: translationService.cancelDownload,
labelText: l10n.translation_manualUrlLabel,
stopLabel: l10n.translation_stop,
),
if (translationService.isDownloading) ...[
const SizedBox(height: 12),
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: _isMerging(translationService)
? null
: translationService.downloadProgress,
),
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: Text(
_downloadProgressLabel(context, translationService),
style: MeshTheme.mono(
fontSize: 14,
color: scheme.onSurfaceVariant,
),
),
),
],
if (settings.translationDownloadedModels.isNotEmpty) ...[
const SizedBox(height: 16),
Align(
alignment: Alignment.centerLeft,
child: Text(
l10n.translation_downloadedModels,
style: textTheme.titleSmall,
),
),
const SizedBox(height: 8),
for (final model in settings.translationDownloadedModels)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Icon(
model.id == settings.translationSelectedModelId
? Icons.check_circle
: Icons.memory_outlined,
size: 24,
color: model.id == settings.translationSelectedModelId
? scheme.primary
: scheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: InkWell(
borderRadius: BorderRadius.circular(MeshRadii.xs),
onTap: () => settingsService
.setTranslationSelectedModelId(model.id),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
translationModelFriendlyName(model),
style: textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
Text(
_downloadedModelLabel(context, model),
style: MeshTheme.mono(
fontSize: 12,
color: scheme.onSurfaceVariant,
),
),
],
),
),
),
IconButton(
tooltip: l10n.translation_deleteModel,
onPressed: translationService.isBusy
? null
: () => _deleteTranslationModel(
context,
translationService,
model,
),
icon: const Icon(Icons.delete_outline),
),
],
),
),
],
if (translationService.lastError != null) ...[
const SizedBox(height: 8),
Text(
translationService.lastError!,
style: TextStyle(color: scheme.error),
),
],
],
),
),
const _TranslationModels(),
],
);
}
static bool _isMerging(TranslationService service) =>
service.downloadFileName == _mergingChunksFileName;
void _showTranslationLanguageDialog(
BuildContext context,
AppSettingsService settingsService,
@@ -308,50 +117,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 +128,324 @@ 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 != _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;
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;
}
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 currentFile = service.downloadFileName;
final fileMatches =
currentFile != null &&
currentFile != _mergingChunksFileName &&
(currentFile == fileName || currentFile == installed?.name);
final downloading =
service.isDownloading &&
(targets(id, sourceUrl, name) || fileMatches);
final failed = !downloading && _failedId == id;
if (downloading || failed) pendingShown = true;
final merging = downloading && _isMerging(service);
final busy = service.isBusy;
final installedModel = installed;
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
? _failedDetail
: 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 (pending != null &&
!pendingShown &&
(service.isDownloading || _failedId == pending.id)) {
final downloading = service.isDownloading;
final merging = downloading && _isMerging(service);
items.add(
ModelDownloadItem(
id: pending.id,
name: pending.name,
status: downloading
? ModelDownloadStatus.downloading
: ModelDownloadStatus.error,
detail: merging
? l10n.translation_mergingChunks
: downloading
? null
: _failedDetail,
progress: downloading && !merging ? service.downloadProgress : null,
downloadedBytes: downloading ? service.downloadedBytes : 0,
totalBytes: downloading ? service.downloadTotalBytes : null,
onCancel: downloading ? service.cancelDownload : null,
onDownload: !service.isBusy && !downloading
? () => _download(
sourceUrl: pending.sourceUrl,
fileName: pending.fileName,
id: pending.modelId,
)
: null,
),
);
}
return items;
}
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 +455,7 @@ class TranslationSettingsSection extends StatelessWidget {
),
);
} catch (error) {
if (!context.mounted) return;
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(
@@ -421,17 +465,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 +504,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 +535,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()),
);
}
}