feat: a full-screen, zoomable picture viewer

- conversation pictures (user attachments, generated and tool-read images)
  no longer open in a small dialog: a full-screen black viewer shows the
  title and page number, pinch zooms to 8x, double-tap toggles 2.5x around
  the touched point, and a zoomed picture pans by dragging
- multiple pictures in the same message / tool run are one gallery: swipe
  while at 1x, but once zoomed the drag pans and paging is disabled until
  the picture returns to 1x
- mirrors dsh-Go's ImageViewerPage/ImagePager/ZoomableImage behaviour
- version 0.6.5+605; tests cover zoom, pan and paging
This commit is contained in:
blumia committed 2026-12-01 00:59:04 +08:00
1 parent 9ae1e9b97a
commit c2dabbe187
6 files changed
+438 -130

No files matched your search

+35 -128
View File
@@ -15,6 +15,7 @@ import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/composer_box.dart';
import '../widgets/diff_view.dart';
import '../widgets/image_viewer.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart';
import '../widgets/shell_jobs.dart';
@@ -729,6 +730,15 @@ class _ChatScreenState extends State<ChatScreen> {
if (m.files[i].isImage) i,
];
final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const <String>[];
final attachmentSlides = [
for (final i in attachedImages)
ImageSlide(
m.files[i].name.isEmpty ? tr('Image') : m.files[i].name,
'data:${m.files[i].mime};base64,${m.files[i].data}'),
];
final localSlides = [
for (final path in localImages) ImageSlide(path.split('/').last, path),
];
final otherFiles = m.files.where((f) => !f.isImage).toList();
return Align(
alignment: Alignment.centerRight,
@@ -748,25 +758,25 @@ class _ChatScreenState extends State<ChatScreen> {
child: Text(m.text,
style: TextStyle(color: theme.colorScheme.onPrimary)),
),
for (final i in attachedImages)
for (var pos = 0; pos < attachedImages.length; pos++)
Padding(
padding: const EdgeInsets.only(top: 6),
child: GestureDetector(
onTap: () => _previewAttachment(m.files[i]),
onTap: () => _showImages(attachmentSlides, pos),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: _attachmentImage(id, i, m.files[i]),
child: _attachmentImage(id, attachedImages[pos], m.files[attachedImages[pos]]),
),
),
),
for (final p in localImages)
for (var pos = 0; pos < localImages.length; pos++)
Padding(
padding: const EdgeInsets.only(top: 4),
child: GestureDetector(
onTap: () => _openPreview(_ImageRef(p, p.split('/').last)),
onTap: () => _showImages(localSlides, pos),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(File(p),
child: Image.file(File(localImages[pos]),
width: 200, height: 150, fit: BoxFit.cover),
),
),
@@ -808,13 +818,6 @@ class _ChatScreenState extends State<ChatScreen> {
return Image.memory(bytes, width: 200, height: 150, fit: BoxFit.cover);
}
void _previewAttachment(FileAttachment f) {
_showImageDialog(
f.name.isEmpty ? 'Image' : f.name,
source: 'data:${f.mime};base64,${f.data}',
);
}
Widget _userActions(String id) {
final m = chat.byId[id]!;
final stamp = m.created > 0
@@ -908,6 +911,7 @@ class _ChatScreenState extends State<ChatScreen> {
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final paths = generatedImagePaths(m.content[part]);
if (paths.isEmpty) return const SizedBox.shrink();
final slides = [for (final path in paths) ImageSlide(pathLeaf(path), path)];
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: Column(
@@ -920,8 +924,7 @@ class _ChatScreenState extends State<ChatScreen> {
source: paths[i],
directory: chat.dir,
client: widget.app.client!,
onTap: () =>
_showImageDialog(pathLeaf(paths[i]), source: paths[i]),
onTap: () => _showImages(slides, i),
),
),
],
@@ -1116,17 +1119,19 @@ class _ChatScreenState extends State<ChatScreen> {
),
),
),
for (final ref in refs)
for (var i = 0; i < refs.length; i++)
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 2),
child: InkWell(
onTap: () => _openPreview(ref),
onTap: () => _showImages(
[for (final ref in refs) ImageSlide(ref.label, ref.source)],
i),
child: Row(
children: [
const AppText('🖼', style: TextStyle(fontSize: 12)),
const SizedBox(width: 6),
Flexible(
child: Text(ref.label,
child: Text(refs[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
@@ -2363,15 +2368,18 @@ class _ChatScreenState extends State<ChatScreen> {
Future<void> _openPreview(_ImageRef ref) =>
_showImageDialog(ref.label, source: ref.source);
Future<void> _showImageDialog(String title, {required String source}) async {
await showDialog(
context: context,
builder: (_) => _ImagePreviewDialog(
title: title,
source: source,
directory: chat.dir,
client: widget.app.client!,
),
Future<void> _showImageDialog(String title, {required String source}) =>
_showImages([ImageSlide(title, source)], 0);
Future<void> _showImages(List<ImageSlide> images, int initial) async {
final client = widget.app.client;
if (client == null || images.isEmpty) return;
await showImageViewer(
context,
images: images,
initial: initial,
directory: chat.dir,
client: client,
);
}
@@ -2754,107 +2762,6 @@ class _GeneratedImageState extends State<_GeneratedImage> {
/// A full-screen-ish image preview that loads itself: the dialog is created
/// first, so the image and its spinner must live in a StatefulWidget.
class _ImagePreviewDialog extends StatefulWidget {
final String title;
final String source;
final String directory;
final Client client;
const _ImagePreviewDialog({
required this.title,
required this.source,
required this.directory,
required this.client,
});
@override
State<_ImagePreviewDialog> createState() => _ImagePreviewDialogState();
}
class _ImagePreviewDialogState extends State<_ImagePreviewDialog> {
Uint8List? _bytes;
Object? _error;
bool _loading = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
// Decoded straight from memory: no temp file, no platform plugin.
final bytes = await _fetch();
if (mounted) {
setState(() {
_bytes = bytes;
_loading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e;
_loading = false;
});
}
}
}
Future<Uint8List> _fetch() =>
_imageBytesFor(widget.client, widget.source, widget.directory);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
Widget body;
if (_loading) {
body = const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
);
} else if (_bytes != null) {
body = Flexible(child: Image.memory(_bytes!, fit: BoxFit.contain));
} else {
body = Padding(
padding: const EdgeInsets.all(24),
child: SelectableText(trArgs('Cannot preview: {0}', ['$_error']),
style: TextStyle(color: theme.colorScheme.error)),
);
}
return Dialog(
insetPadding: const EdgeInsets.all(12),
child: ConstrainedBox(
constraints:
BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.9),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 4, 0),
child: Row(
children: [
Expanded(
child: Text(widget.title,
maxLines: 2, overflow: TextOverflow.ellipsis),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: tr('Close'),
onPressed: () => Navigator.pop(context),
),
],
),
),
body,
const SizedBox(height: 8),
],
),
),
);
}
}
/// The native form/question card: every visible field at once, one answer.
/// Field visibility follows the form's `when` clauses, and required fields
/// must be filled before it can be sent.
+304
View File
@@ -0,0 +1,304 @@
// Full-screen picture viewer, modelled on dsh-Go's image gallery: black
// background, one picture per page, pinch to 8x, double-tap to 2.5x around the
// touched point, drag to pan. Paging is disabled while a picture is zoomed so
// a drag pans the picture instead of swiping to the next one.
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../l10n.dart';
/// One picture in the viewer. [source] is a `data:` URL or a file path the
/// client can read with the session's directory.
class ImageSlide {
final String title;
final String source;
const ImageSlide(this.title, this.source);
}
/// Opens [images] at [initial] as a full-screen gallery.
Future<void> showImageViewer(
BuildContext context, {
required List<ImageSlide> images,
int initial = 0,
required String directory,
required Client client,
}) {
if (images.isEmpty) return Future.value();
return Navigator.of(context).push(PageRouteBuilder<void>(
opaque: true,
transitionDuration: const Duration(milliseconds: 180),
reverseTransitionDuration: const Duration(milliseconds: 140),
pageBuilder: (_, __, ___) => ImageViewerPage(
images: images,
initial: initial.clamp(0, images.length - 1),
directory: directory,
client: client,
),
transitionsBuilder: (_, animation, __, child) =>
FadeTransition(opacity: animation, child: child),
));
}
class ImageViewerPage extends StatefulWidget {
final List<ImageSlide> images;
final int initial;
final String directory;
final Client client;
const ImageViewerPage({
super.key,
required this.images,
this.initial = 0,
required this.directory,
required this.client,
});
@override
State<ImageViewerPage> createState() => _ImageViewerPageState();
}
class _ImageViewerPageState extends State<ImageViewerPage> {
late int _index = widget.initial;
late final PageController _pages = PageController(initialPage: _index);
bool _zoomed = false;
@override
void dispose() {
_pages.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final padding = MediaQuery.paddingOf(context);
final image = widget.images[_index];
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: Scaffold(
backgroundColor: Colors.black,
body: Stack(
children: [
Positioned.fill(
child: PageView.builder(
controller: _pages,
physics: _zoomed
? const NeverScrollableScrollPhysics()
: const PageScrollPhysics(),
itemCount: widget.images.length,
onPageChanged: (index) => setState(() {
_index = index;
_zoomed = false;
}),
itemBuilder: (context, index) => _ZoomableImage(
// A page that leaves the viewport forgets its zoom.
key: ValueKey((index, index == _index)),
slide: widget.images[index],
directory: widget.directory,
client: widget.client,
onZoomChanged: (zoomed) {
if (index == _index && zoomed != _zoomed) {
setState(() => _zoomed = zoomed);
}
},
),
),
),
// A dark scrim keeps the white title and keys readable over a
// bright picture.
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: Container(
height: padding.top + 64,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.black54, Colors.transparent],
),
),
),
),
),
Positioned(
top: padding.top + 4,
left: 8,
right: 8,
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back),
color: Colors.white,
tooltip: tr('Back'),
onPressed: () => Navigator.of(context).maybePop(),
),
const SizedBox(width: 4),
Expanded(
child: Text(
image.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500),
),
),
if (widget.images.length > 1)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(
'${_index + 1} / ${widget.images.length}',
style: const TextStyle(
color: Colors.white70, fontSize: 13),
),
),
],
),
),
],
),
),
);
}
}
class _ZoomableImage extends StatefulWidget {
final ImageSlide slide;
final String directory;
final Client client;
final ValueChanged<bool>? onZoomChanged;
const _ZoomableImage({
super.key,
required this.slide,
required this.directory,
required this.client,
this.onZoomChanged,
});
@override
State<_ZoomableImage> createState() => _ZoomableImageState();
}
class _ZoomableImageState extends State<_ZoomableImage> {
static const double _maxScale = 8;
static const double _doubleTapScale = 2.5;
final TransformationController _transform = TransformationController();
Uint8List? _bytes;
Object? _error;
bool _loading = true;
bool _zoomed = false;
Offset _doubleTap = Offset.zero;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_transform.dispose();
super.dispose();
}
Future<void> _load() async {
try {
final source = widget.slide.source;
final bytes = source.startsWith('data:')
? _dataUrlBytes(source)
: Uint8List.fromList(
await widget.client.rawFile(source, directory: widget.directory));
if (!mounted) return;
setState(() {
_bytes = bytes;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e;
_loading = false;
});
}
}
static Uint8List _dataUrlBytes(String source) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception(tr('Invalid data URL'));
if (!source.substring(5, comma).contains('base64')) {
throw Exception(tr('Unsupported data URL'));
}
return base64Decode(source.substring(comma + 1));
}
void _notifyZoom() {
final zoomed = _transform.value.getMaxScaleOnAxis() > 1.01;
if (zoomed == _zoomed) return;
setState(() => _zoomed = zoomed);
widget.onZoomChanged?.call(zoomed);
}
void _toggleZoom() {
final scale = _transform.value.getMaxScaleOnAxis();
if (scale > 1.01) {
_transform.value = Matrix4.identity();
} else {
final p = _doubleTap;
_transform.value = Matrix4.identity()
..translate(p.dx, p.dy)
..scale(_doubleTapScale)
..translate(-p.dx, -p.dy);
}
_notifyZoom();
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Center(
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white));
}
if (_bytes == null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Text(
trArgs('Cannot preview: {0}', ['$_error']),
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70),
),
),
);
}
return GestureDetector(
onDoubleTapDown: (details) => _doubleTap = details.localPosition,
onDoubleTap: _toggleZoom,
child: InteractiveViewer(
transformationController: _transform,
minScale: 1,
maxScale: _maxScale,
// One finger swipes to the next picture until a pinch zooms in; from
// then on it pans the zoomed picture instead.
panEnabled: _zoomed,
scaleEnabled: true,
onInteractionEnd: (_) => _notifyZoom(),
child: SizedBox.expand(
child: Image.memory(
_bytes!,
fit: BoxFit.contain,
gaplessPlayback: true,
),
),
),
);
}
}