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

+11
View File
@@ -5,6 +5,17 @@
--- ---
## 0.6.5 会话图片全屏查看(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 查看器 | 会话内图片(用户附件、工具生成/读取的图片、生成图片)从对话框改为全屏查看:黑底、返回 + 标题 + 页码;双指缩放最大 8 倍,双击在 2.5 倍与原始大小间切换,缩放后可单指拖动查看局部;多张图片可左右滑动 |
| 翻页与拖动 | 未缩放时单指左右滑动翻页;一旦放大,单指拖动用于平移图片,翻页被禁用,缩回原始大小后恢复翻页 |
| 参考 | dsh-Go 的图片查看器就是这种相册式行为(`ImageViewerPage` + `ImagePager` + `ZoomableImage`:双指 8 倍、双击 2.5 倍、缩放时禁用翻页),本次按同样的交互实现 |
| 版本 | **0.6.5(code 605)** |
---
## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`) ## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -6,7 +6,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.6.4 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.6.5 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live link is pasted or scanned with the camera), session list with search and live
+35 -128
View File
@@ -15,6 +15,7 @@ import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart'; import '../widgets/markdown_view.dart';
import '../widgets/composer_box.dart'; import '../widgets/composer_box.dart';
import '../widgets/diff_view.dart'; import '../widgets/diff_view.dart';
import '../widgets/image_viewer.dart';
import '../widgets/pet_sprite.dart'; import '../widgets/pet_sprite.dart';
import '../widgets/model_controls.dart'; import '../widgets/model_controls.dart';
import '../widgets/shell_jobs.dart'; import '../widgets/shell_jobs.dart';
@@ -729,6 +730,15 @@ class _ChatScreenState extends State<ChatScreen> {
if (m.files[i].isImage) i, if (m.files[i].isImage) i,
]; ];
final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const <String>[]; 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(); final otherFiles = m.files.where((f) => !f.isImage).toList();
return Align( return Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@@ -748,25 +758,25 @@ class _ChatScreenState extends State<ChatScreen> {
child: Text(m.text, child: Text(m.text,
style: TextStyle(color: theme.colorScheme.onPrimary)), style: TextStyle(color: theme.colorScheme.onPrimary)),
), ),
for (final i in attachedImages) for (var pos = 0; pos < attachedImages.length; pos++)
Padding( Padding(
padding: const EdgeInsets.only(top: 6), padding: const EdgeInsets.only(top: 6),
child: GestureDetector( child: GestureDetector(
onTap: () => _previewAttachment(m.files[i]), onTap: () => _showImages(attachmentSlides, pos),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(10), 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(
padding: const EdgeInsets.only(top: 4), padding: const EdgeInsets.only(top: 4),
child: GestureDetector( child: GestureDetector(
onTap: () => _openPreview(_ImageRef(p, p.split('/').last)), onTap: () => _showImages(localSlides, pos),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Image.file(File(p), child: Image.file(File(localImages[pos]),
width: 200, height: 150, fit: BoxFit.cover), 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); 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) { Widget _userActions(String id) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
final stamp = m.created > 0 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(); if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final paths = generatedImagePaths(m.content[part]); final paths = generatedImagePaths(m.content[part]);
if (paths.isEmpty) return const SizedBox.shrink(); if (paths.isEmpty) return const SizedBox.shrink();
final slides = [for (final path in paths) ImageSlide(pathLeaf(path), path)];
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 6), padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: Column( child: Column(
@@ -920,8 +924,7 @@ class _ChatScreenState extends State<ChatScreen> {
source: paths[i], source: paths[i],
directory: chat.dir, directory: chat.dir,
client: widget.app.client!, client: widget.app.client!,
onTap: () => onTap: () => _showImages(slides, i),
_showImageDialog(pathLeaf(paths[i]), source: paths[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(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 2), padding: const EdgeInsets.fromLTRB(10, 0, 10, 2),
child: InkWell( child: InkWell(
onTap: () => _openPreview(ref), onTap: () => _showImages(
[for (final ref in refs) ImageSlide(ref.label, ref.source)],
i),
child: Row( child: Row(
children: [ children: [
const AppText('🖼', style: TextStyle(fontSize: 12)), const AppText('🖼', style: TextStyle(fontSize: 12)),
const SizedBox(width: 6), const SizedBox(width: 6),
Flexible( Flexible(
child: Text(ref.label, child: Text(refs[i].label,
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
@@ -2363,15 +2368,18 @@ class _ChatScreenState extends State<ChatScreen> {
Future<void> _openPreview(_ImageRef ref) => Future<void> _openPreview(_ImageRef ref) =>
_showImageDialog(ref.label, source: ref.source); _showImageDialog(ref.label, source: ref.source);
Future<void> _showImageDialog(String title, {required String source}) async { Future<void> _showImageDialog(String title, {required String source}) =>
await showDialog( _showImages([ImageSlide(title, source)], 0);
context: context,
builder: (_) => _ImagePreviewDialog( Future<void> _showImages(List<ImageSlide> images, int initial) async {
title: title, final client = widget.app.client;
source: source, if (client == null || images.isEmpty) return;
directory: chat.dir, await showImageViewer(
client: widget.app.client!, 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 /// 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. /// 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. /// The native form/question card: every visible field at once, one answer.
/// Field visibility follows the form's `when` clauses, and required fields /// Field visibility follows the form's `when` clauses, and required fields
/// must be filled before it can be sent. /// 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,
),
),
),
);
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.6.4+604 version: 0.6.5+605
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+86
View File
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/widgets/image_viewer.dart';
class _NoopTransport implements Transport {
@override
Future<TransportResponse> send(TransportRequest r) async =>
throw UnimplementedError();
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
// A 1x1 transparent PNG.
const _png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
void main() {
final client = Client(Uri.parse('http://test'), transport: _NoopTransport());
Future<void> pumpViewer(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: ImageViewerPage(
images: const [
ImageSlide('One', 'data:image/png;base64,$_png'),
ImageSlide('Two', 'data:image/png;base64,$_png'),
],
directory: '/home/me',
client: client,
),
));
await tester.pumpAndSettle();
await tester.pump(const Duration(milliseconds: 200));
}
testWidgets('a picture opens full screen and can be zoomed and panned',
(tester) async {
await pumpViewer(tester);
expect(find.text('One'), findsOneWidget);
expect(find.text('1 / 2'), findsOneWidget);
final viewer = find.byType(InteractiveViewer);
expect(viewer, findsOneWidget);
final center = tester.getCenter(viewer);
final left = await tester.startGesture(center - const Offset(20, 0));
final right = await tester.startGesture(center + const Offset(20, 0));
await left.moveTo(center - const Offset(80, 0));
await right.moveTo(center + const Offset(80, 0));
await tester.pump();
await left.up();
await right.up();
await tester.pumpAndSettle();
final zoomed = tester.widget<InteractiveViewer>(viewer);
final controller = zoomed.transformationController!;
expect(controller.value.getMaxScaleOnAxis(), greaterThan(1.0));
// Once zoomed, a one-finger drag pans the picture instead of paging.
final before = controller.value.getTranslation();
await tester.drag(viewer, const Offset(30, 12));
await tester.pumpAndSettle();
final after = controller.value.getTranslation();
expect(after.x, isNot(before.x));
});
testWidgets('a swipe moves to the next picture while not zoomed',
(tester) async {
await pumpViewer(tester);
await tester.drag(find.byType(InteractiveViewer), const Offset(-600, 0));
await tester.pumpAndSettle();
expect(find.text('Two'), findsOneWidget);
expect(find.text('2 / 2'), findsOneWidget);
});
}