Files
blumia fedc4dd79c 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
2026-12-01 11:53:54 +08:00

461 lines
14 KiB
Dart

// 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 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';
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;
/// 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
State<ImageViewerPage> createState() => _ImageViewerPageState();
}
class _ImageViewerPageState extends State<ImageViewerPage> {
static const MethodChannel _media = MethodChannel('openchamber/media');
late int _index = widget.initial;
late final PageController _pages = PageController(initialPage: _index);
final Map<int, Uint8List> _loaded = {};
bool _zoomed = false;
bool _chrome = true;
bool _saving = false;
ImageSlide get _current => widget.images[_index];
Uint8List? get _currentBytes => _loaded[_index];
@override
void dispose() {
_pages.dispose();
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<void> _save() async {
final bytes = _currentBytes;
if (bytes == null || _saving) return;
setState(() => _saving = true);
try {
await _media.invokeMethod<bool>('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<void> _share() async {
final bytes = _currentBytes;
if (bytes == null) return;
try {
await _media.invokeMethod<bool>('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<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,
onTap: _toggleChrome,
onLoaded: (bytes) => _loadedAt(index, bytes),
onZoomChanged: (zoomed) {
if (index == _index && zoomed != _zoomed) {
setState(() => _zoomed = zoomed);
}
},
),
),
),
// 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: 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),
],
),
),
),
),
),
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(
'${_index + 1} / ${widget.images.length}',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70, fontSize: 13),
),
),
),
),
],
),
),
);
}
}
class _ZoomableImage extends StatefulWidget {
final ImageSlide slide;
final String directory;
final Client client;
final VoidCallback? onTap;
final ValueChanged<Uint8List>? onLoaded;
final ValueChanged<bool>? onZoomChanged;
const _ZoomableImage({
super.key,
required this.slide,
required this.directory,
required this.client,
this.onTap,
this.onLoaded,
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;
widget.onLoaded?.call(bytes);
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(
onTap: widget.onTap,
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,
),
),
),
);
}
}