zoomable_image.dart 10 KB

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