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

@@ -56,6 +56,7 @@ class ProtocolConfig {
HttpConfig http = HttpConfig();
BtConfig bt = BtConfig();
Ed2kConfig ed2k = Ed2kConfig();
HlsConfig hls = HlsConfig();
ProtocolConfig();
@@ -65,6 +66,25 @@ class ProtocolConfig {
Map<String, dynamic> toJson() => _$ProtocolConfigToJson(this);
}
@JsonSerializable()
class HlsConfig {
int segmentConnections;
int maxRetries;
int timeoutSeconds;
bool prefetchContentLength;
HlsConfig({
this.segmentConnections = 0,
this.maxRetries = 0,
this.timeoutSeconds = 0,
this.prefetchContentLength = false,
});
factory HlsConfig.fromJson(Map<String, dynamic> json) => _$HlsConfigFromJson(json);
Map<String, dynamic> toJson() => _$HlsConfigToJson(this);
}
@JsonSerializable()
class HttpConfig {
String userAgent;
@@ -125,6 +145,7 @@ class ExtraConfig {
bool notifyWhenNewVersion;
bool desktopNotification;
bool backgroundLocationKeepAlive;
bool backgroundContinuedProcessing;
WindowStateConfig windowState;
Map<String, String> bookmarks;
List<String> createHistory;
@@ -146,6 +167,7 @@ class ExtraConfig {
this.notifyWhenNewVersion = true,
this.desktopNotification = true,
this.backgroundLocationKeepAlive = false,
this.backgroundContinuedProcessing = false,
WindowStateConfig? windowState,
this.bookmarks = const {},
this.createHistory = const [],
@@ -56,12 +56,28 @@ Map<String, dynamic> _$ApiServerConfigToJson(ApiServerConfig instance) => <Strin
ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) => ProtocolConfig()
..http = HttpConfig.fromJson(json['http'] as Map<String, dynamic>)
..bt = BtConfig.fromJson(json['bt'] as Map<String, dynamic>)
..ed2k = Ed2kConfig.fromJson(json['ed2k'] as Map<String, dynamic>);
..ed2k = Ed2kConfig.fromJson(json['ed2k'] as Map<String, dynamic>)
..hls = HlsConfig.fromJson(json['hls'] as Map<String, dynamic>);
Map<String, dynamic> _$ProtocolConfigToJson(ProtocolConfig instance) => <String, dynamic>{
'http': instance.http.toJson(),
'bt': instance.bt.toJson(),
'ed2k': instance.ed2k.toJson(),
'hls': instance.hls.toJson(),
};
HlsConfig _$HlsConfigFromJson(Map<String, dynamic> json) => HlsConfig(
segmentConnections: (json['segmentConnections'] as num?)?.toInt() ?? 0,
maxRetries: (json['maxRetries'] as num?)?.toInt() ?? 0,
timeoutSeconds: (json['timeoutSeconds'] as num?)?.toInt() ?? 0,
prefetchContentLength: json['prefetchContentLength'] as bool? ?? false,
);
Map<String, dynamic> _$HlsConfigToJson(HlsConfig instance) => <String, dynamic>{
'segmentConnections': instance.segmentConnections,
'maxRetries': instance.maxRetries,
'timeoutSeconds': instance.timeoutSeconds,
'prefetchContentLength': instance.prefetchContentLength,
};
HttpConfig _$HttpConfigFromJson(Map<String, dynamic> json) => HttpConfig(
@@ -119,6 +135,10 @@ ExtraConfig _$ExtraConfigFromJson(Map<String, dynamic> json) =>
notifyWhenNewVersion: json['notifyWhenNewVersion'] as bool? ?? true,
desktopNotification: json['desktopNotification'] as bool? ?? true,
backgroundLocationKeepAlive: json['backgroundLocationKeepAlive'] as bool? ?? false,
backgroundContinuedProcessing:
json['backgroundContinuedProcessing']
as bool? ??
false,
windowState: json['windowState'] == null
? null
: WindowStateConfig.fromJson(json['windowState'] as Map<String, dynamic>?),
@@ -146,6 +166,8 @@ Map<String, dynamic> _$ExtraConfigToJson(ExtraConfig instance) => <String, dynam
'notifyWhenNewVersion': instance.notifyWhenNewVersion,
'desktopNotification': instance.desktopNotification,
'backgroundLocationKeepAlive': instance.backgroundLocationKeepAlive,
'backgroundContinuedProcessing':
instance.backgroundContinuedProcessing,
'windowState': instance.windowState.toJson(),
'bookmarks': instance.bookmarks,
'createHistory': instance.createHistory,
+1 -1
View File
@@ -6,7 +6,7 @@ part 'task.g.dart';
enum Status { ready, running, pause, wait, error, done }
enum Protocol { http, bt, ed2k }
enum Protocol { http, bt, ed2k, hls }
// ExtractStatus enum matching Go backend
enum ExtractStatus {
+1 -1
View File
@@ -38,7 +38,7 @@ const _$StatusEnumMap = {
Status.done: 'done',
};
const _$ProtocolEnumMap = {Protocol.http: 'http', Protocol.bt: 'bt', Protocol.ed2k: 'ed2k'};
const _$ProtocolEnumMap = {Protocol.http: 'http', Protocol.bt: 'bt', Protocol.ed2k: 'ed2k', Protocol.hls: 'hls'};
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
used: (json['used'] as num).toInt(),
+1 -1
View File
@@ -55,7 +55,7 @@ sealed class TaskStats {
Protocol.http => HttpTaskStats.fromJson(snapshot),
Protocol.bt => BtTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
Protocol.ed2k => Ed2kTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
null => null,
Protocol.hls || null => null,
};
}
}
+2 -1
View File
@@ -78,7 +78,8 @@ class _GopeedAppState extends ConsumerState<GopeedApp> with WidgetsBindingObserv
return shad.ShadcnApp.router(
debugShowCheckedModeBanner: false,
onGenerateTitle: (context) => context.l10n.appTitle,
disableBrowserContextMenu: false,
title: 'Gopeed',
theme: AppTheme.light(themeColor),
darkTheme: AppTheme.dark(themeColor),
materialTheme: isLightTheme ? AppTheme.materialLight(themeColor) : AppTheme.materialDark(themeColor),
@@ -28,6 +28,13 @@ class AndroidForegroundService {
),
);
// Android 13+ requires runtime permission to show the service notification.
// A denial only hides it from the notification drawer; the service can run.
final permission = await FlutterForegroundTask.checkNotificationPermission();
if (permission == NotificationPermission.denied) {
await FlutterForegroundTask.requestNotificationPermission();
}
if (await FlutterForegroundTask.isRunningService) {
_throwOnFailure(await FlutterForegroundTask.restartService());
return;
@@ -37,10 +37,15 @@ class AppDeepLinkController extends AsyncNotifier<AppDeepLinkState> {
@override
Future<AppDeepLinkState> build() async {
final runtime = ref.watch(appRuntimeControllerProvider).value;
if (runtime == null || _started || kIsWeb) {
if (_started || kIsWeb) {
return AppDeepLinkState(started: _started);
}
// Deep-link handling depends on the runtime being ready, but it must not
// rebuild whenever runtime settings change. A rebuild disposes the active
// platform subscriptions while `_started` remains true, leaving Android
// unable to receive later browser takeover intents (for example after the
// API server is started or stopped from Settings).
await ref.read(appRuntimeControllerProvider.future);
_started = true;
final appLinks = AppLinks();
_subscription = appLinks.uriLinkStream.listen((uri) {
@@ -139,7 +144,7 @@ class AppDeepLinkController extends AsyncNotifier<AppDeepLinkState> {
Map<String, dynamic> _decodeParams(String params) {
final safeParams = params.replaceAll('"', '').replaceAll(' ', '+');
final paramsJson = String.fromCharCodes(base64Decode(base64.normalize(safeParams)));
final paramsJson = utf8.decode(base64Decode(base64.normalize(safeParams)));
return jsonDecode(paramsJson) as Map<String, dynamic>;
}
@@ -2,14 +2,14 @@ import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../../core/common/task_event.dart';
import '../../core/libgopeed_boot.dart';
import '../../l10n/l10n.dart';
import '../../util/log_util.dart';
import '../../util/util.dart';
import 'app_runtime_controller.dart';
@@ -28,13 +28,19 @@ class AppNotificationController extends AsyncNotifier<AppNotificationState> {
StreamSubscription<TaskEvent>? _taskEventSubscription;
var _notificationId = 0;
@visibleForTesting
Stream<TaskEvent> get taskEvents => LibgopeedBoot.instance.taskEvents;
@override
Future<AppNotificationState> build() async {
final runtime = ref.watch(appRuntimeControllerProvider).value;
if (runtime == null || kIsWeb || !Util.isDesktop()) {
return const AppNotificationState();
}
await _initNotifications(appLocalizationsFor(runtime.downloaderConfig.extra.locale));
await _initNotifications(
appLocalizationsFor(runtime.downloaderConfig.extra.locale),
requestPermissions: runtime.downloaderConfig.extra.desktopNotification,
);
_listenTaskEvents();
ref.onDispose(() {
unawaited(_taskEventSubscription?.cancel());
@@ -42,11 +48,13 @@ class AppNotificationController extends AsyncNotifier<AppNotificationState> {
return const AppNotificationState(started: true);
}
Future<void> _initNotifications(AppLocalizations locale) async {
const darwin = DarwinInitializationSettings(
requestAlertPermission: false,
Future<void> _initNotifications(AppLocalizations locale, {required bool requestPermissions}) async {
// The runtime is watched, so enabling notifications in settings also
// requests authorization. macOS remembers previously granted/denied access.
final darwin = DarwinInitializationSettings(
requestAlertPermission: requestPermissions,
requestBadgePermission: false,
requestSoundPermission: false,
requestSoundPermission: requestPermissions,
);
final linux = LinuxInitializationSettings(
defaultActionName: locale.open,
@@ -56,13 +64,27 @@ class AppNotificationController extends AsyncNotifier<AppNotificationState> {
String? windowsIconPath;
try {
if (Util.isWindows()) {
final byteData = await rootBundle.load('assets/icon/icon.ico');
final tempDir = await getTemporaryDirectory();
final file = File('${tempDir.path}/notification_icon.ico');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
windowsIconPath = file.path;
// Windows requires a file path for IconUri, so use the bundled PNG
// beside the executable rather than copying it to another directory.
final file = File(
path.join(
path.dirname(Platform.resolvedExecutable),
'data',
'flutter_assets',
'assets',
'icon',
'icon_512.png',
),
);
if (await file.exists()) {
windowsIconPath = file.absolute.path;
} else {
logger.w('Windows notification icon not found: ${file.path}');
}
}
} catch (_) {}
} catch (error, stackTrace) {
logger.w('prepare Windows notification icon failed', error, stackTrace);
}
final windows = WindowsInitializationSettings(
appName: 'Gopeed',
@@ -78,7 +100,7 @@ class AppNotificationController extends AsyncNotifier<AppNotificationState> {
void _listenTaskEvents() {
_taskEventSubscription?.cancel();
_taskEventSubscription = LibgopeedBoot.instance.taskEvents.listen((event) async {
_taskEventSubscription = taskEvents.listen((event) async {
final runtime = ref.read(appRuntimeControllerProvider).value;
if (runtime?.downloaderConfig.extra.desktopNotification == false) return;
final locale = appLocalizationsFor(runtime?.downloaderConfig.extra.locale ?? '');
@@ -54,6 +54,9 @@ class AppPlatformState {
enum AppUpdateStatus { idle, checking, upToDate, available, failed }
class AppPlatformController extends AsyncNotifier<AppPlatformState> with WindowListener, TrayListener {
@protected
bool get isDesktop => Util.isDesktop();
bool _started = false;
String? _trayLocaleConfig;
bool _updateInitialized = false;
@@ -74,30 +77,54 @@ class AppPlatformController extends AsyncNotifier<AppPlatformState> with WindowL
@override
Future<AppPlatformState> build() async {
final runtime = ref.watch(appRuntimeControllerProvider).value;
if (runtime == null || kIsWeb) {
return _snapshot();
}
if (!Util.isDesktop()) {
_scheduleInitialUpdateCheck();
return _snapshot();
}
if (_started) {
final localeConfig = runtime.downloaderConfig.extra.locale;
if (_trayLocaleConfig != localeConfig) await _initTray();
return _snapshot();
}
await _start();
_scheduleInitialUpdateCheck();
ref.listen(appRuntimeControllerProvider, (_, next) {
unawaited(
_handleRuntimeChange(next.value).catchError((Object error, StackTrace stackTrace) {
if (ref.mounted) state = AsyncValue.error(error, stackTrace);
}),
);
});
ref.onDispose(() {
if (!_started) return;
_started = false;
windowManager.removeListener(this);
trayManager.removeListener(this);
unawaited(HostRpcService.instance.stop());
unawaited(AppWindowCapabilityHost.instance.stop());
});
final runtime = ref.read(appRuntimeControllerProvider).value;
if (runtime == null || kIsWeb) {
return _snapshot();
}
if (!isDesktop) {
_scheduleInitialUpdateCheck();
return _snapshot();
}
if (_started) {
return _snapshot();
}
await _start();
_scheduleInitialUpdateCheck();
return _snapshot();
}
Future<void> _handleRuntimeChange(AppRuntimeState? runtime) async {
if (runtime == null || kIsWeb) return;
if (!isDesktop) {
_scheduleInitialUpdateCheck();
return;
}
if (!_started) {
await _start();
_scheduleInitialUpdateCheck();
_emit();
return;
}
if (_trayLocaleConfig != runtime.downloaderConfig.extra.locale) {
await _initTray();
}
}
void _scheduleInitialUpdateCheck() {
if (_updateInitialized) return;
_updateInitialized = true;
@@ -23,6 +23,7 @@ import '../../util/util.dart';
import '../rpc/webview_rpc_service.dart';
import 'android_foreground_service.dart';
import 'location_keep_alive.dart';
import 'continued_processing.dart';
const unixSocketPath = 'gopeed.sock';
@@ -105,8 +106,14 @@ class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
),
);
unawaited(LocationKeepAliveCoordinator.instance.reconcile(enabled: config.extra.backgroundLocationKeepAlive));
unawaited(
ContinuedProcessing.setEnabled(
config.extra.backgroundContinuedProcessing,
),
);
}
Future<AppRuntimeState> _init() async {
await AppInitializer.ensureStorageInitialized();
try {
@@ -180,6 +187,13 @@ class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
startupError: startupError,
);
if (Util.isIOS()) {
// Make sure the native Continued Processing manager has the
// persisted setting before app initialization completes. This
// avoids the first download racing ahead of setEnabled(true).
await ContinuedProcessing.setEnabled(
config.extra.backgroundContinuedProcessing,
);
LocationKeepAliveCoordinator.instance.start(
() =>
state.value?.downloaderConfig.extra.backgroundLocationKeepAlive ?? config.extra.backgroundLocationKeepAlive,
@@ -0,0 +1,39 @@
import 'dart:io';
import 'package:flutter/services.dart';
class ContinuedProcessing {
const ContinuedProcessing._();
static const _channel =
MethodChannel('gopeed/continued_processing');
static Future<bool> isSupported() async {
if (!Platform.isIOS) return false;
try {
return await _channel.invokeMethod<bool>(
'isSupported',
) ??
false;
} catch (_) {
return false;
}
}
static Future<bool> setEnabled(
bool enabled,
) async {
if (!Platform.isIOS) return false;
try {
return await _channel.invokeMethod<bool>(
'setEnabled',
{'enabled': enabled},
) ??
false;
} catch (_) {
return false;
}
}
}
+61 -32
View File
@@ -1,5 +1,8 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../features/tasks/application/task_list_navigation.dart';
import '../../features/extensions/presentation/pages/extensions_page.dart';
import '../../features/extensions/presentation/pages/extension_details_page.dart';
@@ -13,11 +16,50 @@ import '../../features/tasks/domain/task_record.dart';
import '../../features/tasks/presentation/pages/task_details_page.dart';
import '../../features/tasks/presentation/pages/task_files_page.dart';
import 'shells/main_shell.dart';
import 'mobile_exit_guard.dart';
import 'runtime_page.dart';
class AppRouter {
static final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
static void showDownloadingTasks() {
final context = rootNavigatorKey.currentContext;
if (context == null || !context.mounted) return;
ProviderScope.containerOf(context, listen: false).read(taskListNavigationProvider.notifier).showDownloading();
GoRouter.of(context).go('/');
}
static GoRouter build(WebAuthController webAuthController) {
// Keep desktop and web sections as peers; native mobile retains home below them.
final isMobile =
!kIsWeb && (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS);
final sectionRoutes = [
GoRoute(
path: isMobile ? 'extensions' : '/extensions',
builder: _runtimePage((context, state) => const ExtensionsPage()),
routes: [
GoRoute(
path: ':id',
builder: _runtimePage(
(context, state) => ExtensionDetailsPage(
extensionId: state.pathParameters['id'] ?? '',
initialItem: state.extra is ExtensionListItem ? state.extra as ExtensionListItem : null,
),
),
),
],
),
GoRoute(
path: isMobile ? 'settings' : '/settings',
builder: _runtimePage((context, state) => const SettingsPage()),
routes: [
GoRoute(
path: ':section',
builder: _runtimePage((context, state) => SettingsPage(sectionKey: state.pathParameters['section'])),
),
],
),
];
return GoRouter(
navigatorKey: rootNavigatorKey,
refreshListenable: webAuthController,
@@ -35,60 +77,47 @@ class AppRouter {
routes: [
GoRoute(path: '/login', parentNavigatorKey: rootNavigatorKey, builder: (context, state) => const LoginPage()),
ShellRoute(
builder: (context, state, child) => MainShell(child: child),
builder: (context, state, child) => MobileExitGuard(child: MainShell(child: child)),
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
builder: _runtimePage((context, state) => const HomePage()),
routes: [
GoRoute(path: 'create', builder: (context, state) => const CreateTaskWindowPage()),
GoRoute(path: 'create', builder: _runtimePage((context, state) => const CreateTaskWindowPage())),
GoRoute(
path: 'tasks/:id',
builder: (context, state) => TaskDetailsPage(
taskId: state.pathParameters['id'] ?? '',
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
builder: _runtimePage(
(context, state) => TaskDetailsPage(
taskId: state.pathParameters['id'] ?? '',
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
),
),
routes: [
GoRoute(
path: 'files',
builder: (context, state) => TaskFilesPage(
taskId: state.pathParameters['id'] ?? '',
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
builder: _runtimePage(
(context, state) => TaskFilesPage(
taskId: state.pathParameters['id'] ?? '',
initialTask: state.extra is TaskRecord ? state.extra as TaskRecord : null,
),
),
),
],
),
if (isMobile) ...sectionRoutes,
],
),
GoRoute(
path: '/extensions',
builder: (context, state) => const ExtensionsPage(),
routes: [
GoRoute(
path: ':id',
builder: (context, state) => ExtensionDetailsPage(
extensionId: state.pathParameters['id'] ?? '',
initialItem: state.extra is ExtensionListItem ? state.extra as ExtensionListItem : null,
),
),
],
),
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsPage(),
routes: [
GoRoute(
path: ':section',
builder: (context, state) => SettingsPage(sectionKey: state.pathParameters['section']),
),
],
),
if (!isMobile) ...sectionRoutes,
],
),
],
);
}
static GoRouterWidgetBuilder _runtimePage(GoRouterWidgetBuilder builder) {
return (context, state) => RuntimePage(builder: (context) => builder(context, state));
}
static String _safeReturnLocation(String? location) {
if (location == null || location.isEmpty) return '/';
final uri = Uri.tryParse(location);
@@ -0,0 +1,61 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import '../../shared/navigation/app_exit_confirmation_controller.dart';
/// Handles exit at the shell route after the nested Navigator declines a pop.
/// Child routes and dialogs still pop through GoRouter before reaching this guard.
class MobileExitGuard extends StatefulWidget {
const MobileExitGuard({super.key, required this.child});
final Widget child;
@override
State<MobileExitGuard> createState() => _MobileExitGuardState();
}
class _MobileExitGuardState extends State<MobileExitGuard> with WidgetsBindingObserver {
final _controller = AppExitConfirmationController();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) _controller.dispose();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return widget.child;
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) unawaited(_controller.handleBack(context));
},
child: NotificationListener<NavigationNotification>(
onNotification: (notification) {
if (notification.canHandlePop) return false;
// An empty nested back stack still has this shell's exit guard.
// Otherwise its startup notification disables Android's back callback.
const NavigationNotification(canHandlePop: true).dispatch(context);
return true;
},
child: widget.child,
),
);
}
}
@@ -0,0 +1,30 @@
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../application/app_runtime_controller.dart';
import '../../l10n/l10n.dart';
/// Gates page content without unmounting the Navigator during startup.
class RuntimePage extends ConsumerWidget {
const RuntimePage({super.key, required this.builder});
final WidgetBuilder builder;
@override
Widget build(BuildContext context, WidgetRef ref) {
return ref
.watch(appRuntimeControllerProvider)
.when(
loading: () => const Scaffold(child: Center(child: CircularProgressIndicator())),
error: (error, _) => Scaffold(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: Text(context.l10n.runtimeInitializationFailed(error.toString()), textAlign: TextAlign.center),
),
),
),
data: (_) => builder(context),
);
}
}
@@ -4,7 +4,6 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../api/model/create_task.dart';
import '../../application/app_deep_link_controller.dart';
@@ -16,10 +15,7 @@ import '../../../features/tasks/application/pending_create_task.dart';
import '../../../features/tasks/application/pending_update_task.dart';
import '../../../features/tasks/application/tasks_controller.dart';
import '../../../features/tasks/presentation/widgets/pending_update_dialog.dart';
import '../../../l10n/l10n.dart';
import '../../../core/window/app_window_launcher.dart';
import '../../../core/utils/breakpoints.dart';
import '../../../shared/navigation/app_exit_confirmation_controller.dart';
import '../../../shared/widgets/app_toast.dart';
class MainShell extends ConsumerStatefulWidget {
@@ -34,7 +30,6 @@ class MainShell extends ConsumerStatefulWidget {
class _MainShellState extends ConsumerState<MainShell> {
String? _shownUpdateVersion;
bool _handlingPendingUpdateRequest = false;
final _exitConfirmationController = AppExitConfirmationController();
@override
Widget build(BuildContext context) {
@@ -65,40 +60,13 @@ class _MainShellState extends ConsumerState<MainShell> {
}
});
final runtime = ref.watch(appRuntimeControllerProvider);
final content = runtime.when(
loading: () => const shad.Scaffold(child: Center(child: shad.CircularProgressIndicator())),
error: (error, _) => shad.Scaffold(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: Text(context.l10n.runtimeInitializationFailed(error.toString()), textAlign: TextAlign.center),
),
),
),
data: (_) {
ref.watch(appPlatformControllerProvider);
ref.watch(appDeepLinkControllerProvider);
ref.watch(appNotificationControllerProvider);
return widget.child;
},
);
return _buildMobileBackGuard(context, content);
}
Widget _buildMobileBackGuard(BuildContext context, Widget child) {
final isAndroidMobile =
!kIsWeb &&
defaultTargetPlatform == TargetPlatform.android &&
MediaQuery.sizeOf(context).width < Breakpoints.mobile;
if (!isAndroidMobile || context.canPop()) return child;
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) unawaited(_exitConfirmationController.handleBack(context));
},
child: child,
);
if (runtime.hasValue) {
ref.watch(appPlatformControllerProvider);
ref.watch(appDeepLinkControllerProvider);
ref.watch(appNotificationControllerProvider);
}
// Keep the nested Navigator mounted even while the runtime is starting.
return widget.child;
}
void _schedulePendingUpdateRequest(PendingUpdateRequest request) {
@@ -3,6 +3,7 @@ import 'dart:collection';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import '../../core/common/start_config.dart';
@@ -73,7 +74,6 @@ class WebViewRpcService {
final Map<String, WebViewRpcPageSession> _pagesById = {};
final Completer<void> _overlayReady = Completer<void>();
late final CookieManager _cookieManager = CookieManager.instance();
RpcServerHandle? _server;
int _pageSeq = 0;
@@ -129,6 +129,9 @@ class WebViewRpcService {
switch (method) {
case 'webview.isAvailable':
return {'available': true};
case 'profile.remove':
await _removeProfile(_string(params, 'profileId'));
return {};
case 'page.open':
return _openPage(params);
case 'page.addInitScript':
@@ -162,10 +165,12 @@ class WebViewRpcService {
}
Future<Map<String, dynamic>> _openPage(Map<String, dynamic> params) async {
final profile = WebViewProfile(_string(params, 'profileId'));
await profile.prepare(proxyUrl: Uri.parse(_string(params, 'proxyUrl')));
final pageId = 'page-${++_pageSeq}';
final session = WebViewRpcPageSession(
pageId: pageId,
cookieManager: _cookieManager,
profile: profile,
headless: params['headless'] as bool? ?? false,
debug: params['debug'] as bool? ?? false,
title: params['title'] as String? ?? '',
@@ -185,6 +190,15 @@ class WebViewRpcService {
return {'pageId': pageId};
}
Future<void> _removeProfile(String id) async {
for (final page in _pagesById.values.where((page) => page.profile.id == id).toList()) {
await _closePage(page.pageId);
}
// Let visible platform views unmount before releasing their native store.
await WidgetsBinding.instance.endOfFrame;
await WebViewProfile(id).remove();
}
WebViewRpcPageSession _page(Map<String, dynamic> params) {
final page = _pagesById[_pageId(params)];
if (page == null) {
@@ -271,6 +285,9 @@ class WebViewRpcService {
if (error is WebViewRpcException) {
return {'code': error.code, 'message': error.message};
}
if (error is PlatformException && error.code == 'UNAVAILABLE') {
return {'code': error.code, 'message': error.message ?? 'WebView is unavailable'};
}
final code = switch (method) {
'page.goto' => 'NAVIGATION_FAILED',
'page.execute' => 'EVALUATION_FAILED',
@@ -283,7 +300,7 @@ class WebViewRpcService {
class WebViewRpcPageSession {
WebViewRpcPageSession({
required this.pageId,
required this.cookieManager,
required this.profile,
required this.headless,
required this.debug,
required this.title,
@@ -293,7 +310,8 @@ class WebViewRpcPageSession {
});
final String pageId;
final CookieManager cookieManager;
final WebViewProfile profile;
late final CookieManager cookieManager = profile.cookieManager;
final bool headless;
final bool debug;
final String title;
@@ -449,6 +467,8 @@ class WebViewRpcPageSession {
'path': cookie.path ?? '/',
'secure': cookie.isSecure,
'httpOnly': cookie.isHttpOnly,
if (cookie.expiresDate != null)
'expires': DateTime.fromMillisecondsSinceEpoch(cookie.expiresDate!, isUtc: true).toIso8601String(),
};
})
.toList(growable: false);
@@ -524,6 +544,7 @@ class WebViewRpcPageSession {
}
InAppWebViewSettings get _settings => InAppWebViewSettings(
profileId: profile.id,
javaScriptEnabled: true,
transparentBackground: true,
isInspectable: debug,
@@ -16,12 +16,18 @@ import '../window/app_window_appearance.dart';
import 'capability_rpc.dart';
import 'gopeed_capability.dart';
import 'storage_capability.dart';
import 'app_navigation_capability.dart';
import '../../app/router/app_router.dart';
class AppCapabilities {
AppCapabilities(CapabilityInvoker invoker) : gopeed = GopeedService(invoker), storage = AppStorageService(invoker);
AppCapabilities(CapabilityInvoker invoker)
: gopeed = GopeedService(invoker),
storage = AppStorageService(invoker),
navigation = AppNavigationService(invoker);
final GopeedService gopeed;
final AppStorageService storage;
final AppNavigationService navigation;
}
class LocalAppCapabilities {
@@ -29,6 +35,10 @@ class LocalAppCapabilities {
registry = CapabilityRegistry(codecs);
_bindGopeed(registry);
_bindStorage(registry);
registry.bind(NavigationMethods.showDownloadingTasks, (_) {
AppRouter.showDownloadingTasks();
return const RpcUnit();
});
capabilities = AppCapabilities(LocalCapabilityInvoker(registry));
}
@@ -0,0 +1,15 @@
import 'capability_rpc.dart';
abstract final class NavigationMethods {
static const showDownloadingTasks = RpcMethod<RpcUnit, RpcUnit>('navigation.tasks.downloading');
}
class AppNavigationService {
const AppNavigationService(this._invoker);
final CapabilityInvoker _invoker;
Future<void> showDownloadingTasks() async {
await _invoker.invoke(NavigationMethods.showDownloadingTasks, const RpcUnit());
}
}
@@ -11,6 +11,7 @@ import 'task_event.dart';
class LibgopeedChannel implements LibgopeedInterface {
static const _channel = MethodChannel('gopeed.com/libgopeed');
final _taskEvents = StreamController<TaskEvent>.broadcast();
int _requestID = 0;
LibgopeedChannel() {
_channel.setMethodCallHandler((call) async {
@@ -50,7 +51,9 @@ class LibgopeedChannel implements LibgopeedInterface {
@override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final requestID = _requestID++;
final result = await _channel.invokeMethod<String>('invoke', {
'requestID': requestID,
'method': method,
'path': path,
'query': query,
+10 -64
View File
@@ -1,10 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import '../ffi/libgopeed_bind.dart';
import '../ffi/libgopeed_worker.dart';
import 'api_server_state.dart';
import 'libgopeed_interface.dart';
@@ -12,51 +8,22 @@ import 'start_config.dart';
import 'task_event.dart';
class LibgopeedFFi implements LibgopeedInterface {
late LibgopeedBind _libgopeed;
LibgopeedFFi() {
_worker.taskEvents.listen(_onTaskEvent, onError: _taskEvents.addError);
}
final _taskEvents = StreamController<TaskEvent>.broadcast();
final _worker = LibgopeedWorker();
late final NativeCallable<Void Function(Pointer<Char>)> _taskEventCallback;
LibgopeedFFi(LibgopeedBind libgopeed) {
_libgopeed = libgopeed;
_taskEventCallback = NativeCallable<Void Function(Pointer<Char>)>.listener(_onTaskEvent);
}
void _onTaskEvent(Pointer<Char> payload) {
try {
final decoded = jsonDecode(payload.cast<Utf8>().toDartString()) as Map<String, dynamic>;
_taskEvents.add(TaskEvent.fromJson(decoded));
} finally {
_libgopeed.FreeCString(payload);
}
void _onTaskEvent(Map<String, dynamic> payload) {
_taskEvents.add(TaskEvent.fromJson(payload));
}
@override
Future<int> start(StartConfig cfg) {
var completer = Completer<int>();
final cfgPtr = jsonEncode(cfg).toNativeUtf8();
try {
final result = _libgopeed.Start(cfgPtr.cast());
if (result.r1 != nullptr) {
final message = result.r1.cast<Utf8>().toDartString();
_libgopeed.FreeCString(result.r1);
completer.completeError(Exception(message));
} else {
completer.complete(result.r0);
}
} finally {
malloc.free(cfgPtr);
}
return completer.future;
}
Future<int> start(StartConfig cfg) => _worker.start(jsonEncode(cfg));
@override
Future<void> stop() {
var completer = Completer<void>();
_libgopeed.Stop();
completer.complete();
return completer.future;
}
Future<void> stop() => _worker.stop();
Future<ApiServerOperationResult> _apiServerOperation(String operation) async {
final payload = await _worker.apiServer(operation);
@@ -77,33 +44,12 @@ class LibgopeedFFi implements LibgopeedInterface {
@override
Future<String> invoke(String method, String path, {String query = '', String body = ''}) async {
final methodPtr = method.toNativeUtf8();
final pathPtr = path.toNativeUtf8();
final queryPtr = query.toNativeUtf8();
final bodyPtr = body.toNativeUtf8();
Pointer<Char>? resultPtr;
try {
resultPtr = _libgopeed.Invoke(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast());
if (resultPtr == nullptr) {
throw StateError('Gopeed Invoke returned a null response');
}
return resultPtr.cast<Utf8>().toDartString();
} finally {
malloc.free(methodPtr);
malloc.free(pathPtr);
malloc.free(queryPtr);
malloc.free(bodyPtr);
if (resultPtr != null && resultPtr != nullptr) {
_libgopeed.FreeCString(resultPtr);
}
}
return jsonEncode(await _worker.invoke(method, path, query, body));
}
@override
Stream<TaskEvent> get taskEvents => _taskEvents.stream;
@override
Future<void> subscribeTaskEvents(Set<TaskEventType> events) async {
_libgopeed.SubscribeTaskEvents(events.mask, events.isEmpty ? 0 : _taskEventCallback.nativeFunction.address);
}
Future<void> subscribeTaskEvents(Set<TaskEventType> events) => _worker.subscribeTaskEvents(events.mask);
}
@@ -1,6 +1,4 @@
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import '../../util/util.dart';
import '../common/libgopeed_channel.dart';
@@ -9,7 +7,6 @@ import '../common/libgopeed_interface.dart';
import '../common/api_server_state.dart';
import '../common/start_config.dart';
import '../common/task_event.dart';
import '../ffi/libgopeed_bind.dart';
import '../libgopeed_boot.dart';
LibgopeedBoot create() => LibgopeedBootNative();
@@ -19,17 +16,7 @@ class LibgopeedBootNative implements LibgopeedBoot {
LibgopeedBootNative() {
if (Util.isDesktop()) {
var libName = "libgopeed.";
if (Platform.isWindows) {
libName += "dll";
}
if (Platform.isMacOS) {
libName += "dylib";
}
if (Platform.isLinux) {
libName += "so";
}
_libgopeed = LibgopeedFFi(LibgopeedBind(DynamicLibrary.open(libName)));
_libgopeed = LibgopeedFFi();
} else {
_libgopeed = LibgopeedChannel();
}
+28 -15
View File
@@ -30,53 +30,67 @@ class LibgopeedBind {
late final _StopPtr = _lookup<ffi.NativeFunction<ffi.Void Function()>>('Stop');
late final _Stop = _StopPtr.asFunction<void Function()>();
ffi.Pointer<ffi.Char> GetAPIServerState() => _GetAPIServerState();
ffi.Pointer<ffi.Char> GetAPIServerState() {
return _GetAPIServerState();
}
late final _GetAPIServerStatePtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('GetAPIServerState');
late final _GetAPIServerState = _GetAPIServerStatePtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> StartAPIServer() => _StartAPIServer();
ffi.Pointer<ffi.Char> StartAPIServer() {
return _StartAPIServer();
}
late final _StartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StartAPIServer');
late final _StartAPIServer = _StartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> StopAPIServer() => _StopAPIServer();
ffi.Pointer<ffi.Char> StopAPIServer() {
return _StopAPIServer();
}
late final _StopAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('StopAPIServer');
late final _StopAPIServer = _StopAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> RestartAPIServer() => _RestartAPIServer();
ffi.Pointer<ffi.Char> RestartAPIServer() {
return _RestartAPIServer();
}
late final _RestartAPIServerPtr = _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function()>>('RestartAPIServer');
late final _RestartAPIServer = _RestartAPIServerPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();
ffi.Pointer<ffi.Char> Invoke(
void InvokeAsync(
ffi.Pointer<ffi.Char> method,
ffi.Pointer<ffi.Char> path,
ffi.Pointer<ffi.Char> query,
ffi.Pointer<ffi.Char> body,
int requestID,
int callback,
) {
return _Invoke(method, path, query, body);
return _InvokeAsync(method, path, query, body, requestID, callback);
}
late final _InvokePtr =
late final _InvokeAsyncPtr =
_lookup<
ffi.NativeFunction<
ffi.Pointer<ffi.Char> Function(
ffi.Void Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.UnsignedLongLong,
ffi.UintPtr,
)
>
>('Invoke');
late final _Invoke =
_InvokePtr.asFunction<
ffi.Pointer<ffi.Char> Function(
>('InvokeAsync');
late final _InvokeAsync =
_InvokeAsyncPtr.asFunction<
void Function(
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
int,
int,
)
>();
@@ -84,9 +98,8 @@ class LibgopeedBind {
return _SubscribeTaskEvents(mask, callback);
}
late final _SubscribeTaskEventsPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Uint64, ffi.UintPtr)>>(
'SubscribeTaskEvents',
);
late final _SubscribeTaskEventsPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.UnsignedLongLong, ffi.UintPtr)>>('SubscribeTaskEvents');
late final _SubscribeTaskEvents = _SubscribeTaskEventsPtr.asFunction<void Function(int, int)>();
void FreeCString(ffi.Pointer<ffi.Char> value) {
+161 -37
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
@@ -7,38 +8,74 @@ import 'package:ffi/ffi.dart';
import 'libgopeed_bind.dart';
typedef _InvokeResultNative = Void Function(Uint64 requestID, Int32 success, Pointer<Char> payload);
typedef _TaskEventNative = Void Function(Pointer<Char> payload);
class LibgopeedWorker {
LibgopeedWorker() {
factory LibgopeedWorker() => _instance;
LibgopeedWorker._() {
_receivePort.listen(_handleWorkerMessage);
_errorPort.listen(_handleWorkerError);
_isolateReady = Isolate.spawn(_workerMain, _receivePort.sendPort, onError: _errorPort.sendPort);
}
static final LibgopeedWorker _instance = LibgopeedWorker._();
final ReceivePort _receivePort = ReceivePort();
final ReceivePort _errorPort = ReceivePort();
final Map<int, Completer<String>> _pending = {};
final Map<int, Completer<Object?>> _pending = {};
final StreamController<Map<String, dynamic>> _taskEvents = StreamController<Map<String, dynamic>>.broadcast();
late final Future<Isolate> _isolateReady;
final Completer<SendPort> _sendPort = Completer<SendPort>();
Future<void>? _stopFuture;
int _requestID = 0;
bool _stopping = false;
bool _stopped = false;
Future<String> invoke(String method, String path, String query, String body) async {
await _isolateReady;
final sendPort = await _sendPort.future;
final requestID = _requestID++;
final completer = Completer<String>();
_pending[requestID] = completer;
sendPort.send(['invoke', requestID, method, path, query, body]);
return completer.future;
Stream<Map<String, dynamic>> get taskEvents => _taskEvents.stream;
Future<int> start(String config) => _request<int>('start', [config]);
Future<void> stop() => _stopFuture ??= _stop();
Future<void> _stop() async {
_stopping = true;
// The native bridge owns the bounded drain. Sending Stop immediately is
// important because an InvokeAsync handler such as Resolve may never return.
await _request<Object?>('stop', const [], allowWhileStopping: true);
_stopped = true;
final stoppingError = StateError('libgopeed worker stopped before the request completed');
for (final completer in _pending.values) {
completer.completeError(stoppingError);
}
_pending.clear();
await _taskEvents.close();
_receivePort.close();
_errorPort.close();
}
Future<String> apiServer(String operation) async {
Future<Object?> invoke(String method, String path, String query, String body) {
return _request<Object?>('invoke', [method, path, query, body]);
}
Future<String> apiServer(String operation) => _request<String>('apiServer', [operation]);
Future<void> subscribeTaskEvents(int mask) async {
await _request<Object?>('subscribeTaskEvents', [mask]);
}
Future<T> _request<T>(String type, List<Object?> arguments, {bool allowWhileStopping = false}) async {
if (_stopped || (_stopping && !allowWhileStopping)) {
throw StateError('libgopeed worker is stopping');
}
await _isolateReady;
final sendPort = await _sendPort.future;
final requestID = _requestID++;
final completer = Completer<String>();
final completer = Completer<Object?>();
_pending[requestID] = completer;
sendPort.send(['apiServer', requestID, operation]);
return completer.future;
sendPort.send([type, requestID, ...arguments]);
return (await completer.future) as T;
}
void _handleWorkerMessage(dynamic message) {
@@ -47,13 +84,18 @@ class LibgopeedWorker {
return;
}
final response = message as List<dynamic>;
final requestID = response[0] as int;
final completer = _pending.remove(requestID);
if (completer == null) return;
if (response[1] as bool) {
completer.complete(response[2] as String);
} else {
completer.completeError(StateError(response[2] as String));
switch (response[0] as String) {
case 'response':
final requestID = response[1] as int;
final completer = _pending.remove(requestID);
if (completer == null) return;
if (response[2] as bool) {
completer.complete(response[3]);
} else {
completer.completeError(StateError(response[3] as String));
}
case 'taskEvent':
_taskEvents.add((response[1] as Map<Object?, Object?>).cast<String, dynamic>());
}
}
@@ -65,35 +107,117 @@ class LibgopeedWorker {
completer.completeError(error);
}
_pending.clear();
_taskEvents.addError(error);
}
static void _workerMain(SendPort mainSendPort) {
final requests = ReceivePort();
final bindings = LibgopeedBind(DynamicLibrary.open(_libraryName()));
late final NativeCallable<_InvokeResultNative> invokeResultCallback;
late final NativeCallable<_TaskEventNative> taskEventCallback;
invokeResultCallback = NativeCallable<_InvokeResultNative>.listener((
int requestID,
int success,
Pointer<Char> payload,
) {
if (payload == nullptr) {
mainSendPort.send(['response', requestID, false, 'Gopeed InvokeAsync returned a null response']);
return;
}
try {
final result = payload.cast<Utf8>().toDartString();
mainSendPort.send(['response', requestID, success != 0, success != 0 ? jsonDecode(result) : result]);
} catch (error) {
mainSendPort.send(['response', requestID, false, error.toString()]);
} finally {
bindings.FreeCString(payload);
}
});
taskEventCallback = NativeCallable<_TaskEventNative>.listener((Pointer<Char> payload) {
if (payload == nullptr) return;
try {
final event = jsonDecode(payload.cast<Utf8>().toDartString()) as Map<String, dynamic>;
mainSendPort.send(['taskEvent', event]);
} finally {
bindings.FreeCString(payload);
}
});
mainSendPort.send(requests.sendPort);
requests.listen((dynamic message) {
final request = message as List<dynamic>;
final type = request[0] as String;
final requestID = request[1] as int;
try {
final response = switch (type) {
'invoke' => _invoke(
if (type == 'invoke') {
try {
_invokeAsync(
bindings,
invokeResultCallback.nativeFunction.address,
requestID,
request[2] as String,
request[3] as String,
request[4] as String,
request[5] as String,
),
);
} catch (error) {
mainSendPort.send(['response', requestID, false, error.toString()]);
}
return;
}
try {
final response = switch (type) {
'start' => _start(bindings, request[2] as String),
'stop' => _stopNative(bindings),
'apiServer' => _apiServer(bindings, request[2] as String),
'subscribeTaskEvents' => _subscribeTaskEvents(
bindings,
taskEventCallback.nativeFunction.address,
request[2] as int,
),
_ => throw StateError('Unknown libgopeed worker request: $type'),
};
mainSendPort.send([requestID, true, response]);
mainSendPort.send(['response', requestID, true, response]);
if (type == 'stop') {
invokeResultCallback.close();
taskEventCallback.close();
requests.close();
}
} catch (error) {
mainSendPort.send([requestID, false, error.toString()]);
mainSendPort.send(['response', requestID, false, error.toString()]);
}
});
}
static int _start(LibgopeedBind bindings, String config) {
final configPtr = config.toNativeUtf8();
try {
final result = bindings.Start(configPtr.cast());
if (result.r1 != nullptr) {
try {
throw StateError(result.r1.cast<Utf8>().toDartString());
} finally {
bindings.FreeCString(result.r1);
}
}
return result.r0;
} finally {
malloc.free(configPtr);
}
}
static Object? _stopNative(LibgopeedBind bindings) {
bindings.Stop();
return null;
}
static Object? _subscribeTaskEvents(LibgopeedBind bindings, int callback, int mask) {
bindings.SubscribeTaskEvents(mask, mask == 0 ? 0 : callback);
return null;
}
static String _apiServer(LibgopeedBind bindings, String operation) {
final resultPtr = switch (operation) {
'get' => bindings.GetAPIServerState(),
@@ -112,26 +236,26 @@ class LibgopeedWorker {
}
}
static String _invoke(LibgopeedBind bindings, String method, String path, String query, String body) {
static void _invokeAsync(
LibgopeedBind bindings,
int callback,
int requestID,
String method,
String path,
String query,
String body,
) {
final methodPtr = method.toNativeUtf8();
final pathPtr = path.toNativeUtf8();
final queryPtr = query.toNativeUtf8();
final bodyPtr = body.toNativeUtf8();
Pointer<Char>? resultPtr;
try {
resultPtr = bindings.Invoke(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast());
if (resultPtr == nullptr) {
throw StateError('Gopeed Invoke returned a null response');
}
return resultPtr.cast<Utf8>().toDartString();
bindings.InvokeAsync(methodPtr.cast(), pathPtr.cast(), queryPtr.cast(), bodyPtr.cast(), requestID, callback);
} finally {
malloc.free(methodPtr);
malloc.free(pathPtr);
malloc.free(queryPtr);
malloc.free(bodyPtr);
if (resultPtr != null && resultPtr != nullptr) {
bindings.FreeCString(resultPtr);
}
}
}
@@ -2,9 +2,9 @@ import 'dart:convert';
import 'package:dio/dio.dart';
import '../../../libgopeed_boot.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../../util/util.dart';
import '../../../ffi/libgopeed_worker.dart';
import '../../../libgopeed_boot.dart';
import '../gopeed_transport.dart';
GopeedTransport createTransport(GopeedTransportConfig config) => NativeGopeedTransport();
@@ -32,14 +32,16 @@ class NativeGopeedTransport implements GopeedTransport {
}) async {
final request = _RequestParts.from(path, queryParameters);
final requestBody = data == null ? '' : jsonEncode(data);
final payload = _ffiWorker != null
? await _ffiWorker.invoke(method.toUpperCase(), request.path, request.query, requestBody)
: await LibgopeedBoot.instance.invoke(
method.toUpperCase(),
request.path,
query: request.query,
body: requestBody,
);
final worker = _ffiWorker;
if (worker != null) {
return worker.invoke(method.toUpperCase(), request.path, request.query, requestBody);
}
final payload = await LibgopeedBoot.instance.invoke(
method.toUpperCase(),
request.path,
query: request.query,
body: requestBody,
);
return jsonDecode(payload);
}
@@ -0,0 +1,23 @@
abstract final class CompactCountFormatter {
// Counts start compacting at ten thousand by product convention, then use
// progressively larger decimal units so the rendered label stays bounded.
static const _units = [
(divisor: 1000000000000000000, suffix: 'qi'),
(divisor: 1000000000000000, suffix: 'q'),
(divisor: 1000000000000, suffix: 't'),
(divisor: 1000000000, suffix: 'b'),
(divisor: 1000000, suffix: 'm'),
(divisor: 10000, suffix: 'w'),
];
static String format(int count) {
if (count <= 0) return '0';
if (count < _units.last.divisor) return count.toString();
final unit = _units.firstWhere((unit) => count >= unit.divisor);
final whole = count ~/ unit.divisor;
final tenth = (count % unit.divisor) ~/ (unit.divisor ~/ 10);
final value = whole < 10 && tenth > 0 ? '$whole.$tenth' : '$whole';
return '$value${unit.suffix}';
}
}
@@ -19,7 +19,7 @@ Future<bool> open(String filePath) async {
Future<bool> reveal(String filePath) async {
try {
if (!(Platform.isWindows || Platform.isMacOS || Platform.isLinux)) {
return open(filePath);
return false;
}
if (await FileSystemEntity.isFile(filePath)) {
@@ -16,6 +16,7 @@ class AppWindowBootstrap {
await windowManager.ensureInitialized();
final windowOptions = WindowOptions(
title: 'Gopeed',
size: const Size(1024, 768),
center: true,
skipTaskbar: false,
@@ -74,8 +75,8 @@ class AppWindowBootstrap {
static String subWindowTitle(AppWindowType type, AppLocalizations l10n) {
return switch (type) {
AppWindowType.createTask => '${l10n.create} - Gopeed',
_ => l10n.appTitle,
AppWindowType.createTask => 'Gopeed - ${l10n.create}',
_ => 'Gopeed',
};
}
@@ -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,
),
),
],
),
),
);
}
}
Loaded 50 of 272 files, more files were not shown because too many files have changed in this diff. Show more