feat(download): auto-categorize downloads into folders by file extension (#1572)

This commit is contained in:
WuFeng authored and GitHub committed 2026-10-23 20:38:25 +08:00
1 parent d125d4ab75
commit 9aae13453a
55 files changed
+4403 -217

No files matched your search

@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path/path.dart' as path;
import 'package:go_router/go_router.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import 'package:url_launcher/url_launcher.dart';
@@ -88,6 +89,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
DownloaderConfig? _config;
StartConfig? _startConfig;
String? _loadedSignature;
String? _appliedDownloadDir;
String? _loadedStartSignature;
Timer? _textSaveTimer;
bool _syncingControllers = false;
@@ -470,13 +472,21 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
SettingsItem(
title: context.l10n.downloadCategories,
child: DownloadCategoriesControl(
categories: config.extra.downloadCategories,
categories: config.categories,
displayName: _categoryName,
onAdd: () => unawaited(_editDownloadCategory()),
onEdit: (category) => unawaited(_editDownloadCategory(category)),
onDelete: (category) => unawaited(_deleteDownloadCategory(category)),
),
),
SettingsItem(
title: context.l10n.autoCategorizeByExtension,
subtitle: context.l10n.autoCategorizeByExtensionDescription,
child: shad.Switch(
value: config.autoCategorize,
onChanged: (value) => _mutateConfig((next) => next.autoCategorize = value),
),
),
SettingsItem(
title: context.l10n.maxRunning,
subtitle: context.l10n.maxRunningDescription,
@@ -996,6 +1006,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_config = DownloaderConfig.fromJson(config.toJson());
_syncingControllers = true;
_downloadDirController.text = _config!.downloadDir;
_appliedDownloadDir = _config!.downloadDir;
_maxRunningController.text = _config!.maxRunning.clamp(1, 256).toString();
_httpUserAgentController.text = _config!.protocolConfig.http.userAgent;
_httpConnectionsController.text = _config!.protocolConfig.http.connections.clamp(1, 256).toString();
@@ -1087,7 +1098,13 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
}
void _applyTextControllers(DownloaderConfig config) {
config.downloadDir = _downloadDirController.text.trim();
final downloadDir = _downloadDirController.text.trim();
final previousDownloadDir = _appliedDownloadDir;
_appliedDownloadDir = downloadDir;
if (previousDownloadDir != null && !path.equals(previousDownloadDir, downloadDir)) {
rebaseBuiltinCategoryPaths(config, oldDir: previousDownloadDir, newDir: downloadDir);
}
config.downloadDir = downloadDir;
config.maxRunning = _boundedInt(_maxRunningController, fallback: config.maxRunning, min: 1, max: 256);
config.protocolConfig.http.userAgent = _httpUserAgentController.text.trim();
config.protocolConfig.http.connections = _boundedInt(
@@ -1357,13 +1374,15 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
category: category,
initialName: category == null ? '' : _categoryName(category),
initialPath: _downloadDirController.text.trim(),
categories: _config?.categories ?? const [],
displayName: _categoryName,
);
if (draft == null || !mounted) return;
_mutateConfig((config) {
final categories = List<DownloadCategory>.from(config.extra.downloadCategories);
final categories = List<DownloadCategory>.from(config.categories);
if (category == null) {
categories.add(DownloadCategory(name: draft.name, path: draft.path));
categories.add(DownloadCategory(name: draft.name, path: draft.path, extensions: draft.extensions));
} else {
final index = categories.indexOf(category);
if (index < 0) return;
@@ -1371,10 +1390,11 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
category
..name = draft.name
..path = draft.path
..extensions = draft.extensions
..isDeleted = false;
if (nameChanged) category.nameKey = null;
}
config.extra.downloadCategories = categories;
config.categories = categories;
});
}
@@ -1386,7 +1406,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
category.isDeleted = true;
return;
}
config.extra.downloadCategories = List<DownloadCategory>.from(config.extra.downloadCategories)..remove(category);
config.categories = List<DownloadCategory>.from(config.categories)..remove(category);
});
}
@@ -11,12 +11,14 @@ import '../../../../shared/widgets/app_path_placeholder_button.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../l10n/l10n.dart';
import 'extension_tag_editor.dart';
class DownloadCategoryDraft {
const DownloadCategoryDraft({required this.name, required this.path});
const DownloadCategoryDraft({required this.name, required this.path, required this.extensions});
final String name;
final String path;
final List<String> extensions;
}
class DownloadCategoriesControl extends StatelessWidget {
@@ -93,6 +95,7 @@ class _CategoryRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final extensions = category.effectiveExtensions();
return Row(
key: ValueKey('download-category-${category.nameKey ?? category.name}-${category.path}'),
children: [
@@ -111,6 +114,16 @@ class _CategoryRow extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 12),
),
if (extensions.isNotEmpty) ...[
const SizedBox(height: 3),
Text(
extensions.join(', '),
key: const ValueKey('download-category-extensions'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 11),
),
],
],
),
),
@@ -137,9 +150,29 @@ Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
DownloadCategory? category,
required String initialName,
required String initialPath,
required List<DownloadCategory> categories,
required String Function(DownloadCategory) displayName,
}) async {
final nameController = TextEditingController(text: initialName);
final pathController = TextEditingController(text: category?.path ?? initialPath);
final editorKey = GlobalKey<ExtensionTagEditorState>();
final nameKey = category?.nameKey;
final restoreDefaults = nameKey == null
? const <String>[]
: normalizeCategoryExtensions(kDefaultCategoryExtensions[nameKey] ?? const []);
// Extensions every other live category already owns, mapped to its
// display name; the edited category itself is exempt.
final takenExtensions = <String, String>{};
for (final other in categories) {
if (other.isDeleted || identical(other, category)) continue;
for (final extension in normalizeCategoryExtensions(other.effectiveExtensions())) {
takenExtensions.putIfAbsent(extension, () => displayName(other));
}
}
var extensionConflict = normalizeCategoryExtensions(
category?.effectiveExtensions() ?? const [],
).any(takenExtensions.containsKey);
String? validationMessage;
final overlay = const shad.DialogOverlayHandler().show<DownloadCategoryDraft?>(
@@ -150,14 +183,23 @@ Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
void reportExtensionConflict(bool value) {
if (extensionConflict == value) return;
setDialogState(() => extensionConflict = value);
}
void submit() {
if (extensionConflict) return;
final name = nameController.text.trim();
final path = pathController.text.trim();
if (name.isEmpty || path.isEmpty) {
setDialogState(() => validationMessage = dialogContext.l10n.categoryFieldsRequired);
return;
}
shad.closeOverlay(dialogContext, DownloadCategoryDraft(name: name, path: path));
shad.closeOverlay(
dialogContext,
DownloadCategoryDraft(name: name, path: path, extensions: editorKey.currentState?.flush() ?? const []),
);
}
return shad.AlertDialog(
@@ -165,35 +207,49 @@ Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
content: SizedBox(
key: const ValueKey('download-category-dialog'),
width: (MediaQuery.sizeOf(dialogContext).width - 64).clamp(260.0, 420.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.categoryName, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
AppTextField(key: const ValueKey('download-category-name'), controller: nameController),
const SizedBox(height: 14),
Text(dialogContext.l10n.categoryPath, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
AppPathPickerField.downloadDirectory(
fieldKey: const ValueKey('download-category-path'),
controller: pathController,
desktopWidth: AppDesignTokens.settingsFormControlWidth,
allowAndroidEditing: true,
),
const SizedBox(height: AppDesignTokens.space4),
Align(
alignment: AlignmentDirectional.centerStart,
child: AppPathPlaceholderButton(
key: const ValueKey('download-category-placeholders'),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.categoryName, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
AppTextField(key: const ValueKey('download-category-name'), controller: nameController),
const SizedBox(height: 14),
Text(dialogContext.l10n.categoryPath, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
AppPathPickerField.downloadDirectory(
fieldKey: const ValueKey('download-category-path'),
controller: pathController,
desktopWidth: AppDesignTokens.settingsFormControlWidth,
allowAndroidEditing: true,
),
),
if (validationMessage != null) ...[
const SizedBox(height: 8),
Text(validationMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
const SizedBox(height: AppDesignTokens.space4),
Align(
alignment: AlignmentDirectional.centerStart,
child: AppPathPlaceholderButton(
key: const ValueKey('download-category-placeholders'),
controller: pathController,
),
),
const SizedBox(height: 14),
ExtensionTagEditor(
key: editorKey,
inputKey: const ValueKey('download-category-extensions-input'),
initialTags: category?.effectiveExtensions() ?? const [],
labelText: dialogContext.l10n.categoryExtensions,
placeholderText: dialogContext.l10n.categoryExtensionsEmptyHint,
usagePlaceholderText: dialogContext.l10n.categoryExtensionsUsageHint,
restoreDefaults: restoreDefaults,
takenByCategory: takenExtensions,
onConflictChanged: reportExtensionConflict,
),
if (validationMessage != null) ...[
const SizedBox(height: 8),
Text(validationMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
],
],
],
),
),
),
actions: [
@@ -201,7 +257,7 @@ Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
onPressed: () => shad.closeOverlay(dialogContext),
child: Text(dialogContext.l10n.cancel),
),
AppPrimaryButton(onPressed: submit, child: Text(dialogContext.l10n.save)),
AppPrimaryButton(onPressed: extensionConflict ? null : submit, child: Text(dialogContext.l10n.save)),
],
);
},
@@ -0,0 +1,274 @@
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../api/model/downloader_config.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_text_field.dart';
/// Tag style editor for file extension lists.
///
/// Typed text stays in the input until the submit action (Enter) commits it;
/// commas and whitespace split the committed text into several tags, so
/// `a b,c` becomes `a`, `b` and `c`. Every token goes through
/// [normalizeCategoryExtensions], so the tags are trimmed, lowercased, dot
/// free and deduplicated while keeping the input order. While typing, chips
/// whose tag matches the pending input are highlighted to surface
/// duplicates before they are committed. When the editor is empty and
/// [restoreDefaults] is provided, an outline restore action sits at the end
/// of the [labelText] row and refills the tags. [takenByCategory] lists
/// extensions already claimed by another category: those tokens are never
/// committed, their chips render with the error border, and the editor
/// reports the conflict through [onConflictChanged] so the host can block
/// submission while one is pending.
class ExtensionTagEditor extends StatefulWidget {
const ExtensionTagEditor({
super.key,
this.inputKey,
required this.initialTags,
this.labelText,
this.placeholderText,
this.usagePlaceholderText,
this.restoreDefaults,
this.takenByCategory,
this.onConflictChanged,
});
/// Key attached to the underlying text field so tests can target it.
final Key? inputKey;
final List<String> initialTags;
/// Field label rendered at the top of the editor with the restore action
/// aligned to its end. Null renders no label row unless the restore action
/// itself is visible.
final String? labelText;
/// Shown inside the text field while there is neither a tag nor typed text.
final String? placeholderText;
/// Shown inside the text field while there is no typed text but at least
/// one tag, carrying the usage rules once the empty-state text no longer
/// applies.
final String? usagePlaceholderText;
/// Default extensions offered by the restore action while the editor is
/// empty. Null or empty hides the action (e.g. custom categories).
final List<String>? restoreDefaults;
/// Normalized extensions already owned by another category, mapped to
/// that category's display name. Tokens in this map are rejected with an
/// inline error naming the owner instead of being added to the tags.
final Map<String, String>? takenByCategory;
/// Reports whether the editor currently holds an extension claimed by
/// another category so the host can disable its submit action.
final ValueChanged<bool>? onConflictChanged;
@override
State<ExtensionTagEditor> createState() => ExtensionTagEditorState();
}
class ExtensionTagEditorState extends State<ExtensionTagEditor> {
late final List<String> _tags;
late final TextEditingController _controller;
late bool _lastConflictNotified;
@override
void initState() {
super.initState();
_tags = normalizeCategoryExtensions(widget.initialTags);
_controller = TextEditingController();
// The host seeds its own initial state from the same data, so only
// subsequent changes need to be reported.
_lastConflictNotified = _firstTakenConflict() != null;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
/// Commits any pending input text to the tags and returns the full list.
/// Extensions claimed by [takenByCategory] are left out.
List<String> flush() {
_update(_commitPending);
final taken = widget.takenByCategory;
return List<String>.unmodifiable(taken == null ? _tags : _tags.where((tag) => !taken.containsKey(tag)));
}
void _update(VoidCallback fn) {
setState(fn);
final conflicted = _firstTakenConflict() != null;
if (conflicted != _lastConflictNotified) {
_lastConflictNotified = conflicted;
widget.onConflictChanged?.call(conflicted);
}
}
void _commitPending() {
final rejected = normalizeCategoryExtensions([
_controller.text,
]).where((token) => widget.takenByCategory?.containsKey(token) ?? false).toList(growable: false);
_addTokens(_controller.text);
if (rejected.isEmpty) {
_controller.clear();
} else {
// Keep the rejected tokens in the input so the error stays visible
// until the user edits them away.
_controller.text = rejected.join(' ');
_controller.selection = TextSelection.collapsed(offset: _controller.text.length);
}
}
void _addTokens(String raw) {
for (final token in normalizeCategoryExtensions([raw])) {
if (_tags.contains(token)) continue;
if (widget.takenByCategory?.containsKey(token) ?? false) continue;
_tags.add(token);
}
}
String? _firstTakenConflict() {
final taken = widget.takenByCategory;
if (taken == null || taken.isEmpty) return null;
for (final token in normalizeCategoryExtensions([_controller.text])) {
if (taken.containsKey(token)) return token;
}
for (final tag in _tags) {
if (taken.containsKey(tag)) return tag;
}
return null;
}
void _handleChanged(String value) {
// Keep the placeholder and the duplicate highlight in sync while typing;
// nothing is committed until the submit action.
_update(() {});
}
void _handleSubmitted(String value) {
_update(_commitPending);
}
void _removeTag(String tag) {
_update(() => _tags.remove(tag));
}
void _restoreDefaults() {
_update(() {
_tags
..clear()
..addAll(normalizeCategoryExtensions(widget.restoreDefaults ?? const []));
});
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final showPlaceholder = widget.placeholderText != null && _tags.isEmpty && _controller.text.isEmpty;
final showRestore = showPlaceholder && (widget.restoreDefaults?.isNotEmpty ?? false);
String? placeholder;
if (_controller.text.isEmpty) {
if (showPlaceholder) {
placeholder = widget.placeholderText;
} else if (_tags.isNotEmpty && widget.usagePlaceholderText != null) {
placeholder = widget.usagePlaceholderText;
}
}
final pendingDuplicates = normalizeCategoryExtensions([_controller.text]).toSet();
final conflict = _firstTakenConflict();
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.labelText != null || showRestore) ...[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (widget.labelText != null)
Text(widget.labelText!, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
if (showRestore) _buildRestoreButton(palette),
],
),
const SizedBox(height: 6),
],
if (_tags.isNotEmpty) ...[
Wrap(
spacing: AppDesignTokens.space4,
runSpacing: AppDesignTokens.space4,
children: [
for (final tag in _tags)
_buildChip(
palette,
tag,
duplicate: pendingDuplicates.contains(tag) || (widget.takenByCategory?.containsKey(tag) ?? false),
),
],
),
const SizedBox(height: 6),
],
AppTextField(
key: widget.inputKey,
controller: _controller,
placeholder: placeholder != null
? Text(placeholder, style: TextStyle(fontSize: 12, color: palette.textMuted))
: null,
onChanged: _handleChanged,
onSubmitted: _handleSubmitted,
),
if (conflict != null) ...[
const SizedBox(height: 6),
Text(
context.l10n.categoryExtensionTaken(conflict, widget.takenByCategory![conflict]!),
style: TextStyle(color: palette.error, fontSize: 12),
),
],
],
);
}
Widget _buildRestoreButton(AppPalette palette) {
return shad.OutlineButton(
key: const ValueKey('extension-restore-defaults'),
onPressed: _restoreDefaults,
size: shad.ButtonSize.small,
density: shad.ButtonDensity.compact,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.restart_alt, size: 14, color: palette.brand),
const SizedBox(width: 4),
Text(context.l10n.categoryExtensionsRestoreDefaults, style: TextStyle(fontSize: 12, color: palette.brand)),
],
),
);
}
Widget _buildChip(AppPalette palette, String tag, {required bool duplicate}) {
return Container(
key: ValueKey('extension-chip-$tag'),
padding: const EdgeInsets.only(left: 8, right: 1),
decoration: BoxDecoration(
border: Border.all(color: duplicate ? palette.error : palette.border),
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(tag, style: TextStyle(fontSize: 11, color: palette.textPrimary)),
const SizedBox(width: 2),
GestureDetector(
key: ValueKey('extension-chip-remove-$tag'),
onTap: () => _removeTag(tag),
behavior: HitTestBehavior.opaque,
child: SizedBox(width: 32, height: 32, child: Icon(Icons.close, size: 13, color: palette.textSecondary)),
),
],
),
);
}
}
@@ -92,6 +92,27 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
bool _draggingTorrent = false;
bool _asDefaultPath = false;
String _configuredDownloadDirectory = '';
/// Index into `_downloadCategories` as filtered by `_loadDefaults`
/// (`!isDeleted`), not into the raw config list; null when the directory
/// falls outside every category. Cached, so it can lag the field while the
/// debounce is pending — `onShortcutSelected` reads exactly this value.
int? _activeCategoryIndex;
Timer? _categoryHighlightTimer;
/// Whether the user picked a directory in this dialog. The backend routes a
/// task to its category directory only when this stays false, so the flag is
/// tracked on its own instead of comparing the field with the default dir.
bool _directoryManuallySet = false;
/// Guards the controller listener while the page fills the field itself.
bool _programmaticDirectoryWrite = false;
/// The text of the directory field the page knows about. The controller also
/// reports selection changes, e.g. when the caret moves, so the listener
/// compares the text to tell a user edit from a caret move.
String _lastDirectoryText = '';
String _fileDataUri = '';
bool _programmaticUrlChange = false;
String _lastUrlText = '';
@@ -100,6 +121,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
void initState() {
super.initState();
_urlController.addListener(_handleUrlChanged);
_directoryController.addListener(_handleDirectoryChanged);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final task = widget.initialTask ?? ref.read(pendingCreateTaskProvider);
@@ -127,9 +149,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
void dispose() {
_urlController.removeListener(_handleUrlChanged);
_urlController.dispose();
_directoryController.removeListener(_handleDirectoryChanged);
_categoryHighlightTimer?.cancel();
_categoryHighlightTimer = null;
_renameController.dispose();
_connectionsController.dispose();
_directoryController.dispose();
_connectionsController.dispose();
_proxyServerController.dispose();
_proxyPortController.dispose();
_proxyUsernameController.dispose();
@@ -200,7 +225,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
void _applyInitialTask(CreateTask? task) {
if (task == null || !mounted) return;
final req = task.req;
final opts = task.opts;
final opts = task.opts ?? api_options.Options();
setState(() {
_initialSize = 0;
_checksumAlgorithm = 'md5';
@@ -241,30 +266,35 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
break;
}
}
if (opts != null) {
_initialSize = opts.size;
if (opts.path.isNotEmpty) {
_directoryController.text = opts.path;
// Filling the field is not a manual choice, the caller decides whether
// the task keeps its directory.
_directoryManuallySet = opts.skipAutoCategorize;
_asDefaultPath = opts.skipAutoCategorize && opts.asDefaultPath;
_programmaticDirectoryWrite = true;
// A task without a directory uses the configured one, the field must
// not keep the directory of the previous task.
_directoryController.text = opts.path.isNotEmpty ? opts.path : _configuredDownloadDirectory;
_programmaticDirectoryWrite = false;
_initialSize = opts.size;
if (opts.extra is Map) {
final extra = api_options.OptsExtraHttp.fromJson(Map<String, dynamic>.from(opts.extra! as Map));
if (extra.connections > 0) {
_connectionsController.text = extra.connections.toString();
}
if (opts.extra is Map) {
final extra = api_options.OptsExtraHttp.fromJson(Map<String, dynamic>.from(opts.extra! as Map));
if (extra.connections > 0) {
_connectionsController.text = extra.connections.toString();
}
_autoTorrent = extra.autoTorrent;
_deleteTorrentAfterDownload = extra.deleteTorrentAfterDownload;
_autoExtract = extra.autoExtract;
_archivePasswordController.text = extra.archivePassword;
_deleteAfterExtract = extra.deleteAfterExtract;
if (extra.checksum != null) {
if (extra.checksum!.algorithm.isNotEmpty) {
_checksumAlgorithm = extra.checksum!.algorithm;
}
_checksumHashController.text = extra.checksum!.expected;
_autoTorrent = extra.autoTorrent;
_deleteTorrentAfterDownload = extra.deleteTorrentAfterDownload;
_autoExtract = extra.autoExtract;
_archivePasswordController.text = extra.archivePassword;
_deleteAfterExtract = extra.deleteAfterExtract;
if (extra.checksum != null) {
if (extra.checksum!.algorithm.isNotEmpty) {
_checksumAlgorithm = extra.checksum!.algorithm;
}
_checksumHashController.text = extra.checksum!.expected;
}
}
});
_applyCategoryHighlightNow();
}
void _applyInitialProxy(RequestProxy? proxy) {
@@ -429,15 +459,21 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
setState(() => _asDefaultPath = false);
}
},
onDirectoryPicked: (pickedDirectory) => setState(
() => _asDefaultPath = !_sameDirectory(pickedDirectory, _configuredDownloadDirectory),
),
onDirectoryPicked: (pickedDirectory) {
setState(() {
_directoryManuallySet = true;
_asDefaultPath = !_sameDirectory(pickedDirectory, _configuredDownloadDirectory);
});
_applyCategoryHighlightNow();
},
),
const SizedBox(height: 8),
_DirectoryOptions(
key: const ValueKey('create-task-directory-options-row'),
stacked: stacked,
asDefaultPath: _asDefaultPath,
canSetAsDefaultPath: _directoryManuallySet,
activeIndex: _activeCategoryIndex,
onAsDefaultPathChanged: (value) => setState(() => _asDefaultPath = value),
shortcuts: [
for (final entry in _downloadCategories.indexed)
@@ -448,16 +484,22 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
),
],
onShortcutSelected: (shortcut) {
_directoryController.text = shortcut.path;
if (_asDefaultPath) {
setState(() => _asDefaultPath = false);
}
// Tapping the active shortcut again clears the selection and
// restores the saved default directory. Either tap is an
// explicit directory choice, so the task skips auto classify.
final turnOn = _activeCategoryIndex != shortcut.index;
setState(() {
_directoryManuallySet = true;
_asDefaultPath = false;
});
_directoryController.text = turnOn ? shortcut.path : _configuredDownloadDirectory;
_applyCategoryHighlightNow();
},
),
],
),
),
const SizedBox(height: 14),
const SizedBox(height: 8),
AppFormRow(
direction: stacked ? Axis.vertical : Axis.horizontal,
label: context.l10n.directDownload,
@@ -808,7 +850,9 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_configuredDownloadDirectory = config.downloadDir.trim();
if (config.downloadDir.isNotEmpty &&
(_directoryController.text.isEmpty || _directoryController.text == 'C:/Users/levi/Downloads')) {
_programmaticDirectoryWrite = true;
_directoryController.text = config.downloadDir;
_programmaticDirectoryWrite = false;
}
if (_asDefaultPath && _sameDirectory(_directoryController.text, _configuredDownloadDirectory)) {
_asDefaultPath = false;
@@ -818,10 +862,9 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
_connectionsController.text = connections.toString();
}
_directDownload = config.extra.defaultDirectDownload;
_downloadCategories = config.extra.downloadCategories
.where((category) => !category.isDeleted)
.toList(growable: false);
_downloadCategories = config.categories.where((category) => !category.isDeleted).toList(growable: false);
});
_applyCategoryHighlightNow();
} catch (_) {
// Keep local defaults when the backend is not available yet.
}
@@ -1087,7 +1130,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
return text.length == 40 && RegExp(r'^[0-9a-fA-F]+$').hasMatch(text);
}
api_options.Options _buildOptions({String? name, List<int> selectFiles = const [], bool omitChecksum = false}) {
api_options.Options _buildOptions({
String? name,
List<int> selectFiles = const [],
bool omitChecksum = false,
bool? skipAutoCategorize,
}) {
final urls = _inputUrls();
final connections = int.tryParse(_connectionsController.text.trim()) ?? 0;
final checksumExpected = _checksumHashController.text.trim();
@@ -1099,6 +1147,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
name: name ?? _renameController.text.trim(),
path: _directoryController.text.trim(),
asDefaultPath: _asDefaultPath,
skipAutoCategorize: skipAutoCategorize ?? _directoryManuallySet,
selectFiles: selectFiles,
extra: api_options.OptsExtraHttp(
connections: connections,
@@ -1119,6 +1168,60 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
return path.equals(path.normalize(normalizedLeft), path.normalize(normalizedRight));
}
/// Index of the category whose path matches [value], or null. Category paths
/// are resolved through `_renderPathPlaceholders` before comparing, while
/// [value] is taken verbatim, so a `%year%` pattern only matches once the
/// directory field already holds the rendered path.
int? _categoryIndexFor(String value) {
final target = value.trim();
if (target.isEmpty) return null;
for (final entry in _downloadCategories.indexed) {
if (_sameDirectory(_renderPathPlaceholders(entry.$2.path), target)) return entry.$1;
}
return null;
}
void _applyCategoryHighlight() {
final next = _categoryIndexFor(_directoryController.text);
if (next == _activeCategoryIndex) return;
setState(() => _activeCategoryIndex = next);
}
/// Debounced variant for paths typed into the directory field, so the
/// highlight does not flicker while the path is still incomplete.
/// A text change the user typed is an explicit directory choice; one the
/// page writes itself (initial fill, incoming task) is not. The controller
/// also notifies on selection changes, e.g. when the caret moves, so only a
/// changed text counts as a manual choice.
void _handleDirectoryChanged() {
final text = _directoryController.text;
if (text == _lastDirectoryText) {
return;
}
_lastDirectoryText = text;
if (!_programmaticDirectoryWrite && !_directoryManuallySet) {
setState(() => _directoryManuallySet = true);
}
_scheduleCategoryHighlight();
}
void _scheduleCategoryHighlight() {
_categoryHighlightTimer?.cancel();
_categoryHighlightTimer = Timer(_categoryHighlightDebounce, () {
if (!mounted) return;
_applyCategoryHighlight();
});
}
/// Immediate variant for shortcut clicks and programmatic writes, which
/// cancels a pending debounce instead of waiting for it.
void _applyCategoryHighlightNow() {
_categoryHighlightTimer?.cancel();
_categoryHighlightTimer = null;
if (!mounted) return;
_applyCategoryHighlight();
}
Future<void> _submitResolved(Request request, ResolveResult result, List<int> selectedIndexes) async {
final selected = (selectedIndexes.isEmpty ? result.res.files.asMap().keys.toList() : selectedIndexes.toList())
..sort();
@@ -1136,6 +1239,11 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
if (result.res.files.isNotEmpty) {
// The extension returned a file list, so the resource keeps a directory
// structure. The split tasks must not be classified into a category, the
// structure of the resolved resource is kept. The decision is based on
// the resolved resource, not on the number of selected files.
final keepStructure = _directoryManuallySet || result.res.name.isNotEmpty || result.res.files.length > 1;
final reqs = selected.map((index) {
final file = result.res.files[index];
final fileRequest = file.req ?? request;
@@ -1145,6 +1253,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
size: _parseProtocol(fileRequest.url) == _TaskProtocol.http ? file.size : 0,
name: file.name,
path: path.join(_directoryController.text.trim(), result.res.name, file.path),
skipAutoCategorize: keepStructure,
extra: _buildOptions(omitChecksum: isMultiFile).extra,
),
);
@@ -1154,7 +1263,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
.createTaskBatch(
CreateTaskBatch(
reqs: reqs,
opts: _buildOptions(omitChecksum: isMultiFile),
opts: _buildOptions(omitChecksum: isMultiFile, skipAutoCategorize: keepStructure),
),
);
return;
@@ -1168,6 +1277,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
var selectedIndexes = List<int>.of(initialSelection);
var submitting = false;
String? errorText;
// The directory the task will be saved to. A directory the user named
// wins over the category suggestion of the resolve response, the backend
// keeps it and does not classify the task.
final effectiveDownloadDir = _directoryManuallySet
? _directoryController.text.trim()
: (result.suggestedDownloadDir.isNotEmpty ? result.suggestedDownloadDir : _directoryController.text.trim());
final dialog = const DialogOverlayHandler().show<bool>(
context: context,
@@ -1223,6 +1338,16 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
: dialogContext.l10n.resolvedFileCount(result.res.files.length),
style: TextStyle(color: palette.textSecondary, fontSize: 12),
),
if (effectiveDownloadDir.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
dialogContext.l10n.resolvedCategoryDirectory(effectiveDownloadDir),
key: const ValueKey('resolve-category-directory'),
style: TextStyle(color: palette.textSecondary, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
const SizedBox(height: 12),
SizedBox(
height: treeHeight.clamp(260.0, 460.0),
@@ -1512,9 +1637,10 @@ class _DirectDownloadToggle extends StatelessWidget {
}
class _AsDefaultPathToggle extends StatelessWidget {
const _AsDefaultPathToggle({required this.value, required this.onChanged});
const _AsDefaultPathToggle({required this.value, required this.enabled, required this.onChanged});
final bool value;
final bool enabled;
final ValueChanged<bool> onChanged;
@override
@@ -1523,7 +1649,7 @@ class _AsDefaultPathToggle extends StatelessWidget {
return GestureDetector(
key: const ValueKey('create-task-remember-download-directory'),
behavior: HitTestBehavior.opaque,
onTap: () => onChanged(!value),
onTap: enabled ? () => onChanged(!value) : null,
child: SizedBox(
height: 24,
child: Row(
@@ -1532,7 +1658,7 @@ class _AsDefaultPathToggle extends StatelessWidget {
Checkbox(
key: const ValueKey('create-task-remember-download-directory-checkbox'),
state: value ? CheckboxState.checked : CheckboxState.unchecked,
onChanged: (_) => onChanged(!value),
onChanged: enabled ? (_) => onChanged(!value) : null,
),
const SizedBox(width: AppDesignTokens.checkboxLabelGap),
Flexible(
@@ -1564,6 +1690,8 @@ class _DirectoryOptions extends StatelessWidget {
super.key,
required this.stacked,
required this.asDefaultPath,
required this.canSetAsDefaultPath,
required this.activeIndex,
required this.onAsDefaultPathChanged,
required this.shortcuts,
required this.onShortcutSelected,
@@ -1571,14 +1699,28 @@ class _DirectoryOptions extends StatelessWidget {
final bool stacked;
final bool asDefaultPath;
/// The global default download directory is only saved for a directory the
/// user named explicitly, so the toggle stays disabled until then.
final bool canSetAsDefaultPath;
final int? activeIndex;
final ValueChanged<bool> onAsDefaultPathChanged;
final List<_DirectoryShortcut> shortcuts;
final ValueChanged<_DirectoryShortcut> onShortcutSelected;
@override
Widget build(BuildContext context) {
final toggle = _AsDefaultPathToggle(value: asDefaultPath, onChanged: onAsDefaultPathChanged);
final shortcutList = _DirectoryShortcuts(shortcuts: shortcuts, alignEnd: !stacked, onSelected: onShortcutSelected);
final toggle = _AsDefaultPathToggle(
value: asDefaultPath,
enabled: canSetAsDefaultPath,
onChanged: onAsDefaultPathChanged,
);
final shortcutList = _DirectoryShortcuts(
shortcuts: shortcuts,
activeIndex: activeIndex,
alignEnd: !stacked,
onSelected: onShortcutSelected,
);
if (stacked) {
return Column(
@@ -1613,9 +1755,15 @@ class _DirectoryOptions extends StatelessWidget {
}
class _DirectoryShortcuts extends StatelessWidget {
const _DirectoryShortcuts({required this.shortcuts, required this.alignEnd, required this.onSelected});
const _DirectoryShortcuts({
required this.shortcuts,
required this.activeIndex,
required this.alignEnd,
required this.onSelected,
});
final List<_DirectoryShortcut> shortcuts;
final int? activeIndex;
final bool alignEnd;
final ValueChanged<_DirectoryShortcut> onSelected;
@@ -1631,6 +1779,7 @@ class _DirectoryShortcuts extends StatelessWidget {
_DirectoryShortcutButton(
key: ValueKey('create-task-category-${shortcut.index}'),
shortcut: shortcut,
active: shortcut.index == activeIndex,
onPressed: () => onSelected(shortcut),
),
],
@@ -1651,6 +1800,7 @@ class _DirectoryShortcuts extends StatelessWidget {
_DirectoryShortcutButton(
key: ValueKey('create-task-category-${shortcut.index}'),
shortcut: shortcut,
active: shortcut.index == activeIndex,
onPressed: () => onSelected(shortcut),
),
],
@@ -1662,9 +1812,10 @@ class _DirectoryShortcuts extends StatelessWidget {
}
class _DirectoryShortcutButton extends StatefulWidget {
const _DirectoryShortcutButton({super.key, required this.shortcut, required this.onPressed});
const _DirectoryShortcutButton({super.key, required this.shortcut, required this.active, required this.onPressed});
final _DirectoryShortcut shortcut;
final bool active;
final VoidCallback onPressed;
@override
@@ -1677,10 +1828,12 @@ class _DirectoryShortcutButtonState extends State<_DirectoryShortcutButton> {
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final active = widget.active;
return AppTooltip(
message: widget.shortcut.path,
child: Semantics(
button: true,
selected: active,
label: widget.shortcut.label,
child: MouseRegion(
cursor: SystemMouseCursors.click,
@@ -1696,21 +1849,25 @@ class _DirectoryShortcutButtonState extends State<_DirectoryShortcutButton> {
constraints: const BoxConstraints(maxWidth: 168),
padding: const EdgeInsets.symmetric(horizontal: 9),
decoration: BoxDecoration(
color: _hovered ? palette.surfaceSoft : palette.cardBg,
color: active ? palette.brandSoft : (_hovered ? palette.surfaceSoft : palette.cardBg),
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
border: Border.all(color: palette.border),
border: Border.all(color: active ? palette.brand.withValues(alpha: 0.45) : palette.border),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.folder_outlined, size: 14, color: palette.textMuted),
Icon(Icons.folder_outlined, size: 14, color: active ? palette.brand : palette.textMuted),
const SizedBox(width: 5),
Flexible(
child: Text(
widget.shortcut.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 11.5, fontWeight: FontWeight.w600),
style: TextStyle(
color: active ? palette.textPrimary : palette.textSecondary,
fontSize: 11.5,
fontWeight: FontWeight.w600,
),
),
),
],
@@ -1842,6 +1999,8 @@ class _SegmentButton extends StatelessWidget {
}
}
const _categoryHighlightDebounce = Duration(milliseconds: 300);
const _advancedExpandDuration = Duration(milliseconds: 220);
const _advancedScrollDelay = Duration(milliseconds: 90);
const _advancedScrollDuration = Duration(milliseconds: 260);