From fedc4dd79c96be45f2b2078280d64dabe9997a1b Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Tue, 1 Dec 2026 11:53:54 +0800 Subject: [PATCH] feat: save/share in the picture viewer, and a tap hides its chrome - the viewer's top bar gains Save to Photos and Share on Android: saving writes through MediaStore into Pictures/Chamber Go (no permission on Android 10+, a runtime request on older versions), sharing hands a cache file to the system chooser through a FileProvider; both are a small native channel, not another plugin - dsh-Go keeps its title bar always visible; here a single tap hides the title, keys and page indicator and the next tap brings them back, so they do not cover the picture. Double-tap still zooms, swiping still pages at 1x, dragging pans while zoomed - version 0.6.6+606; the viewer test now covers the platform calls, chrome toggle, zoom, pan and paging --- PLAN.md | 10 + README.md | 2 +- android/app/build.gradle.kts | 4 + android/app/src/main/AndroidManifest.xml | 14 + .../openchamber/flutter/MainActivity.kt | 177 +++++++++++++ android/app/src/main/res/xml/file_paths.xml | 5 + lib/l10n/zh.dart | 8 + lib/widgets/image_viewer.dart | 240 +++++++++++++++--- pubspec.yaml | 2 +- test/image_viewer_test.dart | 54 +++- 10 files changed, 471 insertions(+), 45 deletions(-) create mode 100644 android/app/src/main/res/xml/file_paths.xml diff --git a/PLAN.md b/PLAN.md index d1eea2d..7db00fa 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,16 @@ --- +## 0.6.6 图片查看器:保存/分享与隐藏顶栏(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 保存/分享 | 查看器右上角新增保存到相册、分享(Android):保存通过 MediaStore 写入 `Pictures/Chamber Go`(Android 10+ 无需权限,旧版本按需申请存储权限),分享用 FileProvider 生成临时文件并打开系统分享面板;非 Android 平台不显示这两个按钮 | +| 顶栏 | dsh-Go 的查看器顶栏(返回、文件名)是**始终显示**的;按你的建议,我们改为单指点击图片切换顶栏和底部页码的显示/隐藏,再点一次恢复,避免标题和按钮挡住图片;双击仍用于 2.5 倍缩放,未放大时左右滑动翻页,放大后单指拖动平移 | +| 版本 | **0.6.6(code 606)** | + +--- + ## 0.6.5 会话图片全屏查看(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 8544318..aa04caa 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.5 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.6.6 — 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/android/app/build.gradle.kts b/android/app/build.gradle.kts index 41832f4..624b20a 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -42,6 +42,10 @@ android { } } +dependencies { + implementation("androidx.core:core-ktx:1.13.1") +} + kotlin { compilerOptions { jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index dc09398..fe9eab4 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -2,6 +2,10 @@ xmlns:tools="http://schemas.android.com/tools"> + + @@ -33,6 +37,16 @@ + + + + result.notImplemented() } } + // Saving a conversation picture to the gallery and sharing it: both + // need Android APIs (MediaStore, FileProvider) that a Dart package + // would pull in another native dependency for. + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/media") + .setMethodCallHandler { call, result -> + when (call.method) { + "saveImage" -> { + val bytes = call.argument("bytes") + val name = call.argument("name") + val mime = call.argument("mime") ?: "image/png" + if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) { + result.error("bad_args", "Missing image data", null) + return@setMethodCallHandler + } + saveImage(bytes, name, mime, result) + } + "shareImage" -> { + val bytes = call.argument("bytes") + val name = call.argument("name") + val mime = call.argument("mime") ?: "image/png" + if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) { + result.error("bad_args", "Missing image data", null) + return@setMethodCallHandler + } + shareImage(bytes, name, mime, result) + } + else -> result.notImplemented() + } + } + } + + private fun saveImage( + bytes: ByteArray, + name: String, + mime: String, + result: MethodChannel.Result, + ) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && + checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != + PackageManager.PERMISSION_GRANTED + ) { + if (pendingSave != null) { + result.error("busy", "Another picture is being saved", null) + return + } + pendingSave = PendingSave(bytes, name, mime, result) + requestPermissions( + arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), + REQUEST_SAVE, + ) + return + } + writeImage(bytes, name, mime, result) + } + + private fun writeImage( + bytes: ByteArray, + name: String, + mime: String, + result: MethodChannel.Result, + ) { + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val values = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, name) + put(MediaStore.Images.Media.MIME_TYPE, mime) + put( + MediaStore.Images.Media.RELATIVE_PATH, + "${Environment.DIRECTORY_PICTURES}/Chamber Go", + ) + put(MediaStore.Images.Media.IS_PENDING, 1) + } + val collection = MediaStore.Images.Media.getContentUri( + MediaStore.VOLUME_EXTERNAL_PRIMARY, + ) + val uri = contentResolver.insert(collection, values) + ?: throw IllegalStateException("Could not create the picture") + contentResolver.openOutputStream(uri)?.use { it.write(bytes) } + ?: throw IllegalStateException("Could not open the picture") + values.clear() + values.put(MediaStore.Images.Media.IS_PENDING, 0) + contentResolver.update(uri, values, null, null) + } else { + @Suppress("DEPRECATION") + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + ?: throw IllegalStateException("Could not decode the picture") + @Suppress("DEPRECATION") + val uri = MediaStore.Images.Media.insertImage( + contentResolver, bitmap, name, null, + ) ?: throw IllegalStateException("Could not save the picture") + bitmap.recycle() + @Suppress("DEPRECATION") + MediaScannerConnection.scanFile( + this, + arrayOf(Uri.parse(uri).path ?: ""), + arrayOf(mime), + null, + ) + } + result.success(true) + } catch (e: Exception) { + result.error("save_failed", e.message ?: "Could not save the picture", null) + } + } + + private fun shareImage( + bytes: ByteArray, + name: String, + mime: String, + result: MethodChannel.Result, + ) { + try { + val directory = File(cacheDir, "shared_images").apply { mkdirs() } + val file = File(directory, name) + file.writeBytes(bytes) + val uri = FileProvider.getUriForFile( + this, "$packageName.fileprovider", file, + ) + val intent = Intent(Intent.ACTION_SEND).apply { + type = mime + putExtra(Intent.EXTRA_STREAM, uri) + clipData = ClipData.newRawUri("image", uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + startActivity(Intent.createChooser(intent, "Share image")) + result.success(true) + } catch (e: Exception) { + result.error("share_failed", e.message ?: "Could not share the picture", null) + } + } + + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray, + ) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode != REQUEST_SAVE) return + val pending = pendingSave ?: return + pendingSave = null + if (grantResults.isNotEmpty() && + grantResults[0] == PackageManager.PERMISSION_GRANTED + ) { + writeImage(pending.bytes, pending.name, pending.mime, pending.result) + } else { + pending.result.error( + "permission", + "Storage permission is required to save the picture", + null, + ) + } + } + + private companion object { + const val REQUEST_SAVE = 701 } } diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..bd6e667 --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/lib/l10n/zh.dart b/lib/l10n/zh.dart index 3a8a632..a8c3422 100644 --- a/lib/l10n/zh.dart +++ b/lib/l10n/zh.dart @@ -623,4 +623,12 @@ const Map chineseStrings = { 'No matching projects': '没有匹配的项目', 'Browse archived sessions and restore them': '浏览已归档的会话并恢复', 'Session restored': '会话已恢复', + + // image viewer + 'Share': '分享', + 'Share failed': '分享失败', + 'Save to Photos': '保存到相册', + 'Saved to Photos': '已保存到相册', + "Couldn't save the picture": '无法保存图片', + 'Storage permission is required to save the picture': '保存图片需要存储权限', }; diff --git a/lib/widgets/image_viewer.dart b/lib/widgets/image_viewer.dart index b98481c..488de81 100644 --- a/lib/widgets/image_viewer.dart +++ b/lib/widgets/image_viewer.dart @@ -1,8 +1,11 @@ // 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. +// a drag pans the picture instead of swiping to the next one. A single tap +// hides the title/keys so nothing covers the picture; another tap brings them +// back. import 'dart:convert'; +import 'dart:io' show Platform; import 'dart:typed_data'; import 'package:flutter/material.dart'; @@ -49,12 +52,17 @@ class ImageViewerPage extends StatefulWidget { final String directory; final Client client; + /// Whether to offer save/share; null follows the platform (Android only). + /// Tests set it to true on the desktop host. + final bool? mediaActions; + const ImageViewerPage({ super.key, required this.images, this.initial = 0, required this.directory, required this.client, + this.mediaActions, }); @override @@ -62,9 +70,17 @@ class ImageViewerPage extends StatefulWidget { } class _ImageViewerPageState extends State { + static const MethodChannel _media = MethodChannel('openchamber/media'); + late int _index = widget.initial; late final PageController _pages = PageController(initialPage: _index); + final Map _loaded = {}; bool _zoomed = false; + bool _chrome = true; + bool _saving = false; + + ImageSlide get _current => widget.images[_index]; + Uint8List? get _currentBytes => _loaded[_index]; @override void dispose() { @@ -72,10 +88,110 @@ class _ImageViewerPageState extends State { super.dispose(); } + void _toggleChrome() => setState(() => _chrome = !_chrome); + + void _loadedAt(int index, Uint8List bytes) { + if (_loaded[index] == bytes) return; + // A data URL decodes synchronously, so this can arrive while the page is + // still building; update after the frame. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + setState(() => _loaded[index] = bytes); + }); + } + + void _snack(String text) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(text))); + } + + String _mimeOf(ImageSlide slide) { + final source = slide.source; + if (source.startsWith('data:')) { + final colon = source.indexOf(':'); + final semi = source.indexOf(';'); + if (colon >= 0 && semi > colon) { + return source.substring(colon + 1, semi); + } + } + final name = slide.title.isNotEmpty ? slide.title : source; + final dot = name.lastIndexOf('.'); + final ext = dot >= 0 ? name.substring(dot + 1).toLowerCase() : ''; + return switch (ext) { + 'jpg' || 'jpeg' => 'image/jpeg', + 'gif' => 'image/gif', + 'webp' => 'image/webp', + 'bmp' => 'image/bmp', + 'avif' => 'image/avif', + _ => 'image/png', + }; + } + + String _extensionFor(String mime) => switch (mime) { + 'image/jpeg' => 'jpg', + 'image/gif' => 'gif', + 'image/webp' => 'webp', + 'image/bmp' => 'bmp', + 'image/avif' => 'avif', + _ => 'png', + }; + + String _fileName(ImageSlide slide) { + var name = slide.title.trim().replaceAll(RegExp(r'[/\\]'), '_'); + if (name.isEmpty) name = 'image'; + final dot = name.lastIndexOf('.'); + if (dot <= 0 || dot == name.length - 1) { + name = '$name.${_extensionFor(_mimeOf(slide))}'; + } + return name; + } + + Future _save() async { + final bytes = _currentBytes; + if (bytes == null || _saving) return; + setState(() => _saving = true); + try { + await _media.invokeMethod('saveImage', { + 'bytes': bytes, + 'name': _fileName(_current), + 'mime': _mimeOf(_current), + }); + if (mounted) _snack(tr('Saved to Photos')); + } on PlatformException catch (e) { + if (!mounted) return; + _snack(e.code == 'permission' + ? tr('Storage permission is required to save the picture') + : (e.message ?? tr("Couldn't save the picture"))); + } catch (_) { + if (mounted) _snack(tr("Couldn't save the picture")); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + Future _share() async { + final bytes = _currentBytes; + if (bytes == null) return; + try { + await _media.invokeMethod('shareImage', { + 'bytes': bytes, + 'name': _fileName(_current), + 'mime': _mimeOf(_current), + }); + } on PlatformException catch (e) { + if (mounted) _snack(e.message ?? tr('Share failed')); + } catch (_) { + if (mounted) _snack(tr('Share failed')); + } + } + @override Widget build(BuildContext context) { final padding = MediaQuery.paddingOf(context); final image = widget.images[_index]; + final canSave = _currentBytes != null; + final showMedia = widget.mediaActions ?? Platform.isAndroid; return AnnotatedRegion( value: SystemUiOverlayStyle.light, child: Scaffold( @@ -99,6 +215,8 @@ class _ImageViewerPageState extends State { slide: widget.images[index], directory: widget.directory, client: widget.client, + onTap: _toggleChrome, + onLoaded: (bytes) => _loadedAt(index, bytes), onZoomChanged: (zoomed) { if (index == _index && zoomed != _zoomed) { setState(() => _zoomed = zoomed); @@ -107,61 +225,93 @@ class _ImageViewerPageState extends State { ), ), ), - // A dark scrim keeps the white title and keys readable over a - // bright picture. + // The title and keys cover part of a picture, so a tap hides them + // until the next tap. The gradient keeps them readable. 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], + child: AnimatedOpacity( + key: const ValueKey('viewer-chrome'), + opacity: _chrome ? 1 : 0, + duration: const Duration(milliseconds: 160), + child: IgnorePointer( + ignoring: !_chrome, + child: Container( + padding: EdgeInsets.only(top: padding.top + 4), + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Colors.black54, Colors.transparent], + ), + ), + 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 (showMedia) ...[ + IconButton( + icon: _saving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.white)) + : const Icon(Icons.download_outlined), + color: Colors.white, + tooltip: tr('Save to Photos'), + onPressed: canSave && !_saving ? _save : null, + ), + IconButton( + icon: const Icon(Icons.ios_share), + color: Colors.white, + tooltip: tr('Share'), + onPressed: canSave ? _share : null, + ), + ], + const SizedBox(width: 4), + ], ), ), ), ), ), - 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( + if (widget.images.length > 1) + Positioned( + left: 0, + right: 0, + bottom: padding.bottom + 16, + child: AnimatedOpacity( + key: const ValueKey('viewer-page-indicator'), + opacity: _chrome ? 1 : 0, + duration: const Duration(milliseconds: 160), + child: IgnorePointer( child: Text( - image.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, + '${_index + 1} / ${widget.images.length}', + textAlign: TextAlign.center, style: const TextStyle( - color: Colors.white, - fontSize: 16, - fontWeight: FontWeight.w500), + color: Colors.white70, fontSize: 13), ), ), - 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), - ), - ), - ], + ), ), - ), ], ), ), @@ -173,6 +323,8 @@ class _ZoomableImage extends StatefulWidget { final ImageSlide slide; final String directory; final Client client; + final VoidCallback? onTap; + final ValueChanged? onLoaded; final ValueChanged? onZoomChanged; const _ZoomableImage({ @@ -180,6 +332,8 @@ class _ZoomableImage extends StatefulWidget { required this.slide, required this.directory, required this.client, + this.onTap, + this.onLoaded, this.onZoomChanged, }); @@ -218,6 +372,7 @@ class _ZoomableImageState extends State<_ZoomableImage> { : Uint8List.fromList( await widget.client.rawFile(source, directory: widget.directory)); if (!mounted) return; + widget.onLoaded?.call(bytes); setState(() { _bytes = bytes; _loading = false; @@ -280,6 +435,7 @@ class _ZoomableImageState extends State<_ZoomableImage> { ); } return GestureDetector( + onTap: widget.onTap, onDoubleTapDown: (details) => _doubleTap = details.localPosition, onDoubleTap: _toggleZoom, child: InteractiveViewer( diff --git a/pubspec.yaml b/pubspec.yaml index aadfe01..472dbff 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.5+605 +version: 0.6.6+606 environment: sdk: ^3.14.0 diff --git a/test/image_viewer_test.dart b/test/image_viewer_test.dart index 44f277c..e3889ab 100644 --- a/test/image_viewer_test.dart +++ b/test/image_viewer_test.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:openchamber/api/client.dart'; import 'package:openchamber/api/transport.dart'; +import 'package:openchamber/l10n.dart'; import 'package:openchamber/widgets/image_viewer.dart'; class _NoopTransport implements Transport { @@ -26,9 +28,12 @@ const _png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; void main() { + setUp(() => L10n.instance.apply(AppLanguage.en)); + tearDown(() => L10n.instance.apply(AppLanguage.zh)); + final client = Client(Uri.parse('http://test'), transport: _NoopTransport()); - Future pumpViewer(WidgetTester tester) async { + Future pumpViewer(WidgetTester tester, {bool mediaActions = false}) async { await tester.pumpWidget(MaterialApp( home: ImageViewerPage( images: const [ @@ -37,6 +42,7 @@ void main() { ], directory: '/home/me', client: client, + mediaActions: mediaActions, ), )); await tester.pumpAndSettle(); @@ -83,4 +89,50 @@ void main() { expect(find.text('Two'), findsOneWidget); expect(find.text('2 / 2'), findsOneWidget); }); + + testWidgets('save and share send the current picture to the platform', + (tester) async { + final calls = []; + const channel = MethodChannel('openchamber/media'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return true; + }); + addTearDown(() => TestDefaultBinaryMessengerBinding.instance + .defaultBinaryMessenger + .setMockMethodCallHandler(channel, null)); + + await pumpViewer(tester, mediaActions: true); + + await tester.tap(find.byTooltip('Save to Photos')); + await tester.pump(); + await tester.tap(find.byTooltip('Share')); + await tester.pump(); + + expect(calls.map((call) => call.method), + containsAll(['saveImage', 'shareImage'])); + final save = calls.firstWhere((call) => call.method == 'saveImage'); + final args = save.arguments as Map; + expect(args['name'], 'One.png'); + expect(args['mime'], 'image/png'); + expect(args['bytes'], isA()); + }); + + testWidgets('a tap hides the title and keys until the next tap', + (tester) async { + await pumpViewer(tester); + + double chromeOpacity() => tester + .widget(find.byKey(const ValueKey('viewer-chrome'))) + .opacity; + + expect(chromeOpacity(), 1); + await tester.tap(find.byType(InteractiveViewer)); + await tester.pump(const Duration(milliseconds: 400)); + expect(chromeOpacity(), 0); + await tester.tap(find.byType(InteractiveViewer)); + await tester.pump(const Duration(milliseconds: 400)); + expect(chromeOpacity(), 1); + }); }