zoomable_image.dart 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/widgets.dart';
  5. import 'package:logging/logging.dart';
  6. import 'package:photo_view/photo_view.dart';
  7. import 'package:photos/core/cache/thumbnail_in_memory_cache.dart';
  8. import "package:photos/core/configuration.dart";
  9. import 'package:photos/core/constants.dart';
  10. import 'package:photos/core/event_bus.dart';
  11. import 'package:photos/db/files_db.dart';
  12. import 'package:photos/events/files_updated_event.dart';
  13. import 'package:photos/events/local_photos_updated_event.dart';
  14. import 'package:photos/models/file.dart';
  15. import "package:photos/models/metadata/file_magic.dart";
  16. import "package:photos/services/file_magic_service.dart";
  17. import 'package:photos/ui/common/loading_widget.dart';
  18. import 'package:photos/utils/file_util.dart';
  19. import 'package:photos/utils/image_util.dart';
  20. import 'package:photos/utils/thumbnail_util.dart';
  21. class ZoomableImage extends StatefulWidget {
  22. final EnteFile photo;
  23. final Function(bool)? shouldDisableScroll;
  24. final String? tagPrefix;
  25. final Decoration? backgroundDecoration;
  26. final bool shouldCover;
  27. const ZoomableImage(
  28. this.photo, {
  29. Key? key,
  30. this.shouldDisableScroll,
  31. required this.tagPrefix,
  32. this.backgroundDecoration,
  33. this.shouldCover = false,
  34. }) : super(key: key);
  35. @override
  36. State<ZoomableImage> createState() => _ZoomableImageState();
  37. }
  38. class _ZoomableImageState extends State<ZoomableImage>
  39. with SingleTickerProviderStateMixin {
  40. late Logger _logger;
  41. late EnteFile _photo;
  42. ImageProvider? _imageProvider;
  43. bool _loadedSmallThumbnail = false;
  44. bool _loadingLargeThumbnail = false;
  45. bool _loadedLargeThumbnail = false;
  46. bool _loadingFinalImage = false;
  47. bool _loadedFinalImage = false;
  48. ValueChanged<PhotoViewScaleState>? _scaleStateChangedCallback;
  49. bool _isZooming = false;
  50. PhotoViewController _photoViewController = PhotoViewController();
  51. int? _thumbnailWidth;
  52. late int _currentUserID;
  53. @override
  54. void initState() {
  55. _photo = widget.photo;
  56. _logger = Logger("ZoomableImage_" + _photo.tag);
  57. debugPrint('initState for ${_photo.toString()}');
  58. _scaleStateChangedCallback = (value) {
  59. if (widget.shouldDisableScroll != null) {
  60. widget.shouldDisableScroll!(value != PhotoViewScaleState.initial);
  61. }
  62. _isZooming = value != PhotoViewScaleState.initial;
  63. debugPrint("isZooming = $_isZooming, currentState $value");
  64. // _logger.info('is reakky zooming $_isZooming with state $value');
  65. };
  66. _currentUserID = Configuration.instance.getUserID()!;
  67. super.initState();
  68. }
  69. @override
  70. void dispose() {
  71. _photoViewController.dispose();
  72. super.dispose();
  73. }
  74. @override
  75. Widget build(BuildContext context) {
  76. if (_photo.isRemoteFile) {
  77. _loadNetworkImage();
  78. } else {
  79. _loadLocalImage(context);
  80. }
  81. Widget content;
  82. if (_imageProvider != null) {
  83. content = PhotoViewGestureDetectorScope(
  84. axis: Axis.vertical,
  85. child: PhotoView(
  86. imageProvider: _imageProvider,
  87. controller: _photoViewController,
  88. scaleStateChangedCallback: _scaleStateChangedCallback,
  89. minScale: widget.shouldCover
  90. ? PhotoViewComputedScale.covered
  91. : PhotoViewComputedScale.contained,
  92. gaplessPlayback: true,
  93. heroAttributes: PhotoViewHeroAttributes(
  94. tag: widget.tagPrefix! + _photo.tag,
  95. ),
  96. backgroundDecoration: widget.backgroundDecoration as BoxDecoration?,
  97. ),
  98. );
  99. } else {
  100. content = const EnteLoadingWidget();
  101. }
  102. final GestureDragUpdateCallback? verticalDragCallback = _isZooming
  103. ? null
  104. : (d) => {
  105. if (!_isZooming && d.delta.dy > dragSensitivity)
  106. {Navigator.of(context).pop()},
  107. };
  108. return GestureDetector(
  109. onVerticalDragUpdate: verticalDragCallback,
  110. child: content,
  111. );
  112. }
  113. void _loadNetworkImage() {
  114. if (!_loadedSmallThumbnail && !_loadedFinalImage) {
  115. final cachedThumbnail = ThumbnailInMemoryLruCache.get(_photo);
  116. if (cachedThumbnail != null) {
  117. _imageProvider = Image.memory(cachedThumbnail).image;
  118. _loadedSmallThumbnail = true;
  119. _captureThumbnailDimensions(_imageProvider!);
  120. } else {
  121. getThumbnailFromServer(_photo).then((file) {
  122. final imageProvider = Image.memory(file).image;
  123. if (mounted) {
  124. precacheImage(imageProvider, context).then((value) {
  125. if (mounted) {
  126. setState(() {
  127. _imageProvider = imageProvider;
  128. _loadedSmallThumbnail = true;
  129. _captureThumbnailDimensions(_imageProvider!);
  130. });
  131. }
  132. }).catchError((e) {
  133. _logger.severe("Could not load image " + _photo.toString());
  134. _loadedSmallThumbnail = true;
  135. });
  136. }
  137. });
  138. }
  139. }
  140. if (!_loadedFinalImage && !_loadingFinalImage) {
  141. _loadingFinalImage = true;
  142. getFileFromServer(_photo).then((file) {
  143. _onFinalImageLoaded(
  144. Image.file(
  145. file!,
  146. gaplessPlayback: true,
  147. ).image,
  148. );
  149. });
  150. }
  151. }
  152. void _loadLocalImage(BuildContext context) {
  153. if (!_loadedSmallThumbnail &&
  154. !_loadedLargeThumbnail &&
  155. !_loadedFinalImage) {
  156. final cachedThumbnail =
  157. ThumbnailInMemoryLruCache.get(_photo, thumbnailSmallSize);
  158. if (cachedThumbnail != null) {
  159. _imageProvider = Image.memory(cachedThumbnail).image;
  160. _loadedSmallThumbnail = true;
  161. }
  162. }
  163. if (!_loadingLargeThumbnail &&
  164. !_loadedLargeThumbnail &&
  165. !_loadedFinalImage) {
  166. _loadingLargeThumbnail = true;
  167. getThumbnailFromLocal(_photo, size: thumbnailLargeSize, quality: 100)
  168. .then((cachedThumbnail) {
  169. if (cachedThumbnail != null) {
  170. _onLargeThumbnailLoaded(Image.memory(cachedThumbnail).image, context);
  171. }
  172. });
  173. }
  174. if (!_loadingFinalImage && !_loadedFinalImage) {
  175. _loadingFinalImage = true;
  176. getFile(
  177. _photo,
  178. isOrigin: Platform.isIOS &&
  179. _isGIF(), // since on iOS GIFs playback only when origin-files are loaded
  180. ).then((file) {
  181. if (file != null && file.existsSync()) {
  182. _onFinalImageLoaded(Image.file(file).image);
  183. } else {
  184. _logger.info("File was deleted " + _photo.toString());
  185. if (_photo.uploadedFileID != null) {
  186. _photo.localID = null;
  187. FilesDB.instance.update(_photo);
  188. _loadNetworkImage();
  189. } else {
  190. FilesDB.instance.deleteLocalFile(_photo);
  191. Bus.instance.fire(
  192. LocalPhotosUpdatedEvent(
  193. [_photo],
  194. type: EventType.deletedFromDevice,
  195. source: "zoomPreview",
  196. ),
  197. );
  198. }
  199. }
  200. });
  201. }
  202. }
  203. void _onLargeThumbnailLoaded(
  204. ImageProvider imageProvider,
  205. BuildContext context,
  206. ) {
  207. if (mounted && !_loadedFinalImage) {
  208. precacheImage(imageProvider, context).then((value) {
  209. if (mounted && !_loadedFinalImage) {
  210. setState(() {
  211. _imageProvider = imageProvider;
  212. _loadedLargeThumbnail = true;
  213. });
  214. }
  215. });
  216. }
  217. }
  218. void _onFinalImageLoaded(ImageProvider imageProvider) {
  219. if (mounted) {
  220. precacheImage(imageProvider, context).then((value) async {
  221. if (mounted) {
  222. await _updatePhotoViewController(imageProvider);
  223. setState(() {
  224. _imageProvider = imageProvider;
  225. _loadedFinalImage = true;
  226. _logger.info("Final image loaded");
  227. });
  228. }
  229. });
  230. }
  231. }
  232. Future<void> _captureThumbnailDimensions(ImageProvider imageProvider) async {
  233. final imageInfo = await getImageInfo(imageProvider);
  234. _thumbnailWidth = imageInfo.image.width;
  235. }
  236. Future<void> _updatePhotoViewController(ImageProvider imageProvider) async {
  237. if (_thumbnailWidth == null || _photoViewController.scale == null) {
  238. return;
  239. }
  240. final imageInfo = await getImageInfo(imageProvider);
  241. final scale = _photoViewController.scale! /
  242. (imageInfo.image.width / _thumbnailWidth!);
  243. final currentPosition = _photoViewController.value.position;
  244. final positionScaleFactor = 1 / scale;
  245. final newPosition = currentPosition.scale(
  246. positionScaleFactor,
  247. positionScaleFactor,
  248. );
  249. _photoViewController = PhotoViewController(
  250. initialPosition: newPosition,
  251. initialScale: scale,
  252. );
  253. _updateAspectRatioIfNeeded(imageInfo).ignore();
  254. }
  255. // Fallback logic to finish back fill and update aspect
  256. // ratio if needed.
  257. Future<void> _updateAspectRatioIfNeeded(ImageInfo imageInfo) async {
  258. if (_imageProvider != null &&
  259. widget.photo.isUploaded &&
  260. widget.photo.ownerID == _currentUserID) {
  261. final int h = imageInfo.image.height, w = imageInfo.image.width;
  262. if (h != 0 &&
  263. w != 0 &&
  264. (h != widget.photo.height || w != widget.photo.width)) {
  265. _logger.info('Updating aspect ratio for ${widget.photo} to $h:$w');
  266. await FileMagicService.instance.updatePublicMagicMetadata([
  267. widget.photo,
  268. ], {
  269. heightKey: h,
  270. widthKey: w,
  271. });
  272. }
  273. }
  274. }
  275. bool _isGIF() => _photo.displayName.toLowerCase().endsWith(".gif");
  276. }