Merge branch 'ws-files-viewer'

# Conflicts:
#	app/tool/capture/README.md
This commit is contained in:
2026-11-07 01:45:03 +00:00
32 changed files with 1349 additions and 140 deletions
@@ -47,7 +47,7 @@ class FilesController extends ChangeNotifier {
filter = '';
} catch (e) {
if (_disposed || request != _request) return;
error = '$e';
error = "Couldn't load this folder.";
} finally {
if (!_disposed && request == _request) {
loading = false;
@@ -0,0 +1,98 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../artifacts/actions/artifact_transfer.dart';
import '../../artifacts/domain/artifact_kind.dart';
import '../../artifacts/ui/artifact_external_open.dart';
import '../data/directory_listing.dart';
import 'files_download.dart';
import 'files_models.dart';
import 'files_preview.dart';
import 'files_urls.dart';
/// Details and host-native actions for a file the embedded viewer cannot show.
void showFileDetails(
BuildContext context, {
required DirectoryEntry entry,
required FileUrls? urls,
required Future<ArtifactTransferResult> Function()? download,
required ArtifactExternalOpen openExternal,
}) {
final cupertino = usesCupertinoHost(context);
Widget content(BuildContext sheet) {
Future<void> open() async {
var opened = false;
try {
opened = await openExternal(urls!.view);
} catch (_) {
/* keep the sheet and download action available */
}
if (opened && sheet.mounted) Navigator.pop(sheet);
}
final body = SafeArea(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
entry.name,
style: cupertino
? CupertinoTheme.of(sheet).textTheme.navTitleTextStyle
: Theme.of(sheet).textTheme.titleLarge,
),
const SizedBox(height: 12),
Text(
'${artifactKindLabel(artifactKind(fileContentType(entry.name), entry.name))} · ${fileSizeLabel(entry.size)}',
),
Text('Modified: ${fileModifiedLabel(entry.modified)}'),
const SizedBox(height: 8),
Text(
urls == null
? 'No server address is configured, so this file cannot be fetched.'
: 'This file type cannot be previewed here.',
),
const SizedBox(height: 16),
if (download != null) FileDownloadButton(download: download),
if (urls != null)
cupertino
? CupertinoButton(
onPressed: open,
child: const Text('Open externally'),
)
: TextButton.icon(
onPressed: open,
icon: const Icon(Icons.open_in_new),
label: const Text('Open externally'),
),
if (cupertino)
CupertinoButton(
onPressed: () => Navigator.pop(sheet),
child: const Text('Close'),
),
],
),
),
);
return cupertino
? CupertinoPopupSurface(
child: DefaultTextStyle(
style: CupertinoTheme.of(sheet).textTheme.textStyle,
child: body,
),
)
: body;
}
if (cupertino) {
showCupertinoModalPopup<void>(context: context, builder: content);
} else {
showModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: content,
);
}
}
@@ -0,0 +1,141 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/cupertino.dart';
import '../../../ui/adaptive/host.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../artifacts/actions/artifact_file.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
import '../../artifacts/actions/artifact_transfer.dart';
import '../../artifacts/ui/artifact_viewer_fetch.dart';
import '../data/directory_listing.dart';
import 'files_preview.dart';
import 'files_urls.dart';
const String fileDownloadFailed = 'Could not download the file. Try again.';
/// Opens an attachment url in the browser (web only); tests inject a recorder.
typedef FileUrlLauncher = Future<bool> Function(Uri url);
Future<bool> launchFileUrl(Uri url) =>
launchUrl(url, mode: LaunchMode.externalApplication);
/// Downloads one working-directory file.
///
/// On the web the browser handles the `download=1` url itself: the attachment
/// disposition makes it save the file with its own name, so no bytes pass
/// through the app. Everywhere else the bytes are fetched from the inline url
/// and handed to the host through the artifact file bridge (system "Save as"),
/// exactly as an artifact download is.
Future<ArtifactTransferResult> downloadFile({
required DirectoryEntry entry,
required FileUrls urls,
ArtifactFileBridge bridge = const ArtifactFileBridge(),
ArtifactFetch fetch = fetchArtifact,
FileUrlLauncher launch = launchFileUrl,
}) async {
try {
if (kIsWeb) {
final opened = await launch(urls.download);
return opened
? ArtifactTransferResult(
ArtifactTransferState.saved,
'Downloading ${entry.name}.',
)
: const ArtifactTransferResult(
ArtifactTransferState.failed,
fileDownloadFailed,
);
}
final ArtifactFetchResult result;
try {
result = await fetch(urls.view);
} on ArtifactFetchException {
return const ArtifactTransferResult(
ArtifactTransferState.failed,
fileDownloadFailed,
);
}
if (!result.ok) {
return const ArtifactTransferResult(
ArtifactTransferState.failed,
fileDownloadFailed,
);
}
return await bridge.saveFile(
ArtifactFile(
name: entry.name,
mimeType: fileContentType(entry.name),
bytes: result.bytes,
),
);
} catch (_) {
return const ArtifactTransferResult(
ArtifactTransferState.failed,
fileDownloadFailed,
);
}
}
/// The Download button of the unviewable-file sheet, with its outcome below.
class FileDownloadButton extends StatefulWidget {
const FileDownloadButton({super.key, required this.download});
/// Runs the transfer; the sheet's owner binds the entry, urls and bridge.
final Future<ArtifactTransferResult> Function() download;
@override
State<FileDownloadButton> createState() => _FileDownloadButtonState();
}
class _FileDownloadButtonState extends State<FileDownloadButton> {
bool _busy = false;
String? _status;
Future<void> _download() async {
if (_busy) return;
setState(() {
_busy = true;
_status = null;
});
String status;
try {
status = (await widget.download()).message;
} catch (_) {
status = fileDownloadFailed;
}
if (!mounted) return;
setState(() {
_busy = false;
_status = status.isEmpty ? null : status;
});
}
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (usesCupertinoHost(context))
CupertinoButton.filled(
onPressed: _busy ? null : _download,
child: _busy
? const CupertinoActivityIndicator()
: const Text('Download'),
)
else
FilledButton.icon(
onPressed: _busy ? null : _download,
icon: _busy
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.download_outlined),
label: const Text('Download'),
),
if (_status != null)
Padding(padding: const EdgeInsets.only(top: 8), child: Text(_status!)),
],
);
}
@@ -0,0 +1,137 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/layout/app_overflow_menu.dart';
import '../data/directory_listing.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'files_controller.dart';
import 'files_models.dart';
class FilesHeader extends StatelessWidget {
const FilesHeader({
super.key,
required this.controller,
required this.filter,
});
final FilesController controller;
final TextEditingController filter;
@override
Widget build(BuildContext context) {
final listing = controller.listing;
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 8, 4),
child: Column(
children: [
Row(
children: [
if (listing?.parent != null)
IconButton(
tooltip: 'Back',
onPressed: controller.loading
? null
: () => controller.open(listing!.parent),
icon: const Icon(Icons.arrow_back),
),
Expanded(
child: Text(
homeRelativeLabel(
listing?.home ?? '',
listing?.path ?? controller.initialPath,
),
overflow: TextOverflow.ellipsis,
),
),
IconButton(
tooltip: 'Refresh',
onPressed: controller.loading ? null : controller.retry,
icon: const Icon(Icons.refresh),
),
IconButton(
tooltip: controller.view == FilesViewMode.list
? 'Grid view'
: 'List view',
onPressed: () => controller.setView(
controller.view == FilesViewMode.list
? FilesViewMode.grid
: FilesViewMode.list,
),
icon: Icon(
controller.view == FilesViewMode.list
? Icons.grid_view
: Icons.view_list,
),
),
AppOverflowMenu<FilesSortKey>(
label: 'Sort',
onSelected: (_, key) =>
controller.setSort(controller.sort.reverseOr(key)),
actions: [
for (final key in FilesSortKey.values)
AppMenuAction(
value: key,
label:
'${key.name}${controller.sort.key == key ? (controller.sort.ascending ? ' ↑' : ' ↓') : ''}',
),
],
),
],
),
if (listing != null)
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final crumb in folderCrumbs(listing.home, listing.path))
chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 6),
onPressed: controller.loading
? null
: () => controller.open(crumb.path),
child: Text(crumb.label),
)
: TextButton(
onPressed: controller.loading
? null
: () => controller.open(crumb.path),
child: Text(crumb.label),
),
],
),
),
Row(
children: [
Expanded(
child:
chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoSearchTextField(
controller: filter,
onChanged: controller.setFilter,
placeholder: 'Filter files',
)
: TextField(
controller: filter,
onChanged: controller.setFilter,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Filter files',
isDense: true,
),
),
),
IconButton(
tooltip: 'Show hidden files',
onPressed: () =>
controller.toggleHidden(!controller.showHidden),
icon: Icon(
controller.showHidden
? Icons.visibility
: Icons.visibility_off,
),
),
],
),
],
),
);
}
}
+2 -1
View File
@@ -1,12 +1,13 @@
import 'package:flutter/material.dart';
import '../../artifacts/domain/artifact_kind.dart';
import '../data/directory_listing.dart';
import 'files_preview.dart';
/// Chooses the same broad kind glyphs used by the artifact gallery.
IconData fileIcon(DirectoryEntry entry) {
if (entry.isDir) return Icons.folder_outlined;
switch (artifactKind('', entry.name)) {
switch (artifactKind(fileContentType(entry.name), entry.name)) {
case ArtifactKind.image:
return Icons.image_outlined;
case ArtifactKind.video:
+14 -3
View File
@@ -1,4 +1,5 @@
import '../data/directory_listing.dart';
import 'files_preview.dart';
import '../../artifacts/domain/artifact_kind.dart';
enum FilesViewMode { list, grid }
@@ -39,14 +40,15 @@ List<DirectoryEntry> sortFileEntries(
return result;
}
String fileKind(DirectoryEntry entry) =>
entry.isDir ? 'Folder' : artifactKind('', entry.name).name;
String fileKind(DirectoryEntry entry) => entry.isDir
? 'Folder'
: artifactKind(fileContentType(entry.name), entry.name).name;
String fileSizeLabel(int? size) {
if (size == null) return '—';
if (size < 1024) return '$size B';
final units = ['KiB', 'MiB', 'GiB', 'TiB'];
var value = size.toDouble();
var value = size / 1024;
var unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
@@ -54,3 +56,12 @@ String fileSizeLabel(int? size) {
}
return '${value.toStringAsFixed(value >= 10 ? 0 : 1)} ${units[unit]}';
}
/// A compact local timestamp; keep missing or malformed values unobtrusive.
String fileModifiedLabel(String? value) {
final date = DateTime.tryParse(value ?? '')?.toLocal();
if (date == null) return 'Unknown';
String two(int n) => n.toString().padLeft(2, '0');
return '${date.year}-${two(date.month)}-${two(date.day)} '
'${two(date.hour)}:${two(date.minute)}';
}
+89 -119
View File
@@ -1,10 +1,14 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/transport/pipelines_client.dart';
import '../data/directory_listing.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'files_controller.dart';
import 'files_icons.dart';
import 'files_models.dart';
import 'files_thumbnail.dart';
import 'files_viewer.dart';
import 'files_header.dart';
import '../../../ui/layout/app_overflow_menu.dart';
const double filesPanelMinWidth = 280;
const double filesPanelMaxWidth = 420;
@@ -13,10 +17,21 @@ const double filesPanelFraction = .30;
double filesPanelWidth(double available) => (available * filesPanelFraction)
.clamp(filesPanelMinWidth, filesPanelMaxWidth);
/// The two explicit actions of a file's row or tile menu.
enum FileAction { open, download }
class FilesPanel extends StatefulWidget {
const FilesPanel({super.key, required this.controller, this.onOpen});
const FilesPanel({
super.key,
required this.controller,
this.onOpen,
this.viewer = const FilesViewer(),
});
final FilesController controller;
final ValueChanged<DirectoryEntry>? onOpen;
/// Opens and downloads files; tests inject one that never fetches.
final FilesViewer viewer;
@override
State<FilesPanel> createState() => _FilesPanelState();
}
@@ -24,6 +39,7 @@ class FilesPanel extends StatefulWidget {
class _FilesPanelState extends State<FilesPanel> {
late final TextEditingController _filter = TextEditingController();
FilesController get controller => widget.controller;
String get _endpoint => configuredGatewayEndpoint(controller.gateway);
@override
void initState() {
super.initState();
@@ -32,7 +48,10 @@ class _FilesPanelState extends State<FilesPanel> {
}
void _changed() {
if (mounted) setState(() {});
if (mounted) {
if (_filter.text != controller.filter) _filter.text = controller.filter;
setState(() {});
}
}
@override
@@ -45,6 +64,7 @@ class _FilesPanelState extends State<FilesPanel> {
@override
Widget build(BuildContext context) {
final listing = controller.listing;
final entries = controller.entries;
if (controller.missingDirectory) {
return const _FilesMessage('This chat has no working directory.');
}
@@ -52,7 +72,7 @@ class _FilesPanelState extends State<FilesPanel> {
color: Theme.of(context).colorScheme.surface,
child: Column(
children: [
_header(context, listing),
FilesHeader(controller: controller, filter: _filter),
if (controller.error != null)
ChatErrorNotice(
message: controller.error!,
@@ -60,13 +80,19 @@ class _FilesPanelState extends State<FilesPanel> {
),
if (controller.loading && listing == null)
const Expanded(child: ChatLoadingIndicator())
else if (listing != null &&
controller.entries.isEmpty &&
!controller.loading)
const Expanded(child: _FilesMessage('This folder is empty.'))
else if (listing != null && entries.isEmpty && !controller.loading)
Expanded(
child: _FilesMessage(
controller.filter.isEmpty
? 'This folder is empty.'
: 'No files match your filter.',
),
)
else
Expanded(
child: controller.view == FilesViewMode.grid ? _grid() : _list(),
child: controller.view == FilesViewMode.grid
? _grid(entries)
: _list(entries),
),
if (listing?.truncated == true)
const Padding(
@@ -78,137 +104,55 @@ class _FilesPanelState extends State<FilesPanel> {
);
}
Widget _header(BuildContext context, DirectoryListing? listing) => Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 8, 4),
child: Column(
children: [
Row(
children: [
if (listing?.parent != null)
IconButton(
tooltip: 'Back',
onPressed: controller.loading
? null
: () => controller.open(listing!.parent),
icon: const Icon(Icons.arrow_back),
),
Expanded(
child: Text(
homeRelativeLabel(
listing?.home ?? '',
listing?.path ?? controller.initialPath,
),
overflow: TextOverflow.ellipsis,
),
),
IconButton(
tooltip: 'Refresh',
onPressed: controller.loading ? null : controller.retry,
icon: const Icon(Icons.refresh),
),
IconButton(
tooltip: controller.view == FilesViewMode.list
? 'Grid view'
: 'List view',
onPressed: () => controller.setView(
controller.view == FilesViewMode.list
? FilesViewMode.grid
: FilesViewMode.list,
),
icon: Icon(
controller.view == FilesViewMode.list
? Icons.grid_view
: Icons.view_list,
),
),
PopupMenuButton<FilesSortKey>(
initialValue: controller.sort.key,
tooltip: 'Sort',
onSelected: (key) =>
controller.setSort(controller.sort.reverseOr(key)),
itemBuilder: (_) => [
for (final key in FilesSortKey.values)
PopupMenuItem(value: key, child: Text(key.name)),
],
),
],
),
Row(
children: [
Expanded(
child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoSearchTextField(
controller: _filter,
onChanged: controller.setFilter,
placeholder: 'Filter files',
)
: TextField(
controller: _filter,
onChanged: controller.setFilter,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Filter files',
isDense: true,
),
),
),
IconButton(
tooltip: 'Show hidden files',
onPressed: () => controller.toggleHidden(!controller.showHidden),
icon: Icon(
controller.showHidden ? Icons.visibility : Icons.visibility_off,
),
),
],
),
],
),
);
Widget _list() => ListView.builder(
itemCount: controller.entries.length,
Widget _list(List<DirectoryEntry> entries) => ListView.builder(
itemCount: entries.length,
itemBuilder: (_, index) {
final entry = controller.entries[index];
final entry = entries[index];
return ListTile(
onTap: () => entry.isDir
? controller.open(entry.path)
: widget.onOpen?.call(entry),
leading: Icon(
fileIcon(entry),
),
title: Text(entry.name),
onTap: () => entry.isDir ? controller.open(entry.path) : _open(entry),
leading: Icon(fileIcon(entry)),
title: Text(entry.name, maxLines: 2, overflow: TextOverflow.ellipsis),
subtitle: Text(
entry.isDir
? 'Folder'
: '${entry.modified ?? 'Unknown'} · ${fileSizeLabel(entry.size)}',
: '${fileModifiedLabel(entry.modified)} · ${fileSizeLabel(entry.size)}',
),
trailing: entry.isDir ? null : Text(fileKind(entry)),
trailing: entry.isDir
? null
: Row(
mainAxisSize: MainAxisSize.min,
children: [Text(fileKind(entry)), _menu(entry)],
),
);
},
);
Widget _grid() => GridView.builder(
Widget _grid(List<DirectoryEntry> entries) => GridView.builder(
padding: const EdgeInsets.all(12),
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 180,
childAspectRatio: 1.25,
childAspectRatio: .85,
),
itemCount: controller.entries.length,
itemCount: entries.length,
itemBuilder: (_, index) {
final entry = controller.entries[index];
final entry = entries[index];
return InkWell(
onTap: () => entry.isDir
? controller.open(entry.path)
: widget.onOpen?.call(entry),
onTap: () => entry.isDir ? controller.open(entry.path) : _open(entry),
child: Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
fileIcon(entry),
size: 32,
Align(
alignment: Alignment.centerRight,
child: entry.isDir
? const SizedBox(height: 48)
: _menu(entry),
),
Expanded(
child: Center(
child: FileThumbnail(entry: entry, endpoint: _endpoint),
),
),
const SizedBox(height: 8),
Text(
@@ -224,6 +168,32 @@ class _FilesPanelState extends State<FilesPanel> {
);
},
);
/// Open and Download for one file; a folder has no menu (nothing to save).
Widget _menu(DirectoryEntry entry) => AppOverflowMenu<FileAction>(
label: 'File actions',
sheetTitle: entry.name,
onSelected: (_, action) => switch (action) {
FileAction.open => _open(entry),
FileAction.download => widget.viewer.download(
context,
endpoint: _endpoint,
entry: entry,
),
},
actions: const [
AppMenuAction(value: FileAction.open, label: 'Open'),
AppMenuAction(value: FileAction.download, label: 'Download'),
],
);
void _open(DirectoryEntry entry) {
if (widget.onOpen != null) {
widget.onOpen!(entry);
} else {
widget.viewer.open(context, endpoint: _endpoint, entry: entry);
}
}
}
class _FilesMessage extends StatelessWidget {
@@ -0,0 +1,72 @@
import '../../artifacts/domain/artifact_kind.dart';
/// The media type the files endpoint serves for [name], from its extension.
///
/// The server sets the real `Content-Type` on the wire; this is the client's
/// own classification for choosing a viewer, a thumbnail and a download type.
String fileContentType(String name) {
final dot = name.lastIndexOf('.');
final ext = dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
return _types[ext] ?? 'application/octet-stream';
}
const Map<String, String> _types = {
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'bmp': 'image/bmp',
'avif': 'image/avif',
'dart': 'text/plain',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
'mp4': 'video/mp4',
'webm': 'video/webm',
'mov': 'video/quicktime',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'm4a': 'audio/mp4',
'pdf': 'application/pdf',
'json': 'application/json',
'csv': 'text/csv',
'tsv': 'text/tab-separated-values',
'html': 'text/html',
'htm': 'text/html',
'md': 'text/markdown',
'markdown': 'text/markdown',
'txt': 'text/plain',
'log': 'text/plain',
'zip': 'application/zip',
'gz': 'application/gzip',
'tar': 'application/x-tar',
};
/// How the Files panel's viewer presents [name].
///
/// Unlike the artifact gallery, which keeps a turn's `session.html` export (and
/// its repairs) external-only, every HTML document in a working directory
/// previews inertly here: a file called `session.html` in a folder is just a
/// web page. Everything else follows the shared [artifactPreviewFormat] rule.
ArtifactPreviewFormat filePreviewFormat(String contentType, String name) {
final mime = contentType.split(';').first.trim().toLowerCase();
final lower = name.toLowerCase();
if (mime == 'image/svg+xml' ||
mime == 'text/html' ||
lower.endsWith('.html') ||
lower.endsWith('.htm')) {
return ArtifactPreviewFormat.html;
}
return artifactPreviewFormat(contentType, name);
}
/// Whether the Files panel opens [name] in the in-app viewer rather than the
/// unviewable sheet (PDFs open externally and are not previewable here).
bool isPreviewableFile(String name) =>
filePreviewFormat(fileContentType(name), name) !=
ArtifactPreviewFormat.none;
/// Whether [name] is an image the grid draws as a thumbnail.
bool isThumbnailFile(String name) =>
filePreviewFormat(fileContentType(name), name) ==
ArtifactPreviewFormat.image;
@@ -0,0 +1,95 @@
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import 'files_icons.dart';
import 'files_preview.dart';
import 'files_urls.dart';
/// The logical size of a grid thumbnail.
const double filesThumbnailSize = 56;
/// The largest decode scale a thumbnail is allowed, so a 4x display still
/// decodes a 56 dp tile to at most 224 px per side.
const double filesThumbnailMaxScale = 4;
/// The pixel edge a thumbnail decodes to: the tile size at the display's pixel
/// ratio, bounded. The shared [PaintingBinding.imageCache] then holds a few
/// hundred KiB at most per image instead of a full-size decode.
int filesThumbnailDecodeSize(double devicePixelRatio) =>
(filesThumbnailSize * devicePixelRatio.clamp(1, filesThumbnailMaxScale))
.round();
/// A grid tile's picture: an image file's own bytes from the files endpoint,
/// decoded at tile size, with the kind glyph while loading and when the fetch
/// or decode fails. Non-image files show the kind glyph.
class FileThumbnail extends StatefulWidget {
const FileThumbnail({super.key, required this.entry, required this.endpoint});
final DirectoryEntry entry;
final String endpoint;
@override
State<FileThumbnail> createState() => _FileThumbnailState();
}
class _FileThumbnailState extends State<FileThumbnail> {
ImageProvider? _provider;
String? _url;
int? _decode;
// Keep the shared image cache unchanged. Scrolled-out thumbnails release
// their decoded cache entry, bounding retention to the lazily built tiles.
@override
void dispose() {
_provider?.evict();
super.dispose();
}
@override
Widget build(BuildContext context) {
final entry = widget.entry;
final endpoint = widget.endpoint;
final icon = Icon(fileIcon(entry), size: 32);
if (entry.isDir || !isThumbnailFile(entry.name)) return icon;
final urls = resolveFileUrls(endpoint, entry.path);
if (urls == null) return icon;
final decode = filesThumbnailDecodeSize(
MediaQuery.devicePixelRatioOf(context),
);
if (_url != urls.view.toString() || _decode != decode) {
_provider?.evict();
_url = urls.view.toString();
_decode = decode;
_provider = ResizeImage.resizeIfNeeded(
decode,
decode,
NetworkImage(_url!),
);
}
final scheme = Theme.of(context).colorScheme;
final placeholder = Container(
width: filesThumbnailSize,
height: filesThumbnailSize,
alignment: Alignment.center,
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: icon,
);
return ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image(
image: _provider!,
width: filesThumbnailSize,
height: filesThumbnailSize,
fit: BoxFit.cover,
semanticLabel: entry.name,
loadingBuilder: (_, child, progress) =>
progress == null ? child : placeholder,
errorBuilder: (_, _, _) => icon,
),
);
}
}
@@ -0,0 +1,48 @@
import '../../../core/transport/server_url.dart';
class FileUrls {
const FileUrls({required this.view, required this.download});
/// `GET /files?path=...`: the file inline, with its content type and ranges.
final Uri view;
/// The same file with `download=1`: an attachment disposition.
final Uri download;
}
/// Resolves the files endpoint URLs for one working-directory path.
typedef FileUrlResolver =
FileUrls? Function(String configuredEndpoint, String path);
/// The resolver the Files panel uses for thumbnails, viewing and downloads.
///
/// Production keeps [fileUrls]. The full-app capture fixture
/// (`tool/search_selection_probe_entry.dart`, `?files=1`) swaps in a resolver
/// whose urls point to bundled capture files, because its static server has no `/files`
/// route; widget tests swap in one that ignores the fake gateway's missing
/// endpoint. Restore it after a test.
FileUrlResolver resolveFileUrls = fileUrls;
/// Builds the two same-origin HTTP URLs used by the files endpoint.
FileUrls? fileUrls(String configuredEndpoint, String path) {
final value = path;
if (value.trim().isEmpty) return null;
try {
final endpoint = ServerUrl.validate(configuredEndpoint);
final base = Uri.parse(
endpoint.httpUrl,
).replace(path: '/files', query: null, fragment: null);
Uri make({required bool download}) => base.replace(
queryParameters: <String, String>{
'path': value,
if (download) 'download': '1',
},
);
return FileUrls(
view: make(download: false),
download: make(download: true),
);
} on FormatException {
return null;
}
}
@@ -0,0 +1,158 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
import '../../artifacts/actions/artifact_transfer.dart';
import '../../artifacts/domain/artifact_groups.dart';
import '../../artifacts/domain/artifact_kind.dart';
import '../../artifacts/domain/artifact_record.dart';
import '../../artifacts/domain/gallery_navigation.dart';
import '../../artifacts/ui/artifact_external_open.dart';
import '../../artifacts/ui/artifact_viewer_fetch.dart';
import '../../artifacts/ui/artifact_viewer_page.dart';
import '../data/directory_listing.dart';
import 'files_download.dart';
import 'files_details.dart';
import 'files_preview.dart';
import 'files_urls.dart';
/// Opens and downloads one working-directory file from the Files panel.
///
/// Previewable files (images, video, audio, markdown, text, tables, HTML) open
/// in the shared artifact viewer over the inline `/files` url; a PDF goes to
/// the host's external handler; anything else gets a sheet with Download and
/// Open externally. The host capabilities are injectable so tests never fetch.
class FilesViewer {
const FilesViewer({
this.bridge = const ArtifactFileBridge(),
this.fetch = fetchArtifact,
this.openExternal = openArtifactExternally,
this.launch = launchFileUrl,
});
final ArtifactFileBridge bridge;
final ArtifactFetch fetch;
final ArtifactExternalOpen openExternal;
final FileUrlLauncher launch;
Future<void> open(
BuildContext context, {
required String endpoint,
required DirectoryEntry entry,
}) async {
final urls = resolveFileUrls(endpoint, entry.path);
if (urls == null) {
_showSheet(context, entry, null);
return;
}
final type = fileContentType(entry.name);
if (artifactKind(type, entry.name) == ArtifactKind.pdf) {
var opened = false;
try {
opened = await openExternal(urls.view);
} catch (_) {
/* show fallback actions below */
}
if (!opened && context.mounted) _showSheet(context, entry, urls);
return;
}
if (!isPreviewableFile(entry.name)) {
_showSheet(context, entry, urls);
return;
}
final artifact = ArtifactRecord(
name: entry.name,
url: urls.view.toString(),
contentType: type,
sizeBytes: entry.size ?? 0,
raw: const {},
);
final group = ArtifactGroup(
stageKey: 'Files',
visit: 1,
artifacts: [artifact],
);
final page = ArtifactViewerPage(
groups: [group],
selectedIdentity: artifactVisitIdentityOf(group, artifact),
configuredEndpoint: endpoint,
downloadUrl: urls.download.toString(),
previewFormat: filePreviewFormat,
fetch: fetch,
openExternal: openExternal,
fileBridge: bridge,
);
if (!context.mounted) return;
Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(builder: (_) => page),
);
}
/// Downloads [entry] straight from a row or tile menu and reports the
/// outcome (a snack bar, or an alert for a failure on a host without one);
/// without urls the sheet explains instead.
Future<void> download(
BuildContext context, {
required String endpoint,
required DirectoryEntry entry,
}) async {
final urls = resolveFileUrls(endpoint, entry.path);
if (urls == null) {
_showSheet(context, entry, null);
return;
}
final messenger = ScaffoldMessenger.maybeOf(context);
final result = await _download(entry, urls);
if (result.message.isEmpty) return;
if (messenger != null) {
messenger.showSnackBar(SnackBar(content: Text(result.message)));
return;
}
// A Cupertino host has no snack bar; a failure still has to be said.
if (result.state != ArtifactTransferState.failed || !context.mounted) {
return;
}
await showAdaptiveDialog<void>(
context: context,
builder: (dialog) => AlertDialog.adaptive(
title: Text(entry.name),
content: Text(result.message),
actions: [
if (usesCupertinoHost(dialog))
CupertinoDialogAction(
onPressed: () => Navigator.pop(dialog),
child: const Text('OK'),
)
else
TextButton(
onPressed: () => Navigator.pop(dialog),
child: const Text('OK'),
),
],
),
);
}
Future<ArtifactTransferResult> _download(
DirectoryEntry entry,
FileUrls urls,
) => downloadFile(
entry: entry,
urls: urls,
bridge: bridge,
fetch: fetch,
launch: launch,
);
void _showSheet(BuildContext context, DirectoryEntry entry, FileUrls? urls) =>
showFileDetails(
context,
entry: entry,
urls: urls,
download: urls == null ? null : () => _download(entry, urls),
openExternal: openExternal,
);
}