Files

1122 lines
35 KiB
Dart
Raw Permalink Normal View History

// 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 'browser_panel.dart';
import 'knowledge_panel.dart';
import 'terminal_panel.dart';
import '../l10n.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, String directory) {
return showGeneralDialog<void>(
context: context,
barrierDismissible: true,
barrierLabel: tr('Files'),
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, directory: directory),
),
),
);
},
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;
/// The workspace directory this panel browses. A draft has one before it
/// has a session, so the panel never needs a session.
final String directory;
const FilesPanel({super.key, required this.app, required this.directory});
@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.directory;
Client? get _client => widget.app.client;
String _path = '';
List<FsEntry> _entries = [];
bool _loading = false;
String? _error;
String _query = '';
/// The last gitignore choice seen; the app's server-backed setting can
/// change while the panel is open (the switch writes it, a reload reads it).
bool _lastShowIgnored = 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;
/// The file's size from `fs/stat`, even when too large to preview: the
/// download dialog shows a determinate bar against it when the response
/// carries no Content-Length (the relay forwards bodies chunked).
int? _previewSize;
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;
/// Tabs built at least once. Kept alive (offstage) so the browser, terminal
/// and knowledge pages keep their state when another tab is shown.
final Set<int> _built = {0};
@override
void initState() {
super.initState();
_lastShowIgnored = widget.app.showGitignored;
widget.app.addListener(_onApp);
_path = _root;
if (_root.isNotEmpty) _load();
}
@override
void dispose() {
widget.app.removeListener(_onApp);
_editor.dispose();
_search.dispose();
super.dispose();
}
/// The gitignore setting is shared with the web UI; when it changes (here
/// or on another client), reload the listing with the new filter.
void _onApp() {
if (!mounted || widget.app.showGitignored == _lastShowIgnored) return;
_lastShowIgnored = widget.app.showGitignored;
setState(() {});
if (_previewPath == null) _load();
}
// ------------------------------------------------------------- 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: !widget.app.showGitignored)
..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;
_previewSize = 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 > 0 && mounted) {
setState(() => _previewSize = stat.size);
}
if (stat != null && stat.size > 2 * 1024 * 1024) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = trArgs(
'File is large ({0}), download it to view', [_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('Saved');
} 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,
expectedSize: _previewSize,
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('Saved');
} catch (e) {
_toast(trArgs('Couldn\'t save: {0}', [e]));
}
}
// ---------------------------------------------------------- new file
Future<void> _newEntry({required bool directory}) async {
final client = _client;
if (client == null || _path.isEmpty) return;
final name = await _askName(directory ? 'New folder' : 'New file');
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: AppText(title),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(
labelText: tr('Name'),
hintText: title == 'New folder' ? tr('e.g. docs') : tr('e.g. notes.md'),
),
onSubmitted: (v) => Navigator.of(context).pop(v),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.of(context).pop(controller.text),
child: const AppText('Create')),
],
),
);
controller.dispose();
final trimmed = name?.trim() ?? '';
if (trimmed.isEmpty) return null;
if (trimmed.contains('/') || trimmed.contains('\\')) {
_toast(tr('Names cannot contain slashes'));
return null;
}
return trimmed;
}
void _toast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: AppText(message)));
}
// -------------------------------------------------------------- build
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return SafeArea(
child: Padding(
// The panel is a dialog, so it does not shrink for the keyboard on its
// own: give the IME's height back here, or it covers the terminal's
// key bar and its last lines.
padding:
EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_tabs(theme),
const Divider(height: 1),
Expanded(
child: Stack(
children: [
for (var i = 0; i < 4; i++)
if (_built.contains(i))
Positioned.fill(
child: Offstage(
offstage: _tab != i,
child: _tabBody(i, theme),
),
),
],
),
),
],
),
),
);
}
/// The tab row is the panel's title now; the only global action left is
/// closing the panel. Everything else belongs to the tab's own header.
Widget _tabs(ThemeData theme) {
// Icons only: four labels no longer fit a phone's panel width. The
// tooltips keep them identifiable.
const tabs = [
(Icons.folder_outlined, 'Files'),
(Icons.menu_book_outlined, 'Project knowledge'),
(Icons.terminal, 'Terminal'),
(Icons.public, 'Browser'),
];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 2, 6),
child: Row(
children: [
Expanded(
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < tabs.length; i++)
ButtonSegment(
value: i,
icon: Tooltip(
message: tr(tabs[i].$2),
child: Icon(tabs[i].$1, size: 19),
),
),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() {
_tab = v.first;
_built.add(v.first);
}),
),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: tr('Close sidebar'),
onPressed: () => Navigator.of(context).maybePop(),
),
],
),
);
}
Widget _tabBody(int index, ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: AppText('This session has no directory'));
}
switch (index) {
case 1:
return KnowledgePanel(app: widget.app, directory: _root);
case 2:
return TerminalPanel(app: widget.app, directory: _root);
case 3:
return BrowserPanel(app: widget.app, directory: _root);
default:
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pathBar(theme),
Expanded(
child: _previewPath != null
? _previewBody(theme)
: _browserBody(theme),
),
],
);
}
}
Widget _browserBody(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
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: tr('Search this directory…'),
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: tr('Search subdirectories'),
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),
AppText(trArgs('Searching subdirectories… ({0})', [_deepResults.length]),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
),
Expanded(child: _list(theme)),
],
);
}
/// The tab's own header: where you are, plus what you can do here. The
/// panel's global actions (close) sit in the tab row above.
Widget _pathBar(ThemeData theme) {
final crumbs = _crumbs;
final preview = _previewPath != null;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 4, 4),
child: Row(
children: [
IconButton(
icon: Icon(preview ? Icons.arrow_back : Icons.arrow_upward,
size: 20),
tooltip: preview ? tr('Back') : tr('Up one level'),
onPressed: preview
? () => setState(() => _previewPath = null)
: (_path == _root ? null : _up),
),
Expanded(
child: preview
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_previewName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13.5, fontWeight: FontWeight.w600)),
Text(_previewPath!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11, color: theme.hintColor)),
],
)
: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_crumb(theme, _rootName, () => _load(_root),
last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
AppText(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
],
),
),
),
if (preview) ...[
if (_previewText != null)
IconButton(
icon: Icon(_editing
? Icons.visibility_outlined
: Icons.edit_outlined),
tooltip: _editing ? tr('Preview') : tr('Edit'),
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: tr('Save'),
onPressed: _saving ? null : _save,
),
IconButton(
icon: const Icon(Icons.download_outlined),
tooltip: tr('Download'),
onPressed: _download,
),
] else if (_root.isNotEmpty) ...[
PopupMenuButton<bool>(
icon: const Icon(Icons.add),
tooltip: tr('New'),
onSelected: (directory) => _newEntry(directory: directory),
itemBuilder: (_) => const [
PopupMenuItem(value: false, child: AppText('New file')),
PopupMenuItem(value: true, child: AppText('New folder')),
],
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_horiz),
tooltip: tr('More'),
onSelected: (value) {
if (value == 'ignored') {
widget.app.setShowGitignored(!widget.app.showGitignored);
} else if (value == 'refresh') {
_load();
}
},
itemBuilder: (_) => [
CheckedPopupMenuItem(
value: 'ignored',
checked: widget.app.showGitignored,
child: const AppText('Show git-ignored files'),
),
const PopupMenuItem(
value: 'refresh',
child: Row(
children: [
Icon(Icons.refresh, size: 18),
SizedBox(width: 10),
AppText('Refresh'),
],
),
),
],
),
],
],
),
);
}
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 AppText('Retry')),
],
),
),
);
}
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: AppText(_query.trim().isEmpty ? 'Directory is empty' : 'No matching files',
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: AppText('Subdirectory results',
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: AppText('No matching files in subdirectories',
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 AppText('Download')),
],
),
),
);
}
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),
AppText('This file cannot be previewed',
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 AppText('Download'),
),
],
),
);
}
if (_editing) {
return Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _editor,
maxLines: null,
minLines: 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;
/// The file's size from `fs/stat`; the progress bar is determinate against
/// it from the first byte when the response has no Content-Length.
final int? expectedSize;
final Future<Uint8List> Function(
void Function(int received, int? total) onProgress,
CancelToken cancel) start;
const _DownloadDialog(
{required this.name, this.expectedSize, 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();
_total = (widget.expectedSize ?? 0) > 0 ? widget.expectedSize : null;
_run();
}
Future<void> _run() async {
try {
final bytes = await widget.start((received, total) {
if (!mounted) return;
// The server's own total is more accurate than the stat we started
// with; keep the latter when the response is chunked.
if (total != null) _total = total;
// 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;
final known = _total;
if (known != null && received < known && now - _lastPaint < 80) return;
_lastPaint = now;
setState(() {
_received = received;
});
}, _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 AppText('Downloading'),
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),
AppText(
total != null
? trArgs('{0} / {1} ({2}%)', [
_size(_received),
_size(total),
// Below 10% one decimal says the transfer is moving;
// whole numbers are enough above it.
(fraction! * 100).toStringAsFixed(fraction < 0.1 ? 1 : 0),
])
: trArgs('Downloaded {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: AppText(_cancelling ? 'Canceling…' : 'Cancel'),
)
else
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const AppText('Close'),
),
],
);
}
}