Merge remote-tracking branch 'origin/main' into codex/fix-bt-file-selection

# Conflicts:
#	ui/flutter/test/features/tasks/domain/task_record_test.dart
This commit is contained in:
Levi committed 2026-09-17 00:03:36 +08:00
commit a83e3a2b84
272 files changed
+17212 -1065

No files matched your search

@@ -6,6 +6,7 @@ import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_loading_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
class LoginForm extends StatelessWidget {
const LoginForm({
@@ -159,7 +160,7 @@ class _LoginField extends StatelessWidget {
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w600),
),
const SizedBox(height: AppDesignTokens.space8),
shad.TextField(
AppTextField(
key: fieldKey,
controller: controller,
focusNode: focusNode,
@@ -11,10 +11,12 @@ import 'package:url_launcher/url_launcher.dart';
import '../../../../api/model/extension.dart' as api_extension;
import '../../../../api/model/store_extension.dart';
import '../../../../core/utils/breakpoints.dart';
import '../../../../core/utils/compact_count_formatter.dart';
import '../../../../core/window/app_window_chrome.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../../../l10n/l10n.dart';
@@ -23,8 +25,10 @@ import '../../application/extensions_controller.dart';
import '../../application/pending_extension_install.dart';
import '../widgets/extension_detail_view.dart';
import '../widgets/extension_icon.dart';
import '../widgets/extension_setting_field.dart';
import '../widgets/extension_update_dialog.dart';
const _extensionCardMinWidth = 280.0;
const _extensionCardMinWidth = 290.0;
const _extensionGridSpacing = 10.0;
int _extensionGridColumnCount(double width) {
@@ -44,6 +48,9 @@ class ExtensionsPage extends ConsumerStatefulWidget {
class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
final _searchController = TextEditingController();
final _installController = TextEditingController();
final _installAnchorKey = GlobalKey();
final _installPopoverKey = GlobalKey<_InstallPopoverState>();
bool _installDevMode = false;
final _listScrollController = ScrollController();
final Map<String, TextEditingController> _settingControllers = {};
ExtensionListItem? _detailItem;
@@ -75,15 +82,28 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final isDesktop = MediaQuery.sizeOf(context).width >= Breakpoints.mobile;
ref.listen(pendingExtensionInstallProvider, (previous, next) {
if (next == null) return;
ref.read(pendingExtensionInstallProvider.notifier).clear();
unawaited(
_runAction(
() => ref.read(extensionsControllerProvider.notifier).installFromUrl(next.url, devInstall: next.devMode),
),
);
});
final pendingInstall = ref.watch(pendingExtensionInstallProvider);
if (pendingInstall != null) {
// The request can arrive before this page is mounted. Consume it only
// after the toolbar is laid out, so cold and warm links share the same UI.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !identical(ref.read(pendingExtensionInstallProvider), pendingInstall)) return;
if (_installPopoverKey.currentState?._installing == true) return;
final anchorContext = _installAnchorKey.currentContext;
if (anchorContext == null) return;
_installController.text = pendingInstall.url;
_installDevMode = pendingInstall.devMode;
_showInstallPopover(anchorContext);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !identical(ref.read(pendingExtensionInstallProvider), pendingInstall)) return;
final popover = _installPopoverKey.currentState;
if (popover == null || popover._installing) return;
ref.read(pendingExtensionInstallProvider.notifier).clear();
unawaited(popover._install());
});
WidgetsBinding.instance.ensureVisualUpdate();
});
}
final stateAsync = ref.watch(extensionsControllerProvider);
final body = Stack(
children: [
@@ -151,6 +171,7 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
onSearch: (query) => _runAction(() => ref.read(extensionsControllerProvider.notifier).searchStore(query)),
onSort: (sort) => _runAction(() => ref.read(extensionsControllerProvider.notifier).changeSort(sort)),
onFilter: ref.read(extensionsControllerProvider.notifier).changeFilter,
installAnchorKey: _installAnchorKey,
onOpenInstall: _openInstallPopover,
onDevelopExtension: _openExtensionDevelopmentDocs,
onInstallFolder: _installFromFolder,
@@ -166,7 +187,9 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
Future<void> _installFromUrl() async {
final url = _installController.text.trim();
if (url.isEmpty) return;
await _runAction(() => ref.read(extensionsControllerProvider.notifier).installFromUrl(url));
await _runAction(
() => ref.read(extensionsControllerProvider.notifier).installFromUrl(url, devInstall: _installDevMode),
);
}
Future<void> _loadNextPageIfNeeded() async {
@@ -189,7 +212,14 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
}
void _openInstallPopover(BuildContext anchorContext) {
ref.read(extensionsControllerProvider.notifier).tryOpenDevMode();
if (AppWindowChrome.isDesktopWindow) {
ref.read(extensionsControllerProvider.notifier).tryOpenDevMode();
}
_installDevMode = false;
_showInstallPopover(anchorContext);
}
void _showInstallPopover(BuildContext anchorContext) {
if (_installPopover != null) return;
final overlay = const shad.PopoverOverlayHandler().show<void>(
context: anchorContext,
@@ -198,7 +228,17 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
offset: const Offset(0, 8),
modal: false,
consumeOutsideTaps: false,
builder: (context) => _InstallPopover(controller: _installController, onInstallUrl: _installFromUrl),
// Flutter's native selection toolbar uses the EditableText tap group.
// Pasting from it must not dismiss the form and restore search focus.
regionGroupId: EditableText,
builder: (context) => _InstallPopover(
key: _installPopoverKey,
controller: _installController,
onInstallUrl: _installFromUrl,
onFinished: () {
if (mounted && ref.read(pendingExtensionInstallProvider) != null) setState(() {});
},
),
);
_installPopover = overlay;
unawaited(
@@ -209,7 +249,7 @@ class _ExtensionsPageState extends ConsumerState<ExtensionsPage> {
}
Future<void> _installFromFolder() async {
final folder = await FilePicker.platform.getDirectoryPath();
final folder = await FilePicker.getDirectoryPath();
if (folder == null || folder.isEmpty) return;
await _runAction(() => ref.read(extensionsControllerProvider.notifier).installFromUrl(folder, devInstall: true));
}
@@ -281,6 +321,7 @@ class _Content extends StatelessWidget {
required this.onSearch,
required this.onSort,
required this.onFilter,
required this.installAnchorKey,
required this.onOpenInstall,
required this.onDevelopExtension,
required this.onInstallFolder,
@@ -298,6 +339,7 @@ class _Content extends StatelessWidget {
final ValueChanged<String> onSearch;
final ValueChanged<StoreExtensionSort> onSort;
final ValueChanged<ExtensionListFilter> onFilter;
final GlobalKey installAnchorKey;
final ValueChanged<BuildContext> onOpenInstall;
final VoidCallback onDevelopExtension;
final VoidCallback onInstallFolder;
@@ -319,6 +361,7 @@ class _Content extends StatelessWidget {
onSearch: onSearch,
onSort: onSort,
onRefresh: onRefresh,
installAnchorKey: installAnchorKey,
onOpenInstall: onOpenInstall,
onDevelopExtension: onDevelopExtension,
onInstallFolder: onInstallFolder,
@@ -611,6 +654,7 @@ class _Toolbar extends StatelessWidget {
required this.onSearch,
required this.onSort,
required this.onRefresh,
required this.installAnchorKey,
required this.onOpenInstall,
required this.onDevelopExtension,
required this.onInstallFolder,
@@ -621,6 +665,7 @@ class _Toolbar extends StatelessWidget {
final ValueChanged<String> onSearch;
final ValueChanged<StoreExtensionSort> onSort;
final VoidCallback onRefresh;
final GlobalKey installAnchorKey;
final ValueChanged<BuildContext> onOpenInstall;
final VoidCallback onDevelopExtension;
final VoidCallback onInstallFolder;
@@ -628,10 +673,10 @@ class _Toolbar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final manualInstallBusy = state.busyExtensionIds.contains(ExtensionsController.manualInstallBusyKey);
final search = shad.TextField(
final search = AppTextField(
key: const ValueKey('extension-search-input'),
controller: searchController,
padding: MediaQuery.sizeOf(context).width >= Breakpoints.mobile ? AppDesignTokens.compactTextFieldPadding : null,
placeholder: Text(context.l10n.searchExtensions, style: TextStyle(color: palette.searchHint)),
features: [shad.InputFeature.leading(Icon(Icons.search_rounded, size: 16, color: palette.textMuted))],
onSubmitted: onSearch,
@@ -669,22 +714,21 @@ class _Toolbar extends StatelessWidget {
onPressed: onDevelopExtension,
),
const SizedBox(width: 8),
if (state.devMode) ...[
if (AppWindowChrome.isDesktopWindow && state.devMode) ...[
_OutlineToolbarIconButton(
key: const ValueKey('load-local-extension-button'),
tooltip: context.l10n.extensionLoadLocal,
icon: Icons.folder_open_outlined,
loading: manualInstallBusy,
onPressed: onInstallFolder,
),
const SizedBox(width: 8),
],
Builder(
key: installAnchorKey,
builder: (buttonContext) => _OutlineToolbarIconButton(
key: const ValueKey('install-extension-button'),
tooltip: context.l10n.extensionInstallFromUrl,
icon: Icons.add_link,
loading: manualInstallBusy,
onPressed: () => onOpenInstall(buttonContext),
),
),
@@ -760,18 +804,11 @@ class _FilterBar extends StatelessWidget {
}
class _OutlineToolbarIconButton extends StatelessWidget {
const _OutlineToolbarIconButton({
super.key,
required this.tooltip,
required this.icon,
required this.onPressed,
this.loading = false,
});
const _OutlineToolbarIconButton({super.key, required this.tooltip, required this.icon, required this.onPressed});
final String tooltip;
final IconData icon;
final VoidCallback? onPressed;
final bool loading;
@override
Widget build(BuildContext context) {
@@ -779,23 +816,18 @@ class _OutlineToolbarIconButton extends StatelessWidget {
message: tooltip,
child: SizedBox.square(
dimension: 32,
child: shad.IconButton.outline(
size: shad.ButtonSize.xSmall,
onPressed: loading ? null : onPressed,
icon: loading
? const SizedBox.square(dimension: 13, child: shad.CircularProgressIndicator())
: Icon(icon, size: 17),
),
child: shad.IconButton.outline(size: shad.ButtonSize.xSmall, onPressed: onPressed, icon: Icon(icon, size: 17)),
),
);
}
}
class _InstallPopover extends StatefulWidget {
const _InstallPopover({required this.controller, required this.onInstallUrl});
const _InstallPopover({super.key, required this.controller, required this.onInstallUrl, required this.onFinished});
final TextEditingController controller;
final Future<void> Function() onInstallUrl;
final VoidCallback onFinished;
@override
State<_InstallPopover> createState() => _InstallPopoverState();
@@ -826,7 +858,7 @@ class _InstallPopoverState extends State<_InstallPopover> {
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
),
const SizedBox(height: 10),
shad.TextField(
AppTextField(
key: const ValueKey('extension-install-url-input'),
controller: widget.controller,
autofocus: true,
@@ -857,8 +889,8 @@ class _InstallPopoverState extends State<_InstallPopover> {
setState(() => _installing = true);
await widget.onInstallUrl();
if (!mounted) return;
setState(() => _installing = false);
await shad.closeOverlay(context);
widget.onFinished();
}
}
@@ -992,71 +1024,97 @@ class _ExtensionCard extends ConsumerWidget {
const Spacer(),
Row(
children: [
if (item.store != null) ...[
Icon(Icons.star_rounded, size: 15, color: palette.textMuted),
const SizedBox(width: 3),
Text('${item.stars}', style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(width: 10),
Icon(Icons.download_outlined, size: 15, color: palette.textMuted),
const SizedBox(width: 3),
Text('${item.installCount}', style: TextStyle(color: palette.textSecondary, fontSize: 12)),
],
const Spacer(),
if (canUpdate && installed != null)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: busy
? null
: () =>
onAction(() => ref.read(extensionsControllerProvider.notifier).upgradeExtension(installed)),
child: const Icon(Icons.refresh),
),
if (installed == null && item.store != null)
shad.GhostButton(
key: ValueKey('install-store-extension-${item.store!.id}'),
density: shad.ButtonDensity.icon,
onPressed: busy
? null
: () => onAction(
() => ref.read(extensionsControllerProvider.notifier).installFromStore(item.store!),
),
child: busy
? const SizedBox.square(dimension: 14, child: shad.CircularProgressIndicator())
: const Icon(Icons.download),
),
if ((item.homepage ?? '').isNotEmpty)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: () => unawaited(launchUrl(Uri.parse(item.homepage!))),
child: const Icon(Icons.home_outlined),
),
if ((item.repoUrl ?? '').isNotEmpty)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: () => unawaited(launchUrl(Uri.parse(item.repoUrl!))),
child: const Icon(Icons.code),
),
if (installed?.settings?.isNotEmpty == true)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: busy ? null : () => onOpenSettings(installed!),
child: const Icon(Icons.settings_outlined),
),
if (installed != null)
shad.GhostButton(
key: ValueKey('remove-extension-${installed.identity}'),
density: shad.ButtonDensity.icon,
onPressed: busy
? null
: () async {
final confirmed = await _showRemoveExtensionDialog(context, installed.title);
if (!confirmed || !context.mounted) return;
await onAction(
() => ref.read(extensionsControllerProvider.notifier).removeExtension(installed),
);
},
child: const Icon(Icons.delete_outline),
),
if (item.store != null)
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Row(
key: ValueKey('extension-card-stats-${item.id}'),
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star_rounded, size: 15, color: palette.textMuted),
const SizedBox(width: 3),
Text(
CompactCountFormatter.format(item.stars),
style: TextStyle(color: palette.textSecondary, fontSize: 12),
),
const SizedBox(width: 10),
Icon(Icons.download_outlined, size: 15, color: palette.textMuted),
const SizedBox(width: 3),
Text(
CompactCountFormatter.format(item.installCount),
style: TextStyle(color: palette.textSecondary, fontSize: 12),
),
],
),
),
),
)
else
const Spacer(),
const SizedBox(width: 8),
Row(
key: ValueKey('extension-card-actions-${item.id}'),
mainAxisSize: MainAxisSize.min,
children: [
if (canUpdate && installed != null)
shad.GhostButton(
density: shad.ButtonDensity.icon,
key: ValueKey('update-extension-${installed.identity}'),
onPressed: busy ? null : () => showExtensionUpdateDialog(context, installed),
child: const Icon(Icons.refresh),
),
if (installed == null && item.store != null)
shad.GhostButton(
key: ValueKey('install-store-extension-${item.store!.id}'),
density: shad.ButtonDensity.icon,
onPressed: busy
? null
: () => onAction(
() => ref.read(extensionsControllerProvider.notifier).installFromStore(item.store!),
),
child: busy
? const SizedBox.square(dimension: 14, child: shad.CircularProgressIndicator())
: const Icon(Icons.download),
),
if ((item.homepage ?? '').isNotEmpty)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: () => unawaited(launchUrl(Uri.parse(item.homepage!))),
child: const Icon(Icons.home_outlined),
),
if ((item.repoUrl ?? '').isNotEmpty)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: () => unawaited(launchUrl(Uri.parse(item.repoUrl!))),
child: const Icon(Icons.code),
),
if (installed?.settings?.isNotEmpty == true)
shad.GhostButton(
density: shad.ButtonDensity.icon,
onPressed: busy ? null : () => onOpenSettings(installed!),
child: const Icon(Icons.settings_outlined),
),
if (installed != null)
shad.GhostButton(
key: ValueKey('remove-extension-${installed.identity}'),
density: shad.ButtonDensity.icon,
onPressed: busy
? null
: () async {
final confirmed = await _showRemoveExtensionDialog(context, installed.title);
if (!confirmed || !context.mounted) return;
await onAction(
() => ref.read(extensionsControllerProvider.notifier).removeExtension(installed),
);
},
child: const Icon(Icons.delete_outline),
),
],
),
],
),
],
@@ -1172,7 +1230,7 @@ class _ExtensionSettingsPanel extends StatelessWidget {
separatorBuilder: (_, _) => const SizedBox(height: 14),
itemBuilder: (context, index) {
final setting = settings[index];
return _ExtensionSettingField(setting: setting, controller: controllers[setting.name]!);
return ExtensionSettingField(setting: setting, controller: controllers[setting.name]!);
},
),
),
@@ -1200,39 +1258,6 @@ class _ExtensionSettingsPanel extends StatelessWidget {
}
}
class _ExtensionSettingField extends StatelessWidget {
const _ExtensionSettingField({required this.setting, required this.controller});
final api_extension.Setting setting;
final TextEditingController controller;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
setting.title,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
),
if (setting.description.isNotEmpty) ...[
const SizedBox(height: 4),
Text(setting.description, style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.35)),
],
const SizedBox(height: 8),
if (setting.type == api_extension.SettingType.boolean)
shad.TextField(controller: controller, placeholder: Text(context.l10n.booleanValueHint))
else
shad.TextField(
controller: controller,
keyboardType: setting.type == api_extension.SettingType.number ? TextInputType.number : TextInputType.text,
),
],
);
}
}
class _ErrorState extends StatelessWidget {
const _ErrorState({required this.error, required this.onRetry});
@@ -10,6 +10,7 @@ import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import 'package:url_launcher/url_launcher.dart';
import '../../../../api/model/store_extension.dart';
import '../../../../core/utils/compact_count_formatter.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
@@ -19,6 +20,7 @@ import '../../../../shared/widgets/detail/app_detail_surface.dart';
import '../../../../util/util.dart';
import '../../application/extensions_controller.dart';
import 'extension_icon.dart';
import 'extension_update_dialog.dart';
class ExtensionDetailDrawer extends StatelessWidget {
const ExtensionDetailDrawer({super.key, required this.item, required this.onClose});
@@ -131,14 +133,10 @@ class ExtensionDetailView extends ConsumerWidget {
if (installed != null && canUpdate)
AppLoadingButton(
key: const ValueKey('extension-details-update'),
loading: busy,
loading: false,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.refresh, size: 16),
onPressed: () => _runAction(
context,
() => ref.read(extensionsControllerProvider.notifier).upgradeExtension(installed),
successMessage: context.l10n.extensionUpdateSuccess,
),
onPressed: busy ? null : () => showExtensionUpdateDialog(context, installed),
child: Text(context.l10n.newVersionUpdate),
),
if (installed != null && !canUpdate)
@@ -338,9 +336,9 @@ class _ExtensionStats extends StatelessWidget {
key: const ValueKey('extension-details-stats'),
mainAxisSize: MainAxisSize.min,
children: [
_MetadataItem(icon: Icons.star_rounded, value: store.stars.toString()),
_MetadataItem(icon: Icons.star_rounded, value: CompactCountFormatter.format(store.stars)),
const SizedBox(width: 12),
_MetadataItem(icon: Icons.download_outlined, value: store.installCount.toString()),
_MetadataItem(icon: Icons.download_outlined, value: CompactCountFormatter.format(store.installCount)),
],
);
}
@@ -0,0 +1,87 @@
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:flutter/services.dart';
import '../../../../api/model/extension.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_text_field.dart';
class ExtensionSettingField extends StatelessWidget {
const ExtensionSettingField({super.key, required this.setting, required this.controller});
final Setting setting;
final TextEditingController controller;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
setting.title,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
),
if (setting.description.isNotEmpty) ...[
const SizedBox(height: 4),
Text(setting.description, style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.35)),
],
const SizedBox(height: 8),
_buildInput(),
],
);
}
Widget _buildInput() {
if (setting.type == SettingType.boolean) {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) =>
Switch(value: value.text == 'true', onChanged: (enabled) => controller.text = enabled.toString()),
);
}
final options = setting.options;
if (options != null && options.isNotEmpty) {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) => LayoutBuilder(
builder: (context, constraints) => Select<String>(
value: options.any((option) => option.value.toString() == value.text) ? value.text : null,
placeholder: Text(setting.title),
constraints: BoxConstraints.tightFor(width: constraints.maxWidth),
popupConstraints: const BoxConstraints(maxHeight: 240),
itemBuilder: (context, selectedValue) => Text(
options.firstWhere((option) => option.value.toString() == selectedValue).label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
popup: (context) => SelectPopup<String>(
items: SelectItemList(
children: [
for (final option in options)
SelectItemButton<String>(value: option.value.toString(), child: Text(option.label)),
],
),
),
onChanged: (selectedValue) {
if (selectedValue != null) controller.text = selectedValue;
},
),
),
);
}
final isNumber = setting.type == SettingType.number;
return AppTextField(
controller: controller,
keyboardType: isNumber ? const TextInputType.numberWithOptions(decimal: true, signed: true) : TextInputType.text,
inputFormatters: isNumber
? [
TextInputFormatter.withFunction(
(oldValue, newValue) => RegExp(r'^-?\d*\.?\d*$').hasMatch(newValue.text) ? newValue : oldValue,
),
]
: null,
);
}
}
@@ -0,0 +1,90 @@
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../api/model/extension.dart' as api;
import '../../../../l10n/l10n.dart';
import '../../../../shared/widgets/app_loading_button.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../application/extensions_controller.dart';
Future<void> showExtensionUpdateDialog(BuildContext context, api.Extension extension) async {
final overlay = const DialogOverlayHandler().show<bool>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (_) => _ExtensionUpdateDialog(extension: extension),
);
final updated = await overlay.future;
if (updated == true && context.mounted) {
showAppToast(context, context.l10n.extensionUpdateSuccess);
}
}
class _ExtensionUpdateDialog extends ConsumerStatefulWidget {
const _ExtensionUpdateDialog({required this.extension});
final api.Extension extension;
@override
ConsumerState<_ExtensionUpdateDialog> createState() => _ExtensionUpdateDialogState();
}
class _ExtensionUpdateDialogState extends ConsumerState<_ExtensionUpdateDialog> {
bool _updating = false;
bool _failed = false;
Future<void> _update() async {
if (_updating) return;
setState(() {
_updating = true;
_failed = false;
});
try {
await ref.read(extensionsControllerProvider.notifier).upgradeExtension(widget.extension);
} catch (_) {
if (!mounted) return;
setState(() {
_updating = false;
_failed = true;
});
return;
}
if (mounted) await closeOverlay(context, true);
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: !_updating,
child: AlertDialog(
key: const ValueKey('extension-update-dialog'),
title: Text(context.l10n.extensionCanUpdate),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(context.l10n.extensionUpdateConfirm(widget.extension.title)),
if (_failed) ...[
const SizedBox(height: 12),
Text(context.l10n.updateFailed, key: const ValueKey('extension-update-error')),
],
],
),
actions: [
SecondaryButton(
key: const ValueKey('cancel-update-extension-button'),
onPressed: _updating ? null : () => closeOverlay(context, false),
child: Text(context.l10n.cancel),
),
AppLoadingButton(
key: const ValueKey('confirm-update-extension-button'),
variant: AppLoadingButtonVariant.primary,
loading: _updating,
onPressed: _update,
child: Text(context.l10n.newVersionUpdate),
),
],
),
);
}
}
@@ -19,6 +19,7 @@ import '../../../../shared/widgets/responsive_navigation_layout.dart';
import '../../../../l10n/l10n.dart';
import '../../../../util/util.dart';
import '../../../tasks/application/tasks_controller.dart';
import '../../../tasks/application/task_list_navigation.dart';
import '../../../tasks/application/pending_update_task.dart';
import '../../../tasks/application/task_batch_selection_controller.dart';
import '../../../tasks/domain/task_record.dart';
@@ -29,6 +30,7 @@ import '../../../tasks/presentation/widgets/task_drawer.dart';
import '../../../tasks/presentation/widgets/task_context_menu.dart';
import '../../../tasks/presentation/widgets/task_delete_dialog.dart';
import '../../../tasks/presentation/widgets/task_empty_state.dart';
import '../../../tasks/presentation/widgets/task_create_button.dart';
import '../../../tasks/presentation/widgets/task_file_browser_dialog.dart';
import '../../../tasks/presentation/widgets/task_update_url_dialog.dart';
import '../widgets/primary_rail.dart';
@@ -86,6 +88,11 @@ class _HomePageState extends ConsumerState<HomePage> {
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final tasksAsync = ref.watch(tasksControllerProvider);
ref.listen(taskListNavigationProvider, (_, _) {
_searchController.clear();
_setActiveFilter(_TaskFilter.downloading);
setState(() => _batchMode = false);
});
final tasksState = tasksAsync.value;
final tasks = tasksState?.tasks ?? const <TaskRecord>[];
final filteredTasks = _filteredTasks(tasks);
@@ -166,7 +173,10 @@ class _HomePageState extends ConsumerState<HomePage> {
loading: () => const Center(child: shad.CircularProgressIndicator()),
error: (error, _) => const TaskEmptyState(),
data: (_) => filteredTasks.isEmpty
? TaskEmptyState(message: emptyStateMessage)
? TaskEmptyState(
message: emptyStateMessage,
onCreateTask: _searchController.text.trim().isEmpty ? _handleAddTask : null,
)
: ListView.separated(
padding: const EdgeInsets.only(bottom: 16),
itemCount: filteredTasks.length,
@@ -254,6 +264,7 @@ class _HomePageState extends ConsumerState<HomePage> {
data: (_) => _MobileTasksView(
tasks: filteredTasks,
emptyStateMessage: emptyStateMessage,
onCreateTask: _searchController.text.trim().isEmpty ? _handleAddTask : null,
batchMode: _batchMode,
batchSelection: _batchSelection,
onToggleSelectAll: _toggleSelectAll,
@@ -679,6 +690,7 @@ class _MobileTasksView extends StatelessWidget {
required this.contextActionsForTask,
required this.pendingUpdateTaskId,
this.emptyStateMessage,
this.onCreateTask,
this.loading = false,
});
@@ -699,6 +711,7 @@ class _MobileTasksView extends StatelessWidget {
final TaskContextActions Function(TaskRecord task, bool selected, bool allSelected) contextActionsForTask;
final String? pendingUpdateTaskId;
final String? emptyStateMessage;
final VoidCallback? onCreateTask;
final bool loading;
@override
@@ -739,7 +752,7 @@ class _MobileTasksView extends StatelessWidget {
child: loading
? const Center(child: shad.CircularProgressIndicator())
: tasks.isEmpty
? TaskEmptyState(message: emptyStateMessage)
? TaskEmptyState(message: emptyStateMessage, onCreateTask: onCreateTask)
: ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
itemCount: tasks.length,
@@ -808,9 +821,19 @@ class _MobileTasksHeader extends StatelessWidget {
style: TextStyle(color: palette.textPrimary, fontSize: 22, fontWeight: FontWeight.w800),
),
),
_MobileHeaderIconButton(icon: Icons.add_rounded, onPressed: onAddTask),
const SizedBox(width: AppDesignTokens.space8),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: MediaQuery.sizeOf(context).width * 0.5),
child: TaskCreateButton(
key: const ValueKey('tasks-mobile-create-button'),
onPressed: onAddTask,
minHeight: 34,
compact: true,
),
),
const SizedBox(width: 8),
_MobileHeaderIconButton(
key: const ValueKey('tasks-mobile-batch-button'),
icon: Icons.checklist_rtl_outlined,
active: batchMode,
badge: batchMode && selectedCount > 0 ? selectedCount.toString() : null,
@@ -897,7 +920,13 @@ class _MobileBatchToolbar extends StatelessWidget {
}
class _MobileHeaderIconButton extends StatelessWidget {
const _MobileHeaderIconButton({required this.icon, required this.onPressed, this.active = false, this.badge});
const _MobileHeaderIconButton({
super.key,
required this.icon,
required this.onPressed,
this.active = false,
this.badge,
});
final IconData icon;
final VoidCallback onPressed;
@@ -4,7 +4,8 @@ import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../tasks/presentation/widgets/task_create_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../l10n/l10n.dart';
class TasksTopBar extends StatelessWidget {
@@ -61,7 +62,7 @@ class TasksTopBar extends StatelessWidget {
ConstrainedBox(
key: const ValueKey('tasks-create-button-container'),
constraints: const BoxConstraints(minWidth: 120, maxWidth: 190),
child: _AddTaskButton(onPressed: onAddTask),
child: TaskCreateButton(onPressed: onAddTask),
),
const SizedBox(width: 16),
Row(
@@ -110,7 +111,7 @@ class _SearchField extends StatelessWidget {
),
child: SizedBox(
height: 40,
child: shad.TextField(
child: AppTextField(
controller: controller,
style: TextStyle(color: palette.textPrimary, fontSize: 14, height: 1),
placeholder: Text(
@@ -130,27 +131,6 @@ class _SearchField extends StatelessWidget {
}
}
class _AddTaskButton extends StatelessWidget {
const _AddTaskButton({required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return AppPrimaryButton(
onPressed: onPressed,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.add),
const SizedBox(width: AppDesignTokens.space8),
Flexible(child: Text(context.l10n.create, maxLines: 1, overflow: TextOverflow.ellipsis)),
],
),
);
}
}
class _ActionIconButton extends StatelessWidget {
const _ActionIconButton({required this.icon, required this.onPressed});
@@ -1,6 +1,5 @@
import 'dart:async';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show Divider, Icons, Scrollbar, ScrollbarOrientation;
import 'package:flutter/widgets.dart';
@@ -14,6 +13,7 @@ import '../../../../app/application/app_appearance_controller.dart';
import '../../../../app/application/app_platform_controller.dart';
import '../../../../app/application/app_runtime_controller.dart';
import '../../../../app/application/location_keep_alive.dart';
import '../../../../app/application/continued_processing.dart';
import '../../../../core/common/start_config.dart';
import '../../../../core/network/gopeed/gopeed_transport.dart';
import '../../../../core/utils/breakpoints.dart';
@@ -24,6 +24,7 @@ import '../../../../shared/widgets/app_choice_segmented_control.dart';
import '../../../../shared/widgets/app_loading_button.dart';
import '../../../../shared/widgets/app_number_input.dart';
import '../../../../shared/widgets/app_path_picker_field.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../../../shared/widgets/responsive_menu_layout.dart';
@@ -64,6 +65,8 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
final _maxRunningController = TextEditingController();
final _httpUserAgentController = TextEditingController();
final _httpConnectionsController = TextEditingController();
final _hlsConnectionsController = TextEditingController();
final _hlsMaxRetriesController = TextEditingController();
final _btListenPortController = TextEditingController();
final _btSeedRatioController = TextEditingController();
final _btSeedTimeController = TextEditingController();
@@ -95,6 +98,8 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_maxRunningController,
_httpUserAgentController,
_httpConnectionsController,
_hlsConnectionsController,
_hlsMaxRetriesController,
_btListenPortController,
_btSeedRatioController,
_btSeedTimeController,
@@ -377,6 +382,19 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
onChanged: (value) => unawaited(_setBackgroundLocationKeepAlive(value)),
),
),
if (Util.isIOS())
SettingsItem(
title: context.l10n.backgroundContinuedProcessing,
subtitle:
context.l10n.backgroundContinuedProcessingDescription,
child: shad.Switch(
value:
config.extra.backgroundContinuedProcessing,
onChanged: (value) => unawaited(
_setBackgroundContinuedProcessing(value),
),
),
),
],
),
),
@@ -558,6 +576,32 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
],
),
),
_SettingsBlock(
key: const ValueKey('settings-hls-block'),
title: 'HLS',
child: _SettingsGroup(
children: [
SettingsItem(
title: context.l10n.connections,
child: _NumberSettingControl(
fieldKey: const ValueKey('hls-connections-input'),
controller: _hlsConnectionsController,
min: 1,
max: 256,
),
),
SettingsItem(
title: context.l10n.maxRetries,
child: _NumberSettingControl(
fieldKey: const ValueKey('hls-max-retries-input'),
controller: _hlsMaxRetriesController,
min: 0,
max: 30,
),
),
],
),
),
_SettingsBlock(
title: 'BitTorrent',
child: _SettingsGroup(
@@ -939,6 +983,8 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_maxRunningController.text = _config!.maxRunning.clamp(1, 256).toString();
_httpUserAgentController.text = _config!.protocolConfig.http.userAgent;
_httpConnectionsController.text = _config!.protocolConfig.http.connections.clamp(1, 256).toString();
_hlsConnectionsController.text = _config!.protocolConfig.hls.segmentConnections.clamp(1, 256).toString();
_hlsMaxRetriesController.text = _config!.protocolConfig.hls.maxRetries.clamp(0, 30).toString();
_btListenPortController.text = _config!.protocolConfig.bt.listenPort.clamp(0, 65535).toString();
_btSeedRatioController.text = _config!.protocolConfig.bt.seedRatio.toString();
_btSeedTimeController.text = (_config!.protocolConfig.bt.seedTime ~/ 60).clamp(0, 100000000).toString();
@@ -1034,6 +1080,18 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
min: 1,
max: 256,
);
config.protocolConfig.hls.segmentConnections = _boundedInt(
_hlsConnectionsController,
fallback: config.protocolConfig.hls.segmentConnections,
min: 1,
max: 256,
);
config.protocolConfig.hls.maxRetries = _boundedInt(
_hlsMaxRetriesController,
fallback: config.protocolConfig.hls.maxRetries,
min: 0,
max: 30,
);
config.protocolConfig.bt.listenPort = _boundedInt(
_btListenPortController,
fallback: config.protocolConfig.bt.listenPort,
@@ -1237,6 +1295,43 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
_mutateConfig((config) => config.extra.backgroundLocationKeepAlive = enabled);
await LocationKeepAliveCoordinator.instance.reconcile(enabled: enabled);
}
Future<void>
_setBackgroundContinuedProcessing(
bool enabled,
) async {
if (enabled &&
!await ContinuedProcessing.isSupported()) {
if (mounted) {
_toast(
context.l10n
.backgroundContinuedProcessingUnsupported,
);
}
return;
}
final applied =
await ContinuedProcessing.setEnabled(
enabled,
);
if (enabled && !applied) {
if (mounted) {
_toast(
context.l10n
.backgroundContinuedProcessingUnsupported,
);
}
return;
}
_mutateConfig(
(config) =>
config.extra
.backgroundContinuedProcessing =
enabled,
);
}
List<String> _lines(String text) {
return text.split('\n').map((line) => line.trim()).where((line) => line.isNotEmpty).toList();
@@ -1375,12 +1470,7 @@ class _SettingsPageState extends ConsumerState<SettingsPage> {
title: index == null ? context.l10n.addScript : context.l10n.editScript,
fieldLabel: context.l10n.scriptPath,
initialValue: index == null ? '' : paths[index],
pickPath: Util.isDesktop()
? () async {
final result = await FilePicker.platform.pickFiles();
return result?.files.firstOrNull?.path;
}
: null,
pickFile: true,
);
if (value == null || !mounted) return;
_mutateConfig((config) {
@@ -1849,7 +1939,7 @@ class _TextSettingControl extends StatelessWidget {
final desktop = MediaQuery.sizeOf(context).width >= Breakpoints.mobile;
return SizedBox(
width: desktop ? AppDesignTokens.settingsFormControlWidth : double.infinity,
child: shad.TextField(
child: AppTextField(
key: fieldKey,
controller: controller,
hintText: hintText,
@@ -1919,7 +2009,7 @@ class _HostPortControl extends StatelessWidget {
child: Row(
children: [
Expanded(
child: shad.TextField(
child: AppTextField(
key: hostKey,
controller: hostController,
hintText: context.l10n.server,
@@ -10,6 +10,7 @@ import '../../../../util/package_info.dart';
import '../../../../util/updater.dart';
import '../../../../util/util.dart';
import '../../../../l10n/l10n.dart';
import 'app_update_notes_viewport.dart';
typedef StartAppUpdate = Future<void> Function(VersionInfo versionInfo, UpdateProgressCallback onProgress);
@@ -74,11 +75,18 @@ Future<void> showAppUpdateDialog(
key: const ValueKey('app-update-heading'),
textAlign: TextAlign.center,
),
const SizedBox(height: 3),
const SizedBox(height: 8),
Text(
'$appVersion → ${versionInfo.version}',
textAlign: TextAlign.center,
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w400),
style: DefaultTextStyle.of(dialogContext).style.copyWith(
inherit: false,
color: palette.textSecondary,
fontSize: 12,
fontWeight: FontWeight.w400,
height: 1.4,
decoration: TextDecoration.none,
),
),
],
),
@@ -90,18 +98,9 @@ Future<void> showAppUpdateDialog(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
dialogContext.l10n.releaseNotes,
style: TextStyle(color: palette.textPrimary, fontSize: 12, fontWeight: FontWeight.w700),
),
const SizedBox(height: 10),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 210),
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: _ReleaseNotes(
notes: releaseNotes.isEmpty ? dialogContext.l10n.noReleaseNotes : releaseNotes,
),
AppUpdateNotesViewport(
child: _ReleaseNotes(
notes: releaseNotes.isEmpty ? dialogContext.l10n.noReleaseNotes : releaseNotes,
),
),
if (updating) ...[
@@ -157,7 +156,6 @@ Future<void> showAppUpdateDialog(
onPressed: () => unawaited(update()),
loading: updating,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.system_update_alt_outlined, size: 17),
child: Text(dialogContext.l10n.newVersionUpdate),
),
],
@@ -0,0 +1,59 @@
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../shared/theme/app_design_tokens.dart';
class AppUpdateNotesViewport extends StatefulWidget {
const AppUpdateNotesViewport({super.key, required this.child});
final Widget child;
@override
State<AppUpdateNotesViewport> createState() => _AppUpdateNotesViewportState();
}
class _AppUpdateNotesViewportState extends State<AppUpdateNotesViewport> {
final _controller = ScrollController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
const fadeHeight = AppDesignTokens.space24;
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 240),
child: shad.Scrollbar(
controller: _controller,
thumbVisibility: true,
child: ShaderMask(
blendMode: BlendMode.dstIn,
shaderCallback: (bounds) => LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
// Mask colors control opacity only; they do not tint the content.
colors: const [shad.Colors.white, shad.Colors.white, shad.Colors.transparent],
stops: [0, (1 - fadeHeight / bounds.height).clamp(0.0, 1.0), 1],
).createShader(bounds),
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: SingleChildScrollView(
controller: _controller,
padding: const EdgeInsetsDirectional.fromSTEB(
AppDesignTokens.space4,
0,
AppDesignTokens.space16,
// Keep the final line above the fade at the end of the scroll.
fadeHeight,
),
child: widget.child,
),
),
),
),
);
}
}
@@ -8,6 +8,7 @@ import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_path_picker_field.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../l10n/l10n.dart';
class DownloadCategoryDraft {
@@ -169,7 +170,7 @@ Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
children: [
Text(dialogContext.l10n.categoryName, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
shad.TextField(key: const ValueKey('download-category-name'), controller: nameController),
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),
@@ -9,6 +9,7 @@ import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_loading_button.dart';
import '../../../../shared/widgets/app_path_picker_field.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../l10n/l10n.dart';
class SettingsListEntry {
@@ -121,7 +122,7 @@ Future<String?> showTextSettingDialog(
required String fieldLabel,
String initialValue = '',
bool requireHttpUrl = false,
Future<String?> Function()? pickPath,
bool pickFile = false,
Future<void> Function(String value)? onTest,
}) async {
final controller = TextEditingController(text: initialValue);
@@ -188,16 +189,12 @@ Future<String?> showTextSettingDialog(
children: [
Text(fieldLabel, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
if (pickPath == null)
shad.TextField(controller: controller)
if (!pickFile)
AppTextField(controller: controller)
else
AppPathPickerField(
AppPathPickerField.file(
controller: controller,
desktopWidth: AppDesignTokens.settingsFormControlWidth,
onPick: () async {
final path = await pickPath();
if (path != null && path.isNotEmpty) controller.text = path;
},
),
if (validationMessage != null || testMessage != null) ...[
const SizedBox(height: 8),
@@ -302,7 +299,7 @@ Future<GithubMirrorDraft?> showGithubMirrorDialog(BuildContext context, {GithubM
const SizedBox(height: 14),
Text(dialogContext.l10n.githubMirrorUrl, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
shad.TextField(controller: controller),
AppTextField(controller: controller),
if (validationMessage != null) ...[
const SizedBox(height: 8),
Text(validationMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
@@ -0,0 +1,11 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
final taskListNavigationProvider = NotifierProvider<TaskListNavigation, int>(TaskListNavigation.new);
// A request also resets an already-visible list's filter, search and selection.
class TaskListNavigation extends Notifier<int> {
@override
int build() => 0;
void showDownloading() => state++;
}
@@ -117,7 +117,7 @@ class TaskRecord {
bool get canUpdateUrl =>
protocol == api_task.Protocol.http && (status == TaskStatus.paused || status == TaskStatus.failed);
bool get isIndeterminate => status == TaskStatus.downloading && total == null;
bool get isIndeterminate => status == TaskStatus.downloading && !waiting && total == null;
TaskAssetType get assetType => _assetType(name, isFolder: isFolder, protocol: protocol);
@@ -140,7 +140,7 @@ class TaskRecord {
status: status,
downloaded: _formatBytes(downloadedBytes),
total: totalBytes > 0 ? _formatBytes(totalBytes) : null,
speed: task.progress.speed > 0 ? TransferRateFormatter.format(task.progress.speed).text : null,
speed: totalBytes > 0 || task.progress.speed > 0 ? TransferRateFormatter.format(task.progress.speed).text : null,
uploadSpeed: task.uploading ? TransferRateFormatter.format(task.progress.uploadSpeed).text : null,
remainingSeconds: _remainingSeconds(task, totalBytes, downloadedBytes),
downloadDuration: task.progress.used > 0 ? Duration(microseconds: (task.progress.used + 999) ~/ 1000) : null,
@@ -301,13 +301,14 @@ TaskAssetType _assetType(String name, {required bool isFolder, required api_task
return switch (protocol) {
api_task.Protocol.bt => TaskAssetType.torrent,
api_task.Protocol.ed2k => TaskAssetType.ed2k,
api_task.Protocol.http || null => TaskAssetType.file,
api_task.Protocol.hls || api_task.Protocol.http || null => TaskAssetType.file,
};
}
String _fileExtension(String name) {
final pathWithoutQuery = name.split(RegExp(r'[?#]')).first;
final extension = path.extension(pathWithoutQuery).replaceFirst('.', '').toLowerCase();
final uri = Uri.tryParse(name);
final filePath = uri != null && uri.hasScheme && uri.hasAuthority ? uri.path : name;
final extension = path.extension(filePath).replaceFirst('.', '').toLowerCase();
return extension.length <= 10 ? extension : '';
}
@@ -31,12 +31,15 @@ import '../../../../shared/widgets/app_choice_segmented_control.dart';
import '../../../../shared/widgets/app_http_headers_editor.dart';
import '../../../../shared/widgets/app_number_input.dart';
import '../../../../shared/widgets/app_path_picker_field.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../../../l10n/l10n.dart';
import '../../../../util/util.dart';
import '../../application/pending_create_task.dart';
import '../../application/task_list_navigation.dart';
import '../widgets/history_search_field.dart';
import '../widgets/create_task_action_buttons.dart';
import '../widgets/resolve_file_tree.dart';
class CreateTaskWindowPage extends ConsumerStatefulWidget {
@@ -86,17 +89,28 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
String _configuredDownloadDirectory = '';
String _fileDataUri = '';
bool _programmaticUrlChange = false;
String _lastUrlText = '';
@override
void initState() {
super.initState();
_urlController.addListener(_handleUrlChanged);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final task = widget.initialTask ?? ref.read(pendingCreateTaskProvider);
_applyInitialTask(task);
if (widget.initialTask == null) {
ref.read(pendingCreateTaskProvider.notifier).clear();
}
if (widget.windowController == null && widget.initialTask == null) {
// Navigating to /create again reuses this page, so consume subsequent
// browser/share requests as well as the initial pending task.
ref.listenManual(pendingCreateTaskProvider, (_, next) {
if (next == null) return;
ref.read(pendingCreateTaskProvider.notifier).clear();
_applyInitialTask(next);
});
}
if (task == null || _urlController.text.trim().isEmpty) {
unawaited(_loadClipboardUrl());
}
@@ -161,10 +175,15 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
void _handleUrlChanged() {
if (!_programmaticUrlChange && _fileDataUri.isNotEmpty) {
_fileDataUri = '';
final urlText = _urlController.text;
if (urlText != _lastUrlText) {
_lastUrlText = urlText;
_renameController.clear();
if (!_programmaticUrlChange && _fileDataUri.isNotEmpty) {
_fileDataUri = '';
}
}
_recognizeMagnetUri(_urlController.text.trim());
_recognizeMagnetUri(urlText.trim());
}
void _applyInitialTask(CreateTask? task) {
@@ -173,6 +192,13 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
final opts = task.opts;
setState(() {
if (req?.url.isNotEmpty == true) {
_fileDataUri = '';
_renameController.clear();
_httpMethod = 'GET';
_httpBody = '';
_replaceHttpHeaders(const {'User-Agent': '', 'Cookie': '', 'Referer': ''});
_trackersController.clear();
_protocolTab = 0;
_urlController.text = req!.url;
_initialRawUrl = req.rawUrl;
_initialLabels = req.labels == null ? null : Map<String, String>.of(req.labels!);
@@ -202,9 +228,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
}
if (opts != null) {
if (opts.name.isNotEmpty) {
_renameController.text = opts.name;
}
if (opts.path.isNotEmpty) {
_directoryController.text = opts.path;
}
@@ -257,7 +280,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
final page = Scaffold(
backgroundColor: palette.sideBg,
child: Padding(
padding: EdgeInsets.only(top: AppWindowChrome.reservesHeaderInset ? AppDesignTokens.windowHeaderHeight : 0),
key: const ValueKey('create-task-safe-content'),
padding: EdgeInsets.only(
top: AppWindowChrome.reservesHeaderInset
? AppDesignTokens.windowHeaderHeight
: MediaQuery.paddingOf(context).top,
),
child: Column(
children: [
Container(
@@ -300,7 +328,8 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
children: [
SizedBox(
height: 120,
child: TextField(
child: AppTextField(
key: const ValueKey('create-task-url-input'),
controller: _urlController,
hintText: context.l10n.pasteDownloadLinks,
keyboardType: TextInputType.multiline,
@@ -346,18 +375,12 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
const SizedBox(height: 16),
_FormRow(
label: context.l10n.connections,
child: Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: AppDesignTokens.settingsNumberControlWidth,
child: AppNumberInput(
fieldKey: const ValueKey('create-task-connections-input'),
controller: _connectionsController,
min: 1,
max: 256,
hintText: context.l10n.enterCount,
),
),
child: AppNumberInput(
fieldKey: const ValueKey('create-task-connections-input'),
controller: _connectionsController,
min: 1,
max: 256,
hintText: context.l10n.enterCount,
),
),
const SizedBox(height: 16),
@@ -372,10 +395,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
pickerKey: const ValueKey('create-task-directory-picker'),
controller: _directoryController,
hintText: context.l10n.chooseDownloadDirectory,
filled: true,
border: Border.all(color: palette.border),
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
onChanged: (_) {
if (_asDefaultPath) {
setState(() => _asDefaultPath = false);
@@ -645,7 +664,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
label: context.l10n.trackers,
child: SizedBox(
height: 96,
child: TextField(
child: AppTextField(
controller: _trackersController,
hintText: context.l10n.oneTrackerPerLine,
keyboardType: TextInputType.multiline,
@@ -670,31 +689,27 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(24, 12, 24, 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: palette.border)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SecondaryButton(
onPressed: _creating ? null : _closeWindow,
child: SizedBox(width: 68, child: Center(child: Text(context.l10n.cancel))),
),
const SizedBox(width: 12),
AppPrimaryButton(
onPressed: _creating ? null : _confirm,
child: SizedBox(
width: 68,
child: Center(
child: _creating
? const SizedBox.square(dimension: 14, child: CircularProgressIndicator())
: Text(context.l10n.confirm),
),
SafeArea(
top: false,
child: Container(
padding: const EdgeInsets.fromLTRB(24, 12, 24, 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: palette.border)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CreateTaskActionButtons(
submitting: _creating,
onCancel: _closeWindow,
onSubmit: _confirm,
cancelLabel: context.l10n.cancel,
submitLabel: context.l10n.confirm,
cancelButtonKey: const ValueKey('create-task-cancel-button'),
submitButtonKey: const ValueKey('create-task-confirm-button'),
),
),
],
],
),
),
),
],
@@ -713,6 +728,21 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
await windowManager.close();
}
Future<void> _finishCreation() async {
if (widget.windowController != null) {
// Navigation is best-effort after a successful submission. A navigation
// failure must not leave a completed form available for resubmission.
try {
await ref.read(appCapabilitiesProvider).navigation.showDownloadingTasks();
} catch (error) {
debugPrint('Unable to select downloading tasks: $error');
}
} else {
ref.read(taskListNavigationProvider.notifier).showDownloading();
}
await _closeWindow();
}
Future<void> _loadDefaults() async {
try {
final config = await ref.read(gopeedServiceProvider).getConfig();
@@ -757,15 +787,10 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
Future<void> _pickTorrentFile() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: const ['torrent'],
withData: kIsWeb,
);
final file = result?.files.single;
final file = await FilePicker.pickFile(type: FileType.custom, allowedExtensions: const ['torrent']);
if (file == null) return;
await _applyTorrentFile(name: file.name, filePath: file.path, bytes: file.bytes);
await _applyTorrentFile(name: file.name, filePath: file.path, readBytes: file.readAsBytes);
}
Future<void> _handleDroppedTorrent(DropDoneDetails details) async {
@@ -844,7 +869,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
);
}),
);
await _closeWindow();
await _finishCreation();
return;
}
@@ -852,7 +877,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
final options = _buildOptions();
final result = await ref.read(gopeedServiceProvider).resolve(ResolveTask(req: request, opts: options));
if (!mounted) return;
_syncResolvedName(result);
final created = await _showResolveDialog(request, result);
if (!created) {
if (mounted) {
@@ -860,7 +884,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
}
return;
}
await _closeWindow();
await _finishCreation();
} catch (error) {
if (mounted) {
_showToast(error.toString());
@@ -1137,19 +1161,15 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
),
),
actions: [
SecondaryButton(
onPressed: submitting ? null : () => closeOverlay(dialogContext, false),
child: SizedBox(width: 68, child: Center(child: Text(dialogContext.l10n.cancel))),
),
AppPrimaryButton(
onPressed: submitting ? null : submit,
child: SizedBox(
width: 68,
child: Center(
child: submitting
? const SizedBox.square(dimension: 14, child: CircularProgressIndicator())
: Text(dialogContext.l10n.create),
),
flutter.Flexible(
child: CreateTaskActionButtons(
submitting: submitting,
onCancel: () => closeOverlay(dialogContext, false),
onSubmit: submit,
cancelLabel: dialogContext.l10n.cancel,
submitLabel: dialogContext.l10n.createAction,
cancelButtonKey: const ValueKey('resolve-cancel-button'),
submitButtonKey: const ValueKey('resolve-create-button'),
),
),
],
@@ -1192,7 +1212,7 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
width: contentWidth,
child: Row(
children: [
Expanded(child: Text(dialogContext.l10n.createHistory)),
Expanded(child: Text(dialogContext.l10n.historyLinks)),
AppTooltip(
message: dialogContext.l10n.clearHistory,
child: GhostButton(
@@ -1231,20 +1251,9 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
height: screenSize.height < 560 ? screenSize.height * 0.55 : 360,
child: Column(
children: [
SizedBox(
height: 38,
child: TextField(
key: const ValueKey('create-history-filter'),
controller: filterController,
placeholder: Text(
dialogContext.l10n.searchHistory,
style: TextStyle(color: palette.searchHint, fontSize: 13),
),
features: [
InputFeature.leading(Icon(Icons.search_rounded, size: 15, color: palette.textMuted)),
],
onChanged: (value) => setDialogState(() => filterQuery = value),
),
HistorySearchField(
controller: filterController,
onChanged: (value) => setDialogState(() => filterQuery = value),
),
const SizedBox(height: 10),
Expanded(
@@ -1312,12 +1321,6 @@ class _CreateTaskWindowPageState extends ConsumerState<CreateTaskWindowPage> {
filterController.dispose();
}
void _syncResolvedName(ResolveResult result) {
if (_renameController.text.trim().isEmpty && result.res.name.trim().isNotEmpty) {
_renameController.text = result.res.name;
}
}
void _setUrlText(String value, {String fileDataUri = ''}) {
_programmaticUrlChange = true;
_urlController.text = value;
@@ -1659,17 +1662,12 @@ class _WindowTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return TextField(
return AppTextField(
controller: controller,
hintText: hintText,
keyboardType: keyboardType,
inputFormatters: inputFormatters,
obscureText: obscureText,
filled: true,
border: Border.all(color: palette.border),
borderRadius: BorderRadius.circular(4),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
);
}
}
@@ -0,0 +1,56 @@
import 'package:flutter/widgets.dart' as flutter;
import 'package:shadcn_flutter/shadcn_flutter.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/widgets/app_loading_button.dart';
class CreateTaskActionButtons extends StatelessWidget {
const CreateTaskActionButtons({
super.key,
required this.submitting,
required this.onCancel,
required this.onSubmit,
required this.cancelLabel,
required this.submitLabel,
this.cancelButtonKey,
this.submitButtonKey,
});
final bool submitting;
final VoidCallback onCancel;
final VoidCallback onSubmit;
final String cancelLabel;
final String submitLabel;
final Key? cancelButtonKey;
final Key? submitButtonKey;
@override
Widget build(BuildContext context) {
return flutter.Row(
mainAxisSize: MainAxisSize.min,
children: [
SecondaryButton(
key: cancelButtonKey,
onPressed: submitting ? null : onCancel,
child: SizedBox(
width: _actionContentWidth,
child: Center(child: Text(cancelLabel)),
),
),
const SizedBox(width: AppDesignTokens.space12),
AppLoadingButton(
key: submitButtonKey,
onPressed: onSubmit,
loading: submitting,
variant: AppLoadingButtonVariant.primary,
child: SizedBox(
width: _actionContentWidth,
child: Center(child: Text(submitLabel)),
),
),
],
);
}
}
const _actionContentWidth = 68.0;
@@ -0,0 +1,38 @@
import 'package:shadcn_flutter/shadcn_flutter.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';
class HistorySearchField extends StatelessWidget {
const HistorySearchField({super.key, required this.controller, required this.onChanged});
final TextEditingController controller;
final ValueChanged<String> onChanged;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
const textStyle = TextStyle(fontSize: 13);
return ConstrainedBox(
// Allow large accessibility text to grow instead of clipping the line.
constraints: const BoxConstraints(minHeight: 38),
child: AppTextField(
key: const ValueKey('create-history-filter'),
controller: controller,
style: textStyle,
padding: AppDesignTokens.compactTextFieldPadding,
placeholder: Text(
context.l10n.searchHistory,
// Match the editable text metrics so the cursor and hint align.
style: textStyle.copyWith(color: palette.searchHint),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
features: [InputFeature.leading(Icon(Icons.search_rounded, size: 15, color: palette.textMuted))],
onChanged: onChanged,
),
);
}
}
@@ -61,6 +61,8 @@ class _ResolveFileTreeState extends State<ResolveFileTree> {
child: FileTreeView<int>(
items: _treeItems,
keyPrefix: 'resolve-tree',
rowHeight: _resolveTreeRowHeight,
contentTextStyle: _resolveFileNameStyle,
headerLeading: ExcludeFocus(
child: Checkbox(
state: allSelected
@@ -187,42 +189,48 @@ class _TreeFooter extends StatelessWidget {
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final filters = _FileTypeFilterGroup(
videoActive: activeTypeFilters.contains(_FileTypeFilter.video),
audioActive: activeTypeFilters.contains(_FileTypeFilter.audio),
imageActive: activeTypeFilters.contains(_FileTypeFilter.image),
onSelectVideo: onSelectVideo,
onSelectAudio: onSelectAudio,
onSelectImage: onSelectImage,
final filters = KeyedSubtree(
key: const ValueKey('resolve-tree-filters'),
child: _FileTypeFilterGroup(
videoActive: activeTypeFilters.contains(_FileTypeFilter.video),
audioActive: activeTypeFilters.contains(_FileTypeFilter.audio),
imageActive: activeTypeFilters.contains(_FileTypeFilter.image),
onSelectVideo: onSelectVideo,
onSelectAudio: onSelectAudio,
onSelectImage: onSelectImage,
),
);
final stats = Row(
mainAxisSize: MainAxisSize.min,
final statsStyle = TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600);
final selectedLabel = context.l10n.selectedCount(selectedCount, totalCount);
final sizeLabel = unknownSize ? context.l10n.unknownSize : Util.fmtByte(selectedSize);
final baseline = MediaQuery.textScalerOf(context).scale(statsStyle.fontSize!);
final stats = Wrap(
key: const ValueKey('resolve-tree-selection-stats'),
alignment: WrapAlignment.end,
spacing: AppDesignTokens.space8,
runSpacing: AppDesignTokens.space4,
crossAxisAlignment: WrapCrossAlignment.start,
children: [
Text(
context.l10n.selectedCount(selectedCount, totalCount),
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600),
Baseline(
baseline: baseline,
baselineType: TextBaseline.alphabetic,
child: Text(key: const ValueKey('resolve-tree-selected-count'), selectedLabel, style: statsStyle),
),
const SizedBox(width: 8),
Text(
unknownSize ? context.l10n.unknownSize : Util.fmtByte(selectedSize),
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600),
Baseline(
baseline: baseline,
baselineType: TextBaseline.alphabetic,
child: Text(key: const ValueKey('resolve-tree-selected-size'), sizeLabel, style: statsStyle),
),
],
);
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 360) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(alignment: Alignment.centerLeft, child: filters),
const SizedBox(height: 4),
Align(alignment: Alignment.centerRight, child: stats),
],
);
}
return Row(crossAxisAlignment: CrossAxisAlignment.center, children: [filters, const Spacer(), stats]);
},
return OverflowBar(
key: const ValueKey('resolve-tree-footer'),
spacing: AppDesignTokens.space8,
alignment: MainAxisAlignment.spaceBetween,
overflowAlignment: OverflowBarAlignment.end,
overflowSpacing: AppDesignTokens.space4,
children: [filters, stats],
);
}
}
@@ -288,7 +296,11 @@ class _FilterDivider extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(width: 1, height: 18, child: ColoredBox(color: color));
return SizedBox(
width: _fileTypeFilterDividerWidth,
height: 18,
child: ColoredBox(color: color),
);
}
}
@@ -303,7 +315,7 @@ class _FilterButton extends StatelessWidget {
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return SizedBox(
width: 40,
width: _fileTypeFilterButtonWidth,
height: 28,
child: DecoratedBox(
decoration: BoxDecoration(color: active ? palette.filterActiveBg : null),
@@ -336,3 +348,7 @@ extension on _FileTypeFilter {
const _videoExts = <String>{'mp4', 'mkv', 'avi', 'mov', 'wmv', 'flv', 'webm', 'm4v'};
const _audioExts = <String>{'mp3', 'flac', 'wav', 'aac', 'm4a', 'ogg', 'ape'};
const _imageExts = <String>{'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'};
const _resolveTreeRowHeight = 36.0;
const _resolveFileNameStyle = TextStyle(fontSize: 14, height: 1.25);
const _fileTypeFilterButtonWidth = 40.0;
const _fileTypeFilterDividerWidth = 1.0;
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../../core/window/app_window_chrome.dart';
import '../../../../../shared/theme/app_design_tokens.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../domain/task_record.dart';
@@ -224,7 +225,7 @@ class _ProgressContent extends StatelessWidget {
fillColor: fillColor,
highlightStartColor: fillColor,
highlightEndColor: fillColor,
shimmer: task.status == TaskStatus.downloading,
shimmer: task.status == TaskStatus.downloading && !task.waiting,
),
const SizedBox(height: 6),
TaskCardFooter(task: task, isError: isError),
@@ -237,7 +238,10 @@ class _ProgressContent extends StatelessWidget {
TaskStatus.downloading => [(Icons.pause, onPause), (Icons.close, onDelete)],
TaskStatus.paused => [(Icons.play_arrow, onResume), (Icons.close, onDelete)],
TaskStatus.failed => [(Icons.refresh, onResume), (Icons.delete_outline, onDelete)],
TaskStatus.completed => [(Icons.folder_open_outlined, null), (Icons.delete_outline, onDelete)],
TaskStatus.completed => [
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, null),
(Icons.delete_outline, onDelete),
],
};
return actions
@@ -306,7 +310,10 @@ class _CompletedContent extends StatelessWidget {
TaskStatus.downloading => [(Icons.pause, null), (Icons.close, onDelete)],
TaskStatus.paused => [(Icons.play_arrow, null), (Icons.close, onDelete)],
TaskStatus.failed => [(Icons.refresh, null), (Icons.delete_outline, onDelete)],
TaskStatus.completed => [(Icons.folder_open_outlined, onReveal), (Icons.delete_outline, onDelete)],
TaskStatus.completed => [
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, onReveal),
(Icons.delete_outline, onDelete),
],
};
return actions
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../../core/window/app_window_chrome.dart';
import '../../../../../shared/theme/app_design_tokens.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../domain/task_record.dart';
@@ -148,7 +149,7 @@ class _TaskCardMobileState extends State<TaskCardMobile> {
fillColor: fillColor,
highlightStartColor: fillColor,
highlightEndColor: fillColor,
shimmer: task.status == TaskStatus.downloading,
shimmer: task.status == TaskStatus.downloading && !task.waiting,
),
const SizedBox(height: 6),
TaskCardFooter(task: task, isError: task.status == TaskStatus.failed),
@@ -171,7 +172,10 @@ class _TaskCardMobileState extends State<TaskCardMobile> {
TaskStatus.downloading => [(Icons.pause, widget.onPause), (Icons.close, widget.onDelete)],
TaskStatus.paused => [(Icons.play_arrow, widget.onResume), (Icons.close, widget.onDelete)],
TaskStatus.failed => [(Icons.refresh, widget.onResume), (Icons.delete_outline, widget.onDelete)],
TaskStatus.completed => [(Icons.folder_open_outlined, widget.onReveal), (Icons.delete_outline, widget.onDelete)],
TaskStatus.completed => [
if (AppWindowChrome.isDesktopWindow) (Icons.folder_open_outlined, widget.onReveal),
(Icons.delete_outline, widget.onDelete),
],
};
return actions
@@ -95,14 +95,18 @@ class TaskCardFooter extends StatelessWidget {
children: [
Expanded(
child: Text(
task.total != null ? '${task.downloaded} / ${task.total}' : context.l10n.unknownSize,
task.total != null
? '${task.downloaded} / ${task.total}'
: task.downloadedBytes == 0
? context.l10n.unknownSize
: task.downloaded,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: leftColor, fontSize: 10, height: 1),
),
),
const SizedBox(width: 12),
if (task.speed != null && !isError) ...[
if (task.speed != null) ...[
_TaskTransferSpeed(icon: Icons.south, value: task.speed!, color: metaColor),
const SizedBox(width: 8),
TickDivider(color: palette.progressTrack),
@@ -0,0 +1,42 @@
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/widgets/app_primary_button.dart';
/// Shared creation action for task headers and empty-list guidance.
class TaskCreateButton extends StatelessWidget {
const TaskCreateButton({super.key, required this.onPressed, this.minHeight = 0, this.compact = false});
final VoidCallback onPressed;
final double minHeight;
final bool compact;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(minHeight: minHeight),
child: AppPrimaryButton(
onPressed: onPressed,
size: compact ? shad.ButtonSize.small : shad.ButtonSize.normal,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.add, size: compact ? 16 : null),
SizedBox(width: compact ? AppDesignTokens.space4 : AppDesignTokens.space8),
Flexible(
child: Text(
context.l10n.create,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: compact ? const TextStyle(fontSize: 13) : null,
),
),
],
),
),
);
}
}
@@ -1,7 +1,7 @@
import 'dart:async';
import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform, kIsWeb;
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/material.dart' show Colors, Icons, SelectionArea;
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
@@ -9,6 +9,7 @@ import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_copy_icon_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../shared/widgets/detail/app_detail_surface.dart';
import '../../../../core/utils/text_wrap.dart';
@@ -121,7 +122,7 @@ class _TaskDetailsViewState extends ConsumerState<TaskDetailsView> {
? AppDesignTokens.taskDetailsMobilePadding
: AppDesignTokens.taskDetailsDesktopPadding;
final runtimeStatus = _tabIndex == 1 ? ref.watch(taskRuntimeStatusProvider(widget.task.id)).value : null;
return Column(
final content = Column(
children: [
Container(
height: 48,
@@ -203,6 +204,7 @@ class _TaskDetailsViewState extends ConsumerState<TaskDetailsView> {
),
],
);
return SelectionArea(key: const ValueKey('task-details-selection-area'), child: content);
}
bool get _canOpenStoragePath {
@@ -512,7 +514,7 @@ class _EditableUrlBlock extends StatelessWidget {
children: [
SizedBox(
height: 76,
child: shad.TextField(
child: AppTextField(
controller: controller,
minLines: null,
maxLines: null,
@@ -0,0 +1,49 @@
import 'package:shadcn_flutter/shadcn_flutter.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_tooltip.dart';
/// Keeps the action inside the localized sentence, including RTL word order.
class TaskEmptyCreateHint extends StatelessWidget {
const TaskEmptyCreateHint({super.key, required this.onCreateTask});
final VoidCallback onCreateTask;
@override
Widget build(BuildContext context) {
const actionMarker = '\uFFFC';
final parts = context.l10n.emptyTaskCreateHint(actionMarker).split(actionMarker);
return Text.rich(
TextSpan(
children: [
TextSpan(text: parts.first.trimRight()),
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: AppTooltip(
message: context.l10n.create,
child: Semantics(
label: context.l10n.create,
child: SizedBox.square(
dimension: 30,
child: IconButton.outline(
key: const ValueKey('tasks-empty-create-button'),
density: ButtonDensity.compact,
onPressed: onCreateTask,
icon: const Icon(Icons.add, size: 16),
),
),
),
),
),
),
TextSpan(text: parts.last.trimLeft()),
],
),
textAlign: TextAlign.center,
style: TextStyle(color: AppPalette.of(context).textMuted, fontSize: 13),
);
}
}
@@ -1,35 +1,45 @@
import 'package:flutter/widgets.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import 'task_empty_create_hint.dart';
import '../../../../l10n/l10n.dart';
class TaskEmptyState extends StatelessWidget {
const TaskEmptyState({super.key, this.message});
const TaskEmptyState({super.key, this.message, this.onCreateTask});
final String? message;
final VoidCallback? onCreateTask;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 360),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CustomPaint(
key: const ValueKey('task-empty-illustration'),
size: const Size(148, 108),
painter: _TaskEmptyIllustrationPainter(palette: palette),
),
const SizedBox(height: 18),
Text(
message ?? context.l10n.emptyTaskList,
style: TextStyle(color: palette.textPrimary, fontSize: 17, fontWeight: FontWeight.w700),
),
],
child: SingleChildScrollView(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 360),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CustomPaint(
key: const ValueKey('task-empty-illustration'),
size: const Size(148, 108),
painter: _TaskEmptyIllustrationPainter(palette: palette),
),
const SizedBox(height: 18),
Text(
message ?? context.l10n.emptyTaskList,
textAlign: TextAlign.center,
style: TextStyle(color: palette.textPrimary, fontSize: 17, fontWeight: FontWeight.w700),
),
if (onCreateTask != null) ...[
const SizedBox(height: AppDesignTokens.space24),
TaskEmptyCreateHint(onCreateTask: onCreateTask!),
],
],
),
),
),
),
@@ -109,7 +109,7 @@ class _TaskFileManagerViewState extends State<TaskFileManagerView> {
try {
final renderBox = actionContext.findRenderObject();
final origin = renderBox is RenderBox ? renderBox.localToGlobal(Offset.zero) & renderBox.size : null;
await Share.shareXFiles([XFile(_localPath(entry))], sharePositionOrigin: origin);
await SharePlus.instance.share(ShareParams(files: [XFile(_localPath(entry))], sharePositionOrigin: origin));
} catch (error) {
if (mounted) showAppToast(context, error.toString(), type: AppToastType.error);
}
@@ -145,7 +145,7 @@ class _TaskDownloadProgress extends StatelessWidget {
key: const ValueKey('task-files-total-progress'),
value: progress,
indeterminate: runtime == null && task.isIndeterminate,
shimmer: task.status == TaskStatus.downloading,
shimmer: task.status == TaskStatus.downloading && !task.waiting,
height: 4,
trackColor: palette.progressTrack,
fillColor: palette.brandProgress,
@@ -4,6 +4,7 @@ import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_http_headers_editor.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../shared/widgets/app_text_field.dart';
import '../../../../l10n/l10n.dart';
import '../../domain/task_record.dart';
@@ -47,7 +48,7 @@ Future<TaskUrlUpdate?> showTaskUpdateUrlDialog(BuildContext context, TaskRecord
children: [
Text(dialogContext.l10n.downloadLink, style: TextStyle(color: palette.textPrimary, fontSize: 12)),
const SizedBox(height: 6),
TextField(controller: urlController),
AppTextField(controller: urlController),
const SizedBox(height: 18),
AppHttpHeadersEditor(
controller: headersController,