Files
openchamber-android-native/lib/screens/files_panel.dart
T
blumia 5f95e2da97 feat: the terminal, project knowledge, and downloads that can be cancelled
- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and
  the /api/terminal/ws binary control frames) with a reconnecting socket
  that replays the server snapshot at the size it was drawn for.
- lib/terminal_state.dart: an xterm model plus that socket, kept per
  workspace on AppState, so closing the panel or switching tabs keeps the
  shell; the app reattaches when it returns from the background.
- lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard,
  restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT
  modifiers also apply to what the phone keyboard types.
- lib/screens/knowledge_panel.dart: notes, todos and plans from
  /api/project-context, searchable, with a full page for a plan's Markdown
  and its raw editor.
- Downloads stream with a progress dialog (bytes, total, percent) and a
  cancel that aborts the request; the save dialog only opens on success.
  The request asks for `accept-encoding: identity` so Content-Length exists.
- MarkdownView renders task lists as ✅/⬜ instead of material_ui's
  Checkbox, which wants a material_ui Material ancestor the app lacks.
- Dialogs own their TextEditingControllers, so closing one no longer
  trips a framework assertion in debug builds.
- 0.3.11 (311).
2026-11-21 02:49:07 +08:00

1034 lines
31 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The right-side panel: files of the session's directory (browse, preview,
// search, create, download). Project knowledge and the terminal are planned
// and get their places in the tab row already.
import 'dart:convert';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/transport.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import 'knowledge_panel.dart';
import 'terminal_panel.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, Session session) {
return showGeneralDialog<void>(
context: context,
barrierDismissible: true,
barrierLabel: '文件',
barrierColor: Colors.black54,
transitionDuration: const Duration(milliseconds: 220),
pageBuilder: (context, _, __) {
final width = MediaQuery.of(context).size.width;
return Align(
alignment: Alignment.centerRight,
child: Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
width: width * 0.92,
height: double.infinity,
child: FilesPanel(app: app, session: session),
),
),
);
},
transitionBuilder: (context, animation, _, child) => SlideTransition(
position: Tween(begin: const Offset(1, 0), end: Offset.zero).animate(
CurvedAnimation(parent: animation, curve: Curves.easeOutCubic)),
child: child,
),
);
}
class FilesPanel extends StatefulWidget {
final AppState app;
final Session session;
const FilesPanel({super.key, required this.app, required this.session});
@override
State<FilesPanel> createState() => _FilesPanelState();
}
const _imageExts = {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif', 'ico',
};
const _markdownExts = {'md', 'markdown', 'mdx'};
/// Walks skip these: they are huge and never what a phone search wants.
const _skipDirs = {
'.git', 'node_modules', 'build', '.dart_tool', '.gradle', '.idea',
'dist', 'target', 'vendor', 'Pods', '.venv', '__pycache__', '.next',
};
class _FilesPanelState extends State<FilesPanel> {
String get _root => widget.session.directory;
Client? get _client => widget.app.client;
String _path = '';
List<FsEntry> _entries = [];
bool _loading = false;
String? _error;
String _query = '';
/// A project listing hides what git ignores; the menu can show it.
bool _showIgnored = false;
List<FsEntry> _deepResults = [];
bool _deepDone = false;
bool _searching = false;
/// Preview state. `_previewPath == null` shows the browser.
String? _previewPath;
String _previewName = '';
bool _previewLoading = false;
String? _previewError;
Uint8List? _previewBytes;
String? _previewText;
bool _previewBinary = false;
bool _previewImage = false;
bool _editing = false;
bool _saving = false;
final TextEditingController _editor = TextEditingController();
final TextEditingController _search = TextEditingController();
int _tab = 0;
@override
void initState() {
super.initState();
_path = _root;
if (_root.isNotEmpty) _load();
}
@override
void dispose() {
_editor.dispose();
_search.dispose();
super.dispose();
}
// ------------------------------------------------------------- files
Future<void> _load([String? path]) async {
final client = _client;
if (client == null) return;
final target = path ?? _path;
setState(() {
_path = target;
_loading = true;
_error = null;
_previewPath = null;
_deepResults = [];
_deepDone = false;
});
try {
final list = await client
.fsList(target, directory: _root, respectGitignore: !_showIgnored)
..removeWhere((e) => e.name == '.git');
list.sort((a, b) {
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
if (!mounted) return;
setState(() {
_entries = list;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_loading = false;
_error = e is ApiError ? e.message : '$e';
});
}
}
void _up() {
if (_path == _root) return;
final cut = _path.lastIndexOf('/');
if (cut <= _root.length) {
_load(_root);
} else {
_load(_path.substring(0, cut));
}
}
List<String> get _crumbs {
if (_path == _root) return const [];
final rel = _path.startsWith(_root) ? _path.substring(_root.length) : _path;
return rel.split('/').where((s) => s.isNotEmpty).toList();
}
String get _rootName {
final parts = _root.split('/').where((s) => s.isNotEmpty).toList();
return parts.isEmpty ? _root : parts.last;
}
Future<void> _goToCrumb(int index) async {
final crumbs = _crumbs;
final target = '$_root/${crumbs.take(index + 1).join('/')}';
await _load(target == '$_root/' ? _root : target);
}
Future<void> _deepSearch() async {
final client = _client;
final q = _query.trim().toLowerCase();
if (client == null || q.isEmpty) return;
setState(() {
_searching = true;
_deepResults = [];
_deepDone = false;
});
final found = <FsEntry>[];
final queue = <String>[_path];
var dirs = 0;
while (queue.isNotEmpty && dirs < 400 && found.length < 200) {
if (!mounted) return;
final dir = queue.removeAt(0);
dirs++;
List<FsEntry> list;
try {
list = await client.fsList(dir, directory: _root);
} catch (_) {
continue;
}
for (final e in list) {
if (e.isDirectory) {
if (!_skipDirs.contains(e.name)) queue.add(e.path);
} else if (e.name.toLowerCase().contains(q) && found.length < 200) {
found.add(e);
}
}
if (found.length != _deepResults.length) {
setState(() => _deepResults = List.of(found));
}
}
if (!mounted) return;
setState(() {
_searching = false;
_deepDone = true;
_deepResults = found;
});
}
// ----------------------------------------------------------- preview
Future<void> _openPreview(FsEntry entry) async {
setState(() {
_previewPath = entry.path;
_previewName = entry.name;
_previewLoading = true;
_previewError = null;
_previewBytes = null;
_previewText = null;
_previewBinary = false;
_previewImage = false;
_editing = false;
});
final client = _client;
if (client == null) return;
try {
final stat = await client.fsStat(entry.path, directory: _root);
if (stat != null && stat.size > 2 * 1024 * 1024) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = '文件较大(${_fmtSize(stat.size)}),请下载后查看';
});
return;
}
final bytes =
Uint8List.fromList(await client.rawFile(entry.path, directory: _root));
if (!mounted || _previewPath != entry.path) return;
final image = _imageExts.contains(entry.extension);
final text = image ? null : _decodeText(bytes);
setState(() {
_previewBytes = bytes;
_previewImage = image;
_previewText = text;
_previewBinary = !image && text == null;
_previewLoading = false;
_editor.text = text ?? '';
});
} catch (e) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = e is ApiError ? e.message : '$e';
});
}
}
Future<void> _save() async {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
setState(() => _saving = true);
try {
await client.fsWrite(path, _editor.text, directory: _root);
if (!mounted) return;
setState(() {
_saving = false;
_editing = false;
_previewText = _editor.text;
_previewBinary = false;
});
_toast('已保存');
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
_toast(e is ApiError ? e.message : '$e');
}
}
Future<void> _download() async {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
// A file already in memory needs no progress; the rest stream with one.
var bytes = _previewBytes;
if (bytes == null) {
bytes = await showDialog<Uint8List>(
context: context,
barrierDismissible: false,
builder: (_) => _DownloadDialog(
name: _previewName,
start: (onProgress, cancel) => client.downloadFile(path,
directory: _root, onProgress: onProgress, cancel: cancel),
),
);
}
if (bytes == null || !mounted) return;
try {
final uri = await FilePicker.saveFile(
fileName: _previewName,
bytes: bytes,
);
if (uri != null) _toast('已保存');
} catch (e) {
_toast('保存失败:$e');
}
}
// ---------------------------------------------------------- new file
Future<void> _newEntry({required bool directory}) async {
final client = _client;
if (client == null || _path.isEmpty) return;
final name = await _askName(directory ? '新建文件夹' : '新建文件');
if (name == null) return;
final target = '$_path/$name';
try {
if (directory) {
await client.fsMkdir(target, directory: _root);
} else {
await client.fsWrite(target, '', directory: _root);
}
if (!mounted) return;
await _load();
if (!directory) {
await _openPreview(FsEntry(name: name, path: target));
}
} catch (e) {
_toast(e is ApiError ? e.message : '$e');
}
}
Future<String?> _askName(String title) async {
final controller = TextEditingController();
final name = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(
labelText: '名称',
hintText: title == '新建文件夹' ? '例如 docs' : '例如 notes.md',
),
onSubmitted: (v) => Navigator.of(context).pop(v),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(context).pop(controller.text),
child: const Text('创建')),
],
),
);
controller.dispose();
final trimmed = name?.trim() ?? '';
if (trimmed.isEmpty) return null;
if (trimmed.contains('/') || trimmed.contains('\\')) {
_toast('名称里不能有斜杠');
return null;
}
return trimmed;
}
void _toast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
// -------------------------------------------------------------- build
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_header(theme),
_tabs(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
],
),
);
}
Widget _header(ThemeData theme) {
return Padding(
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
child: Row(
children: [
if (_previewPath != null)
IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: '返回',
onPressed: () => setState(() => _previewPath = null),
)
else
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_previewPath != null ? _previewName : '文件',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
if (_previewPath == null && _root.isNotEmpty)
Text(_rootName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: theme.hintColor)),
],
),
),
if (_previewPath != null) ...[
if (_previewText != null)
IconButton(
icon: Icon(_editing ? Icons.visibility_outlined : Icons.edit_outlined),
tooltip: _editing ? '预览' : '编辑',
onPressed: _saving
? null
: () => setState(() => _editing = !_editing),
),
if (_editing)
IconButton(
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.check),
tooltip: '保存',
onPressed: _saving ? null : _save,
),
IconButton(
icon: const Icon(Icons.download_outlined),
tooltip: '下载',
onPressed: _download,
),
] else if (_root.isNotEmpty) ...[
PopupMenuButton<bool>(
icon: const Icon(Icons.add),
tooltip: '新建',
onSelected: (directory) => _newEntry(directory: directory),
itemBuilder: (_) => const [
PopupMenuItem(value: false, child: Text('新建文件')),
PopupMenuItem(value: true, child: Text('新建文件夹')),
],
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_horiz),
tooltip: '更多',
onSelected: (value) {
if (value == 'ignored') {
setState(() => _showIgnored = !_showIgnored);
_load();
} else if (value == 'refresh') {
_load();
}
},
itemBuilder: (_) => [
CheckedPopupMenuItem(
value: 'ignored',
checked: _showIgnored,
child: const Text('显示被 git 忽略的文件'),
),
const PopupMenuItem(
value: 'refresh',
child: Row(
children: [
Icon(Icons.refresh, size: 18),
SizedBox(width: 10),
Text('刷新'),
],
),
),
],
),
],
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭',
onPressed: () => Navigator.of(context).maybePop(),
),
],
),
);
}
Widget _tabs(ThemeData theme) {
const labels = ['文件', '项目知识', '终端'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < labels.length; i++)
ButtonSegment(value: i, label: Text(labels[i])),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() => _tab = v.first),
),
);
}
Widget _body(ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: Text('这个会话没有关联目录'));
}
switch (_tab) {
case 1:
return KnowledgePanel(app: widget.app, directory: _root);
case 2:
return TerminalPanel(app: widget.app, directory: _root);
default:
if (_previewPath != null) return _previewBody(theme);
return _browser(theme);
}
}
Widget _browser(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pathBar(theme),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (v) => setState(() {
_query = v;
_deepResults = [];
_deepDone = false;
}),
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search, size: 20),
hintText: '搜索当前目录…',
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: '搜索子目录',
onPressed: _searching ? null : _deepSearch,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12)),
contentPadding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
),
),
),
],
),
),
if (_searching)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(width: 8),
Text('正在搜索子目录…(${_deepResults.length})',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
),
Expanded(child: _list(theme)),
],
);
}
Widget _pathBar(ThemeData theme) {
final crumbs = _crumbs;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 8, 4),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 20),
tooltip: '上一级',
onPressed: _path == _root ? null : _up,
),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_crumb(theme, _rootName, () => _load(_root), last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
Text(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
],
),
),
),
],
),
);
}
Widget _crumb(ThemeData theme, String text, VoidCallback onTap,
{required bool last}) {
return InkWell(
onTap: last ? null : onTap,
borderRadius: BorderRadius.circular(6),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: Text(
text,
style: TextStyle(
fontSize: 13,
color: last ? theme.colorScheme.onSurface : theme.colorScheme.primary,
fontWeight: last ? FontWeight.w600 : FontWeight.w400,
),
),
),
);
}
Widget _list(ThemeData theme) {
if (_loading) return const Center(child: CircularProgressIndicator());
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 8),
TextButton(onPressed: () => _load(), child: const Text('重试')),
],
),
),
);
}
final filtered = _query.trim().isEmpty
? _entries
: _entries
.where((e) =>
e.name.toLowerCase().contains(_query.trim().toLowerCase()))
.toList();
if (filtered.isEmpty && _deepResults.isEmpty) {
return Center(
child: Text(_query.trim().isEmpty ? '目录为空' : '没有匹配的文件',
style: TextStyle(color: theme.hintColor)),
);
}
return ListView(
padding: const EdgeInsets.only(bottom: 16),
children: [
for (final e in filtered) _tile(theme, e),
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text('子目录结果',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
for (final e in _deepResults) _tile(theme, e, showPath: true),
],
if (_query.trim().isNotEmpty &&
_deepDone &&
_deepResults.isEmpty &&
!_searching &&
filtered.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text('子目录里没有匹配的文件',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
],
);
}
Widget _tile(ThemeData theme, FsEntry entry, {bool showPath = false}) {
final icon = entry.isDirectory
? Icons.folder_outlined
: _fileIcon(entry.extension);
return ListTile(
dense: true,
leading: Icon(icon,
color: entry.isDirectory
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant),
title: Text(entry.name,
maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 14)),
subtitle: showPath
? Text(_relative(entry.path),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: theme.hintColor))
: null,
trailing: entry.isDirectory
? Icon(Icons.chevron_right, size: 18, color: theme.hintColor)
: null,
onTap: () {
if (entry.isDirectory) {
_load(entry.path);
} else {
_openPreview(entry);
}
},
);
}
String _relative(String path) {
if (path.startsWith(_root)) {
final rel = path.substring(_root.length);
return rel.startsWith('/') ? rel.substring(1) : rel;
}
return path;
}
Widget _previewBody(ThemeData theme) {
if (_previewLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_previewError != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_previewError!, textAlign: TextAlign.center),
const SizedBox(height: 8),
if (_previewBytes != null || _previewError != null)
TextButton(onPressed: _download, child: const Text('下载')),
],
),
),
);
}
if (_previewImage && _previewBytes != null) {
return InteractiveViewer(
maxScale: 6,
child: Center(
child: Image.memory(_previewBytes!, fit: BoxFit.contain),
),
);
}
if (_previewBinary) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.insert_drive_file_outlined,
size: 40, color: theme.hintColor),
const SizedBox(height: 10),
Text('这个文件无法预览',
style: TextStyle(color: theme.hintColor)),
const SizedBox(height: 6),
Text(_fmtSize(_previewBytes?.length ?? 0),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _download,
icon: const Icon(Icons.download_outlined, size: 18),
label: const Text('下载'),
),
],
),
);
}
if (_editing) {
return Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _editor,
maxLines: null,
expands: true,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
textAlignVertical: TextAlignVertical.top,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
contentPadding: const EdgeInsets.all(10),
),
),
);
}
final text = _previewText ?? '';
if (_markdownExts.contains(_fileExt(_previewName))) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
child: MarkdownView(text, fontSize: 14),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 24),
child: SelectableText(
text,
style: const TextStyle(
fontSize: 12.5, height: 1.45, fontFamily: 'monospace'),
),
);
}
static String _fileExt(String name) {
final dot = name.lastIndexOf('.');
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
}
static IconData _fileIcon(String ext) {
if (_imageExts.contains(ext)) return Icons.image_outlined;
if (_markdownExts.contains(ext)) return Icons.description_outlined;
switch (ext) {
case 'json':
case 'yaml':
case 'yml':
case 'toml':
case 'ini':
case 'conf':
return Icons.tune;
case 'dart':
case 'kt':
case 'java':
case 'js':
case 'ts':
case 'tsx':
case 'jsx':
case 'py':
case 'go':
case 'rs':
case 'c':
case 'h':
case 'cpp':
case 'cc':
case 'hpp':
case 'cs':
case 'swift':
case 'rb':
case 'php':
case 'lua':
return Icons.code;
case 'sh':
case 'bash':
case 'zsh':
case 'fish':
return Icons.terminal;
case 'html':
case 'css':
case 'scss':
case 'less':
case 'xml':
return Icons.web_outlined;
case 'png':
case 'jpg':
case 'jpeg':
case 'gif':
case 'webp':
case 'svg':
return Icons.image_outlined;
case 'pdf':
return Icons.picture_as_pdf_outlined;
case 'zip':
case 'tar':
case 'gz':
case 'tgz':
case 'xz':
case '7z':
return Icons.folder_zip_outlined;
default:
return Icons.insert_drive_file_outlined;
}
}
static String? _decodeText(Uint8List bytes) {
if (bytes.isEmpty) return '';
final n = bytes.length < 8000 ? bytes.length : 8000;
var control = 0;
for (var i = 0; i < n; i++) {
final b = bytes[i];
if (b == 0) return null;
if (b < 8 || (b > 13 && b < 32)) control++;
}
if (control > n * 0.02) return null;
try {
return utf8.decode(bytes);
} catch (_) {
return null;
}
}
static String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
/// Streams one download and shows its progress; 取消 aborts the request and
/// the dialog closes with no bytes, so nothing is saved.
class _DownloadDialog extends StatefulWidget {
final String name;
final Future<Uint8List> Function(
void Function(int received, int? total) onProgress,
CancelToken cancel) start;
const _DownloadDialog({required this.name, required this.start});
@override
State<_DownloadDialog> createState() => _DownloadDialogState();
}
class _DownloadDialogState extends State<_DownloadDialog> {
final CancelToken _cancel = CancelToken();
int _received = 0;
int? _total;
bool _cancelling = false;
String? _error;
int _lastPaint = 0;
@override
void initState() {
super.initState();
_run();
}
Future<void> _run() async {
try {
final bytes = await widget.start((received, total) {
if (!mounted) return;
// Chunks arrive every few dozen KB; repaint a few times a second at
// most, and always on the last one.
final now = DateTime.now().millisecondsSinceEpoch;
if (total != null && received < total && now - _lastPaint < 80) return;
_lastPaint = now;
setState(() {
_received = received;
_total = total;
});
}, _cancel);
if (mounted) Navigator.of(context).pop(bytes);
} on DownloadCancelled {
if (mounted) Navigator.of(context).pop();
} catch (error) {
if (!mounted) return;
setState(() => _error = error is ApiError ? error.message : '$error');
}
}
String _size(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final total = _total;
final fraction = total != null && total > 0
? (_received / total).clamp(0.0, 1.0)
: null;
return AlertDialog(
title: const Text('正在下载'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13)),
const SizedBox(height: 12),
if (_error == null) ...[
LinearProgressIndicator(value: fraction),
const SizedBox(height: 8),
Text(
total != null
? '${_size(_received)} / ${_size(total)}'
'(${(fraction! * 100).toStringAsFixed(0)}%)'
: '已下载 ${_size(_received)}',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
] else
Text(_error!,
style:
TextStyle(fontSize: 12.5, color: theme.colorScheme.error)),
],
),
actions: [
if (_error == null)
TextButton(
onPressed: _cancelling
? null
: () {
setState(() => _cancelling = true);
_cancel.cancel();
},
child: Text(_cancelling ? '正在取消…' : '取消'),
)
else
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('关闭'),
),
],
);
}
}