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,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;
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../l10n/l10n.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../util/util.dart';
import '../../domain/task_record.dart';
import 'task_file_manager.dart';
Future<void> browseTaskFiles(BuildContext context, TaskRecord task, {required bool mobile}) async {
if (mobile && !Util.isWeb()) {
await context.push('/tasks/${Uri.encodeComponent(task.id)}/files', extra: task);
return;
}
await showTaskFileBrowserDialog(context, task);
}
Future<void> showTaskFileBrowserDialog(BuildContext context, TaskRecord task) async {
final overlay = const shad.DialogOverlayHandler().show<void>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) {
final viewport = MediaQuery.sizeOf(dialogContext);
final dialogWidth = (viewport.width - 64).clamp(240.0, 820.0);
final dialogHeight = (viewport.height - 160).clamp(180.0, 620.0);
return shad.AlertDialog(
key: const ValueKey('task-file-browser-dialog'),
padding: const EdgeInsets.all(20),
title: SizedBox(
width: dialogWidth,
child: Row(
children: [
Expanded(child: Text(dialogContext.l10n.browseFiles, maxLines: 1, overflow: TextOverflow.ellipsis)),
AppTooltip(
message: dialogContext.l10n.close,
child: shad.IconButton.ghost(
size: shad.ButtonSize.xSmall,
onPressed: () => shad.closeOverlay(dialogContext),
icon: const Icon(Icons.close, size: 18),
),
),
],
),
),
content: SizedBox(
width: dialogWidth,
height: dialogHeight,
child: TaskFileManagerView(task: task),
),
);
},
);
await overlay.future;
}
@@ -0,0 +1,369 @@
import 'dart:async';
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import 'package:share_plus/share_plus.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import 'package:url_launcher/url_launcher.dart';
import '../../../../api/api.dart' as api;
import '../../../../core/utils/file_explorer.dart';
import '../../../../l10n/l10n.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_toast.dart';
import '../../../../shared/widgets/app_tooltip.dart';
import '../../../../util/browser_download/browser_download.dart';
import '../../../../util/util.dart';
import '../../domain/task_record.dart';
class TaskFileManagerView extends StatefulWidget {
const TaskFileManagerView({super.key, required this.task, this.webActions, this.desktopActions});
final TaskRecord task;
final bool? webActions;
final bool? desktopActions;
@override
State<TaskFileManagerView> createState() => _TaskFileManagerViewState();
}
class _TaskFileManagerViewState extends State<TaskFileManagerView> {
late _TaskFileDirectoryIndex _index;
var _directory = '/';
bool get _webActions => widget.webActions ?? Util.isWeb();
bool get _desktopActions => widget.desktopActions ?? Util.isDesktop();
@override
void initState() {
super.initState();
_index = _TaskFileDirectoryIndex(widget.task);
}
@override
void didUpdateWidget(covariant TaskFileManagerView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.task.id != oldWidget.task.id || !identical(widget.task.files, oldWidget.task.files)) {
_index = _TaskFileDirectoryIndex(widget.task);
if (!_index.contains(_directory)) _directory = '/';
}
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final entries = _index.entries(_directory);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_FileBreadcrumb(directory: _directory, onSelected: (directory) => setState(() => _directory = directory)),
Expanded(
child: entries.isEmpty
? Center(
child: Text(context.l10n.noFiles, style: TextStyle(color: palette.textMuted, fontSize: 13)),
)
: ListView.builder(
key: PageStorageKey<String>('task-file-manager-${widget.task.id}-$_directory'),
padding: const EdgeInsets.fromLTRB(16, 4, 16, 20),
itemCount: entries.length,
itemBuilder: (context, index) {
final entry = entries[index];
return _FileManagerRow(
key: ValueKey('managed-file-${entry.fullPath}'),
entry: entry,
childCount: entry.directory ? _index.entries(entry.fullPath).length : 0,
webActions: _webActions,
desktopActions: _desktopActions,
onOpenDirectory: () => setState(() => _directory = entry.fullPath),
onOpenSystemDirectory: () => unawaited(_revealEntry(entry)),
onOpenFile: () => unawaited(_openFile(entry)),
onShareFile: () => unawaited(_shareFile(context, entry)),
onDownloadFile: () => _downloadFile(entry),
);
},
),
),
],
);
}
Future<void> _openFile(_TaskFileEntry entry) async {
final opened = _webActions
? await launchUrl(Uri.parse(_accessUrl(entry)), webOnlyWindowName: '_blank')
: await FileExplorer.open(_localPath(entry));
if (!opened && mounted) {
showAppToast(context, context.l10n.unableOpenPath(entry.name), type: AppToastType.error);
}
}
Future<void> _revealEntry(_TaskFileEntry entry) async {
final entryPath = _localPath(entry);
if (!await FileExplorer.reveal(entryPath) && mounted) {
showAppToast(context, context.l10n.unableLocatePath(entryPath), type: AppToastType.error);
}
}
Future<void> _shareFile(BuildContext actionContext, _TaskFileEntry entry) async {
try {
final renderBox = actionContext.findRenderObject();
final origin = renderBox is RenderBox ? renderBox.localToGlobal(Offset.zero) & renderBox.size : null;
await Share.shareXFiles([XFile(_localPath(entry))], sharePositionOrigin: origin);
} catch (error) {
if (mounted) showAppToast(context, error.toString(), type: AppToastType.error);
}
}
void _downloadFile(_TaskFileEntry entry) {
download(_accessUrl(entry), entry.name);
}
String _localPath(_TaskFileEntry entry) {
if (!widget.task.isFolder && _index.fileCount == 1) return widget.task.storagePath;
final segments = entry.fullPath.split('/').where((part) => part.isNotEmpty);
return path.joinAll([widget.task.storagePath, ...segments]);
}
String _accessUrl(_TaskFileEntry entry) {
final encodedPath = entry.fullPath.split('/').where((part) => part.isNotEmpty).map(Uri.encodeComponent).join('/');
return api.join('/fs/tasks/${Uri.encodeComponent(widget.task.id)}/$encodedPath');
}
}
class _FileBreadcrumb extends StatelessWidget {
const _FileBreadcrumb({required this.directory, required this.onSelected});
final String directory;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final segments = directory.split('/').where((part) => part.isNotEmpty).toList(growable: false);
final crumbs = <({String label, String path})>[(label: '/', path: '/')];
var current = '';
for (final segment in segments) {
current = '$current/$segment';
crumbs.add((label: segment, path: current));
}
return SizedBox(
height: 48,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
for (var index = 0; index < crumbs.length; index++) ...[
if (index > 0) Icon(Icons.chevron_right, size: 16, color: palette.textMuted),
GestureDetector(
key: ValueKey('file-breadcrumb-${crumbs[index].path}'),
onTap: () => onSelected(crumbs[index].path),
behavior: HitTestBehavior.opaque,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 12),
child: Text(
crumbs[index].label,
style: TextStyle(
color: index == crumbs.length - 1 ? palette.textPrimary : palette.textSecondary,
fontSize: 12,
fontWeight: index == crumbs.length - 1 ? FontWeight.w600 : FontWeight.w400,
),
),
),
),
],
],
),
),
);
}
}
class _FileManagerRow extends StatelessWidget {
const _FileManagerRow({
super.key,
required this.entry,
required this.childCount,
required this.webActions,
required this.desktopActions,
required this.onOpenDirectory,
required this.onOpenSystemDirectory,
required this.onOpenFile,
required this.onShareFile,
required this.onDownloadFile,
});
final _TaskFileEntry entry;
final int childCount;
final bool webActions;
final bool desktopActions;
final VoidCallback onOpenDirectory;
final VoidCallback onOpenSystemDirectory;
final VoidCallback onOpenFile;
final VoidCallback onShareFile;
final VoidCallback onDownloadFile;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return GestureDetector(
onTap: entry.directory ? onOpenDirectory : null,
behavior: HitTestBehavior.opaque,
child: Container(
constraints: const BoxConstraints(minHeight: 54),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: palette.border)),
),
child: Row(
children: [
Icon(
taskFileTypeIcon(entry.name, isFolder: entry.directory),
size: 20,
color: entry.directory ? palette.brand : palette.textSecondary,
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
entry.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textPrimary, fontSize: 13, fontWeight: FontWeight.w500),
),
const SizedBox(height: 2),
Text(
entry.directory ? context.l10n.items(childCount) : Util.fmtByte(entry.size),
style: TextStyle(color: palette.textMuted, fontSize: 11),
),
],
),
),
if (entry.directory) ...[
if (desktopActions) ...[
_FileActionButton(
label: context.l10n.openDirectory,
icon: Icons.folder_open_outlined,
onPressed: onOpenSystemDirectory,
),
const SizedBox(width: 4),
],
Icon(Icons.chevron_right, size: 18, color: palette.textMuted),
] else ...[
_FileActionButton(label: context.l10n.openFile, icon: Icons.open_in_new, onPressed: onOpenFile),
if (desktopActions) ...[
const SizedBox(width: 4),
_FileActionButton(
label: context.l10n.openDirectory,
icon: Icons.folder_open_outlined,
onPressed: onOpenSystemDirectory,
),
] else ...[
const SizedBox(width: 4),
if (webActions)
_FileActionButton(
label: context.l10n.download,
icon: Icons.download_outlined,
onPressed: onDownloadFile,
)
else
_FileActionButton(label: context.l10n.share, icon: Icons.share_outlined, onPressed: onShareFile),
],
],
],
),
),
);
}
}
class _FileActionButton extends StatelessWidget {
const _FileActionButton({required this.label, required this.icon, required this.onPressed});
final String label;
final IconData icon;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return AppTooltip(
message: label,
child: shad.IconButton.ghost(
size: shad.ButtonSize.small,
onPressed: onPressed,
icon: Icon(icon, size: 17, color: palette.textSecondary),
),
);
}
}
class _TaskFileDirectoryIndex {
_TaskFileDirectoryIndex(TaskRecord task) {
final sourceFiles = task.files.isEmpty
? [TaskFileNode(path: '/', name: task.name, sizeBytes: task.totalBytes ?? 0)]
: task.files;
fileCount = sourceFiles.length;
final singleFile = !task.isFolder && fileCount == 1;
for (final file in sourceFiles) {
final directory = _normalizeDirectory(file.path);
final name = singleFile ? path.basename(task.storagePath) : file.name;
final fullPath = directory == '/' ? '/$name' : '$directory/$name';
_add(directory, _TaskFileEntry(directory: false, fullPath: fullPath, name: name, size: file.sizeBytes));
_addParentDirectories(directory);
}
for (final entries in _entries.values) {
entries.sort((left, right) {
if (left.directory != right.directory) return left.directory ? -1 : 1;
return left.name.toLowerCase().compareTo(right.name.toLowerCase());
});
}
}
final Map<String, List<_TaskFileEntry>> _entries = {'/': []};
late final int fileCount;
bool contains(String directory) => _entries.containsKey(directory);
List<_TaskFileEntry> entries(String directory) => _entries[directory] ?? const [];
void _addParentDirectories(String directory) {
var current = directory;
while (current != '/') {
final parent = path.posix.dirname(current);
final normalizedParent = parent == '.' ? '/' : parent;
final name = path.posix.basename(current);
_add(normalizedParent, _TaskFileEntry(directory: true, fullPath: current, name: name, size: 0));
_entries.putIfAbsent(current, () => []);
current = normalizedParent;
}
}
void _add(String directory, _TaskFileEntry entry) {
final entries = _entries.putIfAbsent(directory, () => []);
if (!entries.any((item) => item.fullPath == entry.fullPath)) entries.add(entry);
}
}
class _TaskFileEntry {
const _TaskFileEntry({required this.directory, required this.fullPath, required this.name, required this.size});
final bool directory;
final String fullPath;
final String name;
final int size;
}
String _normalizeDirectory(String value) {
var normalized = value.trim().replaceAll('\\', '/');
if (normalized.isEmpty || normalized == '.') return '/';
if (!normalized.startsWith('/')) normalized = '/$normalized';
while (normalized.length > 1 && normalized.endsWith('/')) {
normalized = normalized.substring(0, normalized.length - 1);
}
return normalized;
}
@@ -0,0 +1,308 @@
import 'package:flutter/material.dart' show Icons;
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
import '../../../../api/model/task.dart';
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/file_tree_view.dart';
import '../../../../util/util.dart';
import '../../../../l10n/l10n.dart';
import '../../domain/task_record.dart';
import 'task_progress_bar.dart';
class TaskFileTree extends StatefulWidget {
const TaskFileTree({super.key, required this.task, this.runtimeStatus, this.progressAction});
final TaskRecord task;
final TaskRuntimeStatus? runtimeStatus;
final Widget? progressAction;
@override
State<TaskFileTree> createState() => _TaskFileTreeState();
}
class _TaskFileTreeState extends State<TaskFileTree> {
late List<FileTreeItem<TaskFileNode>> _items;
@override
void initState() {
super.initState();
_items = _buildItems(widget.task.files);
}
@override
void didUpdateWidget(covariant TaskFileTree oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.task.id != oldWidget.task.id || !identical(widget.task.files, oldWidget.task.files)) {
_items = _buildItems(widget.task.files);
}
}
@override
Widget build(BuildContext context) {
final progressByIndex = {
for (final file in widget.runtimeStatus?.files ?? const <FileRuntimeStatus>[]) file.index: file,
};
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TaskDownloadProgress(task: widget.task, runtimeStatus: widget.runtimeStatus, action: widget.progressAction),
const SizedBox(height: 12),
Expanded(
child: FileTreeView<TaskFileNode>(
items: _items,
keyPrefix: 'task-file-tree',
rowHeight: 27,
iconSize: 15,
iconBuilder: (node) => taskFileTypeIcon(node.label, isFolder: node.isFolder),
contentTextStyle: const TextStyle(fontSize: 11, height: 1.1),
trailingHeader: const _TaskFileColumnsHeader(),
trailingBuilder: (context, node) => _FileDownloadProgress(
node: node,
progressByIndex: progressByIndex,
runtimeStatusAvailable: widget.runtimeStatus != null,
fallbackProgress: widget.task.progress,
taskStatus: widget.task.status,
),
),
),
],
);
}
List<FileTreeItem<TaskFileNode>> _buildItems(List<TaskFileNode> files) {
return files
.asMap()
.entries
.map(
(entry) => FileTreeItem<TaskFileNode>(
key: entry.key.toString(),
path: entry.value.path,
name: entry.value.name,
size: entry.value.sizeBytes,
data: entry.value,
),
)
.toList(growable: false);
}
}
class _TaskDownloadProgress extends StatelessWidget {
const _TaskDownloadProgress({required this.task, required this.runtimeStatus, this.action});
final TaskRecord task;
final TaskRuntimeStatus? runtimeStatus;
final Widget? action;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final runtime = runtimeStatus;
final totalBytes = runtime?.total ?? 0;
final downloadedBytes = runtime?.downloaded ?? 0;
final progress = runtime == null
? task.progress
: totalBytes > 0
? (downloadedBytes / totalBytes).clamp(0.0, 1.0)
: null;
final progressLabel = progress == null ? '--' : '${(progress * 100).toStringAsFixed(progress < 0.1 ? 1 : 0)}%';
final transferred = runtime == null
? (task.total == null ? task.downloaded : '${task.downloaded} / ${task.total}')
: totalBytes > 0
? '${Util.fmtByte(downloadedBytes)} / ${Util.fmtByte(totalBytes)}'
: Util.fmtByte(downloadedBytes);
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
context.l10n.progress,
style: TextStyle(color: palette.textPrimary, fontSize: 12, fontWeight: FontWeight.w600),
),
),
Text(transferred, style: TextStyle(color: palette.textSecondary, fontSize: 11)),
const SizedBox(width: 8),
SizedBox(
width: 38,
child: Text(
progressLabel,
textAlign: TextAlign.right,
style: TextStyle(color: palette.textPrimary, fontSize: 11, fontWeight: FontWeight.w600),
),
),
],
),
const SizedBox(height: 7),
TaskProgressBar(
key: const ValueKey('task-files-total-progress'),
value: progress,
indeterminate: runtime == null && task.isIndeterminate,
shimmer: task.status == TaskStatus.downloading,
height: 4,
trackColor: palette.progressTrack,
fillColor: palette.brandProgress,
highlightStartColor: palette.brandProgress.withValues(alpha: 0),
highlightEndColor: palette.brandProgress.withValues(alpha: 0),
),
],
),
),
if (action != null) ...[const SizedBox(width: 12), action!],
],
);
}
}
class _FileDownloadProgress extends StatelessWidget {
const _FileDownloadProgress({
required this.node,
required this.progressByIndex,
required this.runtimeStatusAvailable,
required this.fallbackProgress,
required this.taskStatus,
});
final FileTreeNode<TaskFileNode> node;
final Map<int, FileRuntimeStatus> progressByIndex;
final bool runtimeStatusAvailable;
final double? fallbackProgress;
final TaskStatus taskStatus;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final taskStateIcon = switch (taskStatus) {
TaskStatus.paused => Semantics(
label: context.l10n.pause,
child: Icon(Icons.pause_circle_filled, size: 16, color: palette.textMuted),
),
TaskStatus.failed => Semantics(
label: context.l10n.failed,
child: Icon(Icons.error_rounded, size: 16, color: palette.error),
),
TaskStatus.completed => Semantics(
label: context.l10n.completed,
child: Icon(shad.BootstrapIcons.checkCircleFill, size: 16, color: palette.brandProgress),
),
TaskStatus.downloading => null,
};
if (taskStateIcon != null) {
return SizedBox(
key: ValueKey('task-file-progress-${node.key}'),
width: 116,
child: _TaskFileColumns(progress: taskStateIcon, size: _formatFileSize(node.size)),
);
}
final selectedFiles = node.leafItems
.map((item) => int.tryParse(item.key))
.whereType<int>()
.map((index) => progressByIndex[index])
.whereType<FileRuntimeStatus>()
.toList(growable: false);
if (selectedFiles.isEmpty) {
final progress = runtimeStatusAvailable ? null : fallbackProgress;
final showFallbackProgress = !runtimeStatusAvailable && progress != null;
return SizedBox(
key: showFallbackProgress ? ValueKey('task-file-progress-${node.key}') : null,
width: 116,
child: _TaskFileColumns(
progress: showFallbackProgress
? Semantics(
label: '${(progress * 100).toStringAsFixed(0)}%',
child: shad.CircularProgressIndicator(
value: progress,
size: 16,
strokeWidth: 2,
color: palette.brandProgress,
backgroundColor: palette.progressTrack,
),
)
: const SizedBox.square(dimension: 16),
size: _formatFileSize(node.size),
),
);
}
final downloaded = selectedFiles.fold<int>(0, (total, file) => total + file.downloaded);
final sizeKnown = selectedFiles.every((file) => file.size > 0);
final size = sizeKnown ? selectedFiles.fold<int>(0, (total, file) => total + file.size) : 0;
final progress = size > 0 ? (downloaded / size).clamp(0.0, 1.0) : null;
final completed = progress != null && progress >= 1;
final progressLabel = progress == null ? Util.fmtByte(downloaded) : '${(progress * 100).toStringAsFixed(0)}%';
return SizedBox(
key: ValueKey('task-file-progress-${node.key}'),
width: 116,
child: _TaskFileColumns(
progress: Semantics(
label: completed ? context.l10n.completed : progressLabel,
child: completed
? Icon(shad.BootstrapIcons.checkCircleFill, size: 16, color: palette.brandProgress)
: shad.CircularProgressIndicator(
value: progress ?? (downloaded > 0 ? null : 0),
size: 16,
strokeWidth: 2,
color: palette.brandProgress,
backgroundColor: palette.progressTrack,
),
),
size: _formatFileSize(node.size),
),
);
}
}
class _TaskFileColumnsHeader extends StatelessWidget {
const _TaskFileColumnsHeader();
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final style = TextStyle(color: palette.textSecondary, fontSize: 10, fontWeight: FontWeight.w600);
return _TaskFileColumns(
progress: Text(context.l10n.progress, maxLines: 1, style: style),
size: context.l10n.size,
sizeStyle: style,
);
}
}
class _TaskFileColumns extends StatelessWidget {
const _TaskFileColumns({required this.progress, required this.size, this.sizeStyle});
final Widget progress;
final String size;
final TextStyle? sizeStyle;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return Row(
children: [
SizedBox(width: 44, child: Center(child: progress)),
const SizedBox(width: 4),
Expanded(
child: Text(
size,
maxLines: 1,
overflow: TextOverflow.fade,
softWrap: false,
textAlign: TextAlign.right,
style: sizeStyle ?? TextStyle(color: palette.textSecondary, fontSize: 10),
),
),
],
);
}
}
String _formatFileSize(int size) => size > 0 ? Util.fmtByte(size) : '--';
@@ -0,0 +1,200 @@
import 'package:flutter/widgets.dart';
class TaskProgressBar extends StatefulWidget {
const TaskProgressBar({
super.key,
required this.trackColor,
required this.fillColor,
required this.highlightStartColor,
required this.highlightEndColor,
this.value,
this.indeterminate = false,
this.shimmer = true,
this.height = 2,
});
final Color trackColor;
final Color fillColor;
final Color highlightStartColor;
final Color highlightEndColor;
final double? value;
final bool indeterminate;
final bool shimmer;
final double height;
@override
State<TaskProgressBar> createState() => _TaskProgressBarState();
}
class _TaskProgressBarState extends State<TaskProgressBar> with SingleTickerProviderStateMixin {
static const double _shimmerPixelsPerSecond = 140.0;
static const double _shimmerMinDurationMs = 900;
static const double _shimmerMaxDurationMs = 3200;
late final AnimationController _controller;
bool get _shouldAnimate => widget.indeterminate || widget.shimmer;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 1600));
_syncAnimation();
}
@override
void didUpdateWidget(covariant TaskProgressBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.indeterminate != oldWidget.indeterminate || widget.shimmer != oldWidget.shimmer) {
_syncAnimation();
}
}
void _syncAnimation() {
if (_shouldAnimate) {
if (!_controller.isAnimating) _controller.repeat();
} else {
_controller.stop();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: widget.height,
child: ClipRRect(
borderRadius: BorderRadius.circular(999),
child: ColoredBox(
color: widget.trackColor,
child: LayoutBuilder(
builder: (context, constraints) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
if (widget.indeterminate) {
final segmentWidth = constraints.maxWidth * 0.4;
final left = lerpDouble(-segmentWidth, constraints.maxWidth, _controller.value);
return Stack(
fit: StackFit.expand,
children: [
Positioned(
left: left,
width: segmentWidth,
top: 0,
bottom: 0,
child: _ProgressFill(
color: widget.fillColor,
shimmer: widget.shimmer,
highlightStartColor: widget.highlightStartColor,
highlightEndColor: widget.highlightEndColor,
bandLeft: lerpDouble(-segmentWidth, segmentWidth * 2, _controller.value),
bandWidth: segmentWidth * 0.5,
),
),
],
);
}
final fillWidth = constraints.maxWidth * ((widget.value ?? 0).clamp(0, 1));
final bandWidth = fillWidth == 0 ? 0.0 : (fillWidth * 0.35).clamp(16.0, 40.0);
final travelDistance = fillWidth + bandWidth * 2;
final durationMs = (travelDistance / _shimmerPixelsPerSecond * 1000)
.clamp(_shimmerMinDurationMs, _shimmerMaxDurationMs)
.round();
if (widget.shimmer && widget.value != null && fillWidth > 0) {
final duration = Duration(milliseconds: durationMs);
if (_controller.duration != duration) {
_controller.duration = duration;
}
}
return Stack(
fit: StackFit.expand,
children: [
Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: fillWidth,
child: _ProgressFill(
color: widget.fillColor,
shimmer: widget.shimmer,
highlightStartColor: widget.highlightStartColor,
highlightEndColor: widget.highlightEndColor,
bandLeft: lerpDouble(-bandWidth, fillWidth + bandWidth, _controller.value),
bandWidth: bandWidth,
),
),
),
],
);
},
);
},
),
),
),
);
}
double lerpDouble(double min, double max, double t) => min + ((max - min) * t);
}
class _ProgressFill extends StatelessWidget {
const _ProgressFill({
required this.color,
required this.shimmer,
required this.highlightStartColor,
required this.highlightEndColor,
required this.bandLeft,
required this.bandWidth,
});
final Color color;
final bool shimmer;
final Color highlightStartColor;
final Color highlightEndColor;
final double bandLeft;
final double bandWidth;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(999),
boxShadow: shimmer ? [BoxShadow(color: const Color(0x33FFFFFF), blurRadius: 8)] : null,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(999),
child: shimmer
? Stack(
fit: StackFit.expand,
children: [
Positioned(
left: bandLeft,
width: bandWidth,
top: 0,
bottom: 0,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [highlightStartColor, const Color(0xFFFFFFFF), highlightEndColor],
),
),
),
),
],
)
: const SizedBox.expand(),
),
);
}
}
@@ -0,0 +1,236 @@
import 'dart:math' as math;
import 'package:flutter/material.dart' show Icons, Scrollbar, ScrollbarOrientation;
import 'package:flutter/widgets.dart';
import '../../../../../api/model/task_stats.dart';
import '../../../../../core/utils/byte_size_formatter.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../../../l10n/l10n.dart';
enum PeerTableProtocol { bt, ed2k }
enum _PeerSortColumn { address, client, transport, downloadSpeed, uploadSpeed, pieces, completion, relevance, source }
class PeerTable extends StatefulWidget {
const PeerTable({super.key, required this.protocol, required this.peers});
final PeerTableProtocol protocol;
final List<TaskPeerStats> peers;
@override
State<PeerTable> createState() => _PeerTableState();
}
class _PeerTableState extends State<PeerTable> {
static const _headerHeight = 40.0;
static const _rowHeight = 38.0;
double get _tableWidth => widget.protocol == PeerTableProtocol.bt ? 1070 : 870;
final ScrollController _horizontalController = ScrollController();
final ScrollController _verticalController = ScrollController();
_PeerSortColumn _sortColumn = _PeerSortColumn.downloadSpeed;
bool _ascending = false;
@override
void dispose() {
_horizontalController.dispose();
_verticalController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
final peers = [...widget.peers]..sort(_comparePeers);
return SizedBox(
height: 300,
child: LayoutBuilder(
builder: (context, constraints) {
final contentWidth = math.max(_tableWidth, constraints.maxWidth);
return Scrollbar(
controller: _horizontalController,
thumbVisibility: true,
trackVisibility: true,
interactive: true,
thickness: 7,
scrollbarOrientation: ScrollbarOrientation.bottom,
child: SingleChildScrollView(
controller: _horizontalController,
scrollDirection: Axis.horizontal,
child: SizedBox(
width: contentWidth,
height: constraints.maxHeight,
child: Column(
children: [
Container(
height: _headerHeight,
decoration: BoxDecoration(
color: palette.sideBg,
border: Border(bottom: BorderSide(color: palette.border)),
),
child: Row(children: _headers(context)),
),
Expanded(
child: ListView.builder(
controller: _verticalController,
padding: const EdgeInsets.only(bottom: 12),
itemCount: peers.length,
itemExtent: _rowHeight,
itemBuilder: (context, index) => _PeerRow(protocol: widget.protocol, peer: peers[index]),
),
),
],
),
),
),
);
},
),
);
}
List<Widget> _headers(BuildContext context) => [
_header(context.l10n.address, _PeerSortColumn.address, 180),
_header(context.l10n.client, _PeerSortColumn.client, 150),
_header(context.l10n.protocol, _PeerSortColumn.transport, 80),
_header(context.l10n.speed, _PeerSortColumn.downloadSpeed, 120),
_header(context.l10n.uploadSpeed, _PeerSortColumn.uploadSpeed, 120),
_header(context.l10n.pieces, _PeerSortColumn.pieces, 100),
if (widget.protocol == PeerTableProtocol.bt) ...[
_header(context.l10n.progress, _PeerSortColumn.completion, 100),
_header(context.l10n.fileRelevance, _PeerSortColumn.relevance, 100),
],
_header(context.l10n.source, _PeerSortColumn.source, 120),
];
Widget _header(String label, _PeerSortColumn column, double width) {
final palette = AppPalette.of(context);
final active = _sortColumn == column;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
setState(() {
if (_sortColumn == column) {
_ascending = !_ascending;
} else {
_sortColumn = column;
_ascending = column != _PeerSortColumn.downloadSpeed && column != _PeerSortColumn.uploadSpeed;
}
});
},
child: SizedBox(
width: width,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: [
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: active ? palette.textPrimary : palette.textSecondary,
fontSize: 11,
fontWeight: FontWeight.w700,
),
),
),
if (active) ...[
const SizedBox(width: 3),
Icon(_ascending ? Icons.arrow_upward : Icons.arrow_downward, size: 12, color: palette.textMuted),
],
],
),
),
),
);
}
int _comparePeers(TaskPeerStats a, TaskPeerStats b) {
final result = switch (_sortColumn) {
_PeerSortColumn.address => a.address.compareTo(b.address),
_PeerSortColumn.client => a.client.compareTo(b.client),
_PeerSortColumn.transport => a.transport.compareTo(b.transport),
_PeerSortColumn.downloadSpeed => a.downloadSpeed.compareTo(b.downloadSpeed),
_PeerSortColumn.uploadSpeed => a.uploadSpeed.compareTo(b.uploadSpeed),
_PeerSortColumn.pieces => a.pieceCount.compareTo(b.pieceCount),
_PeerSortColumn.completion => (a.completion ?? -1).compareTo(b.completion ?? -1),
_PeerSortColumn.relevance => (a.relevance ?? -1).compareTo(b.relevance ?? -1),
_PeerSortColumn.source => a.source.compareTo(b.source),
};
return _ascending ? result : -result;
}
}
class _PeerRow extends StatelessWidget {
const _PeerRow({required this.protocol, required this.peer});
final PeerTableProtocol protocol;
final TaskPeerStats peer;
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return DecoratedBox(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: palette.border)),
),
child: Row(
children: [
_cell(context, peer.address, 180),
_cell(context, peer.client, 150),
_cell(context, _formatProtocol(protocol, peer.transport), 80),
_cell(context, _formatRate(peer.downloadSpeed), 120),
_cell(context, _formatRate(peer.uploadSpeed), 120),
_cell(context, peer.pieceCount.toString(), 100),
if (protocol == PeerTableProtocol.bt) ...[
_cell(context, _formatPercentage(peer.completion), 100),
_cell(context, _formatPercentage(peer.relevance), 100),
],
_cell(context, peer.source, 120),
],
),
);
}
Widget _cell(BuildContext context, String value, double width) {
final palette = AppPalette.of(context);
return SizedBox(
width: width,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Text(
value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: palette.textSecondary, fontSize: 11),
),
),
);
}
}
String _formatRate(int bytesPerSecond) => bytesPerSecond <= 0 ? '—' : '${_formatBytes(bytesPerSecond)}/s';
String _formatProtocol(PeerTableProtocol protocol, String transport) {
if (protocol == PeerTableProtocol.ed2k) return 'ED2K';
return switch (transport.toLowerCase()) {
'utp' => 'uTP',
'webrtc' => 'WebRTC',
_ => 'BT',
};
}
String _formatPercentage(double? ratio) {
if (ratio == null) return '—';
final percentage = ratio.clamp(0.0, 1.0) * 100;
final fractionDigits = percentage == percentage.roundToDouble() ? 0 : 1;
return '${percentage.toStringAsFixed(fractionDigits)}%';
}
String _formatBytes(int bytes) {
return ByteSizeFormatter.format(bytes);
}
@@ -0,0 +1,204 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import '../../../../../api/model/task_stats.dart';
import '../../../../../core/utils/byte_size_formatter.dart';
import '../../../../../shared/theme/app_palette.dart';
import '../../../../../l10n/l10n.dart';
class PieceMap extends StatefulWidget {
const PieceMap({super.key, required this.pieceMap, this.totalBytes});
final TaskPieceMap pieceMap;
final int? totalBytes;
@override
State<PieceMap> createState() => _PieceMapState();
}
class _PieceMapState extends State<PieceMap> {
static const _gap = 3.0;
static const _targetCellSize = 11.0;
// The default desktop drawer fits 28 columns, so 252 cells fill 9 rows.
static const _maxPaintedCells = 252;
int? _focusedCell;
PointerDeviceKind? _lastPointerKind;
@override
void didUpdateWidget(covariant PieceMap oldWidget) {
super.didUpdateWidget(oldWidget);
if (_focusedCell != null && _focusedCell! >= math.min(widget.pieceMap.pieceCount, _maxPaintedCells)) {
_focusedCell = null;
}
}
List<TaskPieceState> _displayPieces(int displayCount) {
final pieceMap = widget.pieceMap;
if (pieceMap.pieceCount <= displayCount) {
return List.generate(pieceMap.pieceCount, pieceMap.stateAt, growable: false);
}
return List.generate(displayCount, (cell) {
final start = cell * pieceMap.pieceCount ~/ displayCount;
final end = math.max(start + 1, (cell + 1) * pieceMap.pieceCount ~/ displayCount);
var allCompleted = true;
for (var index = start; index < math.min(end, pieceMap.pieceCount); index++) {
final state = pieceMap.stateAt(index);
if (state != TaskPieceState.completed) allCompleted = false;
}
if (allCompleted) return TaskPieceState.completed;
return TaskPieceState.pending;
});
}
@override
Widget build(BuildContext context) {
final palette = AppPalette.of(context);
return LayoutBuilder(
builder: (context, constraints) {
if (widget.pieceMap.isEmpty) return const SizedBox.shrink();
final width = constraints.maxWidth;
final columns = math.max(1, ((width + _gap) / (_targetCellSize + _gap)).floor());
final displayCount = math.min(widget.pieceMap.pieceCount, _maxPaintedCells);
final pieces = _displayPieces(displayCount);
final focusedCell = _focusedCell != null && _focusedCell! < pieces.length ? _focusedCell : null;
final cellSize = (width - _gap * (columns - 1)) / columns;
final rows = (pieces.length / columns).ceil();
final mapHeight = rows * cellSize + math.max(0, rows - 1) * _gap;
int? cellAt(Offset offset) {
final column = (offset.dx / (cellSize + _gap)).floor();
final row = (offset.dy / (cellSize + _gap)).floor();
if (column < 0 || column >= columns || row < 0 || row >= rows) return null;
final localX = offset.dx - column * (cellSize + _gap);
final localY = offset.dy - row * (cellSize + _gap);
if (localX > cellSize || localY > cellSize) return null;
final index = row * columns + column;
return index < pieces.length ? index : null;
}
void updateFocus(PointerEvent event, {required bool pressed}) {
final index = cellAt(event.localPosition);
if (pressed || event.kind == PointerDeviceKind.mouse || event.kind == PointerDeviceKind.trackpad) {
setState(() {
_focusedCell = index;
_lastPointerKind = event.kind;
});
}
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MouseRegion(
onExit: (_) {
if (_lastPointerKind == PointerDeviceKind.mouse || _lastPointerKind == PointerDeviceKind.trackpad) {
setState(() => _focusedCell = null);
}
},
child: Listener(
behavior: HitTestBehavior.opaque,
onPointerHover: (event) => updateFocus(event, pressed: false),
onPointerDown: (event) => updateFocus(event, pressed: true),
child: CustomPaint(
size: Size(width, mapHeight),
painter: _PieceMapPainter(
pieces: pieces,
columns: columns,
cellSize: cellSize,
gap: _gap,
palette: palette,
focusedCell: focusedCell,
),
),
),
),
SizedBox(
height: 24,
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
focusedCell == null ? '' : _rangeLabel(focusedCell, pieces.length),
style: TextStyle(color: palette.textMuted, fontSize: 11),
),
),
),
],
);
},
);
}
String _rangeLabel(int displayIndex, int displayCount) {
final sourceCount = widget.pieceMap.pieceCount;
final startPiece = displayIndex * sourceCount ~/ displayCount;
final endPiece = math.max(startPiece + 1, (displayIndex + 1) * sourceCount ~/ displayCount) - 1;
final pieceLabel = startPiece == endPiece
? context.l10n.piece(startPiece + 1)
: context.l10n.pieceRange(startPiece + 1, endPiece + 1);
final bytesPerPiece = widget.pieceMap.pieceSize;
if (bytesPerPiece <= 0) return pieceLabel;
final startByte = startPiece * bytesPerPiece;
final rawEnd = (endPiece + 1) * bytesPerPiece - 1;
final endByte = widget.totalBytes == null ? rawEnd : math.min(rawEnd, widget.totalBytes! - 1);
return '$pieceLabel · ${_formatBytes(startByte)}–${_formatBytes(math.max(startByte, endByte))}';
}
}
class _PieceMapPainter extends CustomPainter {
const _PieceMapPainter({
required this.pieces,
required this.columns,
required this.cellSize,
required this.gap,
required this.palette,
required this.focusedCell,
});
final List<TaskPieceState> pieces;
final int columns;
final double cellSize;
final double gap;
final AppPalette palette;
final int? focusedCell;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint();
for (var index = 0; index < pieces.length; index++) {
final column = index % columns;
final row = index ~/ columns;
final cellRect = Rect.fromLTWH(column * (cellSize + gap), row * (cellSize + gap), cellSize, cellSize);
final rect = RRect.fromRectAndRadius(cellRect, const Radius.circular(2));
final state = pieces[index];
paint.color = switch (state) {
TaskPieceState.pending => palette.surfaceSoft,
TaskPieceState.completed => palette.success,
};
canvas.drawRRect(rect, paint);
if (focusedCell == index) {
paint
..style = PaintingStyle.stroke
..strokeWidth = 1.5
..color = palette.textPrimary;
canvas.drawRRect(rect, paint);
paint.style = PaintingStyle.fill;
}
}
}
@override
bool shouldRepaint(covariant _PieceMapPainter oldDelegate) {
return oldDelegate.pieces != pieces ||
oldDelegate.palette != palette ||
oldDelegate.focusedCell != focusedCell ||
oldDelegate.columns != columns ||
oldDelegate.cellSize != cellSize;
}
}
String _formatBytes(int bytes) {
return ByteSizeFormatter.format(bytes);
}
@@ -0,0 +1,81 @@
import 'package:flutter/widgets.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' hide Column, Expanded, Row;
import '../../../../shared/theme/app_palette.dart';
import '../../../../shared/widgets/app_http_headers_editor.dart';
import '../../../../shared/widgets/app_primary_button.dart';
import '../../../../l10n/l10n.dart';
import '../../domain/task_record.dart';
class TaskUrlUpdate {
const TaskUrlUpdate({required this.url, required this.headers});
final String url;
final Map<String, String> headers;
}
Future<TaskUrlUpdate?> showTaskUpdateUrlDialog(BuildContext context, TaskRecord task) async {
final urlController = TextEditingController(text: task.url);
final headersController = AppHttpHeadersController(headers: task.requestHeaders);
final dialog = const DialogOverlayHandler().show<TaskUrlUpdate?>(
context: context,
alignment: Alignment.center,
barrierDismissable: false,
builder: (dialogContext) {
String? errorText;
return StatefulBuilder(
builder: (dialogContext, setDialogState) {
final palette = AppPalette.of(dialogContext);
void submit() {
final url = urlController.text.trim();
if (url.isEmpty) {
setDialogState(() => errorText = dialogContext.l10n.downloadLinkValid);
return;
}
closeOverlay(dialogContext, TaskUrlUpdate(url: url, headers: headersController.toMap()));
}
return AlertDialog(
title: Text(dialogContext.l10n.updateUrl),
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680, maxHeight: 480),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(dialogContext.l10n.downloadLink, style: TextStyle(color: palette.textPrimary, fontSize: 12)),
const SizedBox(height: 6),
TextField(controller: urlController),
const SizedBox(height: 18),
AppHttpHeadersEditor(
controller: headersController,
label: dialogContext.l10n.httpHeader,
keyPrefix: 'update-task-http-header',
),
if (errorText != null) ...[
const SizedBox(height: 10),
Text(errorText!, style: TextStyle(color: palette.error, fontSize: 12)),
],
],
),
),
),
actions: [
SecondaryButton(onPressed: () => closeOverlay(dialogContext), child: Text(dialogContext.l10n.cancel)),
AppPrimaryButton(onPressed: submit, child: Text(dialogContext.l10n.updateAndResume)),
],
);
},
);
},
);
try {
return await dialog.future;
} finally {
urlController.dispose();
headersController.dispose();
}
}