feat: new ui (#1455)

This commit is contained in:
Levi authored and GitHub committed 2026-09-05 19:53:41 +08:00
1 parent 3be8db664c
commit 177c225f16
742 files changed
+59951 -5934

No files matched your search

@@ -0,0 +1,50 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/api.dart' as api;
import '../../../api/model/login.dart';
final webAuthControllerProvider = Provider<WebAuthController>((ref) {
final controller = WebAuthController();
ref.onDispose(controller.dispose);
return controller;
});
enum WebLoginFailure { credentials, network }
class WebAuthController extends ChangeNotifier {
bool _loginRequired = false;
bool _isLoggingIn = false;
bool get loginRequired => _loginRequired;
bool get isLoggingIn => _isLoggingIn;
void requireLogin() {
if (_loginRequired) return;
_loginRequired = true;
notifyListeners();
}
Future<WebLoginFailure?> login({required String username, required String password}) async {
if (_isLoggingIn) return null;
_isLoggingIn = true;
notifyListeners();
try {
await api.login(LoginReq(username: username, password: password));
return null;
} on api.ApiTimeoutException {
return WebLoginFailure.network;
} catch (_) {
return WebLoginFailure.credentials;
} finally {
_isLoggingIn = false;
notifyListeners();
}
}
void completeLogin() {
if (!_loginRequired) return;
_loginRequired = false;
notifyListeners();
}
}
@@ -0,0 +1,236 @@
import 'dart:math' as math;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../app/application/app_runtime_controller.dart';
import '../../../../core/window/app_window_chrome.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../application/web_auth_controller.dart';
import '../widgets/login_brand_art.dart';
import '../widgets/login_form.dart';
class LoginPage extends ConsumerStatefulWidget {
const LoginPage({super.key});
@override
ConsumerState<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends ConsumerState<LoginPage> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final _usernameFocusNode = FocusNode();
final _passwordFocusNode = FocusNode();
String? _usernameError;
String? _passwordError;
WebLoginFailure? _loginFailure;
bool _completingLogin = false;
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
_usernameFocusNode.dispose();
_passwordFocusNode.dispose();
super.dispose();
}
Future<void> _submit() async {
final username = _usernameController.text.trim();
final password = _passwordController.text;
setState(() {
_usernameError = username.isEmpty ? context.l10n.username_required : null;
_passwordError = password.isEmpty ? context.l10n.password_required : null;
_loginFailure = null;
});
if (_usernameError != null || _passwordError != null) {
if (_usernameError != null) {
_usernameFocusNode.requestFocus();
} else {
_passwordFocusNode.requestFocus();
}
return;
}
final authController = ref.read(webAuthControllerProvider);
final failure = await authController.login(username: username, password: password);
if (!mounted) return;
if (failure != null) {
setState(() => _loginFailure = failure);
return;
}
setState(() => _completingLogin = true);
try {
await ref.read(appRuntimeControllerProvider.notifier).reloadConfig();
if (!mounted) return;
TextInput.finishAutofillContext(shouldSave: true);
authController.completeLogin();
} catch (_) {
authController.requireLogin();
if (!mounted) return;
setState(() => _loginFailure = WebLoginFailure.network);
} finally {
if (mounted) setState(() => _completingLogin = false);
}
}
@override
Widget build(BuildContext context) {
final authController = ref.read(webAuthControllerProvider);
return ListenableBuilder(
listenable: authController,
builder: (context, _) {
final loading = authController.isLoggingIn || _completingLogin;
return _LoginPageLayout(
form: LoginForm(
usernameController: _usernameController,
passwordController: _passwordController,
usernameFocusNode: _usernameFocusNode,
passwordFocusNode: _passwordFocusNode,
loading: loading,
usernameError: _usernameError,
passwordError: _passwordError,
loginError: switch (_loginFailure) {
WebLoginFailure.credentials => context.l10n.login_failed,
WebLoginFailure.network => context.l10n.login_failed_network,
null => null,
},
onUsernameChanged: (_) {
if (_usernameError == null && _loginFailure == null) return;
setState(() {
_usernameError = null;
_loginFailure = null;
});
},
onPasswordChanged: (_) {
if (_passwordError == null && _loginFailure == null) return;
setState(() {
_passwordError = null;
_loginFailure = null;
});
},
onSubmit: _submit,
),
);
},
);
}
}
class _LoginPageLayout extends StatelessWidget {
const _LoginPageLayout({required this.form});
final Widget form;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final topInset = AppWindowChrome.reservesHeaderInset ? AppDesignTokens.windowHeaderHeight : 0.0;
return shad.Scaffold(
child: ColoredBox(
color: palette.bg,
child: Padding(
padding: EdgeInsets.only(top: topInset),
child: SafeArea(
top: false,
child: LayoutBuilder(
builder: (context, constraints) {
final desktop = constraints.maxWidth >= 900;
final horizontalPadding = desktop ? AppDesignTokens.space32 : AppDesignTokens.space16;
final verticalPadding = desktop ? AppDesignTokens.space24 : AppDesignTokens.space16;
final availableWidth = math.max(0.0, constraints.maxWidth - horizontalPadding * 2);
final cardWidth = math.min(desktop ? 980.0 : 440.0, availableWidth);
final card = SizedBox(
width: cardWidth,
child: desktop ? _DesktopLoginCard(form: form) : _CompactLoginCard(form: form),
);
if (desktop) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: horizontalPadding, vertical: verticalPadding),
child: Center(
child: FittedBox(fit: BoxFit.scaleDown, child: card),
),
);
}
return Padding(
padding: EdgeInsets.symmetric(horizontal: horizontalPadding, vertical: verticalPadding),
child: Center(
child: FittedBox(fit: BoxFit.scaleDown, child: card),
),
);
},
),
),
),
),
);
}
}
class _DesktopLoginCard extends StatelessWidget {
const _DesktopLoginCard({required this.form});
final Widget form;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return shad.Card(
key: const ValueKey('login-desktop-card'),
padding: EdgeInsets.zero,
borderRadius: BorderRadius.circular(AppDesignTokens.windowRadius),
borderColor: palette.border,
boxShadow: [
BoxShadow(color: palette.textPrimary.withValues(alpha: 0.08), blurRadius: 36, offset: const Offset(0, 14)),
],
clipBehavior: Clip.antiAlias,
child: Row(
children: [
const Expanded(child: SizedBox(height: 520, child: LoginBrandArt())),
SizedBox(
width: 420,
child: Padding(padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 56), child: form),
),
],
),
);
}
}
class _CompactLoginCard extends StatelessWidget {
const _CompactLoginCard({required this.form});
final Widget form;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: shad.Card(
key: const ValueKey('login-compact-card'),
padding: EdgeInsets.zero,
borderRadius: BorderRadius.circular(AppDesignTokens.windowRadius),
borderColor: palette.border,
boxShadow: [
BoxShadow(color: palette.textPrimary.withValues(alpha: 0.08), blurRadius: 28, offset: const Offset(0, 10)),
],
clipBehavior: Clip.antiAlias,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 190, child: LoginBrandArt(compact: true)),
Padding(padding: const EdgeInsets.all(AppDesignTokens.space24), child: form),
],
),
),
);
}
}
@@ -0,0 +1,238 @@
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
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/gopeed_app_mark.dart';
class LoginBrandArt extends StatelessWidget {
const LoginBrandArt({super.key, this.compact = false});
final bool compact;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: AlignmentDirectional.topStart,
end: AlignmentDirectional.bottomEnd,
colors: [palette.sideBg, Color.alphaBlend(palette.brandSoft, palette.sideBg), palette.cardBg],
),
),
child: Stack(
fit: StackFit.expand,
children: [
CustomPaint(
painter: _TransferFlowPainter(palette: palette, compact: compact),
),
PositionedDirectional(
start: compact ? AppDesignTokens.space24 : AppDesignTokens.space32,
top: compact ? AppDesignTokens.space16 : AppDesignTokens.space32,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Gopeed',
style: TextStyle(
color: palette.textPrimary,
fontSize: compact ? 17 : 19,
fontWeight: FontWeight.w800,
letterSpacing: 0.4,
),
),
],
),
),
Center(child: _TransferOrbit(compact: compact)),
],
),
);
}
}
class _TransferOrbit extends StatelessWidget {
const _TransferOrbit({required this.compact});
final bool compact;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final size = compact ? 132.0 : 260.0;
final coreSize = compact ? 62.0 : 96.0;
return SizedBox.square(
dimension: size,
child: Stack(
alignment: Alignment.center,
clipBehavior: Clip.none,
children: [
CustomPaint(
size: Size.square(size),
painter: _OrbitPainter(palette: palette),
),
Container(
width: coreSize,
height: coreSize,
padding: EdgeInsets.all(compact ? 7 : 11),
decoration: BoxDecoration(
color: palette.cardBg,
shape: BoxShape.circle,
border: Border.all(color: palette.brand.withValues(alpha: 0.42)),
boxShadow: [
BoxShadow(color: palette.brand.withValues(alpha: 0.18), blurRadius: compact ? 18 : 32, spreadRadius: 2),
],
),
child: GopeedAppMark(size: coreSize - (compact ? 14 : 22)),
),
PositionedDirectional(
top: compact ? 5 : 16,
end: compact ? 3 : 20,
child: _OrbitNode(icon: shad.LucideIcons.cloudDownload, compact: compact),
),
PositionedDirectional(
bottom: compact ? 7 : 20,
start: compact ? 0 : 14,
child: _OrbitNode(icon: shad.LucideIcons.hardDriveDownload, compact: compact),
),
if (!compact)
PositionedDirectional(
bottom: 4,
end: 38,
child: _OrbitNode(icon: shad.LucideIcons.gauge, compact: false, small: true),
),
],
),
);
}
}
class _OrbitNode extends StatelessWidget {
const _OrbitNode({required this.icon, required this.compact, this.small = false});
final IconData icon;
final bool compact;
final bool small;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final dimension = small
? 34.0
: compact
? 30.0
: 42.0;
return Container(
width: dimension,
height: dimension,
decoration: BoxDecoration(
color: palette.cardBg,
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius + 4),
border: Border.all(color: palette.border),
boxShadow: [
BoxShadow(color: palette.textPrimary.withValues(alpha: 0.08), blurRadius: 12, offset: const Offset(0, 4)),
],
),
child: Icon(
icon,
size: small
? 15
: compact
? 14
: 18,
color: palette.brand,
),
);
}
}
class _TransferFlowPainter extends CustomPainter {
const _TransferFlowPainter({required this.palette, required this.compact});
final AppPalette palette;
final bool compact;
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final dotPaint = Paint()..color = palette.textMuted.withValues(alpha: 0.12);
final gap = compact ? 24.0 : 28.0;
for (var x = gap / 2; x < size.width; x += gap) {
for (var y = gap / 2; y < size.height; y += gap) {
canvas.drawCircle(Offset(x, y), 1, dotPaint);
}
}
final paths = <Path>[
Path()
..moveTo(-size.width * 0.08, size.height * 0.32)
..cubicTo(size.width * 0.20, size.height * 0.18, center.dx * 0.65, center.dy * 0.72, center.dx, center.dy),
Path()
..moveTo(size.width * 1.08, size.height * 0.72)
..cubicTo(size.width * 0.78, size.height * 0.84, center.dx * 1.35, center.dy * 1.18, center.dx, center.dy),
Path()
..moveTo(size.width * 0.18, size.height * 1.06)
..cubicTo(size.width * 0.26, size.height * 0.72, center.dx * 0.72, center.dy * 1.28, center.dx, center.dy),
];
for (var index = 0; index < paths.length; index++) {
canvas.drawPath(
paths[index],
Paint()
..color = (index == 0 ? palette.brand : palette.textMuted).withValues(alpha: index == 0 ? 0.28 : 0.13)
..style = PaintingStyle.stroke
..strokeWidth = index == 0 ? 1.8 : 1.0,
);
}
final glowPaint = Paint()
..shader = RadialGradient(
colors: [palette.brand.withValues(alpha: 0.13), palette.brand.withValues(alpha: 0)],
).createShader(Rect.fromCircle(center: center, radius: compact ? 90 : 180));
canvas.drawCircle(center, compact ? 90 : 180, glowPaint);
}
@override
bool shouldRepaint(_TransferFlowPainter oldDelegate) =>
oldDelegate.palette != palette || oldDelegate.compact != compact;
}
class _OrbitPainter extends CustomPainter {
const _OrbitPainter({required this.palette});
final AppPalette palette;
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final radius = size.shortestSide * 0.39;
canvas.drawCircle(
center,
radius,
Paint()
..color = palette.brand.withValues(alpha: 0.26)
..style = PaintingStyle.stroke
..strokeWidth = 1.2,
);
canvas.drawArc(
Rect.fromCircle(center: center, radius: radius * 0.72),
-math.pi * 0.85,
math.pi * 1.38,
false,
Paint()
..color = palette.brand.withValues(alpha: 0.52)
..style = PaintingStyle.stroke
..strokeWidth = 2.2
..strokeCap = StrokeCap.round,
);
for (final angle in [-0.72, 0.18, 0.76]) {
final point = center + Offset(math.cos(angle * math.pi), math.sin(angle * math.pi)) * radius;
canvas.drawCircle(point, 3.2, Paint()..color = palette.brand);
}
}
@override
bool shouldRepaint(_OrbitPainter oldDelegate) => oldDelegate.palette != palette;
}
@@ -0,0 +1,190 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_loading_button.dart';
class LoginForm extends StatelessWidget {
const LoginForm({
super.key,
required this.usernameController,
required this.passwordController,
required this.usernameFocusNode,
required this.passwordFocusNode,
required this.loading,
required this.onSubmit,
required this.onUsernameChanged,
required this.onPasswordChanged,
this.usernameError,
this.passwordError,
this.loginError,
});
final TextEditingController usernameController;
final TextEditingController passwordController;
final FocusNode usernameFocusNode;
final FocusNode passwordFocusNode;
final bool loading;
final VoidCallback onSubmit;
final ValueChanged<String> onUsernameChanged;
final ValueChanged<String> onPasswordChanged;
final String? usernameError;
final String? passwordError;
final String? loginError;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return AutofillGroup(
onDisposeAction: AutofillContextAction.cancel,
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
context.l10n.login,
key: const ValueKey('login-title'),
style: TextStyle(color: palette.textPrimary, fontSize: 30, fontWeight: FontWeight.w700, height: 1.15),
),
const SizedBox(height: AppDesignTokens.space24),
_LoginField(
fieldKey: const ValueKey('login-username-field'),
label: context.l10n.username,
controller: usernameController,
focusNode: usernameFocusNode,
autofocus: true,
enabled: !loading,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.done,
autofillHints: const [AutofillHints.username],
error: usernameError,
onChanged: onUsernameChanged,
onSubmitted: (_) => onSubmit(),
),
const SizedBox(height: AppDesignTokens.space16),
_LoginField(
fieldKey: const ValueKey('login-password-field'),
label: context.l10n.password,
controller: passwordController,
focusNode: passwordFocusNode,
enabled: !loading,
keyboardType: TextInputType.visiblePassword,
textInputAction: TextInputAction.done,
autofillHints: const [AutofillHints.password],
obscureText: true,
error: passwordError,
onChanged: onPasswordChanged,
onSubmitted: (_) => onSubmit(),
),
AnimatedSize(
duration: const Duration(milliseconds: 160),
curve: Curves.easeOut,
child: loginError == null
? const SizedBox(height: AppDesignTokens.space24)
: Padding(
padding: const EdgeInsets.only(top: AppDesignTokens.space12, bottom: AppDesignTokens.space12),
child: Text(
loginError!,
key: const ValueKey('login-error'),
style: TextStyle(color: palette.error, fontSize: 12, height: 1.35),
),
),
),
Center(
child: SizedBox(
key: const ValueKey('login-submit-button-container'),
width: 148,
height: 40,
child: AppLoadingButton(
key: const ValueKey('login-submit-button'),
onPressed: loading ? null : onSubmit,
loading: loading,
alignment: Alignment.center,
variant: AppLoadingButtonVariant.primary,
child: Text(context.l10n.login, textAlign: TextAlign.center),
),
),
),
],
),
),
);
}
}
class _LoginField extends StatelessWidget {
const _LoginField({
required this.fieldKey,
required this.label,
required this.controller,
required this.focusNode,
required this.enabled,
required this.keyboardType,
required this.textInputAction,
required this.autofillHints,
required this.onChanged,
required this.onSubmitted,
this.autofocus = false,
this.obscureText = false,
this.error,
});
final Key fieldKey;
final String label;
final TextEditingController controller;
final FocusNode focusNode;
final bool enabled;
final TextInputType keyboardType;
final TextInputAction textInputAction;
final Iterable<String> autofillHints;
final ValueChanged<String> onChanged;
final ValueChanged<String> onSubmitted;
final bool autofocus;
final bool obscureText;
final String? error;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
label,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w600),
),
const SizedBox(height: AppDesignTokens.space8),
shad.TextField(
key: fieldKey,
controller: controller,
focusNode: focusNode,
autofocus: autofocus,
enabled: enabled,
keyboardType: keyboardType,
textInputAction: textInputAction,
autofillHints: autofillHints,
autocorrect: false,
enableSuggestions: false,
obscureText: obscureText,
onChanged: onChanged,
onSubmitted: onSubmitted,
border: Border.all(color: error == null ? palette.border : palette.error),
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
filled: true,
features: obscureText
? const [shad.InputPasswordToggleFeature(mode: shad.PasswordPeekMode.toggle)]
: const [],
),
if (error != null) ...[
const SizedBox(height: AppDesignTokens.space4),
Text(error!, style: TextStyle(color: palette.error, fontSize: 12, height: 1.3)),
],
],
);
}
}
@@ -0,0 +1,377 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/gopeed_site_api.dart';
import '../../../api/model/extension.dart';
import '../../../api/model/install_extension.dart';
import '../../../api/model/store_extension.dart';
import '../../../api/model/switch_extension.dart';
import '../../../api/model/update_extension_settings.dart';
import '../../../core/capabilities/app_capabilities.dart';
final extensionsControllerProvider = AsyncNotifierProvider<ExtensionsController, ExtensionsState>(
ExtensionsController.new,
);
enum ExtensionListFilter { market, installed }
class ExtensionListItem {
const ExtensionListItem({this.installed, this.store});
final Extension? installed;
final StoreExtension? store;
bool get isInstalled => installed != null;
String get id => installed?.identity ?? store!.id;
String get title => installed?.title ?? store?.title ?? '';
String get author => installed?.author ?? store?.author ?? '';
String get description => installed?.description ?? store?.description ?? '';
String get version => installed?.version ?? store?.version ?? '0.0.0';
String? get homepage => installed?.homepage.isNotEmpty == true ? installed!.homepage : store?.homepage;
String? get repoUrl => installed?.repository?.url.isNotEmpty == true ? installed!.repository!.url : store?.repoUrl;
int get stars => store?.stars ?? 0;
int get installCount => store?.installCount ?? 0;
}
class ExtensionsState {
const ExtensionsState({
this.installedExtensions = const [],
this.storeExtensions = const [],
this.updateFlags = const {},
this.storePagination,
this.storeQuery = '',
this.storeSort = StoreExtensionSort.stars,
this.listFilter = ExtensionListFilter.market,
this.loadingInstalled = false,
this.loadingStore = false,
this.loadingMoreStore = false,
this.busyExtensionIds = const {},
this.devMode = false,
});
final List<Extension> installedExtensions;
final List<StoreExtension> storeExtensions;
final Map<String, String> updateFlags;
final StorePagination? storePagination;
final String storeQuery;
final StoreExtensionSort storeSort;
final ExtensionListFilter listFilter;
final bool loadingInstalled;
final bool loadingStore;
final bool loadingMoreStore;
final Set<String> busyExtensionIds;
final bool devMode;
UnmodifiableMapView<String, Extension> get installedMap =>
UnmodifiableMapView({for (final ext in installedExtensions) ext.identity: ext});
UnmodifiableMapView<String, StoreExtension> get storeMap =>
UnmodifiableMapView({for (final ext in storeExtensions) ext.id: ext});
List<ExtensionListItem> get displayItems {
if (listFilter == ExtensionListFilter.installed) {
return installedExtensions
.map((ext) => ExtensionListItem(installed: ext, store: storeMap[ext.identity]))
.toList();
}
return storeExtensions.map((ext) => ExtensionListItem(installed: installedMap[ext.id], store: ext)).toList();
}
ExtensionListItem? findItem(String id) {
final installed = installedMap[id];
final store = storeMap[id];
if (installed == null && store == null) return null;
return ExtensionListItem(installed: installed, store: store);
}
ExtensionsState copyWith({
List<Extension>? installedExtensions,
List<StoreExtension>? storeExtensions,
Map<String, String>? updateFlags,
StorePagination? storePagination,
bool clearStorePagination = false,
String? storeQuery,
StoreExtensionSort? storeSort,
ExtensionListFilter? listFilter,
bool? loadingInstalled,
bool? loadingStore,
bool? loadingMoreStore,
Set<String>? busyExtensionIds,
bool? devMode,
}) {
return ExtensionsState(
installedExtensions: installedExtensions ?? this.installedExtensions,
storeExtensions: storeExtensions ?? this.storeExtensions,
updateFlags: updateFlags ?? this.updateFlags,
storePagination: clearStorePagination ? null : storePagination ?? this.storePagination,
storeQuery: storeQuery ?? this.storeQuery,
storeSort: storeSort ?? this.storeSort,
listFilter: listFilter ?? this.listFilter,
loadingInstalled: loadingInstalled ?? this.loadingInstalled,
loadingStore: loadingStore ?? this.loadingStore,
loadingMoreStore: loadingMoreStore ?? this.loadingMoreStore,
busyExtensionIds: busyExtensionIds ?? this.busyExtensionIds,
devMode: devMode ?? this.devMode,
);
}
}
class ExtensionsController extends AsyncNotifier<ExtensionsState> {
static const manualInstallBusyKey = '__manual_install__';
int _devModeCount = 0;
@override
Future<ExtensionsState> build() async {
var next = const ExtensionsState(loadingInstalled: true, loadingStore: true);
state = AsyncValue.data(next);
final installed = await _loadInstalled(refreshUpdates: true, current: next);
next = state.value ?? installed;
await _refreshStore(current: next);
return state.value ?? next;
}
Future<void> loadInitialData() async {
state = const AsyncValue.loading();
state = AsyncValue.data(await build());
}
Future<void> loadInstalled({bool refreshUpdates = false}) async {
await _loadInstalled(refreshUpdates: refreshUpdates, current: _current.copyWith(loadingInstalled: true));
}
Future<void> refreshStore() async {
await _refreshStore(current: _current.copyWith(loadingStore: true));
}
Future<void> loadMoreStore() async {
final current = _current;
final pagination = current.storePagination;
if (pagination == null || !pagination.hasNext || current.loadingMoreStore) return;
state = AsyncValue.data(current.copyWith(loadingMoreStore: true));
try {
final page = await GopeedSiteApi.instance.getExtensions(
page: pagination.page + 1,
limit: pagination.limit,
sort: current.storeSort,
query: current.storeQuery,
);
state = AsyncValue.data(
_current.copyWith(
storeExtensions: [..._current.storeExtensions, ...page.data],
storePagination: page.pagination,
loadingMoreStore: false,
),
);
} catch (_) {
state = AsyncValue.data(_current.copyWith(loadingMoreStore: false));
rethrow;
}
}
Future<void> searchStore(String query) async {
state = AsyncValue.data(_current.copyWith(storeQuery: query.trim()));
await refreshStore();
}
Future<void> changeSort(StoreExtensionSort sort) async {
state = AsyncValue.data(_current.copyWith(storeSort: sort));
await refreshStore();
}
void changeFilter(ExtensionListFilter filter) {
state = AsyncValue.data(_current.copyWith(listFilter: filter));
}
bool canUpdateItem(ExtensionListItem item) {
final current = _current;
if (item.installed == null) return false;
if (current.listFilter == ExtensionListFilter.market && item.store != null) {
return _compareVersion(item.store!.version, item.installed!.version) > 0;
}
return current.updateFlags.containsKey(item.installed!.identity);
}
Future<void> installFromStore(StoreExtension extension) async {
await _runBusy(extension.id, () async {
final installUrl = (extension.directory ?? '').trim().isEmpty
? extension.repoUrl
: '${extension.repoUrl}#${extension.directory!.trim()}';
final installedId = await ref.read(gopeedServiceProvider).installExtension(InstallExtension(url: installUrl));
await loadInstalled(refreshUpdates: false);
unawaited(checkUpdate());
_bumpStoreInstallCount(installedId.isNotEmpty ? installedId : extension.id);
_reportInstallSafe(installedId.isNotEmpty ? installedId : extension.id);
});
}
Future<void> installFromUrl(String url, {bool devInstall = false}) async {
await _runBusy(manualInstallBusyKey, () async {
final installedId = await ref
.read(gopeedServiceProvider)
.installExtension(InstallExtension(devMode: devInstall, url: url));
await loadInstalled(refreshUpdates: false);
unawaited(checkUpdate());
if (installedId.isNotEmpty) {
_bumpStoreInstallCount(installedId);
_reportInstallSafe(installedId);
}
});
}
Future<void> toggleExtension(Extension extension, bool enabled) async {
await _runBusy(extension.identity, () async {
await ref.read(gopeedServiceProvider).switchExtension(extension.identity, SwitchExtension(status: enabled));
await loadInstalled(refreshUpdates: false);
});
}
Future<void> removeExtension(Extension extension) async {
await _runBusy(extension.identity, () async {
await ref.read(gopeedServiceProvider).deleteExtension(extension.identity);
await loadInstalled(refreshUpdates: false);
final flags = Map<String, String>.of(_current.updateFlags)..remove(extension.identity);
state = AsyncValue.data(_current.copyWith(updateFlags: flags));
});
}
Future<void> upgradeExtension(Extension extension) async {
await _runBusy(extension.identity, () async {
await ref.read(gopeedServiceProvider).updateExtension(extension.identity);
await loadInstalled(refreshUpdates: false);
unawaited(checkUpdate());
_bumpStoreInstallCount(extension.identity);
_reportInstallSafe(extension.identity);
});
}
Future<void> saveExtensionSettings(Extension extension, Map<String, dynamic> settings) async {
await _runBusy(extension.identity, () async {
await ref
.read(gopeedServiceProvider)
.updateExtensionSettings(extension.identity, UpdateExtensionSettings(settings: settings));
await loadInstalled(refreshUpdates: false);
});
}
Future<void> checkUpdate() async {
final flags = <String, String>{};
for (final ext in _current.installedExtensions) {
try {
final resp = await ref.read(gopeedServiceProvider).upgradeCheckExtension(ext.identity);
if (resp.newVersion.isNotEmpty) {
flags[ext.identity] = resp.newVersion;
}
} catch (_) {}
}
state = AsyncValue.data(_current.copyWith(updateFlags: flags));
}
void tryOpenDevMode() {
if (_devModeCount == 0) {
Future.delayed(const Duration(seconds: 2), () {
if (_current.devMode) return;
_devModeCount = 0;
});
}
_devModeCount++;
if (_devModeCount >= 5) {
state = AsyncValue.data(_current.copyWith(devMode: true));
}
}
ExtensionsState get _current => state.value ?? const ExtensionsState();
Future<ExtensionsState> _loadInstalled({required bool refreshUpdates, required ExtensionsState current}) async {
state = AsyncValue.data(current.copyWith(loadingInstalled: true));
final installed = await ref.read(gopeedServiceProvider).getExtensions();
state = AsyncValue.data(_current.copyWith(installedExtensions: installed, loadingInstalled: false));
if (refreshUpdates) {
await checkUpdate();
}
return _current;
}
Future<void> _refreshStore({required ExtensionsState current}) async {
state = AsyncValue.data(current.copyWith(loadingStore: true));
final page = await GopeedSiteApi.instance.getExtensions(
page: 1,
limit: 20,
sort: _current.storeSort,
query: _current.storeQuery,
);
state = AsyncValue.data(
_current.copyWith(storeExtensions: page.data, storePagination: page.pagination, loadingStore: false),
);
}
Future<void> _runBusy(String id, Future<void> Function() action) async {
if (_current.busyExtensionIds.contains(id)) return;
state = AsyncValue.data(_current.copyWith(busyExtensionIds: {..._current.busyExtensionIds, id}));
try {
await action();
} finally {
final busy = Set<String>.of(_current.busyExtensionIds)..remove(id);
state = AsyncValue.data(_current.copyWith(busyExtensionIds: busy));
}
}
void _bumpStoreInstallCount(String id) {
final current = _current;
final index = current.storeExtensions.indexWhere((e) => e.id == id);
if (index < 0) return;
final ext = current.storeExtensions[index];
final updated = [...current.storeExtensions];
updated[index] = StoreExtension(
id: ext.id,
repoFullName: ext.repoFullName,
repoUrl: ext.repoUrl,
directory: ext.directory,
commitSha: ext.commitSha,
name: ext.name,
author: ext.author,
title: ext.title,
description: ext.description,
icon: ext.icon,
version: ext.version,
homepage: ext.homepage,
readme: ext.readme,
installCount: ext.installCount + 1,
stars: ext.stars,
topics: ext.topics,
createdAt: ext.createdAt,
updatedAt: ext.updatedAt,
);
state = AsyncValue.data(current.copyWith(storeExtensions: updated));
}
void _reportInstallSafe(String id) {
unawaited(() async {
try {
await GopeedSiteApi.instance.reportExtensionInstall(id);
} catch (_) {}
}());
}
static int _compareVersion(String a, String b) {
final aNums = _toVersionNumbers(a);
final bNums = _toVersionNumbers(b);
final maxLen = aNums.length > bNums.length ? aNums.length : bNums.length;
for (var i = 0; i < maxLen; i++) {
final left = i < aNums.length ? aNums[i] : 0;
final right = i < bNums.length ? bNums[i] : 0;
if (left > right) return 1;
if (left < right) return -1;
}
return 0;
}
static List<int> _toVersionNumbers(String version) {
return version
.split(RegExp(r'[^0-9]+'))
.where((part) => part.isNotEmpty)
.map((part) => int.tryParse(part) ?? 0)
.toList();
}
}
@@ -0,0 +1,20 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/install_extension.dart';
final pendingExtensionInstallProvider = NotifierProvider<PendingExtensionInstall, InstallExtension?>(
PendingExtensionInstall.new,
);
class PendingExtensionInstall extends Notifier<InstallExtension?> {
@override
InstallExtension? build() => null;
void set(InstallExtension? install) {
state = install;
}
void clear() {
state = null;
}
}
@@ -0,0 +1,36 @@
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 '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/detail/app_detail_surface.dart';
import '../../application/extensions_controller.dart';
import '../widgets/extension_detail_view.dart';
class ExtensionDetailsPage extends ConsumerWidget {
const ExtensionDetailsPage({super.key, required this.extensionId, this.initialItem});
final String extensionId;
final ExtensionListItem? initialItem;
@override
Widget build(BuildContext context, WidgetRef ref) {
final stateAsync = ref.watch(extensionsControllerProvider);
final item = stateAsync.value?.findItem(extensionId) ?? initialItem;
final palette = AppPalette.of(context);
return AppDetailPage(
title: item?.title ?? context.l10n.extensions,
onBack: () => context.canPop() ? context.pop() : context.go('/extensions'),
child: item == null
? Center(
child: stateAsync.isLoading
? const shad.CircularProgressIndicator()
: Text(context.l10n.noExtensions, style: TextStyle(color: palette.textMuted, fontSize: 13)),
)
: ExtensionDetailView(key: ValueKey(item.id), item: item, mobile: true),
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,467 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path/path.dart' as path;
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import 'package:url_launcher/url_launcher.dart';
import '../../../../api/model/store_extension.dart';
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_toast.dart';
import '../../../../shared/widgets/detail/app_detail_surface.dart';
import '../../../../util/util.dart';
import '../../application/extensions_controller.dart';
import 'extension_icon.dart';
class ExtensionDetailDrawer extends StatelessWidget {
const ExtensionDetailDrawer({super.key, required this.item, required this.onClose});
final ExtensionListItem? item;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
return AppDetailDrawer(
open: item != null,
title: item?.title ?? '',
onClose: onClose,
drawerKey: const ValueKey('extension-details-drawer'),
child: item == null ? const SizedBox.shrink() : ExtensionDetailView(item: item!),
);
}
}
class ExtensionDetailView extends ConsumerWidget {
const ExtensionDetailView({super.key, required this.item, this.mobile = false});
final ExtensionListItem item;
final bool mobile;
@override
Widget build(BuildContext context, WidgetRef ref) {
final palette = AppPalette.of(context);
final state = ref.watch(extensionsControllerProvider).value;
final current = state?.findItem(item.id) ?? item;
final installed = current.installed;
final store = current.store;
final busy = state?.busyExtensionIds.contains(current.id) ?? false;
final canUpdate = ref.read(extensionsControllerProvider.notifier).canUpdateItem(current);
final horizontalPadding = mobile ? AppDesignTokens.space16 : AppDesignTokens.space32;
return ListView(
key: const ValueKey('extension-details-content'),
padding: EdgeInsets.fromLTRB(horizontalPadding, mobile ? 24 : 28, horizontalPadding, mobile ? 40 : 48),
children: [
Row(
key: const ValueKey('extension-details-hero'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ExtensionIcon(
item: current,
size: mobile ? 60 : 68,
borderRadius: BorderRadius.circular(14),
fallbackPadding: EdgeInsets.all((mobile ? 60 : 68) * 0.16),
fallbackBackgroundColor: palette.surfaceSoft,
),
SizedBox(width: mobile ? 16 : 20),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
current.author,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: palette.textPrimary,
fontSize: 12,
fontWeight: FontWeight.w700,
letterSpacing: 0.15,
),
),
const SizedBox(height: 7),
Text(
current.description,
style: TextStyle(color: palette.textSecondary, fontSize: mobile ? 14 : 13.5, height: 1.5),
),
const SizedBox(height: 10),
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 9,
runSpacing: 5,
children: [
Text(
'v${current.version}',
style: TextStyle(color: palette.textMuted, fontSize: 11.5, fontWeight: FontWeight.w600),
),
if (store != null) _ExtensionStats(store: store),
if (installed != null && canUpdate)
_ExtensionStatus(label: context.l10n.extensionCanUpdate, emphasized: true),
],
),
],
),
),
],
),
SizedBox(height: mobile ? 24 : 28),
Wrap(
key: const ValueKey('extension-details-actions'),
spacing: 4,
runSpacing: 6,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (installed == null && store != null)
AppLoadingButton(
key: const ValueKey('extension-details-install'),
loading: busy,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.download_outlined, size: 16),
onPressed: () =>
_runAction(context, () => ref.read(extensionsControllerProvider.notifier).installFromStore(store)),
child: Text(context.l10n.extensionInstall),
),
if (installed != null && canUpdate)
AppLoadingButton(
key: const ValueKey('extension-details-update'),
loading: busy,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.refresh, size: 16),
onPressed: () => _runAction(
context,
() => ref.read(extensionsControllerProvider.notifier).upgradeExtension(installed),
successMessage: context.l10n.extensionUpdateSuccess,
),
child: Text(context.l10n.newVersionUpdate),
),
if (installed != null && !canUpdate)
AppLoadingButton(
key: const ValueKey('extension-details-installed'),
loading: false,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.check_circle_outline, size: 16),
onPressed: null,
child: Text(context.l10n.extensionInstalled),
),
if ((current.homepage ?? '').isNotEmpty)
shad.SecondaryButton(
key: const ValueKey('extension-details-homepage'),
onPressed: () => unawaited(_openUrl(current.homepage!)),
child: _LinkButtonContent(icon: Icons.home_outlined, label: context.l10n.homepage),
),
if ((current.repoUrl ?? '').isNotEmpty)
shad.SecondaryButton(
key: const ValueKey('extension-details-github'),
onPressed: () => unawaited(_openUrl(current.repoUrl!)),
child: const _LinkButtonContent(icon: Icons.code, label: 'GitHub'),
),
],
),
if (store != null) ...[SizedBox(height: mobile ? 24 : 28), _ExtensionReadme(item: current, mobile: mobile)],
],
);
}
Future<void> _runAction(BuildContext context, Future<void> Function() action, {String? successMessage}) async {
try {
await action();
if (context.mounted && successMessage != null) {
showAppToast(context, successMessage, type: AppToastType.success);
}
} catch (error) {
if (context.mounted) showAppToast(context, error.toString(), type: AppToastType.error);
}
}
}
class _ExtensionReadme extends StatefulWidget {
const _ExtensionReadme({required this.item, required this.mobile});
final ExtensionListItem item;
final bool mobile;
@override
State<_ExtensionReadme> createState() => _ExtensionReadmeState();
}
class _ExtensionReadmeState extends State<_ExtensionReadme> {
late Future<_ReadmeInfo> _readme;
@override
void initState() {
super.initState();
_readme = _loadReadme(widget.item);
}
@override
void didUpdateWidget(covariant _ExtensionReadme oldWidget) {
super.didUpdateWidget(oldWidget);
final previous = oldWidget.item.installed;
final current = widget.item.installed;
if (previous?.identity != current?.identity ||
previous?.devMode != current?.devMode ||
previous?.devPath != current?.devPath ||
oldWidget.item.store?.readme != widget.item.store?.readme) {
_readme = _loadReadme(widget.item);
}
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return FutureBuilder<_ReadmeInfo>(
future: _readme,
builder: (context, snapshot) {
final info = snapshot.data;
if (info == null) {
return const SizedBox.shrink();
}
if (info.content.trim().isEmpty) {
return const SizedBox.shrink();
}
return Padding(
key: const ValueKey('extension-details-readme'),
padding: EdgeInsets.only(top: widget.mobile ? 32 : 36),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'README',
style: TextStyle(
color: palette.textMuted,
fontSize: 10.5,
fontWeight: FontWeight.w800,
letterSpacing: 1.2,
),
),
const SizedBox(height: 16),
MarkdownBody(
data: info.content,
selectable: true,
styleSheet: _markdownStyle(palette, mobile: widget.mobile),
onTapLink: (_, href, _) {
final resolved = _resolveReadmeUrl(widget.item, href, info: info, forImage: false);
if (resolved != null) unawaited(_openUrl(resolved));
},
imageBuilder: (uri, title, alt) {
final resolved = _resolveReadmeUrl(widget.item, uri.toString(), info: info, forImage: true);
if (resolved == null) return const SizedBox.shrink();
final image = resolved.startsWith('file:')
? Image.file(
File(Uri.parse(resolved).toFilePath()),
fit: BoxFit.contain,
errorBuilder: (_, _, _) => const SizedBox.shrink(),
)
: Image.network(
resolved,
fit: BoxFit.contain,
errorBuilder: (_, _, _) => const SizedBox.shrink(),
);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: ClipRRect(borderRadius: BorderRadius.circular(6), child: image),
);
},
),
],
),
);
},
);
}
}
class _ExtensionStatus extends StatelessWidget {
const _ExtensionStatus({required this.label, required this.emphasized});
final String label;
final bool emphasized;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final dotColor = emphasized ? palette.brand : palette.success;
final textColor = emphasized ? palette.textPrimary : palette.success;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 5,
height: 5,
decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle),
),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(color: textColor, fontSize: 11.5, fontWeight: FontWeight.w600),
),
],
);
}
}
class _LinkButtonContent extends StatelessWidget {
const _LinkButtonContent({required this.icon, required this.label});
final IconData icon;
final String label;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 15, color: palette.textMuted),
const SizedBox(width: 7),
Text(label),
],
);
}
}
class _ExtensionStats extends StatelessWidget {
const _ExtensionStats({required this.store});
final StoreExtension store;
@override
Widget build(BuildContext context) {
return Row(
key: const ValueKey('extension-details-stats'),
mainAxisSize: MainAxisSize.min,
children: [
_MetadataItem(icon: Icons.star_rounded, value: store.stars.toString()),
const SizedBox(width: 12),
_MetadataItem(icon: Icons.download_outlined, value: store.installCount.toString()),
],
);
}
}
class _MetadataItem extends StatelessWidget {
const _MetadataItem({required this.icon, required this.value});
final IconData icon;
final String value;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: palette.textMuted),
const SizedBox(width: 6),
Text(
value,
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600),
),
],
);
}
}
MarkdownStyleSheet _markdownStyle(AppPalette palette, {required bool mobile}) {
final paragraph = TextStyle(color: palette.textSecondary, fontSize: mobile ? 14 : 13.5, height: 1.62);
final heading = TextStyle(color: palette.textPrimary, fontWeight: FontWeight.w800, height: 1.25);
return MarkdownStyleSheet(
a: paragraph.copyWith(color: palette.brand, decoration: TextDecoration.underline),
p: paragraph,
code: paragraph.copyWith(fontFamily: 'monospace', fontSize: 12, backgroundColor: palette.surfaceSoft),
h1: heading.copyWith(fontSize: mobile ? 21 : 20),
h2: heading.copyWith(fontSize: mobile ? 18 : 17),
h3: heading.copyWith(fontSize: mobile ? 16 : 15),
h4: heading.copyWith(fontSize: 14),
h5: heading.copyWith(fontSize: 13),
h6: heading.copyWith(fontSize: 12),
em: paragraph.copyWith(fontStyle: FontStyle.italic),
strong: paragraph.copyWith(fontWeight: FontWeight.w800, color: palette.textPrimary),
blockSpacing: 12,
listIndent: 22,
listBullet: paragraph,
blockquote: paragraph,
blockquotePadding: const EdgeInsets.fromLTRB(12, 8, 10, 8),
blockquoteDecoration: BoxDecoration(
color: palette.surfaceSoft,
border: Border(left: BorderSide(color: palette.brand, width: 3)),
),
codeblockPadding: const EdgeInsets.all(12),
codeblockDecoration: BoxDecoration(
color: palette.surfaceSoft,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: palette.border),
),
horizontalRuleDecoration: BoxDecoration(
border: Border(top: BorderSide(color: palette.border)),
),
tableHead: paragraph.copyWith(color: palette.textPrimary, fontWeight: FontWeight.w800),
tableBody: paragraph,
tableBorder: TableBorder.all(color: palette.border),
tableCellsPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
);
}
Future<_ReadmeInfo> _loadReadme(ExtensionListItem item) async {
final installed = item.installed;
final remote = item.store?.readme ?? '';
if (installed == null || Util.isWeb()) return _ReadmeInfo(content: remote);
try {
final rootDirectory = installed.devMode
? installed.devPath
: path.join(Util.getStorageDir(), 'extensions', installed.identity);
for (final name in const ['README.md', 'readme.md', 'README.MD']) {
final filePath = path.join(rootDirectory, name);
final file = File(filePath);
if (file.existsSync()) {
return _ReadmeInfo(content: file.readAsStringSync(), localPath: filePath);
}
}
} catch (_) {
// Fall back to the store copy when local storage is unavailable or unreadable.
}
return _ReadmeInfo(content: remote);
}
String? _resolveReadmeUrl(ExtensionListItem item, String? raw, {required _ReadmeInfo info, required bool forImage}) {
final store = item.store;
final value = raw?.trim() ?? '';
if (value.isEmpty) return null;
final parsed = Uri.tryParse(value);
if (parsed != null && parsed.hasScheme) return parsed.toString();
if (forImage && info.localPath != null) {
final clean = value.split('#').first;
return Uri.file(path.normalize(path.join(path.dirname(info.localPath!), clean))).toString();
}
if (store == null) return null;
final ref = store.commitSha?.isNotEmpty == true ? store.commitSha! : 'HEAD';
final directory = (store.directory ?? '').split('/').where((segment) => segment.isNotEmpty).join('/');
final suffix = directory.isEmpty ? '' : '$directory/';
final base = forImage
? Uri.https('raw.githubusercontent.com', '/${store.repoFullName}/$ref/$suffix')
: Uri.https('github.com', '/${store.repoFullName}/blob/$ref/$suffix');
return base.resolve(value).toString();
}
class _ReadmeInfo {
const _ReadmeInfo({required this.content, this.localPath});
final String content;
final String? localPath;
}
Future<void> _openUrl(String value) async {
final uri = Uri.tryParse(value);
if (uri == null) return;
await launchUrl(uri, mode: LaunchMode.externalApplication);
}
@@ -0,0 +1,104 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import '../../../../api/model/extension.dart';
import '../../../../util/util.dart';
import '../../application/extensions_controller.dart';
enum ExtensionIconSourceKind { asset, file, network }
@immutable
class ExtensionIconSource {
const ExtensionIconSource(this.kind, this.location);
final ExtensionIconSourceKind kind;
final String location;
}
@visibleForTesting
ExtensionIconSource resolveExtensionIconSource(ExtensionListItem item, {bool? web, String? storageDirectory}) {
const fallbackAsset = 'assets/extension/default_icon.png';
final installed = item.installed;
if (installed != null) {
final icon = installed.icon.trim();
if (icon.isEmpty) {
return const ExtensionIconSource(ExtensionIconSourceKind.asset, fallbackAsset);
}
if (web ?? kIsWeb) {
return ExtensionIconSource(ExtensionIconSourceKind.network, _installedExtensionIconUrl(installed, icon));
}
final rootDirectory = installed.devMode
? installed.devPath
: path.join(storageDirectory ?? Util.getStorageDir(), 'extensions', installed.identity);
return ExtensionIconSource(ExtensionIconSourceKind.file, path.join(rootDirectory, icon));
}
final remoteIcon = item.store?.icon?.trim() ?? '';
if (remoteIcon.isNotEmpty) {
return ExtensionIconSource(ExtensionIconSourceKind.network, remoteIcon);
}
return const ExtensionIconSource(ExtensionIconSourceKind.asset, fallbackAsset);
}
String _installedExtensionIconUrl(Extension extension, String icon) {
final iconSegments = icon
.replaceAll('\\', '/')
.split('/')
.where((segment) => segment.isNotEmpty && segment != '.')
.toList();
return Uri(pathSegments: ['', 'fs', 'extensions', extension.identity, ...iconSegments]).toString();
}
class ExtensionIcon extends StatelessWidget {
const ExtensionIcon({
super.key,
required this.item,
required this.size,
required this.borderRadius,
this.fallbackPadding = EdgeInsets.zero,
this.fallbackBackgroundColor,
this.fallbackFit = BoxFit.contain,
});
final ExtensionListItem item;
final double size;
final BorderRadius borderRadius;
final EdgeInsetsGeometry fallbackPadding;
final Color? fallbackBackgroundColor;
final BoxFit fallbackFit;
@override
Widget build(BuildContext context) {
final fallback = Container(
width: size,
height: size,
padding: fallbackPadding,
color: fallbackBackgroundColor,
child: Image.asset('assets/extension/default_icon.png', fit: fallbackFit),
);
final source = resolveExtensionIconSource(item);
final image = switch (source.kind) {
ExtensionIconSourceKind.asset => fallback,
ExtensionIconSourceKind.file => Image.file(
File(source.location),
width: size,
height: size,
fit: BoxFit.cover,
errorBuilder: (_, _, _) => fallback,
),
ExtensionIconSourceKind.network => Image.network(
source.location,
width: size,
height: size,
fit: BoxFit.cover,
errorBuilder: (_, _, _) => fallback,
),
};
return ClipRRect(borderRadius: borderRadius, child: image);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,152 @@
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import '../../../../core/window/app_window_chrome.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../l10n/l10n.dart';
import '../../../tasks/domain/task_record.dart';
import '../../../tasks/presentation/widgets/speed_monitor_card.dart';
enum TaskFilter { all, downloading, completed, paused, failed }
class FilterSidebar extends StatelessWidget {
const FilterSidebar({super.key, required this.activeFilter, required this.onFilterSelected, required this.tasks});
final TaskFilter activeFilter;
final ValueChanged<TaskFilter> onFilterSelected;
final List<TaskRecord> tasks;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final titleStyle = TextStyle(
color: palette.textMuted,
fontSize: 12,
fontWeight: FontWeight.w700,
letterSpacing: 2.4,
);
return Container(
width: AppDesignTokens.filterSidebarWidth,
color: palette.sideBg,
padding: EdgeInsets.only(top: AppWindowChrome.reservesHeaderInset ? AppDesignTokens.windowHeaderHeight : 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: AppDesignTokens.contentHeaderHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Align(
alignment: Alignment.centerLeft,
child: Text(context.l10n.filters.toUpperCase(), style: titleStyle),
),
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
children: [
_FilterItem(
label: context.l10n.allTasks,
icon: Icons.grid_view_rounded,
active: activeFilter == TaskFilter.all,
count: tasks.length.toString(),
onTap: () => onFilterSelected(TaskFilter.all),
),
_FilterItem(
label: context.l10n.downloading,
icon: Icons.south_rounded,
active: activeFilter == TaskFilter.downloading,
count: _count(TaskStatus.downloading).toString(),
onTap: () => onFilterSelected(TaskFilter.downloading),
),
_FilterItem(
label: context.l10n.completed,
icon: Icons.check_circle_outline,
active: activeFilter == TaskFilter.completed,
onTap: () => onFilterSelected(TaskFilter.completed),
),
_FilterItem(
label: context.l10n.pause,
icon: Icons.pause_circle_outline,
active: activeFilter == TaskFilter.paused,
onTap: () => onFilterSelected(TaskFilter.paused),
),
_FilterItem(
label: context.l10n.failed,
icon: Icons.error_outline,
active: activeFilter == TaskFilter.failed,
onTap: () => onFilterSelected(TaskFilter.failed),
),
],
),
),
const Spacer(),
const SpeedMonitorCard(),
],
),
);
}
int _count(TaskStatus status) {
return tasks.where((task) => task.status == status).length;
}
}
class _FilterItem extends StatelessWidget {
const _FilterItem({required this.label, required this.icon, required this.active, required this.onTap, this.count});
final String label;
final IconData icon;
final bool active;
final VoidCallback onTap;
final String? count;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.only(bottom: 4),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: active ? palette.itemActiveBg : Colors.transparent,
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
),
child: Row(
children: [
Icon(icon, size: 16, color: active ? palette.textPrimary : palette.textSecondary),
const SizedBox(width: 12),
Expanded(
child: Text(
label,
style: TextStyle(
color: active ? palette.textPrimary : palette.textSecondary,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
),
if (count != null)
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(color: palette.cardHoverBg, borderRadius: BorderRadius.circular(4)),
child: Text(
count!,
style: TextStyle(
color: active ? palette.textPrimary : palette.textSecondary,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,6 @@
const double kWindowTaskbarHeight = 30;
const double kColumnHeaderContentHeight = 30;
const double kColumnHeaderTotalHeight = kWindowTaskbarHeight + kColumnHeaderContentHeight;
const double kContentTopBarHeight = 40;
const double kSidebarItemHeight = 40;
const double kSidebarItemGap = 3;
@@ -0,0 +1,198 @@
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.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_tooltip.dart';
import '../../../../shared/widgets/gopeed_app_mark.dart';
import '../../../../l10n/l10n.dart';
enum RailSection { tasks, extensions, settings }
class PrimaryRail extends StatelessWidget {
const PrimaryRail({super.key, this.activeSection = RailSection.tasks});
final RailSection activeSection;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Container(
width: AppDesignTokens.railWidth,
color: palette.railBg,
padding: EdgeInsets.only(top: AppWindowChrome.reservesHeaderInset ? AppDesignTokens.windowHeaderHeight : 0),
child: Column(
children: [
SizedBox(
height: AppDesignTokens.contentHeaderHeight,
child: const Center(child: GopeedAppMark(key: ValueKey('primary-rail-app-mark'))),
),
const SizedBox(height: AppDesignTokens.space8),
_RailItem(
key: const ValueKey('primary-rail-tasks-item'),
icon: Icons.download_rounded,
label: context.l10n.task,
active: activeSection == RailSection.tasks,
onTap: () => context.go('/'),
),
const SizedBox(height: 28),
_RailItem(
icon: Icons.extension_outlined,
label: context.l10n.extensions,
active: activeSection == RailSection.extensions,
onTap: () => context.go('/extensions'),
),
const SizedBox(height: 28),
_RailItem(
icon: Icons.settings_outlined,
label: context.l10n.setting,
active: activeSection == RailSection.settings,
onTap: () => context.go('/settings'),
),
const Spacer(),
],
),
);
}
}
class PrimaryBottomNavigation extends StatelessWidget {
const PrimaryBottomNavigation({super.key, this.activeSection = RailSection.tasks});
final RailSection activeSection;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Container(
decoration: BoxDecoration(
color: palette.railBg,
border: Border(top: BorderSide(color: palette.border)),
),
child: SafeArea(
top: false,
child: SizedBox(
height: 64,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: [
Expanded(
child: _BottomNavItem(
icon: Icons.download_rounded,
label: context.l10n.task,
active: activeSection == RailSection.tasks,
onTap: () => context.go('/'),
),
),
Expanded(
child: _BottomNavItem(
icon: Icons.extension_outlined,
label: context.l10n.extensions,
active: activeSection == RailSection.extensions,
onTap: () => context.go('/extensions'),
),
),
Expanded(
child: _BottomNavItem(
icon: Icons.settings_outlined,
label: context.l10n.setting,
active: activeSection == RailSection.settings,
onTap: () => context.go('/settings'),
),
),
],
),
),
),
),
);
}
}
class _RailItem extends StatelessWidget {
const _RailItem({super.key, required this.icon, required this.label, required this.onTap, this.active = false});
final IconData icon;
final String label;
final VoidCallback onTap;
final bool active;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return AppTooltip(
message: label,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: SizedBox(
width: AppDesignTokens.railWidth,
height: 24,
child: Stack(
children: [
if (active)
Align(
alignment: Alignment.centerLeft,
child: Container(
key: const ValueKey('primary-rail-active-indicator'),
width: 2,
height: 24,
color: palette.textPrimary,
),
),
Center(child: Icon(icon, size: 18, color: active ? palette.textPrimary : palette.textMuted)),
],
),
),
),
),
);
}
}
class _BottomNavItem extends StatelessWidget {
const _BottomNavItem({required this.icon, required this.label, required this.onTap, this.active = false});
final IconData icon;
final String label;
final VoidCallback onTap;
final bool active;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: SizedBox(
height: 54,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 19, color: active ? palette.textPrimary : palette.textMuted),
const SizedBox(height: 4),
Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: active ? palette.textPrimary : palette.textMuted,
fontSize: 10,
fontWeight: active ? FontWeight.w700 : FontWeight.w600,
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
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 '../../../../l10n/l10n.dart';
class TasksTopBar extends StatelessWidget {
const TasksTopBar({
super.key,
required this.searchController,
required this.onAddTask,
required this.batchMode,
required this.selectedBatchCount,
required this.canPauseSelected,
required this.canResumeSelected,
required this.onToggleBatchMode,
required this.onPauseSelected,
required this.onResumeSelected,
required this.onDeleteSelected,
});
final TextEditingController searchController;
final VoidCallback onAddTask;
final bool batchMode;
final int selectedBatchCount;
final bool canPauseSelected;
final bool canResumeSelected;
final VoidCallback onToggleBatchMode;
final VoidCallback onPauseSelected;
final VoidCallback onResumeSelected;
final VoidCallback onDeleteSelected;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final headerBorder = palette.border;
return SizedBox(
height: AppDesignTokens.contentHeaderHeight,
child: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.only(left: 32, right: 32),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: ConstrainedBox(
key: const ValueKey('tasks-search-field-container'),
constraints: const BoxConstraints(maxWidth: 240),
child: _SearchField(controller: searchController, palette: palette, borderColor: headerBorder),
),
),
),
const SizedBox(width: 16),
ConstrainedBox(
key: const ValueKey('tasks-create-button-container'),
constraints: const BoxConstraints(maxWidth: 190),
child: _AddTaskButton(onPressed: onAddTask),
),
const SizedBox(width: 16),
Row(
key: const ValueKey('tasks-top-action-buttons'),
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_ActionIconButton(
icon: Icons.pause_outlined,
onPressed: !batchMode || canPauseSelected ? onPauseSelected : null,
),
const SizedBox(width: 4),
_ActionIconButton(
icon: Icons.play_arrow_outlined,
onPressed: !batchMode || canResumeSelected ? onResumeSelected : null,
),
const SizedBox(width: 4),
_ActionIconButton(
icon: Icons.delete_outline,
onPressed: selectedBatchCount > 0 ? onDeleteSelected : null,
),
const SizedBox(width: 4),
_ActionIconButton(icon: Icons.checklist_rtl_outlined, onPressed: onToggleBatchMode),
],
),
],
),
),
),
);
}
}
class _SearchField extends StatelessWidget {
const _SearchField({required this.controller, required this.palette, required this.borderColor});
final TextEditingController controller;
final AppPalette palette;
final Color borderColor;
@override
Widget build(BuildContext context) {
return shad.ComponentTheme<shad.FocusOutlineTheme>(
data: const shad.FocusOutlineTheme(
align: 0,
border: Border.fromBorderSide(BorderSide(color: Colors.transparent, width: 0)),
),
child: SizedBox(
height: 40,
child: shad.TextField(
controller: controller,
style: TextStyle(color: palette.textPrimary, fontSize: 14, height: 1),
placeholder: Text(
context.l10n.searchDownloads,
style: TextStyle(color: palette.searchHint, fontSize: 14, height: 1),
),
features: [shad.InputFeature.leading(Icon(Icons.search_rounded, size: 14, color: palette.textMuted))],
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
decoration: BoxDecoration(
color: palette.inputBg,
borderRadius: BorderRadius.circular(4),
border: Border.all(color: borderColor),
),
),
),
);
}
}
class _AddTaskButton extends StatelessWidget {
const _AddTaskButton({required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return AppPrimaryButton(
onPressed: onPressed,
leading: const Icon(Icons.add),
child: Text(context.l10n.create, maxLines: 1, overflow: TextOverflow.ellipsis),
);
}
}
class _ActionIconButton extends StatelessWidget {
const _ActionIconButton({required this.icon, required this.onPressed});
final IconData icon;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return SizedBox.square(
dimension: 30,
child: shad.IconButton.outline(size: shad.ButtonSize.xSmall, onPressed: onPressed, icon: Icon(icon, size: 18)),
);
}
}
@@ -0,0 +1,49 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:window_manager/window_manager.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/window/desktop_window_header.dart';
import 'layout_constants.dart';
class WindowChromeOverlay extends StatelessWidget {
const WindowChromeOverlay({super.key});
@override
Widget build(BuildContext context) {
final isWindowsDesktop = !kIsWeb && defaultTargetPlatform == TargetPlatform.windows;
return SizedBox(
height: kWindowTaskbarHeight,
child: Row(
children: [
SizedBox(
width: 64 + 264,
child: isWindowsDesktop ? const DragToMoveArea(child: SizedBox.expand()) : const SizedBox.shrink(),
),
const Expanded(child: _WindowTaskbar()),
],
),
);
}
}
class _WindowTaskbar extends StatelessWidget {
const _WindowTaskbar();
@override
Widget build(BuildContext context) {
final isWindowsDesktop = !kIsWeb && defaultTargetPlatform == TargetPlatform.windows;
final palette = AppPalette.of(context);
return Container(
color: palette.bg,
child: Row(
children: [
Expanded(child: isWindowsDesktop ? const DragToMoveArea(child: SizedBox.expand()) : const SizedBox.shrink()),
if (isWindowsDesktop) const WindowCaptionControls(),
],
),
);
}
}
+1
View File
@@ -0,0 +1 @@
# Search feature
@@ -0,0 +1 @@
# Settings feature
@@ -0,0 +1,44 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/downloader_config.dart';
import '../../../app/application/app_runtime_controller.dart';
import '../../../core/capabilities/app_capabilities.dart';
final settingsControllerProvider = AsyncNotifierProvider.autoDispose<SettingsController, SettingsState>(
SettingsController.new,
);
class SettingsState {
const SettingsState({required this.config, this.saving = false});
final DownloaderConfig config;
final bool saving;
SettingsState copyWith({DownloaderConfig? config, bool? saving}) {
return SettingsState(config: config ?? this.config, saving: saving ?? this.saving);
}
}
class SettingsController extends AsyncNotifier<SettingsState> {
@override
Future<SettingsState> build() async {
await ref.read(appRuntimeControllerProvider.future);
return SettingsState(config: await ref.read(gopeedServiceProvider).getConfig());
}
Future<void> reload({bool showLoading = true}) async {
if (showLoading) state = const AsyncValue.loading();
state = AsyncValue.data(SettingsState(config: await ref.read(gopeedServiceProvider).getConfig()));
}
Future<void> save(DownloaderConfig config) async {
state = AsyncValue.data(SettingsState(config: config, saving: true));
await ref.read(gopeedServiceProvider).putConfig(config);
ref.read(appRuntimeControllerProvider.notifier).replaceDownloaderConfig(config);
state = AsyncValue.data(SettingsState(config: config));
}
Future<void> testWebhook(String url) async {
await ref.read(gopeedServiceProvider).testWebhook(url);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,224 @@
import 'dart:async';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_loading_button.dart';
import '../../../../util/package_info.dart';
import '../../../../util/updater.dart';
import '../../../../util/util.dart';
import '../../../../l10n/l10n.dart';
typedef StartAppUpdate = Future<void> Function(VersionInfo versionInfo, UpdateProgressCallback onProgress);
Future<void> showAppUpdateDialog(
BuildContext context, {
required VersionInfo versionInfo,
required StartAppUpdate onUpdate,
}) async {
final overlay = const shad.DialogOverlayHandler().show<void>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) {
var updating = false;
var received = 0;
var total = 0;
String? errorMessage;
return StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
final availableWidth = MediaQuery.sizeOf(dialogContext).width - 104;
final dialogWidth = availableWidth.clamp(260.0, 380.0);
final releaseNotes = localizedReleaseNotes(
versionInfo.changeLog,
Localizations.localeOf(dialogContext).languageCode,
);
final progress = total > 0 ? (received / total).clamp(0.0, 1.0) : null;
Future<void> update() async {
setDialogState(() {
updating = true;
errorMessage = null;
});
try {
await onUpdate(versionInfo, (nextReceived, nextTotal) {
if (!dialogContext.mounted) return;
setDialogState(() {
received = nextReceived;
total = nextTotal;
});
});
} catch (error) {
if (!dialogContext.mounted) return;
setDialogState(() {
updating = false;
errorMessage = dialogContext.l10n.updateFailed;
});
}
}
return shad.AlertDialog(
padding: const EdgeInsets.all(20),
title: SizedBox(
width: dialogWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
dialogContext.l10n.newVersionAvailable,
key: const ValueKey('app-update-heading'),
textAlign: TextAlign.center,
),
const SizedBox(height: 3),
Text(
'$appVersion → ${versionInfo.version}',
textAlign: TextAlign.center,
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w400),
),
],
),
),
content: SizedBox(
key: const ValueKey('app-update-dialog'),
width: dialogWidth,
child: Column(
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,
),
),
),
if (updating) ...[
const SizedBox(height: 16),
shad.LinearProgressIndicator(
value: progress,
minHeight: 5,
borderRadius: BorderRadius.circular(999),
color: palette.brand,
backgroundColor: palette.progressTrack,
),
const SizedBox(height: 7),
Row(
children: [
Text(
progress == null
? dialogContext.l10n.preparingDownload
: '${(progress * 100).toStringAsFixed(0)}%',
style: TextStyle(color: palette.textSecondary, fontSize: 11),
),
const Spacer(),
if (total > 0)
Text(
'${Util.fmtByte(received)} / ${Util.fmtByte(total)}',
style: TextStyle(color: palette.textSecondary, fontSize: 11),
),
],
),
],
if (errorMessage != null) ...[
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 15, color: palette.error),
const SizedBox(width: 6),
Text(errorMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
],
),
],
const SizedBox(height: 18),
Wrap(
key: const ValueKey('app-update-actions'),
alignment: WrapAlignment.center,
spacing: 8,
runSpacing: 8,
children: [
shad.SecondaryButton(
onPressed: updating ? null : () => unawaited(shad.closeOverlay(dialogContext)),
child: Text(dialogContext.l10n.newVersionLater),
),
AppLoadingButton(
onPressed: () => unawaited(update()),
loading: updating,
variant: AppLoadingButtonVariant.primary,
icon: const Icon(Icons.system_update_alt_outlined, size: 17),
child: Text(dialogContext.l10n.newVersionUpdate),
),
],
),
],
),
),
);
},
);
},
);
await overlay.future;
}
class _ReleaseNotes extends StatelessWidget {
const _ReleaseNotes({required this.notes});
final String notes;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final lines = notes
.split('\n')
.map((line) => line.trimRight())
.where((line) => line.trim().isNotEmpty)
.where((line) => !RegExp(r'^#\s+(Release notes|更新日志)\s*$', caseSensitive: false).hasMatch(line.trim()));
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final line in lines) ...[
if (line.startsWith('#'))
Text(
_plainMarkdown(line.replaceFirst(RegExp(r'^#+\s*'), '')),
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
)
else if (line.trimLeft().startsWith('- '))
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('• ', style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.45)),
Expanded(
child: Text(
_plainMarkdown(line.trimLeft().substring(2).replaceFirst(RegExp(r'\s+@[\w-]+\s+\(#\d+\)\s*$'), '')),
style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.45),
),
),
],
)
else
Text(_plainMarkdown(line), style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.45)),
const SizedBox(height: 7),
],
],
);
}
}
String _plainMarkdown(String value) {
return value
.replaceAllMapped(RegExp(r'\[([^\]]+)\]\([^\)]+\)'), (match) => match.group(1) ?? '')
.replaceAll(RegExp(r'\*\*|__|`'), '');
}
@@ -0,0 +1,225 @@
import 'package:flutter/material.dart' show Divider, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../api/model/downloader_config.dart';
import '../../../../core/utils/breakpoints.dart';
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 '../../../../l10n/l10n.dart';
class DownloadCategoryDraft {
const DownloadCategoryDraft({required this.name, required this.path});
final String name;
final String path;
}
class DownloadCategoriesControl extends StatelessWidget {
const DownloadCategoriesControl({
super.key,
required this.categories,
required this.displayName,
required this.onAdd,
required this.onEdit,
required this.onDelete,
});
final List<DownloadCategory> categories;
final String Function(DownloadCategory category) displayName;
final VoidCallback onAdd;
final ValueChanged<DownloadCategory> onEdit;
final ValueChanged<DownloadCategory> onDelete;
@override
Widget build(BuildContext context) {
final desktop = MediaQuery.sizeOf(context).width >= Breakpoints.mobile;
final visibleCategories = categories.where((category) => !category.isDeleted).toList(growable: false);
final palette = AppPalette.of(context);
return SizedBox(
key: const ValueKey('download-categories-editor'),
width: desktop ? AppDesignTokens.settingsFormControlWidth : double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < visibleCategories.length; index++) ...[
if (index > 0)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Divider(color: palette.border),
),
_CategoryRow(
category: visibleCategories[index],
name: displayName(visibleCategories[index]),
onEdit: () => onEdit(visibleCategories[index]),
onDelete: () => onDelete(visibleCategories[index]),
),
],
if (visibleCategories.isNotEmpty) const SizedBox(height: 10),
Align(
alignment: desktop ? Alignment.centerRight : Alignment.centerLeft,
child: shad.SecondaryButton(
key: const ValueKey('add-download-category'),
onPressed: onAdd,
leading: const Icon(Icons.add, size: 17),
child: Text(context.l10n.add),
),
),
],
),
);
}
}
class _CategoryRow extends StatelessWidget {
const _CategoryRow({required this.category, required this.name, required this.onEdit, required this.onDelete});
final DownloadCategory category;
final String name;
final VoidCallback onEdit;
final VoidCallback onDelete;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Row(
key: ValueKey('download-category-${category.nameKey ?? category.name}-${category.path}'),
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
),
const SizedBox(height: 3),
Text(
category.path,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 12),
),
],
),
),
const SizedBox(width: 8),
shad.GhostButton(
key: ValueKey('edit-download-category-${category.nameKey ?? category.name}'),
density: shad.ButtonDensity.icon,
onPressed: onEdit,
child: const Icon(Icons.edit_outlined, size: 17),
),
shad.GhostButton(
key: ValueKey('delete-download-category-${category.nameKey ?? category.name}'),
density: shad.ButtonDensity.icon,
onPressed: onDelete,
child: const Icon(Icons.delete_outline, size: 17),
),
],
);
}
}
Future<DownloadCategoryDraft?> showDownloadCategoryDialog(
BuildContext context, {
DownloadCategory? category,
required String initialName,
required String initialPath,
}) async {
final nameController = TextEditingController(text: initialName);
final pathController = TextEditingController(text: category?.path ?? initialPath);
String? validationMessage;
final overlay = const shad.DialogOverlayHandler().show<DownloadCategoryDraft?>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
void submit() {
final name = nameController.text.trim();
final path = pathController.text.trim();
if (name.isEmpty || path.isEmpty) {
setDialogState(() => validationMessage = dialogContext.l10n.categoryFieldsRequired);
return;
}
shad.closeOverlay(dialogContext, DownloadCategoryDraft(name: name, path: path));
}
return shad.AlertDialog(
title: Text(category == null ? dialogContext.l10n.addCategory : dialogContext.l10n.editCategory),
content: SizedBox(
key: const ValueKey('download-category-dialog'),
width: (MediaQuery.sizeOf(dialogContext).width - 64).clamp(260.0, 420.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.categoryName, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
shad.TextField(key: const ValueKey('download-category-name'), controller: nameController),
const SizedBox(height: 14),
Text(dialogContext.l10n.categoryPath, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
AppPathPickerField.downloadDirectory(
fieldKey: const ValueKey('download-category-path'),
controller: pathController,
desktopWidth: AppDesignTokens.settingsFormControlWidth,
allowAndroidEditing: true,
),
if (validationMessage != null) ...[
const SizedBox(height: 8),
Text(validationMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
],
],
),
),
actions: [
shad.SecondaryButton(
onPressed: () => shad.closeOverlay(dialogContext),
child: Text(dialogContext.l10n.cancel),
),
AppPrimaryButton(onPressed: submit, child: Text(dialogContext.l10n.confirm)),
],
);
},
),
);
try {
return await overlay.future;
} finally {
await WidgetsBinding.instance.endOfFrame;
nameController.dispose();
pathController.dispose();
}
}
Future<bool> showDeleteDownloadCategoryDialog(BuildContext context, String name) async {
final overlay = const shad.DialogOverlayHandler().show<bool>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) => shad.AlertDialog(
title: Text(dialogContext.l10n.deleteCategoryTitle),
content: Text(dialogContext.l10n.confirmDeleteNamed(name)),
actions: [
shad.SecondaryButton(
onPressed: () => shad.closeOverlay(dialogContext, false),
child: Text(dialogContext.l10n.cancel),
),
shad.DestructiveButton(
onPressed: () => shad.closeOverlay(dialogContext, true),
child: Text(dialogContext.l10n.delete),
),
],
),
);
return await overlay.future ?? false;
}
@@ -0,0 +1,22 @@
import 'package:flutter/widgets.dart';
import '../../../../shared/theme/app_design_tokens.dart';
class SettingsContentFrame extends StatelessWidget {
const SettingsContentFrame({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppDesignTokens.space24),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppDesignTokens.settingsContentMaxWidth),
child: SizedBox(width: double.infinity, child: child),
),
),
);
}
}
@@ -0,0 +1,80 @@
import 'package:flutter/widgets.dart';
import '../../../../core/utils/breakpoints.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
class SettingsItem extends StatelessWidget {
const SettingsItem({super.key, required this.title, required this.child, this.subtitle});
final String title;
final String? subtitle;
final Widget child;
@override
Widget build(BuildContext context) {
final desktop = MediaQuery.sizeOf(context).width >= Breakpoints.mobile;
if (desktop) {
return LayoutBuilder(
builder: (context, constraints) {
const leadingSpace = 2.0;
const columnGap = AppDesignTokens.space24;
final maxControlWidth =
(constraints.maxWidth - leadingSpace - columnGap - AppDesignTokens.settingsItemMinLabelWidth).clamp(
0.0,
double.infinity,
);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(width: leadingSpace),
Expanded(
child: _SettingsItemLabel(title: title, subtitle: subtitle),
),
const SizedBox(width: columnGap),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxControlWidth),
child: child,
),
],
);
},
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_SettingsItemLabel(title: title, subtitle: subtitle),
const SizedBox(height: 10),
Align(alignment: Alignment.centerLeft, child: child),
],
);
}
}
class _SettingsItemLabel extends StatelessWidget {
const _SettingsItemLabel({required this.title, this.subtitle});
final String title;
final String? subtitle;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final subtitleText = subtitle?.trim();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w700),
),
if (subtitleText != null && subtitleText.isNotEmpty) ...[
const SizedBox(height: 4),
Text(subtitleText, style: TextStyle(color: palette.textSecondary, fontSize: 12, height: 1.3)),
],
],
);
}
}
@@ -0,0 +1,84 @@
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../core/utils/breakpoints.dart';
import '../../../../l10n/l10n.dart';
class SettingsLanguageSelect extends StatelessWidget {
const SettingsLanguageSelect({super.key, required this.value, required this.onChanged});
final String value;
final ValueChanged<String> onChanged;
static List<Locale> get supportedLocales => AppLocalizations.supportedLocales;
static Set<String> get supportedValues => supportedLocales.map(localeConfigValue).toSet();
@override
Widget build(BuildContext context) {
final isMobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
final popupMaxHeight = isMobile ? math.min(MediaQuery.sizeOf(context).height * 0.62, 420.0) : 240.0;
return LayoutBuilder(
builder: (context, constraints) {
final width = isMobile || constraints.maxWidth < 220 ? constraints.maxWidth : 220.0;
return shad.Select<String>(
key: const ValueKey('settings-language-select'),
value: value,
constraints: BoxConstraints.tightFor(width: width, height: isMobile ? 44 : 36),
popupConstraints: BoxConstraints(maxHeight: popupMaxHeight),
itemBuilder: (context, selectedValue) => Text(_labelFor(context, selectedValue)),
popup: (context) => shad.SelectPopup<String>(
items: shad.SelectItemList(
children: [
shad.SelectItemButton<String>(
value: 'system',
child: _LanguageOptionLabel(label: context.l10n.followSystem, mobile: isMobile),
),
for (final locale in supportedLocales)
shad.SelectItemButton<String>(
value: localeConfigValue(locale),
child: _LanguageOptionLabel(label: lookupAppLocalizations(locale).label, mobile: isMobile),
),
],
),
),
onChanged: (selectedValue) {
if (selectedValue != null) {
onChanged(selectedValue);
}
},
);
},
);
}
String _labelFor(BuildContext context, String selectedValue) {
if (selectedValue == 'system') return context.l10n.followSystem;
final locale = localeFromConfig(selectedValue);
if (locale != null && supportedValues.contains(localeConfigValue(locale))) {
return lookupAppLocalizations(locale).label;
}
return context.l10n.followSystem;
}
}
class _LanguageOptionLabel extends StatelessWidget {
const _LanguageOptionLabel({required this.label, required this.mobile});
final String label;
final bool mobile;
@override
Widget build(BuildContext context) {
return SizedBox(
height: mobile ? 28 : 20,
child: Align(
alignment: Alignment.centerLeft,
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
),
);
}
}
@@ -0,0 +1,348 @@
import 'package:flutter/material.dart' show Divider, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../api/model/downloader_config.dart';
import '../../../../core/utils/breakpoints.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_path_picker_field.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../l10n/l10n.dart';
class SettingsListEntry {
const SettingsListEntry({required this.id, required this.title, this.subtitle});
final String id;
final String title;
final String? subtitle;
}
class SettingsListEditor extends StatelessWidget {
const SettingsListEditor({
super.key,
required this.entries,
required this.onAdd,
required this.onEdit,
required this.onDelete,
this.addLabel,
this.addButtonKey,
});
final List<SettingsListEntry> entries;
final VoidCallback onAdd;
final ValueChanged<int> onEdit;
final ValueChanged<int> onDelete;
final String? addLabel;
final Key? addButtonKey;
@override
Widget build(BuildContext context) {
final desktop = MediaQuery.sizeOf(context).width >= Breakpoints.mobile;
final palette = AppPalette.of(context);
return SizedBox(
width: desktop ? AppDesignTokens.settingsFormControlWidth : double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < entries.length; index++) ...[
if (index > 0)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Divider(color: palette.border),
),
Row(
key: ValueKey('settings-list-entry-${entries[index].id}'),
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
entries[index].title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textPrimary, fontSize: 13),
),
if (entries[index].subtitle case final subtitle?) ...[
const SizedBox(height: 3),
Text(
subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 11),
),
],
],
),
),
const SizedBox(width: 8),
shad.GhostButton(
key: ValueKey('edit-settings-list-${entries[index].id}'),
density: shad.ButtonDensity.icon,
onPressed: () => onEdit(index),
child: const Icon(Icons.edit_outlined, size: 17),
),
shad.GhostButton(
key: ValueKey('delete-settings-list-${entries[index].id}'),
density: shad.ButtonDensity.icon,
onPressed: () => onDelete(index),
child: const Icon(Icons.delete_outline, size: 17),
),
],
),
],
if (entries.isNotEmpty) const SizedBox(height: 10),
Align(
alignment: desktop ? Alignment.centerRight : Alignment.centerLeft,
child: shad.SecondaryButton(
key: addButtonKey,
onPressed: onAdd,
leading: const Icon(Icons.add, size: 17),
child: Text(addLabel ?? context.l10n.add),
),
),
],
),
);
}
}
Future<String?> showTextSettingDialog(
BuildContext context, {
required String title,
required String fieldLabel,
String initialValue = '',
bool requireHttpUrl = false,
Future<String?> Function()? pickPath,
Future<void> Function(String value)? onTest,
}) async {
final controller = TextEditingController(text: initialValue);
String? validationMessage;
bool testing = false;
String? testMessage;
bool? testSucceeded;
final overlay = const shad.DialogOverlayHandler().show<String?>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
String? validate() {
final value = controller.text.trim();
if (value.isEmpty) return dialogContext.l10n.fieldRequired(fieldLabel);
if (requireHttpUrl && !(value.startsWith('http://') || value.startsWith('https://'))) {
return dialogContext.l10n.urlInvalid;
}
return null;
}
Future<void> test() async {
final error = validate();
if (error != null) {
setDialogState(() => validationMessage = error);
return;
}
setDialogState(() {
testing = true;
validationMessage = null;
testMessage = null;
testSucceeded = null;
});
try {
await onTest!(controller.text.trim());
if (dialogContext.mounted) {
setDialogState(() {
testMessage = dialogContext.l10n.webhookTestSuccess;
testSucceeded = true;
});
}
} catch (_) {
if (dialogContext.mounted) {
setDialogState(() {
testMessage = dialogContext.l10n.webhookTestFail;
testSucceeded = false;
});
}
} finally {
if (dialogContext.mounted) setDialogState(() => testing = false);
}
}
return shad.AlertDialog(
title: Text(title),
content: SizedBox(
width: (MediaQuery.sizeOf(dialogContext).width - 64).clamp(260.0, 420.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(fieldLabel, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
if (pickPath == null)
shad.TextField(controller: controller)
else
AppPathPickerField(
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),
Text(
validationMessage ?? testMessage!,
style: TextStyle(
color: validationMessage != null
? palette.error
: testSucceeded == true
? palette.success
: palette.error,
fontSize: 12,
),
),
],
],
),
),
actions: [
if (onTest != null)
AppLoadingButton(
onPressed: test,
loading: testing,
icon: const Icon(Icons.send_outlined, size: 16),
child: Text(dialogContext.l10n.webhookTest),
),
shad.SecondaryButton(
onPressed: () => shad.closeOverlay(dialogContext),
child: Text(dialogContext.l10n.cancel),
),
AppPrimaryButton(
onPressed: () {
final error = validate();
if (error != null) {
setDialogState(() => validationMessage = error);
return;
}
shad.closeOverlay(dialogContext, controller.text.trim());
},
child: Text(dialogContext.l10n.confirm),
),
],
);
},
),
);
try {
return await overlay.future;
} finally {
await WidgetsBinding.instance.endOfFrame;
controller.dispose();
}
}
class GithubMirrorDraft {
const GithubMirrorDraft({required this.type, required this.url});
final GithubMirrorType type;
final String url;
}
Future<GithubMirrorDraft?> showGithubMirrorDialog(BuildContext context, {GithubMirror? mirror}) async {
var selectedType = mirror?.type ?? GithubMirrorType.jsdelivr;
final controller = TextEditingController(text: mirror?.url ?? '');
String? validationMessage;
final overlay = const shad.DialogOverlayHandler().show<GithubMirrorDraft?>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
return shad.AlertDialog(
title: Text(mirror == null ? dialogContext.l10n.addGithubMirror : dialogContext.l10n.editGithubMirror),
content: SizedBox(
width: (MediaQuery.sizeOf(dialogContext).width - 64).clamp(260.0, 420.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.githubMirrorType, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
Wrap(
spacing: 8,
children: [
for (final type in GithubMirrorType.values)
shad.SecondaryButton(
onPressed: () => setDialogState(() => selectedType = type),
leading: selectedType == type ? const Icon(Icons.check, size: 15) : null,
child: Text(type.name),
),
],
),
const SizedBox(height: 14),
Text(dialogContext.l10n.githubMirrorUrl, style: TextStyle(color: palette.textSecondary, fontSize: 12)),
const SizedBox(height: 6),
shad.TextField(controller: controller),
if (validationMessage != null) ...[
const SizedBox(height: 8),
Text(validationMessage!, style: TextStyle(color: palette.error, fontSize: 12)),
],
],
),
),
actions: [
shad.SecondaryButton(
onPressed: () => shad.closeOverlay(dialogContext),
child: Text(dialogContext.l10n.cancel),
),
AppPrimaryButton(
onPressed: () {
final value = controller.text.trim();
if (value.isEmpty || !(value.startsWith('http://') || value.startsWith('https://'))) {
setDialogState(() => validationMessage = dialogContext.l10n.urlInvalid);
return;
}
shad.closeOverlay(dialogContext, GithubMirrorDraft(type: selectedType, url: value));
},
child: Text(dialogContext.l10n.confirm),
),
],
);
},
),
);
try {
return await overlay.future;
} finally {
controller.dispose();
}
}
Future<bool> showDeleteSettingsEntryDialog(BuildContext context, String name) async {
final overlay = const shad.DialogOverlayHandler().show<bool>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) => shad.AlertDialog(
title: Text(dialogContext.l10n.confirmDeleteTitle),
content: Text(dialogContext.l10n.confirmDeleteNamed(name)),
actions: [
shad.SecondaryButton(
onPressed: () => shad.closeOverlay(dialogContext, false),
child: Text(dialogContext.l10n.cancel),
),
shad.DestructiveButton(
onPressed: () => shad.closeOverlay(dialogContext, true),
child: Text(dialogContext.l10n.delete),
),
],
),
);
return await overlay.future ?? false;
}
@@ -0,0 +1,316 @@
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import '../../../../app/application/app_appearance_controller.dart';
import '../../../../core/utils/breakpoints.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/theme/app_theme_color.dart';
import '../../../../l10n/l10n.dart';
class ThemeModeSelector extends StatelessWidget {
const ThemeModeSelector({super.key, required this.value, required this.accent, required this.onChanged});
final AppThemeMode value;
final AppThemeColor accent;
final ValueChanged<AppThemeMode> onChanged;
@override
Widget build(BuildContext context) {
final mobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
return LayoutBuilder(
builder: (context, constraints) {
final available = constraints.maxWidth.isFinite ? constraints.maxWidth : 390.0;
final optionWidth = ((available - 16) / 3).clamp(84.0, 116.0);
return Wrap(
spacing: 8,
runSpacing: 10,
alignment: mobile ? WrapAlignment.start : WrapAlignment.end,
children: [
_ThemeModeOption(
mode: AppThemeMode.system,
label: context.l10n.themeSystem,
icon: Icons.desktop_windows_outlined,
width: optionWidth,
selected: value == AppThemeMode.system,
accent: accent,
onPressed: onChanged,
),
_ThemeModeOption(
mode: AppThemeMode.light,
label: context.l10n.themeLight,
icon: Icons.light_mode_outlined,
width: optionWidth,
selected: value == AppThemeMode.light,
accent: accent,
onPressed: onChanged,
),
_ThemeModeOption(
mode: AppThemeMode.dark,
label: context.l10n.themeDark,
icon: Icons.dark_mode_outlined,
width: optionWidth,
selected: value == AppThemeMode.dark,
accent: accent,
onPressed: onChanged,
),
],
);
},
);
}
}
class ThemeColorSelector extends StatelessWidget {
const ThemeColorSelector({super.key, required this.value, required this.onChanged});
final AppThemeColor value;
final ValueChanged<AppThemeColor> onChanged;
@override
Widget build(BuildContext context) {
final dark = AppPalette.of(context).bg.computeLuminance() < 0.2;
final mobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
final swatchSize = mobile ? 38.0 : 30.0;
return Wrap(
spacing: mobile ? 14 : 10,
runSpacing: 12,
alignment: mobile ? WrapAlignment.start : WrapAlignment.end,
children: [
for (final color in AppThemeColor.values)
Semantics(
button: true,
selected: value == color,
label: _colorLabel(context, color),
child: GestureDetector(
key: ValueKey('theme-color-${color.key}'),
behavior: HitTestBehavior.opaque,
onTap: () => onChanged(color),
child: SizedBox.square(
dimension: swatchSize,
child: DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: value == color
? AppPalette.of(context).textPrimary
: AppPalette.of(context).border.withValues(alpha: 0),
width: 2,
),
),
child: Padding(
padding: const EdgeInsets.all(4),
child: DecoratedBox(
decoration: BoxDecoration(
color: dark ? color.dark : color.light,
shape: BoxShape.circle,
border: Border.all(color: AppPalette.of(context).border),
),
),
),
),
),
),
),
],
);
}
}
String _colorLabel(BuildContext context, AppThemeColor color) => switch (color) {
AppThemeColor.green => context.l10n.colorGreen,
AppThemeColor.red => context.l10n.colorRed,
AppThemeColor.rose => context.l10n.colorRose,
AppThemeColor.orange => context.l10n.colorOrange,
AppThemeColor.cyan => context.l10n.colorCyan,
AppThemeColor.blue => context.l10n.colorBlue,
AppThemeColor.amber => context.l10n.colorAmber,
AppThemeColor.purple => context.l10n.colorPurple,
};
class _ThemeModeOption extends StatefulWidget {
const _ThemeModeOption({
required this.mode,
required this.label,
required this.icon,
required this.width,
required this.selected,
required this.accent,
required this.onPressed,
});
final AppThemeMode mode;
final String label;
final IconData icon;
final double width;
final bool selected;
final AppThemeColor accent;
final ValueChanged<AppThemeMode> onPressed;
@override
State<_ThemeModeOption> createState() => _ThemeModeOptionState();
}
class _ThemeModeOptionState extends State<_ThemeModeOption> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Semantics(
button: true,
selected: widget.selected,
label: widget.label,
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
cursor: SystemMouseCursors.click,
child: GestureDetector(
key: ValueKey('theme-mode-${widget.mode.key}'),
behavior: HitTestBehavior.opaque,
onTap: () => widget.onPressed(widget.mode),
child: SizedBox(
width: widget.width,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 140),
height: 52,
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: _hovered ? palette.cardHoverBg : palette.cardBg,
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius + 2),
border: Border.all(
color: widget.selected ? palette.brand : palette.border,
width: widget.selected ? 2 : 1,
),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
child: _ThemePreview(mode: widget.mode, accent: widget.accent),
),
),
const SizedBox(height: 7),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(widget.icon, size: 14, color: palette.textSecondary),
const SizedBox(width: 5),
Flexible(
child: Text(
widget.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: widget.selected ? palette.textPrimary : palette.textSecondary,
fontSize: 12,
fontWeight: widget.selected ? FontWeight.w700 : FontWeight.w600,
),
),
),
],
),
],
),
),
),
),
);
}
}
class _ThemePreview extends StatelessWidget {
const _ThemePreview({required this.mode, required this.accent});
final AppThemeMode mode;
final AppThemeColor accent;
@override
Widget build(BuildContext context) {
return switch (mode) {
AppThemeMode.light => _PreviewSurface(
background: AppThemePreviewColors.lightBackground,
side: AppThemePreviewColors.lightSide,
line: AppThemePreviewColors.lightLine,
accent: accent.light,
),
AppThemeMode.dark => _PreviewSurface(
background: AppThemePreviewColors.darkBackground,
side: AppThemePreviewColors.darkSide,
line: AppThemePreviewColors.darkLine,
accent: accent.dark,
),
AppThemeMode.system => Stack(
fit: StackFit.expand,
children: [
const ColoredBox(color: AppThemePreviewColors.lightBackground),
Align(
alignment: Alignment.centerRight,
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 1,
child: const ColoredBox(color: AppThemePreviewColors.darkBackground),
),
),
_PreviewSurface(
background: AppThemePreviewColors.transparent,
side: AppThemePreviewColors.systemSide,
line: AppThemePreviewColors.systemLine,
accent: accent.light,
),
],
),
};
}
}
class _PreviewSurface extends StatelessWidget {
const _PreviewSurface({required this.background, required this.side, required this.line, required this.accent});
final Color background;
final Color side;
final Color line;
final Color accent;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: background,
child: Row(
children: [
SizedBox(width: 14, child: ColoredBox(color: side)),
Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 6, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 3,
width: 32,
decoration: BoxDecoration(color: line, borderRadius: BorderRadius.circular(2)),
),
const SizedBox(height: 5),
Container(
height: 3,
width: 22,
decoration: BoxDecoration(
color: line.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(2),
),
),
const Spacer(),
Container(
height: 3,
decoration: BoxDecoration(color: accent, borderRadius: BorderRadius.circular(2)),
),
],
),
),
),
],
),
);
}
}
@@ -0,0 +1,18 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/create_task.dart';
final pendingCreateTaskProvider = NotifierProvider<PendingCreateTask, CreateTask?>(PendingCreateTask.new);
class PendingCreateTask extends Notifier<CreateTask?> {
@override
CreateTask? build() => null;
void set(CreateTask? task) {
state = task;
}
void clear() {
state = null;
}
}
@@ -0,0 +1,51 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/create_task.dart';
class PendingUpdateTask {
const PendingUpdateTask({required this.id, required this.name});
final String id;
final String name;
}
final pendingUpdateTaskProvider = NotifierProvider<PendingUpdateTaskController, PendingUpdateTask?>(
PendingUpdateTaskController.new,
);
class PendingUpdateTaskController extends Notifier<PendingUpdateTask?> {
@override
PendingUpdateTask? build() => null;
void set(PendingUpdateTask? task) {
state = task;
}
void clear() {
state = null;
}
}
class PendingUpdateRequest {
const PendingUpdateRequest({required this.task, required this.createTask});
final PendingUpdateTask task;
final CreateTask createTask;
}
final pendingUpdateRequestProvider = NotifierProvider<PendingUpdateRequestController, PendingUpdateRequest?>(
PendingUpdateRequestController.new,
);
class PendingUpdateRequestController extends Notifier<PendingUpdateRequest?> {
@override
PendingUpdateRequest? build() => null;
void set(PendingUpdateRequest request) {
state = request;
}
void clear() {
state = null;
}
}
@@ -0,0 +1,54 @@
import 'package:flutter/foundation.dart';
class TaskBatchSelectionController extends ChangeNotifier {
final Set<String> _selectedIds = <String>{};
int get count => _selectedIds.length;
bool get isEmpty => _selectedIds.isEmpty;
bool get isNotEmpty => _selectedIds.isNotEmpty;
bool contains(String taskId) => _selectedIds.contains(taskId);
bool areAllSelected(Iterable<String> taskIds) {
var hasTasks = false;
for (final taskId in taskIds) {
hasTasks = true;
if (!_selectedIds.contains(taskId)) return false;
}
return hasTasks;
}
List<String> toList() => _selectedIds.toList(growable: false);
Iterable<String> where(bool Function(String taskId) test) => _selectedIds.where(test);
void toggle(String taskId) {
if (!_selectedIds.remove(taskId)) {
_selectedIds.add(taskId);
}
notifyListeners();
}
void replaceWith(Iterable<String> taskIds) {
final next = taskIds.toSet();
if (setEquals(_selectedIds, next)) return;
_selectedIds
..clear()
..addAll(next);
notifyListeners();
}
void removeAll(Iterable<String> taskIds) {
var changed = false;
for (final taskId in taskIds) {
changed = _selectedIds.remove(taskId) || changed;
}
if (changed) notifyListeners();
}
void clear() {
if (_selectedIds.isEmpty) return;
_selectedIds.clear();
notifyListeners();
}
}
@@ -0,0 +1,13 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/task.dart';
import '../../../core/capabilities/app_capabilities.dart';
final taskRuntimeStatusProvider = FutureProvider.autoDispose.family<TaskRuntimeStatus, String>((ref, taskId) async {
final status = await ref.read(gopeedServiceProvider).getTaskStatus(taskId);
final refreshTimer = Timer(const Duration(seconds: 1), ref.invalidateSelf);
ref.onDispose(refreshTimer.cancel);
return status;
});
@@ -0,0 +1,16 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/task.dart';
import '../../../api/model/task_stats.dart';
import '../../../core/capabilities/app_capabilities.dart';
typedef TaskStatsRequest = ({String taskId, Protocol? protocol});
final taskStatsProvider = FutureProvider.autoDispose.family<TaskStats?, TaskStatsRequest>((ref, request) async {
final refreshTimer = Timer(const Duration(seconds: 2), ref.invalidateSelf);
ref.onDispose(refreshTimer.cancel);
final json = await ref.read(gopeedServiceProvider).getTaskStats(request.taskId);
return TaskStats.fromJson(request.protocol, json);
});
@@ -0,0 +1,136 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../api/model/request.dart';
import '../../../api/model/resolve_task.dart';
import '../../../api/model/task.dart' as api_model;
import '../../../core/capabilities/app_capabilities.dart';
import '../domain/task_record.dart';
final tasksControllerProvider = AsyncNotifierProvider<TasksController, TasksState>(TasksController.new);
class TasksState {
const TasksState({
required this.tasks,
this.downloadSpeedBytesPerSecond = 0,
this.uploadSpeedBytesPerSecond = 0,
this.lastError,
});
final List<TaskRecord> tasks;
final int downloadSpeedBytesPerSecond;
final int uploadSpeedBytesPerSecond;
final Object? lastError;
TasksState copyWith({
List<TaskRecord>? tasks,
int? downloadSpeedBytesPerSecond,
int? uploadSpeedBytesPerSecond,
Object? lastError,
}) {
return TasksState(
tasks: tasks ?? this.tasks,
downloadSpeedBytesPerSecond: downloadSpeedBytesPerSecond ?? this.downloadSpeedBytesPerSecond,
uploadSpeedBytesPerSecond: uploadSpeedBytesPerSecond ?? this.uploadSpeedBytesPerSecond,
lastError: lastError,
);
}
}
({int downloadBytesPerSecond, int uploadBytesPerSecond}) aggregateTaskTransferSpeeds(Iterable<api_model.Task> tasks) {
var downloadBytesPerSecond = 0;
var uploadBytesPerSecond = 0;
for (final task in tasks) {
if (task.status == api_model.Status.running) {
downloadBytesPerSecond += task.progress.speed > 0 ? task.progress.speed : 0;
}
if (task.uploading && (task.status == api_model.Status.running || task.status == api_model.Status.done)) {
uploadBytesPerSecond += task.progress.uploadSpeed > 0 ? task.progress.uploadSpeed : 0;
}
}
return (downloadBytesPerSecond: downloadBytesPerSecond, uploadBytesPerSecond: uploadBytesPerSecond);
}
class TasksController extends AsyncNotifier<TasksState> {
Timer? _timer;
@override
Future<TasksState> build() async {
_timer = Timer.periodic(const Duration(seconds: 1), (_) => unawaited(refresh(silent: true)));
ref.onDispose(() => _timer?.cancel());
return _fetch();
}
Future<void> refresh({bool silent = false}) async {
if (!silent) {
state = const AsyncValue.loading();
}
try {
state = AsyncValue.data(await _fetch());
} catch (error, stackTrace) {
final previous = state.value;
if (previous != null && silent) {
state = AsyncValue.data(previous.copyWith(lastError: error));
} else {
state = AsyncValue.error(error, stackTrace);
}
}
}
Future<void> pause(String id) async {
await ref.read(gopeedServiceProvider).pauseTask(id);
await refresh(silent: true);
}
Future<void> resume(String id) async {
await ref.read(gopeedServiceProvider).continueTask(id);
await refresh(silent: true);
}
Future<void> updateUrl(String id, String url, {Map<String, String> headers = const {}}) async {
await updateRequest(
id,
Request(
url: url,
extra: ReqExtraHttp(header: headers).toJson(),
),
);
}
Future<void> updateRequest(String id, Request request) async {
await ref.read(gopeedServiceProvider).patchTask(id, ResolveTask(req: request));
await ref.read(gopeedServiceProvider).continueTask(id);
await refresh(silent: true);
}
Future<void> pauseAll(List<String>? ids) async {
await ref.read(gopeedServiceProvider).pauseAllTasks(ids);
await refresh(silent: true);
}
Future<void> resumeAll(List<String>? ids) async {
await ref.read(gopeedServiceProvider).continueAllTasks(ids);
await refresh(silent: true);
}
Future<void> deleteSelected(List<String>? ids, {bool force = false}) async {
await ref.read(gopeedServiceProvider).deleteTasks(ids, force);
await refresh(silent: true);
}
Future<TasksState> _fetch() async {
final tasks = await ref.read(gopeedServiceProvider).getTasks(api_model.Status.values);
final transferSpeeds = aggregateTaskTransferSpeeds(tasks);
tasks.sort((a, b) {
if (a.status == api_model.Status.running && b.status != api_model.Status.running) return -1;
if (a.status != api_model.Status.running && b.status == api_model.Status.running) return 1;
return b.updatedAt.compareTo(a.updatedAt);
});
return TasksState(
tasks: tasks.map(TaskRecord.fromApi).toList(growable: false),
downloadSpeedBytesPerSecond: transferSpeeds.downloadBytesPerSecond,
uploadSpeedBytesPerSecond: transferSpeeds.uploadBytesPerSecond,
);
}
}
@@ -0,0 +1,327 @@
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import '../../../api/model/resource.dart' as api_resource;
import '../../../api/model/task.dart' as api_task;
import '../../../core/icons/gopeed_icons.dart';
import '../../../core/utils/byte_size_formatter.dart';
import '../../../core/utils/transfer_rate_formatter.dart';
enum TaskStatus { downloading, completed, paused, failed }
enum TaskAssetType {
file,
folder,
torrentFolder,
torrent,
ed2k,
installer,
androidPackage,
iosPackage,
diskImage,
web,
text,
pdf,
document,
spreadsheet,
presentation,
archive,
image,
audio,
video,
code,
ebook,
font,
database,
}
class TaskFileNode {
const TaskFileNode({required this.path, required this.name, required this.sizeBytes, this.downloadedBytes});
final String path;
final String name;
final int sizeBytes;
final int? downloadedBytes;
double? get progress {
final downloaded = downloadedBytes;
if (downloaded == null || sizeBytes <= 0) return null;
return (downloaded / sizeBytes).clamp(0.0, 1.0);
}
}
class TaskRecord {
const TaskRecord({
required this.id,
required this.name,
required this.status,
required this.downloaded,
required this.url,
required this.storagePath,
required this.files,
required this.uploading,
this.isFolder = false,
this.protocol,
this.requestHeaders = const {},
this.total,
this.speed,
this.uploadSpeed,
this.remaining,
this.downloadDuration,
this.createdAt,
this.progress,
this.error,
this.completedLabel,
this.downloadedBytes,
this.totalBytes,
this.speedBytes,
this.uploadedBytes,
this.remainingSeconds,
this.waiting = false,
}) : assert(!uploading || uploadSpeed != null);
final String id;
final String name;
final TaskStatus status;
final String downloaded;
final String? total;
final String? speed;
final String? uploadSpeed;
final String? remaining;
final Duration? downloadDuration;
final DateTime? createdAt;
final double? progress;
final String url;
final String storagePath;
final String? error;
final String? completedLabel;
final int? downloadedBytes;
final int? totalBytes;
final int? speedBytes;
final int? uploadedBytes;
final int? remainingSeconds;
final bool waiting;
final List<TaskFileNode> files;
final bool uploading;
final bool isFolder;
final api_task.Protocol? protocol;
final Map<String, String> requestHeaders;
bool get canUpdateUrl =>
protocol == api_task.Protocol.http && (status == TaskStatus.paused || status == TaskStatus.failed);
bool get isIndeterminate => status == TaskStatus.downloading && total == null;
TaskAssetType get assetType => _assetType(name, isFolder: isFolder, protocol: protocol);
IconData get icon => taskFileTypeIcon(name, isFolder: isFolder, protocol: protocol);
factory TaskRecord.fromApi(api_task.Task task) {
final totalBytes = task.meta.res?.size ?? 0;
final downloadedBytes = task.progress.downloaded;
final progress = totalBytes > 0 ? (downloadedBytes / totalBytes).clamp(0.0, 1.0) : null;
final status = _statusFromApi(task.status);
final name = task.name.isNotEmpty ? task.name : task.meta.res?.name;
final fileName = (name == null || name.isEmpty) ? task.meta.req.url : name;
final rawUrl = task.meta.req.rawUrl;
final displayUrl = rawUrl != null && rawUrl.isNotEmpty ? rawUrl : task.meta.req.url;
final storagePath = task.meta.opts.path.isEmpty ? fileName : path.join(task.meta.opts.path, fileName);
return TaskRecord(
id: task.id,
name: fileName,
status: status,
downloaded: _formatBytes(downloadedBytes),
total: totalBytes > 0 ? _formatBytes(totalBytes) : null,
speed: 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,
createdAt: task.createdAt,
waiting: task.status == api_task.Status.wait,
progress: progress,
url: displayUrl,
storagePath: storagePath,
downloadedBytes: downloadedBytes,
totalBytes: totalBytes > 0 ? totalBytes : null,
speedBytes: task.progress.speed,
uploadedBytes: task.progress.uploaded,
files: _fileNodes(task.meta.res?.files),
uploading: task.uploading,
isFolder: task.meta.res?.name.isNotEmpty ?? false,
protocol: task.protocol,
requestHeaders: _requestHeaders(task.meta.req.extra),
);
}
}
Map<String, String> _requestHeaders(Object? extra) {
if (extra is! Map) return const {};
final header = extra['header'];
if (header is! Map) return const {};
return {for (final entry in header.entries) entry.key.toString(): entry.value.toString()};
}
TaskStatus _statusFromApi(api_task.Status status) {
return switch (status) {
api_task.Status.running || api_task.Status.wait => TaskStatus.downloading,
api_task.Status.done => TaskStatus.completed,
api_task.Status.pause => TaskStatus.paused,
api_task.Status.error => TaskStatus.failed,
api_task.Status.ready => TaskStatus.paused,
};
}
const _installerExtensions = {'exe', 'msi', 'dmg', 'deb', 'rpm', 'pkg', 'appimage', 'flatpak', 'snap'};
const _androidPackageExtensions = {'apk', 'aab'};
const _iosPackageExtensions = {'ipa'};
const _diskImageExtensions = {'iso', 'img'};
const _webExtensions = {'html', 'htm', 'xhtml'};
const _textExtensions = {'txt', 'md', 'log', 'csv', 'tsv', 'json', 'yaml', 'yml', 'toml', 'ini', 'conf', 'cfg'};
const _pdfExtensions = {'pdf'};
const _documentExtensions = {'doc', 'docx', 'odt', 'rtf', 'pages'};
const _spreadsheetExtensions = {'xls', 'xlsx', 'ods', 'numbers'};
const _presentationExtensions = {'ppt', 'pptx', 'odp', 'key'};
const _archiveExtensions = {'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'zst', 'tgz', 'tbz2', 'txz', 'cab'};
const _imageExtensions = {
'jpg',
'jpeg',
'png',
'gif',
'bmp',
'tif',
'tiff',
'svg',
'webp',
'heic',
'avif',
'ico',
'raw',
};
const _audioExtensions = {'mp3', 'wav', 'flac', 'aac', 'ogg', 'oga', 'wma', 'm4a', 'opus', 'aiff'};
const _videoExtensions = {'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', 'm4v', 'mpg', 'mpeg', '3gp', 'ts'};
const _codeExtensions = {
'js',
'jsx',
'ts',
'tsx',
'css',
'scss',
'less',
'xml',
'java',
'kt',
'kts',
'cpp',
'cc',
'c',
'h',
'hpp',
'dart',
'py',
'rb',
'php',
'swift',
'go',
'rs',
'sh',
'bash',
'zsh',
'ps1',
'sql',
'vue',
'svelte',
'git',
};
const _ebookExtensions = {'epub', 'mobi', 'azw', 'azw3', 'fb2'};
const _fontExtensions = {'ttf', 'otf', 'woff', 'woff2'};
const _databaseExtensions = {'db', 'sqlite', 'sqlite3', 'mdb', 'accdb', 'parquet'};
IconData taskFileTypeIcon(String name, {bool isFolder = false, api_task.Protocol? protocol}) {
return switch (_assetType(name, isFolder: isFolder, protocol: protocol)) {
TaskAssetType.file => GopeedIcons.file,
TaskAssetType.folder => GopeedIcons.folder,
TaskAssetType.torrentFolder => GopeedIcons.folderBt,
TaskAssetType.torrent => GopeedIcons.protocolBt,
TaskAssetType.ed2k => GopeedIcons.protocolEd2k,
TaskAssetType.installer => GopeedIcons.fileInstaller,
TaskAssetType.androidPackage => GopeedIcons.fileAndroid,
TaskAssetType.iosPackage => GopeedIcons.fileIos,
TaskAssetType.diskImage => GopeedIcons.fileDiskImage,
TaskAssetType.web => GopeedIcons.fileWeb,
TaskAssetType.text => GopeedIcons.fileText,
TaskAssetType.pdf => GopeedIcons.filePdf,
TaskAssetType.document => GopeedIcons.fileDocument,
TaskAssetType.spreadsheet => GopeedIcons.fileSpreadsheet,
TaskAssetType.presentation => GopeedIcons.filePresentation,
TaskAssetType.archive => GopeedIcons.fileArchive,
TaskAssetType.image => GopeedIcons.fileImage,
TaskAssetType.audio => GopeedIcons.fileAudio,
TaskAssetType.video => GopeedIcons.fileVideo,
TaskAssetType.code => GopeedIcons.fileCode,
TaskAssetType.ebook => GopeedIcons.fileEbook,
TaskAssetType.font => GopeedIcons.fileFont,
TaskAssetType.database => GopeedIcons.fileDatabase,
};
}
TaskAssetType _assetType(String name, {required bool isFolder, required api_task.Protocol? protocol}) {
if (isFolder) {
return protocol == api_task.Protocol.bt ? TaskAssetType.torrentFolder : TaskAssetType.folder;
}
final extension = _fileExtension(name);
if (extension == 'torrent') return TaskAssetType.torrent;
if (_installerExtensions.contains(extension)) return TaskAssetType.installer;
if (_androidPackageExtensions.contains(extension)) return TaskAssetType.androidPackage;
if (_iosPackageExtensions.contains(extension)) return TaskAssetType.iosPackage;
if (_diskImageExtensions.contains(extension)) return TaskAssetType.diskImage;
if (_webExtensions.contains(extension)) return TaskAssetType.web;
if (_textExtensions.contains(extension)) return TaskAssetType.text;
if (_pdfExtensions.contains(extension)) return TaskAssetType.pdf;
if (_documentExtensions.contains(extension)) return TaskAssetType.document;
if (_spreadsheetExtensions.contains(extension)) return TaskAssetType.spreadsheet;
if (_presentationExtensions.contains(extension)) return TaskAssetType.presentation;
if (_archiveExtensions.contains(extension)) return TaskAssetType.archive;
if (_imageExtensions.contains(extension)) return TaskAssetType.image;
if (_audioExtensions.contains(extension)) return TaskAssetType.audio;
if (_videoExtensions.contains(extension)) return TaskAssetType.video;
if (_codeExtensions.contains(extension)) return TaskAssetType.code;
if (_ebookExtensions.contains(extension)) return TaskAssetType.ebook;
if (_fontExtensions.contains(extension)) return TaskAssetType.font;
if (_databaseExtensions.contains(extension)) return TaskAssetType.database;
return switch (protocol) {
api_task.Protocol.bt => TaskAssetType.torrent,
api_task.Protocol.ed2k => TaskAssetType.ed2k,
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();
return extension.length <= 10 ? extension : '';
}
int? _remainingSeconds(api_task.Task task, int totalBytes, int downloadedBytes) {
if (task.status != api_task.Status.running) return null;
final speed = task.progress.speed;
if (speed <= 0 || totalBytes <= downloadedBytes) {
return null;
}
return ((totalBytes - downloadedBytes) / speed).ceil();
}
List<TaskFileNode> _fileNodes(List<api_resource.FileInfo>? files) {
if (files == null || files.isEmpty) {
return const [];
}
return files
.map((file) => TaskFileNode(path: file.path, name: file.name, sizeBytes: file.size))
.toList(growable: false);
}
String _formatBytes(int bytes) {
return ByteSizeFormatter.format(bytes);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
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 '../../../../core/utils/file_explorer.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../../../shared/widgets/detail/app_detail_surface.dart';
import '../../../../l10n/l10n.dart';
import '../../application/tasks_controller.dart';
import '../../domain/task_record.dart';
import '../widgets/task_drawer.dart';
class TaskDetailsPage extends ConsumerWidget {
const TaskDetailsPage({super.key, required this.taskId, this.initialTask});
final String taskId;
final TaskRecord? initialTask;
@override
Widget build(BuildContext context, WidgetRef ref) {
final tasksAsync = ref.watch(tasksControllerProvider);
TaskRecord? task = initialTask;
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
if (item.id == taskId) {
task = item;
break;
}
}
final palette = AppPalette.of(context);
return AppDetailPage(
title: context.l10n.taskDetails,
onBack: () => context.canPop() ? context.pop() : context.go('/'),
child: task == null
? Center(
child: tasksAsync.isLoading
? const shad.CircularProgressIndicator()
: Text(context.l10n.taskNotFound, style: TextStyle(color: palette.textMuted, fontSize: 13)),
)
: TaskDetailsView(
key: ValueKey(task.id),
task: task,
mobile: true,
onOpenStorage: () => FileExplorer.reveal(task!.storagePath),
onUpdateUrl: (url) async {
try {
await ref
.read(tasksControllerProvider.notifier)
.updateUrl(task!.id, url, headers: task.requestHeaders);
} catch (error) {
if (context.mounted) {
showAppToast(context, error.toString(), type: AppToastType.error);
}
rethrow;
}
},
),
);
}
}
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart' show Icons;
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 '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../application/tasks_controller.dart';
import '../../domain/task_record.dart';
import '../widgets/task_file_manager.dart';
class TaskFilesPage extends ConsumerWidget {
const TaskFilesPage({super.key, required this.taskId, this.initialTask});
final String taskId;
final TaskRecord? initialTask;
@override
Widget build(BuildContext context, WidgetRef ref) {
final tasksAsync = ref.watch(tasksControllerProvider);
TaskRecord? task = initialTask;
for (final item in tasksAsync.value?.tasks ?? const <TaskRecord>[]) {
if (item.id == taskId) {
task = item;
break;
}
}
final palette = AppPalette.of(context);
return shad.Scaffold(
backgroundColor: palette.bg,
child: ColoredBox(
color: palette.bg,
child: Column(
children: [
SafeArea(
bottom: false,
child: Container(
height: 52,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: palette.border)),
),
child: Row(
children: [
SizedBox(
width: 44,
child: AppTooltip(
message: context.l10n.close,
child: shad.IconButton.ghost(
onPressed: () => context.canPop() ? context.pop() : context.go('/tasks/$taskId'),
icon: Icon(Icons.arrow_back, size: 20, color: palette.textPrimary),
),
),
),
Expanded(
child: Text(
task?.name ?? context.l10n.taskDetailsFilesTab,
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textPrimary, fontSize: 16, fontWeight: FontWeight.w700),
),
),
const SizedBox(width: 44),
],
),
),
),
Expanded(
child: task == null
? Center(
child: tasksAsync.isLoading
? const shad.CircularProgressIndicator()
: Text(context.l10n.taskNotFound, style: TextStyle(color: palette.textMuted, fontSize: 13)),
)
: TaskFileManagerView(task: task),
),
],
),
),
);
}
}
@@ -0,0 +1,50 @@
import '../../../l10n/app_localizations.dart';
import '../domain/task_record.dart';
extension TaskRecordLocalizations on TaskRecord {
String localizedStatus(AppLocalizations l10n) => switch (status) {
TaskStatus.downloading when waiting => l10n.waiting,
TaskStatus.downloading => l10n.downloading,
TaskStatus.completed => l10n.completed,
TaskStatus.paused => l10n.pause,
TaskStatus.failed => l10n.failed,
};
String localizedStatusUppercase(AppLocalizations l10n) => localizedStatus(l10n).toUpperCase();
String? localizedRemaining(AppLocalizations l10n) {
if (status == TaskStatus.completed) return null;
if (remaining case final value?) return value;
if (waiting) return l10n.waiting;
if (status == TaskStatus.paused) return l10n.pause;
final seconds = remainingSeconds;
if (seconds == null) return null;
return _formatTaskTime(l10n, seconds, remaining: true);
}
String? localizedDownloadDuration(AppLocalizations l10n) {
final duration = downloadDuration;
if (duration == null) return null;
return formatTaskDuration(l10n, duration);
}
}
String formatTaskDuration(AppLocalizations l10n, Duration duration) {
final microseconds = duration.inMicroseconds;
final seconds = microseconds <= 0
? 0
: (microseconds + Duration.microsecondsPerSecond - 1) ~/ Duration.microsecondsPerSecond;
return _formatTaskTime(l10n, seconds, remaining: false);
}
String _formatTaskTime(AppLocalizations l10n, int seconds, {required bool remaining}) {
if (seconds < Duration.secondsPerMinute) {
return remaining ? l10n.secondsRemaining(seconds) : l10n.secondsDuration(seconds);
}
if (seconds < Duration.secondsPerHour) {
final minutes = (seconds / Duration.secondsPerMinute).ceil();
return remaining ? l10n.minutesRemaining(minutes) : l10n.minutesDuration(minutes);
}
final hours = (seconds / Duration.secondsPerHour).ceil();
return remaining ? l10n.hoursRemaining(hours) : l10n.hoursDuration(hours);
}
@@ -0,0 +1,55 @@
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
import '../../../../l10n/l10n.dart';
import '../../../../shared/widgets/app_primary_button.dart';
enum PendingUpdateDecision { updateTask, createTask, cancel }
Future<PendingUpdateDecision?> showPendingUpdateDialog(BuildContext context, {required String taskName}) {
final dialog = const DialogOverlayHandler().show<PendingUpdateDecision>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) {
final contentWidth = (MediaQuery.sizeOf(dialogContext).width - 64).clamp(240.0, 420.0);
return AlertDialog(
title: Text(dialogContext.l10n.pendingUpdateFound),
content: SizedBox(
width: contentWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.pendingUpdateConfirm(taskName)),
const SizedBox(height: 20),
Align(
alignment: Alignment.centerRight,
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: [
SecondaryButton(
onPressed: () => closeOverlay(dialogContext, PendingUpdateDecision.cancel),
child: Text(dialogContext.l10n.cancel),
),
SecondaryButton(
onPressed: () => closeOverlay(dialogContext, PendingUpdateDecision.createTask),
child: Text(dialogContext.l10n.pendingUpdateNo),
),
AppPrimaryButton(
onPressed: () => closeOverlay(dialogContext, PendingUpdateDecision.updateTask),
child: Text(dialogContext.l10n.pendingUpdateYes),
),
],
),
),
],
),
),
);
},
);
return dialog.future;
}
@@ -0,0 +1,338 @@
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
import '../../../../api/model/resource.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/file_tree_view.dart';
import '../../../../util/util.dart';
class ResolveFileTree extends StatefulWidget {
const ResolveFileTree({
super.key,
required this.files,
required this.initialSelection,
required this.onSelectionChanged,
});
final List<FileInfo> files;
final List<int> initialSelection;
final ValueChanged<List<int>> onSelectionChanged;
@override
State<ResolveFileTree> createState() => _ResolveFileTreeState();
}
class _ResolveFileTreeState extends State<ResolveFileTree> {
late List<FileTreeItem<int>> _treeItems;
late List<int> _allFileIndexes;
late final Set<int> _selectedIndexes;
final Set<_FileTypeFilter> _activeTypeFilters = {};
@override
void initState() {
super.initState();
_selectedIndexes = widget.initialSelection.where(_isValidIndex).toSet();
_rebuildTreeItems();
WidgetsBinding.instance.addPostFrameCallback((_) => _notifySelection());
}
@override
void didUpdateWidget(covariant ResolveFileTree oldWidget) {
super.didUpdateWidget(oldWidget);
if (identical(widget.files, oldWidget.files)) return;
_selectedIndexes.removeWhere((index) => !_isValidIndex(index));
_activeTypeFilters.clear();
_rebuildTreeItems();
WidgetsBinding.instance.addPostFrameCallback((_) => _notifySelection());
}
@override
Widget build(BuildContext context) {
final selectedCount = _selectedIndexes.length;
final allSelected = _allFileIndexes.isNotEmpty && selectedCount == _allFileIndexes.length;
final partiallySelected = selectedCount > 0 && !allSelected;
final selectedSize = _selectedIndexes.fold<int>(0, (sum, index) => sum + widget.files[index].size);
return Column(
children: [
Expanded(
child: FileTreeView<int>(
items: _treeItems,
keyPrefix: 'resolve-tree',
headerLeading: ExcludeFocus(
child: Checkbox(
state: allSelected
? CheckboxState.checked
: (partiallySelected ? CheckboxState.indeterminate : CheckboxState.unchecked),
onChanged: _allFileIndexes.isEmpty ? null : (_) => _setFileSelection(_allFileIndexes, !allSelected),
),
),
leadingBuilder: (context, node) {
final indexes = node.leafItems.map((item) => item.data).toList(growable: false);
final nodeSelectedCount = indexes.where(_selectedIndexes.contains).length;
final selected = indexes.isNotEmpty && nodeSelectedCount == indexes.length;
final partial = nodeSelectedCount > 0 && !selected;
return ExcludeFocus(
child: Checkbox(
state: selected
? CheckboxState.checked
: (partial ? CheckboxState.indeterminate : CheckboxState.unchecked),
onChanged: (_) => _setFileSelection(indexes, !selected),
),
);
},
onNodePressed: _toggleNodeSelection,
),
),
const SizedBox(height: 12),
_TreeFooter(
selectedCount: selectedCount,
totalCount: _allFileIndexes.length,
selectedSize: selectedSize,
unknownSize: selectedCount > 0 && selectedSize == 0,
activeTypeFilters: _activeTypeFilters,
onSelectVideo: () => _toggleTypeFilter(_FileTypeFilter.video),
onSelectAudio: () => _toggleTypeFilter(_FileTypeFilter.audio),
onSelectImage: () => _toggleTypeFilter(_FileTypeFilter.image),
),
],
);
}
bool _isValidIndex(int index) => index >= 0 && index < widget.files.length;
void _rebuildTreeItems() {
_allFileIndexes = List<int>.generate(widget.files.length, (index) => index, growable: false);
_treeItems = widget.files
.asMap()
.entries
.map(
(entry) => FileTreeItem<int>(
key: entry.key.toString(),
path: entry.value.path,
name: entry.value.name,
size: entry.value.size,
data: entry.key,
),
)
.toList(growable: false);
}
void _setFileSelection(Iterable<int> indexes, bool selected) {
setState(() {
_activeTypeFilters.clear();
if (selected) {
_selectedIndexes.addAll(indexes);
} else {
_selectedIndexes.removeAll(indexes);
}
});
_notifySelection();
}
void _toggleNodeSelection(FileTreeNode<int> node) {
final indexes = node.leafItems.map((item) => item.data).toList(growable: false);
final selected = indexes.isNotEmpty && indexes.every(_selectedIndexes.contains);
_setFileSelection(indexes, !selected);
}
void _toggleTypeFilter(_FileTypeFilter filter) {
setState(() {
if (!_activeTypeFilters.remove(filter)) {
_activeTypeFilters.add(filter);
}
final extensions = <String>{for (final activeFilter in _activeTypeFilters) ...activeFilter.extensions};
_selectedIndexes
..clear()
..addAll(
widget.files
.asMap()
.entries
.where((entry) => extensions.contains(_extensionOf(entry.value.name)))
.map((entry) => entry.key),
);
});
_notifySelection();
}
void _notifySelection() {
final values = _selectedIndexes.toList()..sort();
widget.onSelectionChanged(values);
}
}
class _TreeFooter extends StatelessWidget {
const _TreeFooter({
required this.selectedCount,
required this.totalCount,
required this.selectedSize,
required this.unknownSize,
required this.activeTypeFilters,
required this.onSelectVideo,
required this.onSelectAudio,
required this.onSelectImage,
});
final int selectedCount;
final int totalCount;
final int selectedSize;
final bool unknownSize;
final Set<_FileTypeFilter> activeTypeFilters;
final VoidCallback onSelectVideo;
final VoidCallback onSelectAudio;
final VoidCallback onSelectImage;
@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 stats = Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.selectedCount(selectedCount, totalCount),
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600),
),
const SizedBox(width: 8),
Text(
unknownSize ? context.l10n.unknownSize : Util.fmtByte(selectedSize),
style: TextStyle(color: palette.textSecondary, fontSize: 12, fontWeight: FontWeight.w600),
),
],
);
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]);
},
);
}
}
class _FileTypeFilterGroup extends StatelessWidget {
const _FileTypeFilterGroup({
required this.videoActive,
required this.audioActive,
required this.imageActive,
required this.onSelectVideo,
required this.onSelectAudio,
required this.onSelectImage,
});
final bool videoActive;
final bool audioActive;
final bool imageActive;
final VoidCallback onSelectVideo;
final VoidCallback onSelectAudio;
final VoidCallback onSelectImage;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: palette.border),
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_FilterButton(
key: const ValueKey('resolve-tree-filter-video'),
icon: Icons.movie_outlined,
active: videoActive,
onPressed: onSelectVideo,
),
_FilterDivider(color: palette.border),
_FilterButton(
key: const ValueKey('resolve-tree-filter-audio'),
icon: Icons.audiotrack_outlined,
active: audioActive,
onPressed: onSelectAudio,
),
_FilterDivider(color: palette.border),
_FilterButton(
key: const ValueKey('resolve-tree-filter-image'),
icon: Icons.image_outlined,
active: imageActive,
onPressed: onSelectImage,
),
],
),
);
}
}
class _FilterDivider extends StatelessWidget {
const _FilterDivider({required this.color});
final Color color;
@override
Widget build(BuildContext context) {
return SizedBox(width: 1, height: 18, child: ColoredBox(color: color));
}
}
class _FilterButton extends StatelessWidget {
const _FilterButton({super.key, required this.icon, required this.active, required this.onPressed});
final IconData icon;
final bool active;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return SizedBox(
width: 40,
height: 28,
child: DecoratedBox(
decoration: BoxDecoration(color: active ? palette.filterActiveBg : null),
child: GhostButton(
density: ButtonDensity.compact,
onPressed: onPressed,
child: Icon(icon, size: 14, color: active ? palette.brand : palette.textSecondary),
),
),
);
}
}
String _extensionOf(String name) {
final index = name.lastIndexOf('.');
if (index < 0 || index == name.length - 1) return '';
return name.substring(index + 1).toLowerCase();
}
enum _FileTypeFilter { video, audio, image }
extension on _FileTypeFilter {
Set<String> get extensions => switch (this) {
_FileTypeFilter.video => _videoExts,
_FileTypeFilter.audio => _audioExts,
_FileTypeFilter.image => _imageExts,
};
}
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'};
@@ -0,0 +1,360 @@
import 'dart:math';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';
import '../../../../core/utils/transfer_rate_formatter.dart';
import '../../../../shared/theme/app_palette.dart';
class SpeedMonitorCard extends StatefulWidget {
const SpeedMonitorCard({super.key, this.downloadBytesPerSecond = 0, this.uploadBytesPerSecond = 0});
final int downloadBytesPerSecond;
final int uploadBytesPerSecond;
@override
State<SpeedMonitorCard> createState() => _SpeedMonitorCardState();
}
class _SpeedMonitorCardState extends State<SpeedMonitorCard> with SingleTickerProviderStateMixin {
static const _needleSpring = SpringDescription(mass: 1, stiffness: 140, damping: 11);
static const int _sampleWindowSize = 30;
static const double _maxNeedleLaunchVelocity = 4.4;
static const double _minVelocityFloor = 0.18;
static const double _displayHeadroom = 1.2;
static const double _minDisplayMax = 12;
static const double _maxDisplayMax = 100;
static const double _displayDecayFactor = 0.965;
static const double _highPressureThreshold = 0.9;
static const int _highPressureWindow = 2;
static const double _highPressureBoost = 1.12;
final List<double> _downloadSamples = <double>[];
late final AnimationController _needleController;
late double _download;
late double _displayMax;
int _highPressureStreak = 0;
@override
void initState() {
super.initState();
_download = _toMegabytesPerSecond(widget.downloadBytesPerSecond);
_displayMax = max(_minDisplayMax, _download * _displayHeadroom);
_primeSamples(_download);
_needleController = AnimationController.unbounded(vsync: this, value: (_download / _displayMax).clamp(0.0, 1.0))
..addListener(() {
if (mounted) {
setState(() {});
}
});
}
@override
void didUpdateWidget(SpeedMonitorCard oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.downloadBytesPerSecond == widget.downloadBytesPerSecond) {
return;
}
_setDownloadSpeed(_toMegabytesPerSecond(widget.downloadBytesPerSecond));
}
void _setDownloadSpeed(double download) {
final previousDownload = _download;
final nextDisplayMax = _resolveDisplayMax(download);
_download = download;
_displayMax = nextDisplayMax;
final target = (download / nextDisplayMax).clamp(0.0, 1.0);
final launchVelocity = _computeNeedleLaunchVelocity(previousDownload: previousDownload, nextDownload: download);
_needleController.animateWith(SpringSimulation(_needleSpring, _needleController.value, target, launchVelocity));
}
void _primeSamples(double initialValue) {
_downloadSamples
..clear()
..add(initialValue);
_highPressureStreak = 0;
}
double _resolveDisplayMax(double currentDownload) {
_downloadSamples.add(currentDownload);
if (_downloadSamples.length > _sampleWindowSize) {
_downloadSamples.removeAt(0);
}
final currentUsage = _displayMax <= 0 ? 0.0 : (currentDownload / _displayMax).clamp(0.0, 2.0);
if (currentUsage >= _highPressureThreshold) {
_highPressureStreak += 1;
} else {
_highPressureStreak = 0;
}
final sorted = List<double>.from(_downloadSamples)..sort();
final p95Index = ((sorted.length - 1) * 0.95).round().clamp(0, sorted.length - 1);
final percentile95 = sorted[p95Index];
var targetMax = (percentile95 * _displayHeadroom).clamp(_minDisplayMax, _maxDisplayMax);
if (_highPressureStreak >= _highPressureWindow) {
targetMax = max(targetMax, (_displayMax * _highPressureBoost).clamp(_minDisplayMax, _maxDisplayMax));
}
if (targetMax >= _displayMax) {
return targetMax;
}
// Expand quickly, contract slowly, so the gauge does not jitter when
// bandwidth fluctuates downward for a moment.
return max(targetMax, _displayMax * _displayDecayFactor);
}
double _computeNeedleLaunchVelocity({required double previousDownload, required double nextDownload}) {
final delta = nextDownload - previousDownload;
if (delta.abs() < 0.01) {
return 0;
}
if (delta < 0) {
// Falling speeds should settle quickly instead of overshooting downward.
return min(_needleController.velocity, 0) * 0.22;
}
final combined = previousDownload + nextDownload;
final relativeJump = combined <= 0 ? 1.0 : delta / combined;
final absoluteJump = delta / 100.0;
// Relative jump adapts to slow and fast networks; absolute jump prevents
// large moves at high speeds from feeling underpowered.
final jumpFactor = (relativeJump * 0.72) + (sqrt(absoluteJump.clamp(0.0, 1.0)) * 0.28);
final normalized = jumpFactor.clamp(0.0, 1.0);
final launchVelocity = _minVelocityFloor + (_maxNeedleLaunchVelocity - _minVelocityFloor) * normalized;
// Keep a little of the current momentum so rapid consecutive spikes feel continuous.
final carriedMomentum = max(_needleController.velocity, 0) * 0.2;
return min(_maxNeedleLaunchVelocity, max(launchVelocity, carriedMomentum));
}
@override
void dispose() {
_needleController.dispose();
super.dispose();
}
double _toMegabytesPerSecond(int bytesPerSecond) => max(0, bytesPerSecond) / (1024 * 1024);
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final gaugeForeground = palette.textPrimary;
final arcColor = gaugeForeground;
final needleColor = gaugeForeground;
final trackColor = gaugeForeground.withValues(alpha: 0.12);
final tickColor = gaugeForeground.withValues(alpha: 0.18);
Widget buildGauge() {
return SizedBox(
key: const ValueKey('speed-monitor-gauge'),
width: 60,
height: 32,
child: TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: (_download / _displayMax).clamp(0.0, 1.0)),
duration: const Duration(milliseconds: 650),
curve: Curves.easeOutCubic,
builder: (context, value, _) {
return CustomPaint(
painter: _SpeedGaugePainter(
value: value.clamp(0.0, 1.0),
needleValue: _needleController.value.clamp(-0.08, 1.08),
arcColor: arcColor,
needleColor: needleColor,
trackColor: trackColor,
tickColor: tickColor,
),
);
},
),
);
}
Widget buildSpeedLines({required bool compact}) {
return Column(
key: const ValueKey('speed-monitor-values'),
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_SpeedLine(
key: const ValueKey('speed-monitor-download-line'),
icon: Icons.south,
bytesPerSecond: widget.downloadBytesPerSecond,
foreground: palette.textPrimary,
unitColor: palette.textSecondary,
compact: compact,
valueSize: compact ? 12 : 13,
),
SizedBox(height: compact ? 3 : 4),
_SpeedLine(
key: const ValueKey('speed-monitor-upload-line'),
icon: Icons.north,
bytesPerSecond: widget.uploadBytesPerSecond,
foreground: palette.textSecondary,
unitColor: palette.textMuted,
compact: compact,
valueSize: compact ? 10 : 11,
),
],
);
}
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
margin: const EdgeInsets.fromLTRB(8, 0, 8, 24),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
decoration: BoxDecoration(
color: palette.cardBg.withValues(alpha: 0.72),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: palette.border),
),
child: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 170) {
final gauge = buildGauge();
return Row(
children: [
gauge,
const SizedBox(width: 6),
Expanded(child: buildSpeedLines(compact: true)),
],
);
}
final gauge = buildGauge();
return Row(
children: [
gauge,
const SizedBox(width: 14),
Expanded(child: buildSpeedLines(compact: false)),
],
);
},
),
);
}
}
class _SpeedLine extends StatelessWidget {
const _SpeedLine({
super.key,
required this.icon,
required this.bytesPerSecond,
required this.foreground,
required this.unitColor,
this.valueSize = 13,
this.compact = false,
});
final IconData icon;
final int bytesPerSecond;
final Color foreground;
final Color unitColor;
final double valueSize;
final bool compact;
@override
Widget build(BuildContext context) {
final display = TransferRateFormatter.format(bytesPerSecond);
return Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(icon, size: compact ? 8 : 10, color: foreground),
SizedBox(width: compact ? 2 : 4),
Text(
display.value,
maxLines: 1,
style: TextStyle(color: foreground, fontSize: valueSize, fontWeight: FontWeight.w700, height: 1),
),
SizedBox(width: compact ? 2 : 4),
Text(
display.unit,
maxLines: 1,
style: TextStyle(
color: unitColor,
fontSize: compact ? 8 : 9,
fontWeight: FontWeight.w600,
letterSpacing: compact ? 0 : 1.2,
height: 1,
),
),
],
);
}
}
class _SpeedGaugePainter extends CustomPainter {
const _SpeedGaugePainter({
required this.value,
required this.needleValue,
required this.arcColor,
required this.needleColor,
required this.trackColor,
required this.tickColor,
});
final double value;
final double needleValue;
final Color arcColor;
final Color needleColor;
final Color trackColor;
final Color tickColor;
@override
void paint(Canvas canvas, Size size) {
final radius = min(size.width / 2 - 6, size.height - 6);
final center = Offset(size.width / 2, (size.height + radius) / 2);
final rect = Rect.fromCircle(center: center, radius: radius);
final tickPaint = Paint()
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = 1.4
..color = tickColor;
final trackPaint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round
..color = trackColor;
final activePaint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round
..color = arcColor;
const tickCount = 5;
for (var i = 0; i < tickCount; i++) {
final t = i / (tickCount - 1);
final tickAngle = pi + (pi * t);
final outerRadius = radius - 2;
final innerRadius = outerRadius - 4;
final start = Offset(center.dx + cos(tickAngle) * innerRadius, center.dy + sin(tickAngle) * innerRadius);
final end = Offset(center.dx + cos(tickAngle) * outerRadius, center.dy + sin(tickAngle) * outerRadius);
canvas.drawLine(start, end, tickPaint);
}
canvas.drawArc(rect, pi, pi, false, trackPaint);
canvas.drawArc(rect, pi, pi * value, false, activePaint);
final angle = pi + (pi * needleValue);
final needleEnd = Offset(center.dx + cos(angle) * (radius - 6), center.dy + sin(angle) * (radius - 6));
final needlePaint = Paint()
..color = needleColor
..strokeWidth = 1.6
..strokeCap = StrokeCap.round;
canvas.drawLine(center, needleEnd, needlePaint);
canvas.drawCircle(center, 2.6, Paint()..color = needleColor);
}
@override
bool shouldRepaint(covariant _SpeedGaugePainter oldDelegate) {
return oldDelegate.value != value ||
oldDelegate.needleValue != needleValue ||
oldDelegate.arcColor != arcColor ||
oldDelegate.needleColor != needleColor ||
oldDelegate.trackColor != trackColor ||
oldDelegate.tickColor != tickColor;
}
}
@@ -0,0 +1,69 @@
import 'package:flutter/widgets.dart';
import '../../application/task_batch_selection_controller.dart';
typedef TaskBatchSelectionWidgetBuilder = Widget Function(BuildContext context, bool selected, bool allSelected);
class TaskBatchSelectionBuilder extends StatefulWidget {
const TaskBatchSelectionBuilder({
super.key,
required this.controller,
required this.taskId,
required this.visibleTaskIds,
required this.builder,
});
final TaskBatchSelectionController controller;
final String taskId;
final List<String> visibleTaskIds;
final TaskBatchSelectionWidgetBuilder builder;
@override
State<TaskBatchSelectionBuilder> createState() => _TaskBatchSelectionBuilderState();
}
class _TaskBatchSelectionBuilderState extends State<TaskBatchSelectionBuilder> {
late bool _selected;
late bool _allSelected;
@override
void initState() {
super.initState();
_readSelection();
widget.controller.addListener(_handleSelectionChanged);
}
@override
void didUpdateWidget(TaskBatchSelectionBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_handleSelectionChanged);
widget.controller.addListener(_handleSelectionChanged);
}
_readSelection();
}
@override
void dispose() {
widget.controller.removeListener(_handleSelectionChanged);
super.dispose();
}
void _readSelection() {
_selected = widget.controller.contains(widget.taskId);
_allSelected = widget.controller.areAllSelected(widget.visibleTaskIds);
}
void _handleSelectionChanged() {
final selected = widget.controller.contains(widget.taskId);
final allSelected = widget.controller.areAllSelected(widget.visibleTaskIds);
if (selected == _selected && allSelected == _allSelected) return;
setState(() {
_selected = selected;
_allSelected = allSelected;
});
}
@override
Widget build(BuildContext context) => widget.builder(context, _selected, _allSelected);
}
@@ -0,0 +1,81 @@
import 'package:flutter/widgets.dart';
import '../../../../../core/utils/breakpoints.dart';
import '../../../domain/task_record.dart';
import '../task_context_menu.dart';
import 'task_card_desktop.dart';
import 'task_card_mobile.dart';
class TaskCard extends StatelessWidget {
const TaskCard({
super.key,
required this.task,
required this.selected,
required this.batchMode,
required this.selectedInBatch,
required this.onPressed,
required this.onToggleBatch,
this.onPause,
this.onResume,
this.onDelete,
this.onOpen,
this.onReveal,
this.contextActions,
this.listeningForUpdate = false,
});
final TaskRecord task;
final bool selected;
final bool batchMode;
final bool selectedInBatch;
final VoidCallback onPressed;
final VoidCallback onToggleBatch;
final VoidCallback? onPause;
final VoidCallback? onResume;
final VoidCallback? onDelete;
final VoidCallback? onOpen;
final VoidCallback? onReveal;
final TaskContextActions? contextActions;
final bool listeningForUpdate;
@override
Widget build(BuildContext context) {
final isMobile = MediaQuery.sizeOf(context).width < Breakpoints.mobile;
if (isMobile) {
final card = TaskCardMobile(
task: task,
selected: selected,
batchMode: batchMode,
selectedInBatch: selectedInBatch,
onPressed: onPressed,
onToggleBatch: onToggleBatch,
onPause: onPause,
onResume: onResume,
onDelete: onDelete,
onOpen: onOpen,
onReveal: onReveal,
listeningForUpdate: listeningForUpdate,
);
final actions = contextActions;
return actions == null ? card : TaskContextMenu(task: task, actions: actions, child: card);
}
final card = TaskCardDesktop(
task: task,
selected: selected,
batchMode: batchMode,
selectedInBatch: selectedInBatch,
onPressed: onPressed,
onToggleBatch: onToggleBatch,
onPause: onPause,
onResume: onResume,
onDelete: onDelete,
onOpen: onOpen,
onReveal: onReveal,
listeningForUpdate: listeningForUpdate,
);
final actions = contextActions;
return actions == null ? card : TaskContextMenu(task: task, actions: actions, child: card);
}
}
@@ -0,0 +1,323 @@
import 'package:flutter/gestures.dart' show TapUpDetails, kDoubleTapSlop, kDoubleTapTimeout;
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../../shared/theme/app_design_tokens.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../domain/task_record.dart';
import '../task_progress_bar.dart';
import 'task_card_parts.dart';
class TaskCardDesktop extends StatefulWidget {
const TaskCardDesktop({
super.key,
required this.task,
required this.selected,
required this.batchMode,
required this.selectedInBatch,
required this.onPressed,
required this.onToggleBatch,
this.onPause,
this.onResume,
this.onDelete,
this.onOpen,
this.onReveal,
this.listeningForUpdate = false,
});
final TaskRecord task;
final bool selected;
final bool batchMode;
final bool selectedInBatch;
final VoidCallback onPressed;
final VoidCallback onToggleBatch;
final VoidCallback? onPause;
final VoidCallback? onResume;
final VoidCallback? onDelete;
final VoidCallback? onOpen;
final VoidCallback? onReveal;
final bool listeningForUpdate;
@override
State<TaskCardDesktop> createState() => _TaskCardDesktopState();
}
class _TaskCardDesktopState extends State<TaskCardDesktop> {
bool _hovered = false;
DateTime? _lastTapTime;
Offset? _lastTapPosition;
void _handleTap(TapUpDetails details) {
final now = DateTime.now();
final lastTapTime = _lastTapTime;
final lastTapPosition = _lastTapPosition;
final isDoubleTap =
!widget.batchMode &&
widget.task.status == TaskStatus.completed &&
lastTapTime != null &&
now.difference(lastTapTime) <= kDoubleTapTimeout &&
lastTapPosition != null &&
(details.globalPosition - lastTapPosition).distance <= kDoubleTapSlop;
_lastTapTime = isDoubleTap ? null : now;
_lastTapPosition = isDoubleTap ? null : details.globalPosition;
widget.onPressed();
if (isDoubleTap) {
widget.onOpen?.call();
}
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final task = widget.task;
final isDark = shad.Theme.of(context).brightness == Brightness.dark;
final isError = task.status == TaskStatus.failed;
final borderColor = isDark ? palette.border : palette.border.withValues(alpha: 0.6);
final baseColor = isDark ? palette.cardBg : palette.cardBg.withValues(alpha: 0.92);
final hoverColor = palette.taskCardHoverBg;
final radius = BorderRadius.circular(AppDesignTokens.controlRadius);
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTapUp: _handleTap,
child: Container(
height: AppDesignTokens.taskRowHeight,
decoration: BoxDecoration(
borderRadius: radius,
boxShadow: widget.selected
? [BoxShadow(color: palette.taskCardSelectedBorder, blurRadius: 0, spreadRadius: 1)]
: null,
),
child: ClipRRect(
borderRadius: radius,
clipBehavior: Clip.hardEdge,
child: Stack(
fit: StackFit.expand,
children: [
ColoredBox(color: baseColor),
if (_hovered)
IgnorePointer(
child: ColoredBox(key: const ValueKey('task-card-hover-surface'), color: hoverColor),
),
IgnorePointer(
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: radius,
border: Border.all(color: _hovered ? palette.border : borderColor),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 17, vertical: 13),
child: Row(
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 220),
width: widget.batchMode ? 36 : 0,
child: widget.batchMode
? Align(
alignment: Alignment.centerLeft,
child: shad.Checkbox(
state: widget.selectedInBatch
? shad.CheckboxState.checked
: shad.CheckboxState.unchecked,
onChanged: (_) => widget.onToggleBatch(),
borderColor: palette.border,
backgroundColor: palette.cardBg,
size: 20,
),
)
: const SizedBox.shrink(),
),
TaskCardIcon(task: task),
const SizedBox(width: 16),
Expanded(
child: SizedBox(
height: 46,
child: task.status == TaskStatus.completed
? _CompletedContent(
task: task,
isDark: isDark,
onReveal: widget.onReveal,
onDelete: widget.onDelete,
listeningForUpdate: widget.listeningForUpdate,
)
: _ProgressContent(
task: task,
isError: isError,
isDark: isDark,
onPause: widget.onPause,
onResume: widget.onResume,
onDelete: widget.onDelete,
listeningForUpdate: widget.listeningForUpdate,
),
),
),
],
),
),
],
),
),
),
),
);
}
}
class _ProgressContent extends StatelessWidget {
const _ProgressContent({
required this.task,
required this.isError,
required this.isDark,
this.onPause,
this.onResume,
this.onDelete,
required this.listeningForUpdate,
});
final TaskRecord task;
final bool isError;
final bool isDark;
final VoidCallback? onPause;
final VoidCallback? onResume;
final VoidCallback? onDelete;
final bool listeningForUpdate;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final fillColor = taskCardFillColor(palette, task.status, isDark);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 21,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
task.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w500, height: 1),
),
),
const SizedBox(width: 16),
if (listeningForUpdate) ...[const TaskUpdateListeningIndicator(), const SizedBox(width: 8)],
Row(mainAxisSize: MainAxisSize.min, children: _buildActionButtons(task, palette, isDark)),
],
),
),
const SizedBox(height: 6),
TaskProgressBar(
value: task.progress,
indeterminate: task.isIndeterminate,
trackColor: palette.brandTrack,
fillColor: fillColor,
highlightStartColor: fillColor,
highlightEndColor: fillColor,
shimmer: task.status == TaskStatus.downloading,
),
const SizedBox(height: 6),
TaskCardFooter(task: task, isError: isError),
],
);
}
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
final actions = switch (task.status) {
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)],
};
return actions
.map(
(action) => TaskCardActionButton(
icon: action.$1,
color: palette.taskCardAction,
onPressed: action.$2 ?? () {},
hoverBackground: isDark ? palette.border : Colors.transparent,
),
)
.toList(growable: false);
}
}
class _CompletedContent extends StatelessWidget {
const _CompletedContent({
required this.task,
required this.isDark,
required this.listeningForUpdate,
this.onReveal,
this.onDelete,
});
final TaskRecord task;
final bool isDark;
final VoidCallback? onReveal;
final VoidCallback? onDelete;
final bool listeningForUpdate;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 21,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
task.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w500, height: 1),
),
),
const SizedBox(width: 16),
if (listeningForUpdate) ...[const TaskUpdateListeningIndicator(), const SizedBox(width: 8)],
Row(mainAxisSize: MainAxisSize.min, children: _buildActionButtons(task, palette, isDark)),
],
),
),
const SizedBox(height: 6),
TaskCardCompletedMeta(task: task),
],
);
}
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
final actions = switch (task.status) {
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)],
};
return actions
.map(
(action) => TaskCardActionButton(
icon: action.$1,
color: palette.taskCardAction,
onPressed: action.$2 ?? () {},
hoverBackground: isDark ? palette.border : Colors.transparent,
),
)
.toList(growable: false);
}
}
@@ -0,0 +1,190 @@
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../../shared/theme/app_design_tokens.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../domain/task_record.dart';
import '../task_progress_bar.dart';
import 'task_card_parts.dart';
class TaskCardMobile extends StatefulWidget {
const TaskCardMobile({
super.key,
required this.task,
required this.selected,
required this.batchMode,
required this.selectedInBatch,
required this.onPressed,
required this.onToggleBatch,
this.onPause,
this.onResume,
this.onDelete,
this.onOpen,
this.onReveal,
this.listeningForUpdate = false,
});
final TaskRecord task;
final bool selected;
final bool batchMode;
final bool selectedInBatch;
final VoidCallback onPressed;
final VoidCallback onToggleBatch;
final VoidCallback? onPause;
final VoidCallback? onResume;
final VoidCallback? onDelete;
final VoidCallback? onOpen;
final VoidCallback? onReveal;
final bool listeningForUpdate;
@override
State<TaskCardMobile> createState() => _TaskCardMobileState();
}
class _TaskCardMobileState extends State<TaskCardMobile> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final isDark = shad.Theme.of(context).brightness == Brightness.dark;
final borderColor = isDark ? palette.border : palette.border.withValues(alpha: 0.6);
final baseColor = isDark ? palette.cardBg : palette.cardBg.withValues(alpha: 0.92);
final hoverColor = palette.taskCardHoverBg;
final radius = BorderRadius.circular(AppDesignTokens.controlRadius);
final task = widget.task;
final fillColor = taskCardFillColor(palette, task.status, isDark);
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onPressed,
onDoubleTap: !widget.batchMode && task.status == TaskStatus.completed ? widget.onOpen : null,
child: Container(
key: const ValueKey('task-card-mobile-surface'),
decoration: BoxDecoration(
borderRadius: radius,
boxShadow: widget.selected
? [BoxShadow(color: palette.taskCardSelectedBorder, blurRadius: 0, spreadRadius: 1)]
: null,
),
child: ClipRRect(
borderRadius: radius,
clipBehavior: Clip.hardEdge,
child: Stack(
children: [
Positioned.fill(child: ColoredBox(color: baseColor)),
if (_hovered)
Positioned.fill(
child: IgnorePointer(
child: ColoredBox(key: const ValueKey('task-card-hover-surface'), color: hoverColor),
),
),
Positioned.fill(
child: IgnorePointer(
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: radius,
border: Border.all(color: _hovered ? palette.border : borderColor),
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
AnimatedSize(
duration: const Duration(milliseconds: 160),
curve: Curves.easeOutCubic,
child: widget.batchMode
? Padding(
padding: const EdgeInsets.only(right: AppDesignTokens.checkboxLabelGap),
child: shad.Checkbox(
state: widget.selectedInBatch
? shad.CheckboxState.checked
: shad.CheckboxState.unchecked,
onChanged: (_) => widget.onToggleBatch(),
borderColor: palette.border,
backgroundColor: palette.cardBg,
),
)
: const SizedBox.shrink(),
),
TaskCardIcon(task: task),
const SizedBox(width: 12),
Expanded(
child: Text(
task.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: palette.textPrimary,
fontSize: 14,
fontWeight: FontWeight.w500,
height: 1.1,
),
),
),
const SizedBox(width: 8),
if (widget.listeningForUpdate) ...[
const TaskUpdateListeningIndicator(),
const SizedBox(width: 6),
],
if (!widget.batchMode) ..._buildActionButtons(task, palette, isDark),
],
),
const SizedBox(height: 8),
if (task.status != TaskStatus.completed) ...[
TaskProgressBar(
value: task.progress,
indeterminate: task.isIndeterminate,
trackColor: palette.brandTrack,
fillColor: fillColor,
highlightStartColor: fillColor,
highlightEndColor: fillColor,
shimmer: task.status == TaskStatus.downloading,
),
const SizedBox(height: 6),
TaskCardFooter(task: task, isError: task.status == TaskStatus.failed),
] else ...[
TaskCardCompletedMeta(task: task),
],
],
),
),
],
),
),
),
),
);
}
List<Widget> _buildActionButtons(TaskRecord task, AppPalette palette, bool isDark) {
final actions = switch (task.status) {
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)],
};
return actions
.map(
(action) => TaskCardActionButton(
icon: action.$1,
color: palette.taskCardAction,
onPressed: action.$2 ?? () {},
hoverBackground: isDark ? palette.border : Colors.transparent,
buttonSize: 20,
iconSize: 13,
),
)
.toList(growable: false);
}
}
@@ -0,0 +1,278 @@
import 'package:flutter/material.dart' show Colors, Icons;
import 'package:flutter/widgets.dart';
import '../../../domain/task_record.dart';
import '../../../../../shared/theme/app_design_tokens.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../../../shared/widgets/app_tooltip.dart';
import '../../../../../l10n/l10n.dart';
import '../../task_record_localizations.dart';
Color taskCardFillColor(AppPalette palette, TaskStatus status, bool isDark) {
if (isDark) {
switch (status) {
case TaskStatus.failed:
return palette.error;
case TaskStatus.paused:
return palette.textMuted;
case TaskStatus.downloading:
case TaskStatus.completed:
return palette.brandProgress;
}
}
switch (status) {
case TaskStatus.failed:
return palette.error;
case TaskStatus.paused:
return palette.textMuted;
case TaskStatus.downloading:
case TaskStatus.completed:
return palette.brandProgress;
}
}
class TaskUpdateListeningIndicator extends StatelessWidget {
const TaskUpdateListeningIndicator({super.key});
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return AppTooltip(
message: context.l10n.waitingForReplacementUrl,
child: Icon(Icons.hearing, size: 15, color: palette.brandProgress),
);
}
}
class TaskCardIcon extends StatelessWidget {
const TaskCardIcon({super.key, required this.task});
final TaskRecord task;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return SizedBox(
width: 32,
height: 32,
child: ClipRRect(
borderRadius: BorderRadius.circular(AppDesignTokens.controlRadius),
clipBehavior: Clip.hardEdge,
child: ColoredBox(
color: palette.taskCardIconBg,
child: Center(child: Icon(task.icon, size: 20, color: palette.textSecondary)),
),
),
);
}
}
class TaskCardFooter extends StatelessWidget {
const TaskCardFooter({super.key, required this.task, required this.isError});
final TaskRecord task;
final bool isError;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final metaColor = palette.taskMeta;
final leftColor = isError ? palette.error : metaColor;
final rightColor = isError ? palette.taskErrorMeta : metaColor;
final statusText = switch (task.status) {
TaskStatus.downloading => task.localizedRemaining(context.l10n) ?? context.l10n.downloading,
TaskStatus.paused => task.localizedRemaining(context.l10n) ?? context.l10n.pause,
TaskStatus.completed => context.l10n.completed,
TaskStatus.failed => context.l10n.failed,
};
return SizedBox(
height: 10,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
task.total != null ? '${task.downloaded} / ${task.total}' : context.l10n.unknownSize,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: leftColor, fontSize: 10, height: 1),
),
),
const SizedBox(width: 12),
if (task.speed != null && !isError) ...[
_TaskTransferSpeed(icon: Icons.south, value: task.speed!, color: metaColor),
const SizedBox(width: 8),
TickDivider(color: palette.progressTrack),
const SizedBox(width: 8),
],
if (task.uploading) ...[
_TaskTransferSpeed(icon: Icons.north, value: task.uploadSpeed!, color: metaColor),
const SizedBox(width: 8),
TickDivider(color: palette.progressTrack),
const SizedBox(width: 8),
],
Text(
statusText,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: rightColor, fontSize: 10, height: 1),
),
],
),
);
}
}
class TaskCardCompletedMeta extends StatelessWidget {
const TaskCardCompletedMeta({super.key, required this.task});
final TaskRecord task;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final metaColor = palette.taskMeta;
return SizedBox(
height: 10,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
task.total ?? task.downloaded,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: metaColor, fontSize: 10, height: 1),
),
),
const SizedBox(width: 12),
if (task.speed != null) ...[
_TaskTransferSpeed(icon: Icons.south, value: task.speed!, color: metaColor),
const SizedBox(width: 8),
TickDivider(color: palette.progressTrack),
const SizedBox(width: 8),
],
if (task.uploading) ...[
_TaskTransferSpeed(icon: Icons.north, value: task.uploadSpeed!, color: metaColor),
const SizedBox(width: 8),
TickDivider(color: palette.progressTrack),
const SizedBox(width: 8),
],
Text(context.l10n.completed, style: TextStyle(color: palette.taskMetaSubtle, fontSize: 10, height: 1)),
],
),
);
}
}
class _TaskTransferSpeed extends StatelessWidget {
const _TaskTransferSpeed({required this.icon, required this.value, required this.color});
final IconData icon;
final String value;
final Color color;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(icon, size: 10, color: color),
const SizedBox(width: 2),
Text(value, style: TextStyle(color: color, fontSize: 10, height: 1)),
],
);
}
}
class TickDivider extends StatelessWidget {
const TickDivider({super.key, required this.color});
final Color color;
@override
Widget build(BuildContext context) {
return Container(
width: 4,
height: 4,
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(999)),
);
}
}
class TaskCardActionButton extends StatelessWidget {
const TaskCardActionButton({
super.key,
required this.icon,
required this.color,
required this.onPressed,
required this.hoverBackground,
this.buttonSize = 21,
this.iconSize = 14,
});
final IconData icon;
final Color color;
final VoidCallback onPressed;
final Color hoverBackground;
final double buttonSize;
final double iconSize;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 4),
child: HoverActionButton(
hoverBackground: hoverBackground,
onPressed: onPressed,
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: Center(
child: Icon(icon, size: iconSize, color: color),
),
),
),
);
}
}
class HoverActionButton extends StatefulWidget {
const HoverActionButton({super.key, required this.child, required this.onPressed, required this.hoverBackground});
final Widget child;
final VoidCallback onPressed;
final Color hoverBackground;
@override
State<HoverActionButton> createState() => _HoverActionButtonState();
}
class _HoverActionButtonState extends State<HoverActionButton> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onPressed,
child: AnimatedContainer(
duration: const Duration(milliseconds: 140),
decoration: BoxDecoration(
color: _hovered ? widget.hoverBackground : Colors.transparent,
borderRadius: BorderRadius.circular(4),
),
child: widget.child,
),
),
);
}
}
@@ -0,0 +1,148 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../domain/task_record.dart';
import '../../../../l10n/l10n.dart';
import '../../../../util/util.dart';
class TaskContextActions {
const TaskContextActions({
required this.selected,
required this.allSelected,
required this.listeningForUpdate,
required this.onShowDetails,
required this.onOpenFile,
required this.onOpenDirectory,
required this.onBrowseFiles,
required this.onToggleSelectAll,
required this.onToggleSelected,
required this.onPause,
required this.onResume,
required this.onDelete,
required this.onUpdateUrl,
required this.onToggleUpdateListener,
});
final bool selected;
final bool allSelected;
final bool listeningForUpdate;
final VoidCallback onShowDetails;
final VoidCallback onOpenFile;
final VoidCallback onOpenDirectory;
final VoidCallback onBrowseFiles;
final VoidCallback onToggleSelectAll;
final VoidCallback onToggleSelected;
final VoidCallback onPause;
final VoidCallback onResume;
final VoidCallback onDelete;
final VoidCallback onUpdateUrl;
final VoidCallback onToggleUpdateListener;
}
class TaskContextMenu extends StatelessWidget {
const TaskContextMenu({super.key, required this.task, required this.actions, required this.child});
final TaskRecord task;
final TaskContextActions actions;
final Widget child;
@override
Widget build(BuildContext context) {
return shad.ContextMenu(
items: [
shad.MenuButton(
key: const ValueKey('task-context-select-all'),
leading: Icon(actions.allSelected ? Icons.deselect : Icons.select_all, size: 16),
onPressed: (_) => actions.onToggleSelectAll(),
child: Text(actions.allSelected ? context.l10n.clearSelection : context.l10n.selectAll),
),
shad.MenuButton(
key: const ValueKey('task-context-select'),
leading: Icon(actions.selected ? Icons.check_box : Icons.check_box_outline_blank, size: 16),
onPressed: (_) => actions.onToggleSelected(),
child: Text(actions.selected ? context.l10n.deselectTask : context.l10n.selectTask),
),
const shad.MenuDivider(),
shad.MenuButton(
key: const ValueKey('task-context-resume'),
leading: const Icon(Icons.play_arrow, size: 16),
enabled: task.status == TaskStatus.paused || task.status == TaskStatus.failed,
onPressed: (_) => actions.onResume(),
child: Text(context.l10n.continueAction),
),
shad.MenuButton(
key: const ValueKey('task-context-pause'),
leading: const Icon(Icons.pause, size: 16),
enabled: task.status == TaskStatus.downloading,
onPressed: (_) => actions.onPause(),
child: Text(context.l10n.pause),
),
shad.MenuButton(
key: const ValueKey('task-context-delete'),
leading: const Icon(Icons.delete_outline, size: 16),
onPressed: (_) => actions.onDelete(),
child: Text(context.l10n.delete),
),
const shad.MenuDivider(),
shad.MenuButton(
key: const ValueKey('task-context-update-url'),
leading: const Icon(Icons.link, size: 16),
enabled: task.canUpdateUrl,
subMenu: [
shad.MenuButton(
leading: const Icon(Icons.edit_note, size: 16),
onPressed: (_) => actions.onUpdateUrl(),
child: Text(context.l10n.updateManually),
),
shad.MenuButton(
leading: Icon(actions.listeningForUpdate ? Icons.hearing_disabled : Icons.hearing, size: 16),
onPressed: (_) => actions.onToggleUpdateListener(),
child: Text(actions.listeningForUpdate ? context.l10n.stopListening : context.l10n.listenForUrl),
),
],
child: Text(context.l10n.updateUrl),
),
const shad.MenuDivider(),
shad.MenuButton(
key: const ValueKey('task-context-details'),
leading: const Icon(Icons.info_outline, size: 16),
onPressed: (_) => actions.onShowDetails(),
child: Text(context.l10n.taskDetailsInfoTab),
),
if (shouldShowTaskOpenFileAction(task))
shad.MenuButton(
key: const ValueKey('task-context-open-file'),
leading: const Icon(Icons.open_in_new, size: 16),
onPressed: (_) => actions.onOpenFile(),
child: Text(context.l10n.openFile),
),
if (shouldShowTaskOpenDirectoryAction())
shad.MenuButton(
key: const ValueKey('task-context-open-directory'),
leading: const Icon(Icons.folder_open_outlined, size: 16),
onPressed: (_) => actions.onOpenDirectory(),
child: Text(context.l10n.openDirectory),
),
shad.MenuButton(
key: const ValueKey('task-context-browse-files'),
leading: const Icon(Icons.snippet_folder_outlined, size: 16),
onPressed: (_) => actions.onBrowseFiles(),
child: Text(context.l10n.browseFiles),
),
],
child: child,
);
}
}
@visibleForTesting
bool shouldShowTaskOpenFileAction(TaskRecord task, {bool? web}) {
return !(web ?? kIsWeb) && !task.isFolder && task.status == TaskStatus.completed;
}
@visibleForTesting
bool shouldShowTaskOpenDirectoryAction({bool? web, bool? desktop}) {
return !(web ?? kIsWeb) && (desktop ?? Util.isDesktop());
}
@@ -0,0 +1,78 @@
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/theme/app_design_tokens.dart';
import '../../../../l10n/l10n.dart';
Future<bool?> showTaskDeleteDialog(BuildContext context, {required int taskCount, required bool keepFiles}) async {
var currentKeepFiles = keepFiles;
final dialog = const DialogOverlayHandler().show<bool>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) {
return StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
final contentWidth = (MediaQuery.sizeOf(dialogContext).width - 128).clamp(180.0, 380.0);
return AlertDialog(
leading: Container(
key: const ValueKey('task-delete-dialog-icon'),
width: 40,
height: 40,
decoration: BoxDecoration(
color: palette.error.withValues(alpha: 0.08),
border: Border.all(color: palette.error.withValues(alpha: 0.16)),
borderRadius: BorderRadius.circular(10),
),
alignment: Alignment.center,
child: Icon(Icons.delete_outline, size: 20, color: palette.error),
),
title: Text(dialogContext.l10n.deleteTasksTitle(taskCount)),
content: SizedBox(
width: contentWidth,
child: AnimatedContainer(
key: const ValueKey('task-delete-keep-files-option'),
duration: const Duration(milliseconds: 160),
padding: const EdgeInsets.symmetric(
horizontal: AppDesignTokens.space16,
vertical: AppDesignTokens.space12,
),
decoration: BoxDecoration(
color: currentKeepFiles ? palette.brandSoft : palette.surfaceSoft,
border: Border.all(color: currentKeepFiles ? palette.brand.withValues(alpha: 0.45) : palette.border),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Expanded(
child: Text(
dialogContext.l10n.deleteTaskTip,
style: TextStyle(color: palette.textPrimary, fontSize: 14, fontWeight: FontWeight.w500),
),
),
const SizedBox(width: AppDesignTokens.space16),
Switch(
key: const ValueKey('task-delete-keep-files-switch'),
value: currentKeepFiles,
onChanged: (value) => setDialogState(() => currentKeepFiles = value),
),
],
),
),
),
actions: [
SecondaryButton(onPressed: () => closeOverlay(dialogContext), child: Text(dialogContext.l10n.cancel)),
DestructiveButton(
onPressed: () => closeOverlay(dialogContext, currentKeepFiles),
child: Text(dialogContext.l10n.delete),
),
],
);
},
);
},
);
return dialog.future;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,103 @@
import 'package:flutter/widgets.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../l10n/l10n.dart';
class TaskEmptyState extends StatelessWidget {
const TaskEmptyState({super.key, this.message});
final String? message;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 360),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CustomPaint(
key: const ValueKey('task-empty-illustration'),
size: const Size(148, 108),
painter: _TaskEmptyIllustrationPainter(palette: palette),
),
const SizedBox(height: 18),
Text(
message ?? context.l10n.emptyTaskList,
style: TextStyle(color: palette.textPrimary, fontSize: 17, fontWeight: FontWeight.w700),
),
],
),
),
),
);
}
}
class _TaskEmptyIllustrationPainter extends CustomPainter {
const _TaskEmptyIllustrationPainter({required this.palette});
final AppPalette palette;
@override
void paint(Canvas canvas, Size size) {
final borderPaint = Paint()
..color = palette.border
..style = PaintingStyle.stroke
..strokeWidth = 1.4;
final sheetRect = RRect.fromRectAndRadius(Rect.fromLTWH(size.width / 2 - 34, 6, 68, 72), const Radius.circular(7));
canvas.drawRRect(sheetRect.shift(const Offset(0, 3)), Paint()..color = palette.textMuted.withValues(alpha: 0.06));
canvas.drawRRect(sheetRect, Paint()..color = palette.cardBg);
canvas.drawRRect(sheetRect, borderPaint);
final rowPaint = Paint()
..color = palette.textMuted.withValues(alpha: 0.34)
..strokeWidth = 2
..strokeCap = StrokeCap.round;
final centerX = size.width / 2;
for (var row = 0; row < 2; row++) {
final y = 20.0 + row * 14;
canvas.drawCircle(Offset(centerX - 22, y), 2.5, Paint()..color = palette.surfaceSoft);
canvas.drawLine(Offset(centerX - 14, y), Offset(centerX + 21, y), rowPaint);
}
final emptyBadgePaint = Paint()
..color = palette.surfaceSoft
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(centerX, 56), 11, emptyBadgePaint);
canvas.drawCircle(Offset(centerX, 56), 11, borderPaint);
canvas.drawLine(Offset(centerX - 4, 56), Offset(centerX + 4, 56), rowPaint);
final trayPath = Path()
..moveTo(26, 63)
..lineTo(49, 63)
..lineTo(57, 75)
..quadraticBezierTo(59, 78, 63, 78)
..lineTo(85, 78)
..quadraticBezierTo(89, 78, 91, 75)
..lineTo(99, 63)
..lineTo(122, 63)
..lineTo(115, 96)
..quadraticBezierTo(114, 101, 108, 101)
..lineTo(40, 101)
..quadraticBezierTo(34, 101, 33, 96)
..close();
canvas.drawPath(trayPath, Paint()..color = palette.surfaceSoft);
final trayPaint = Paint()
..color = palette.textSecondary.withValues(alpha: 0.72)
..style = PaintingStyle.stroke
..strokeWidth = 1.8
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round;
canvas.drawPath(trayPath, trayPaint);
}
@override
bool shouldRepaint(_TaskEmptyIllustrationPainter oldDelegate) {
return oldDelegate.palette != palette;
}
}
Loaded 50 of 742 files, more files were not shown because too many files have changed in this diff. Show more