thumbnail_widget.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import 'package:flutter/material.dart';
  2. import 'package:logging/logging.dart';
  3. import 'package:photos/core/cache/thumbnail_in_memory_cache.dart';
  4. import 'package:photos/core/configuration.dart';
  5. import 'package:photos/core/constants.dart';
  6. import 'package:photos/core/errors.dart';
  7. import 'package:photos/core/event_bus.dart';
  8. import 'package:photos/db/files_db.dart';
  9. import 'package:photos/db/trash_db.dart';
  10. import 'package:photos/events/files_updated_event.dart';
  11. import "package:photos/events/local_photos_updated_event.dart";
  12. import "package:photos/models/api/collection/user.dart";
  13. import 'package:photos/models/file.dart';
  14. import 'package:photos/models/file_type.dart';
  15. import 'package:photos/models/trash_file.dart';
  16. import 'package:photos/services/collections_service.dart';
  17. import 'package:photos/services/favorites_service.dart';
  18. import 'package:photos/ui/viewer/file/file_icons_widget.dart';
  19. import 'package:photos/utils/file_util.dart';
  20. import 'package:photos/utils/thumbnail_util.dart';
  21. class ThumbnailWidget extends StatefulWidget {
  22. final EnteFile? file;
  23. final BoxFit fit;
  24. final bool shouldShowSyncStatus;
  25. final bool shouldShowArchiveStatus;
  26. final bool shouldShowPinIcon;
  27. final bool showFavForAlbumOnly;
  28. final bool shouldShowLivePhotoOverlay;
  29. final Duration? diskLoadDeferDuration;
  30. final Duration? serverLoadDeferDuration;
  31. final int thumbnailSize;
  32. final bool shouldShowOwnerAvatar;
  33. ThumbnailWidget(
  34. this.file, {
  35. Key? key,
  36. this.fit = BoxFit.cover,
  37. this.shouldShowSyncStatus = true,
  38. this.shouldShowLivePhotoOverlay = false,
  39. this.shouldShowArchiveStatus = false,
  40. this.shouldShowPinIcon = false,
  41. this.showFavForAlbumOnly = false,
  42. this.shouldShowOwnerAvatar = false,
  43. this.diskLoadDeferDuration,
  44. this.serverLoadDeferDuration,
  45. this.thumbnailSize = thumbnailSmallSize,
  46. }) : super(key: key ?? Key(file!.tag));
  47. @override
  48. State<ThumbnailWidget> createState() => _ThumbnailWidgetState();
  49. }
  50. class _ThumbnailWidgetState extends State<ThumbnailWidget> {
  51. static final _logger = Logger("ThumbnailWidget");
  52. bool _hasLoadedThumbnail = false;
  53. bool _isLoadingLocalThumbnail = false;
  54. bool _errorLoadingLocalThumbnail = false;
  55. bool _isLoadingRemoteThumbnail = false;
  56. bool _errorLoadingRemoteThumbnail = false;
  57. ImageProvider? _imageProvider;
  58. int? optimizedImageHeight;
  59. int? optimizedImageWidth;
  60. @override
  61. void initState() {
  62. super.initState();
  63. assignOptimizedImageDimensions();
  64. }
  65. @override
  66. void dispose() {
  67. super.dispose();
  68. Future.delayed(const Duration(milliseconds: 10), () {
  69. // Cancel request only if the widget has been unmounted
  70. if (!mounted && widget.file!.isRemoteFile && !_hasLoadedThumbnail) {
  71. removePendingGetThumbnailRequestIfAny(widget.file!);
  72. }
  73. });
  74. }
  75. @override
  76. void didUpdateWidget(ThumbnailWidget oldWidget) {
  77. super.didUpdateWidget(oldWidget);
  78. if (widget.file!.generatedID != oldWidget.file!.generatedID) {
  79. _reset();
  80. }
  81. }
  82. ///Assigned dimension will be the size of a grid item. The size will be
  83. ///assigned to the side which is smaller in dimension.
  84. void assignOptimizedImageDimensions() {
  85. if (widget.file!.width == 0 || widget.file!.height == 0) {
  86. return;
  87. }
  88. if (widget.file!.width < widget.file!.height) {
  89. optimizedImageWidth = widget.thumbnailSize;
  90. } else {
  91. optimizedImageHeight = widget.thumbnailSize;
  92. }
  93. }
  94. @override
  95. Widget build(BuildContext context) {
  96. if (widget.file!.isRemoteFile) {
  97. _loadNetworkImage();
  98. } else {
  99. _loadLocalImage(context);
  100. }
  101. Widget? image;
  102. if (_imageProvider != null) {
  103. image = Image(
  104. image: optimizedImageHeight != null || optimizedImageWidth != null
  105. ? ResizeImage(
  106. _imageProvider!,
  107. width: optimizedImageWidth,
  108. height: optimizedImageHeight,
  109. )
  110. : _imageProvider!,
  111. fit: widget.fit,
  112. );
  113. }
  114. // todo: [2ndJuly22] pref-review if the content Widget which depends on
  115. // thumbnail fetch logic should be part of separate stateFull widget.
  116. // If yes, parent thumbnail widget can be stateless
  117. Widget? content;
  118. if (image != null) {
  119. final List<Widget> contentChildren = [image];
  120. if (FavoritesService.instance.isFavoriteCache(
  121. widget.file!,
  122. checkOnlyAlbum: widget.showFavForAlbumOnly,
  123. )) {
  124. contentChildren.add(const FavoriteOverlayIcon());
  125. }
  126. if (widget.file!.fileType == FileType.video) {
  127. contentChildren.add(const VideoOverlayIcon());
  128. } else if (widget.shouldShowLivePhotoOverlay &&
  129. (widget.file!.fileType == FileType.livePhoto ||
  130. ((widget.file!.pubMagicMetadata?.mvi ?? 0) > 0))) {
  131. contentChildren.add(const LivePhotoOverlayIcon());
  132. }
  133. if (widget.shouldShowOwnerAvatar) {
  134. if (widget.file!.ownerID != null &&
  135. widget.file!.ownerID != Configuration.instance.getUserID()) {
  136. final owner = CollectionsService.instance
  137. .getFileOwner(widget.file!.ownerID!, widget.file!.collectionID);
  138. // hide this icon if the current thumbnail is being showed as album
  139. // cover
  140. contentChildren.add(
  141. OwnerAvatarOverlayIcon(owner),
  142. );
  143. } else if (widget.file!.pubMagicMetadata!.uploaderName != null) {
  144. contentChildren.add(
  145. // Use -1 as userID for enforcing black avatar color
  146. OwnerAvatarOverlayIcon(
  147. User(
  148. id: -1,
  149. email: '',
  150. name: widget.file!.pubMagicMetadata!.uploaderName,
  151. ),
  152. ),
  153. );
  154. }
  155. }
  156. content = contentChildren.length == 1
  157. ? contentChildren.first
  158. : Stack(
  159. fit: StackFit.expand,
  160. children: contentChildren,
  161. );
  162. }
  163. final List<Widget> viewChildren = [
  164. const ThumbnailPlaceHolder(),
  165. content ?? const SizedBox(),
  166. ];
  167. if (widget.shouldShowSyncStatus && widget.file!.uploadedFileID == null) {
  168. viewChildren.add(const UnSyncedIcon());
  169. }
  170. if (widget.file is TrashFile) {
  171. viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
  172. }
  173. // todo: Move this icon overlay to the collection widget.
  174. if (widget.shouldShowArchiveStatus) {
  175. viewChildren.add(const ArchiveOverlayIcon());
  176. }
  177. if (widget.shouldShowPinIcon) {
  178. viewChildren.add(const PinOverlayIcon());
  179. }
  180. return Stack(
  181. fit: StackFit.expand,
  182. children: viewChildren,
  183. );
  184. }
  185. void _loadLocalImage(BuildContext context) {
  186. if (!_hasLoadedThumbnail &&
  187. !_errorLoadingLocalThumbnail &&
  188. !_isLoadingLocalThumbnail) {
  189. _isLoadingLocalThumbnail = true;
  190. final cachedSmallThumbnail =
  191. ThumbnailInMemoryLruCache.get(widget.file!, thumbnailSmallSize);
  192. if (cachedSmallThumbnail != null) {
  193. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  194. _hasLoadedThumbnail = true;
  195. } else {
  196. if (widget.diskLoadDeferDuration != null) {
  197. Future.delayed(widget.diskLoadDeferDuration!, () {
  198. if (mounted) {
  199. _getThumbnailFromDisk();
  200. }
  201. });
  202. } else {
  203. _getThumbnailFromDisk();
  204. }
  205. }
  206. }
  207. }
  208. Future _getThumbnailFromDisk() async {
  209. getThumbnailFromLocal(
  210. widget.file!,
  211. size: widget.thumbnailSize,
  212. ).then((thumbData) async {
  213. if (thumbData == null) {
  214. if (widget.file!.uploadedFileID != null) {
  215. _logger.fine("Removing localID reference for " + widget.file!.tag);
  216. widget.file!.localID = null;
  217. if (widget.file is TrashFile) {
  218. TrashDB.instance.update(widget.file as TrashFile);
  219. } else {
  220. FilesDB.instance.update(widget.file!);
  221. }
  222. _loadNetworkImage();
  223. } else {
  224. if (await doesLocalFileExist(widget.file!) == false) {
  225. _logger.info("Deleting file " + widget.file!.tag);
  226. FilesDB.instance.deleteLocalFile(widget.file!);
  227. Bus.instance.fire(
  228. LocalPhotosUpdatedEvent(
  229. [widget.file!],
  230. type: EventType.deletedFromDevice,
  231. source: "thumbFileDeleted",
  232. ),
  233. );
  234. }
  235. }
  236. return;
  237. }
  238. if (mounted) {
  239. final imageProvider = Image.memory(thumbData).image;
  240. _cacheAndRender(imageProvider);
  241. }
  242. ThumbnailInMemoryLruCache.put(
  243. widget.file!,
  244. thumbData,
  245. thumbnailSmallSize,
  246. );
  247. }).catchError((e) {
  248. _logger.warning("Could not load image: ", e);
  249. _errorLoadingLocalThumbnail = true;
  250. });
  251. }
  252. void _loadNetworkImage() {
  253. if (!_hasLoadedThumbnail &&
  254. !_errorLoadingRemoteThumbnail &&
  255. !_isLoadingRemoteThumbnail) {
  256. _isLoadingRemoteThumbnail = true;
  257. final cachedThumbnail = ThumbnailInMemoryLruCache.get(widget.file!);
  258. if (cachedThumbnail != null) {
  259. _imageProvider = Image.memory(cachedThumbnail).image;
  260. _hasLoadedThumbnail = true;
  261. return;
  262. }
  263. if (widget.serverLoadDeferDuration != null) {
  264. Future.delayed(widget.serverLoadDeferDuration!, () {
  265. if (mounted) {
  266. _getThumbnailFromServer();
  267. }
  268. });
  269. } else {
  270. _getThumbnailFromServer();
  271. }
  272. }
  273. }
  274. void _getThumbnailFromServer() async {
  275. try {
  276. final thumbnail = await getThumbnailFromServer(widget.file!);
  277. if (mounted) {
  278. final imageProvider = Image.memory(thumbnail).image;
  279. _cacheAndRender(imageProvider);
  280. }
  281. } catch (e) {
  282. if (e is RequestCancelledError) {
  283. if (mounted) {
  284. _logger.info(
  285. "Thumbnail request was aborted although it is in view, will retry",
  286. );
  287. _reset();
  288. setState(() {});
  289. }
  290. } else {
  291. _logger.severe("Could not load image " + widget.file.toString(), e);
  292. _errorLoadingRemoteThumbnail = true;
  293. }
  294. }
  295. }
  296. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  297. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  298. _logger.info("Clearing image cache");
  299. imageCache.clear();
  300. imageCache.clearLiveImages();
  301. }
  302. precacheImage(imageProvider, context).then((value) {
  303. if (mounted) {
  304. setState(() {
  305. _imageProvider = imageProvider;
  306. _hasLoadedThumbnail = true;
  307. });
  308. }
  309. });
  310. }
  311. void _reset() {
  312. _hasLoadedThumbnail = false;
  313. _isLoadingLocalThumbnail = false;
  314. _isLoadingRemoteThumbnail = false;
  315. _errorLoadingLocalThumbnail = false;
  316. _errorLoadingRemoteThumbnail = false;
  317. _imageProvider = null;
  318. }
  319. }