Merge branch 'ws-files-viewer'
# Conflicts: # app/tool/capture/README.md
This commit is contained in:
@@ -198,7 +198,16 @@ bool isMarkdownArtifact(String contentType, String name) {
|
||||
|
||||
/// How the viewer presents an artifact in-app, or [none] when it only offers
|
||||
/// Open/Download.
|
||||
enum ArtifactPreviewFormat { image, video, markdown, text, table, html, none }
|
||||
enum ArtifactPreviewFormat {
|
||||
image,
|
||||
video,
|
||||
audio,
|
||||
markdown,
|
||||
text,
|
||||
table,
|
||||
html,
|
||||
none,
|
||||
}
|
||||
|
||||
/// The one rule for in-app previews, shared by the gallery's paging and the
|
||||
/// viewer's fetch plan. Images and videos come from the content type; markdown
|
||||
@@ -210,6 +219,7 @@ ArtifactPreviewFormat artifactPreviewFormat(String contentType, String name) {
|
||||
if (isVideoContentType(contentType)) return ArtifactPreviewFormat.video;
|
||||
final mime = contentType.split(';').first.trim().toLowerCase();
|
||||
final ext = _extensionOf(name);
|
||||
if (mime.startsWith('audio/')) return ArtifactPreviewFormat.audio;
|
||||
if (mime == 'text/markdown' || ext == 'md' || ext == 'markdown') {
|
||||
return ArtifactPreviewFormat.markdown;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ enum ArtifactPreviewKind {
|
||||
/// fetched as bytes, never autoplayed), as the web viewer does.
|
||||
video,
|
||||
|
||||
/// A same-origin audio file, played with the shared media controller.
|
||||
audio,
|
||||
|
||||
/// A CSV/TSV drawn as a table from its fetched text.
|
||||
table,
|
||||
|
||||
@@ -68,13 +71,16 @@ const String artifactPreviewExternalUrl =
|
||||
|
||||
/// Classifies [artifact] against the configured server origin.
|
||||
///
|
||||
/// The format comes from [artifactPreviewFormat]: images are drawn from the
|
||||
/// The format comes from [format] (the shared [artifactPreviewFormat] unless a
|
||||
/// caller such as the chat Files panel has its own rule): images are drawn from the
|
||||
/// resolved bytes, a video plays from the resolved url, markdown goes to the
|
||||
/// injected builder and the text family is selectable monospace text.
|
||||
/// Everything else is explicitly unsupported rather than faked.
|
||||
ArtifactPreviewPlan planArtifactPreview({
|
||||
required ArtifactRecord artifact,
|
||||
required String configuredEndpoint,
|
||||
ArtifactPreviewFormat Function(String contentType, String name) format =
|
||||
artifactPreviewFormat,
|
||||
}) {
|
||||
if (!artifact.hasUrl) {
|
||||
return const ArtifactPreviewPlan(
|
||||
@@ -98,12 +104,10 @@ ArtifactPreviewPlan planArtifactPreview({
|
||||
message: artifactPreviewExternalUrl,
|
||||
);
|
||||
}
|
||||
final kind = switch (artifactPreviewFormat(
|
||||
artifact.contentType,
|
||||
artifact.name,
|
||||
)) {
|
||||
final kind = switch (format(artifact.contentType, artifact.name)) {
|
||||
ArtifactPreviewFormat.image => ArtifactPreviewKind.image,
|
||||
ArtifactPreviewFormat.video => ArtifactPreviewKind.video,
|
||||
ArtifactPreviewFormat.audio => ArtifactPreviewKind.audio,
|
||||
ArtifactPreviewFormat.markdown => ArtifactPreviewKind.markdown,
|
||||
ArtifactPreviewFormat.text => ArtifactPreviewKind.text,
|
||||
ArtifactPreviewFormat.table => ArtifactPreviewKind.table,
|
||||
|
||||
@@ -224,6 +224,8 @@ IconData artifactKindIcon(ArtifactRecord artifact, {required bool cupertino}) {
|
||||
cupertino ? CupertinoIcons.photo : Icons.image_outlined,
|
||||
ArtifactPreviewFormat.video =>
|
||||
cupertino ? CupertinoIcons.film : Icons.movie_outlined,
|
||||
ArtifactPreviewFormat.audio =>
|
||||
cupertino ? CupertinoIcons.music_note : Icons.audio_file_outlined,
|
||||
ArtifactPreviewFormat.markdown =>
|
||||
cupertino ? CupertinoIcons.doc_text : Icons.article_outlined,
|
||||
ArtifactPreviewFormat.text =>
|
||||
|
||||
@@ -4,7 +4,7 @@ import 'package:video_player/video_player.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
|
||||
/// Creates the player for one video url; tests inject a fake controller.
|
||||
/// Creates the player for one media url; tests inject a fake controller.
|
||||
typedef ArtifactVideoControllerFactory =
|
||||
VideoPlayerController Function(Uri uri);
|
||||
|
||||
@@ -13,6 +13,8 @@ VideoPlayerController defaultArtifactVideoController(Uri uri) =>
|
||||
|
||||
const String artifactVideoPlayLabel = 'Play video';
|
||||
const String artifactVideoPauseLabel = 'Pause video';
|
||||
const String artifactAudioPlayLabel = 'Play audio';
|
||||
const String artifactAudioPauseLabel = 'Pause audio';
|
||||
const String artifactVideoError = 'The video could not be played.';
|
||||
|
||||
/// Plays one recorded same-origin video in the viewer, as the web viewer's
|
||||
@@ -22,10 +24,12 @@ class ArtifactVideoPlayer extends StatefulWidget {
|
||||
super.key,
|
||||
required this.uri,
|
||||
this.controllerFactory = defaultArtifactVideoController,
|
||||
this.audio = false,
|
||||
});
|
||||
|
||||
final Uri uri;
|
||||
final ArtifactVideoControllerFactory controllerFactory;
|
||||
final bool audio;
|
||||
|
||||
@override
|
||||
State<ArtifactVideoPlayer> createState() => _ArtifactVideoPlayerState();
|
||||
@@ -95,23 +99,29 @@ class _ArtifactVideoPlayerState extends State<ArtifactVideoPlayer> {
|
||||
);
|
||||
}
|
||||
final label = value.isPlaying
|
||||
? artifactVideoPauseLabel
|
||||
: artifactVideoPlayLabel;
|
||||
? (widget.audio ? artifactAudioPauseLabel : artifactVideoPauseLabel)
|
||||
: (widget.audio ? artifactAudioPlayLabel : artifactVideoPlayLabel);
|
||||
final icon = cupertino
|
||||
? (value.isPlaying
|
||||
? CupertinoIcons.pause_fill
|
||||
: CupertinoIcons.play_fill)
|
||||
: (value.isPlaying ? Icons.pause : Icons.play_arrow);
|
||||
return Column(
|
||||
key: const Key('artifact-video'),
|
||||
key: Key(widget.audio ? 'artifact-audio' : 'artifact-video'),
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: AspectRatio(
|
||||
aspectRatio: value.aspectRatio,
|
||||
child: VideoPlayer(_controller),
|
||||
if (!widget.audio)
|
||||
Flexible(
|
||||
child: AspectRatio(
|
||||
aspectRatio: value.aspectRatio,
|
||||
child: VideoPlayer(_controller),
|
||||
),
|
||||
)
|
||||
else
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Icon(Icons.audio_file_outlined, size: 64),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: Row(
|
||||
|
||||
@@ -30,6 +30,7 @@ class ArtifactViewerBar extends StatelessWidget {
|
||||
required this.count,
|
||||
required this.fetch,
|
||||
required this.fileBridge,
|
||||
this.downloadResolved,
|
||||
required this.onOpen,
|
||||
required this.onCopy,
|
||||
required this.onPrevious,
|
||||
@@ -44,6 +45,7 @@ class ArtifactViewerBar extends StatelessWidget {
|
||||
final int count;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
final ResolvedArtifactUrl? downloadResolved;
|
||||
final VoidCallback onOpen;
|
||||
final VoidCallback onCopy;
|
||||
final VoidCallback onPrevious;
|
||||
@@ -123,7 +125,7 @@ class ArtifactViewerBar extends StatelessWidget {
|
||||
'${page.group.visit}\u0000${page.artifact.url}',
|
||||
),
|
||||
artifact: page.artifact,
|
||||
resolved: resolved,
|
||||
resolved: downloadResolved ?? resolved,
|
||||
fetch: fetch,
|
||||
bridge: fileBridge,
|
||||
compact: true,
|
||||
|
||||
@@ -8,6 +8,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart';
|
||||
import '../actions/artifact_file_actions.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../domain/gallery_navigation.dart';
|
||||
import 'artifact_html_view.dart';
|
||||
import 'artifact_viewer_bar.dart';
|
||||
@@ -39,6 +40,7 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
required this.onCopy,
|
||||
this.fetch = fetchArtifact,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
this.downloadResolved,
|
||||
this.text,
|
||||
this.bytes,
|
||||
this.error,
|
||||
@@ -73,6 +75,7 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
final VoidCallback onCopy;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
final ResolvedArtifactUrl? downloadResolved;
|
||||
final String? text;
|
||||
final Uint8List? bytes;
|
||||
final String? error;
|
||||
@@ -138,6 +141,7 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
count: count,
|
||||
fetch: fetch,
|
||||
fileBridge: fileBridge,
|
||||
downloadResolved: downloadResolved,
|
||||
onOpen: onOpen,
|
||||
onCopy: onCopy,
|
||||
onPrevious: onPrevious,
|
||||
|
||||
@@ -111,6 +111,14 @@ class ArtifactPreviewBody extends StatelessWidget {
|
||||
controllerFactory: videoControllerFactory,
|
||||
),
|
||||
);
|
||||
case ArtifactPreviewKind.audio:
|
||||
return Center(
|
||||
child: ArtifactVideoPlayer(
|
||||
uri: plan.resolved!.uri,
|
||||
controllerFactory: videoControllerFactory,
|
||||
audio: true,
|
||||
),
|
||||
);
|
||||
case ArtifactPreviewKind.unsupported:
|
||||
case ArtifactPreviewKind.unavailable:
|
||||
return const SizedBox.shrink();
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../../../ui/input/arrow_key_pager.dart';
|
||||
import 'artifact_selection_facts.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import '../domain/artifact_kind.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_preview_failure.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
@@ -43,6 +44,8 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
required this.selectedIdentity,
|
||||
this.includeExternalDocuments = false,
|
||||
this.configuredEndpoint = '',
|
||||
this.downloadUrl,
|
||||
this.previewFormat = artifactPreviewFormat,
|
||||
this.fetch = fetchArtifact,
|
||||
this.markdownBuilder = defaultArtifactMarkdown,
|
||||
this.openExternal = openArtifactExternally,
|
||||
@@ -60,6 +63,11 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
final bool includeExternalDocuments;
|
||||
|
||||
final String configuredEndpoint;
|
||||
final String? downloadUrl;
|
||||
|
||||
/// The preview rule; the Files panel passes its own (every HTML previews).
|
||||
final ArtifactPreviewFormat Function(String contentType, String name)
|
||||
previewFormat;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactMarkdownBuilder markdownBuilder;
|
||||
final ArtifactExternalOpen openExternal;
|
||||
@@ -110,6 +118,7 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage>
|
||||
return planArtifactPreview(
|
||||
artifact: page.artifact,
|
||||
configuredEndpoint: widget.configuredEndpoint,
|
||||
format: widget.previewFormat,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -224,6 +233,9 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage>
|
||||
Widget buildFrame(BuildContext context, {required bool fullscreen}) {
|
||||
final page = _page;
|
||||
final plan = _plan;
|
||||
final downloadResolved = widget.downloadUrl == null
|
||||
? null
|
||||
: resolveArtifactUrl(widget.configuredEndpoint, widget.downloadUrl!);
|
||||
final title = page == null
|
||||
? artifactViewerTitle
|
||||
: artifactDisplayName(page.artifact);
|
||||
@@ -266,6 +278,7 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage>
|
||||
status: _status,
|
||||
fetch: widget.fetch,
|
||||
fileBridge: widget.fileBridge,
|
||||
downloadResolved: downloadResolved,
|
||||
onPrevious: () => _step(-1),
|
||||
onNext: () => _step(1),
|
||||
// A failure is never cached, so loading again fetches afresh.
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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)}';
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user