From c2dabbe187fd6be530ad8f55faa478bdb0bf869a Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Tue, 1 Dec 2026 00:59:04 +0800 Subject: [PATCH] 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 --- PLAN.md | 11 ++ README.md | 2 +- lib/screens/chat_screen.dart | 163 ++++-------------- lib/widgets/image_viewer.dart | 304 ++++++++++++++++++++++++++++++++++ pubspec.yaml | 2 +- test/image_viewer_test.dart | 86 ++++++++++ 6 files changed, 438 insertions(+), 130 deletions(-) create mode 100644 lib/widgets/image_viewer.dart create mode 100644 test/image_viewer_test.dart diff --git a/PLAN.md b/PLAN.md index 5f277cb..d1eea2d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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`) | 项 | 结果 | diff --git a/README.md b/README.md index a1c5890..8544318 100644 --- a/README.md +++ b/README.md @@ -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 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 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 diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index fcc7342..4252581 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -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 { if (m.files[i].isImage) i, ]; final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const []; + 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 { 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 { 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 { 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 { 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 { ), ), ), - 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 { Future _openPreview(_ImageRef ref) => _showImageDialog(ref.label, source: ref.source); - Future _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 _showImageDialog(String title, {required String source}) => + _showImages([ImageSlide(title, source)], 0); + + Future _showImages(List 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 _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 _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. diff --git a/lib/widgets/image_viewer.dart b/lib/widgets/image_viewer.dart new file mode 100644 index 0000000..b98481c --- /dev/null +++ b/lib/widgets/image_viewer.dart @@ -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 showImageViewer( + BuildContext context, { + required List images, + int initial = 0, + required String directory, + required Client client, +}) { + if (images.isEmpty) return Future.value(); + return Navigator.of(context).push(PageRouteBuilder( + 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 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 createState() => _ImageViewerPageState(); +} + +class _ImageViewerPageState extends State { + 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( + 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? 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 _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, + ), + ), + ), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 45d5019..aadfe01 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.6.4+604 +version: 0.6.5+605 environment: sdk: ^3.14.0 diff --git a/test/image_viewer_test.dart b/test/image_viewer_test.dart new file mode 100644 index 0000000..44f277c --- /dev/null +++ b/test/image_viewer_test.dart @@ -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 send(TransportRequest r) async => + throw UnimplementedError(); + + @override + Future webSocket(String path, + {String? rawQuery, Map 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 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(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); + }); +}