thumbnail_widget.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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/constants.dart';
  5. import 'package:photos/core/errors.dart';
  6. import 'package:photos/core/event_bus.dart';
  7. import 'package:photos/db/files_db.dart';
  8. import 'package:photos/db/trash_db.dart';
  9. import 'package:photos/events/files_updated_event.dart';
  10. import "package:photos/events/local_photos_updated_event.dart";
  11. import "package:photos/models/api/collection/user.dart";
  12. import "package:photos/models/file/extensions/file_props.dart";
  13. import 'package:photos/models/file/file.dart';
  14. import 'package:photos/models/file/file_type.dart';
  15. import 'package:photos/models/file/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.isLiveOrMotionPhoto) {
  130. contentChildren.add(const LivePhotoOverlayIcon());
  131. }
  132. if (widget.shouldShowOwnerAvatar) {
  133. if (!widget.file.isOwner) {
  134. final owner = CollectionsService.instance
  135. .getFileOwner(widget.file.ownerID!, widget.file.collectionID);
  136. contentChildren.add(
  137. OwnerAvatarOverlayIcon(owner),
  138. );
  139. } else if (widget.file.isCollect) {
  140. contentChildren.add(
  141. // Use -1 as userID for enforcing black avatar color
  142. OwnerAvatarOverlayIcon(
  143. User(id: -1, email: '', name: widget.file.uploaderName),
  144. ),
  145. );
  146. }
  147. }
  148. content = contentChildren.length == 1
  149. ? contentChildren.first
  150. : Stack(
  151. fit: StackFit.expand,
  152. children: contentChildren,
  153. );
  154. }
  155. final List<Widget> viewChildren = [
  156. const ThumbnailPlaceHolder(),
  157. content ?? const SizedBox(),
  158. ];
  159. if (widget.shouldShowSyncStatus && !widget.file.isUploaded) {
  160. viewChildren.add(const UnSyncedIcon());
  161. }
  162. if (widget.file.isTrash) {
  163. viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
  164. }
  165. // todo: Move this icon overlay to the collection widget.
  166. if (widget.shouldShowArchiveStatus) {
  167. viewChildren.add(const ArchiveOverlayIcon());
  168. }
  169. if (widget.shouldShowPinIcon) {
  170. viewChildren.add(const PinOverlayIcon());
  171. }
  172. return Stack(
  173. fit: StackFit.expand,
  174. children: viewChildren,
  175. );
  176. }
  177. void _loadLocalImage(BuildContext context) {
  178. if (!_hasLoadedThumbnail &&
  179. !_errorLoadingLocalThumbnail &&
  180. !_isLoadingLocalThumbnail) {
  181. _isLoadingLocalThumbnail = true;
  182. final cachedSmallThumbnail =
  183. ThumbnailInMemoryLruCache.get(widget.file, thumbnailSmallSize);
  184. if (cachedSmallThumbnail != null) {
  185. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  186. _hasLoadedThumbnail = true;
  187. } else {
  188. if (widget.diskLoadDeferDuration != null) {
  189. Future.delayed(widget.diskLoadDeferDuration!, () {
  190. if (mounted) {
  191. _getThumbnailFromDisk();
  192. }
  193. });
  194. } else {
  195. _getThumbnailFromDisk();
  196. }
  197. }
  198. }
  199. }
  200. Future _getThumbnailFromDisk() async {
  201. getThumbnailFromLocal(
  202. widget.file,
  203. size: widget.thumbnailSize,
  204. ).then((thumbData) async {
  205. if (thumbData == null) {
  206. if (widget.file.isUploaded) {
  207. _logger.fine("Removing localID reference for " + widget.file.tag);
  208. widget.file.localID = null;
  209. if (widget.file.isTrash) {
  210. TrashDB.instance.update(widget.file as TrashFile);
  211. } else {
  212. FilesDB.instance.update(widget.file);
  213. }
  214. _loadNetworkImage();
  215. } else {
  216. if (await doesLocalFileExist(widget.file) == false) {
  217. _logger.info("Deleting file " + widget.file.tag);
  218. FilesDB.instance.deleteLocalFile(widget.file);
  219. Bus.instance.fire(
  220. LocalPhotosUpdatedEvent(
  221. [widget.file],
  222. type: EventType.deletedFromDevice,
  223. source: "thumbFileDeleted",
  224. ),
  225. );
  226. }
  227. }
  228. return;
  229. }
  230. if (mounted) {
  231. final imageProvider = Image.memory(thumbData).image;
  232. _cacheAndRender(imageProvider);
  233. }
  234. ThumbnailInMemoryLruCache.put(
  235. widget.file,
  236. thumbData,
  237. thumbnailSmallSize,
  238. );
  239. }).catchError((e) {
  240. _logger.warning("Could not load image: ", e);
  241. _errorLoadingLocalThumbnail = true;
  242. });
  243. }
  244. void _loadNetworkImage() {
  245. if (!_hasLoadedThumbnail &&
  246. !_errorLoadingRemoteThumbnail &&
  247. !_isLoadingRemoteThumbnail) {
  248. _isLoadingRemoteThumbnail = true;
  249. final cachedThumbnail = ThumbnailInMemoryLruCache.get(widget.file);
  250. if (cachedThumbnail != null) {
  251. _imageProvider = Image.memory(cachedThumbnail).image;
  252. _hasLoadedThumbnail = true;
  253. return;
  254. }
  255. if (widget.serverLoadDeferDuration != null) {
  256. Future.delayed(widget.serverLoadDeferDuration!, () {
  257. if (mounted) {
  258. _getThumbnailFromServer();
  259. }
  260. });
  261. } else {
  262. _getThumbnailFromServer();
  263. }
  264. }
  265. }
  266. void _getThumbnailFromServer() async {
  267. try {
  268. final thumbnail = await getThumbnailFromServer(widget.file);
  269. if (mounted) {
  270. final imageProvider = Image.memory(thumbnail).image;
  271. _cacheAndRender(imageProvider);
  272. }
  273. } catch (e) {
  274. if (e is RequestCancelledError) {
  275. if (mounted) {
  276. _logger.info(
  277. "Thumbnail request was aborted although it is in view, will retry",
  278. );
  279. _reset();
  280. setState(() {});
  281. }
  282. } else {
  283. _logger.severe("Could not load image " + widget.file.toString(), e);
  284. _errorLoadingRemoteThumbnail = true;
  285. }
  286. }
  287. }
  288. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  289. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  290. _logger.info("Clearing image cache");
  291. imageCache.clear();
  292. imageCache.clearLiveImages();
  293. }
  294. precacheImage(imageProvider, context).then((value) {
  295. if (mounted) {
  296. setState(() {
  297. _imageProvider = imageProvider;
  298. _hasLoadedThumbnail = true;
  299. });
  300. }
  301. });
  302. }
  303. void _reset() {
  304. _hasLoadedThumbnail = false;
  305. _isLoadingLocalThumbnail = false;
  306. _isLoadingRemoteThumbnail = false;
  307. _errorLoadingLocalThumbnail = false;
  308. _errorLoadingRemoteThumbnail = false;
  309. _imageProvider = null;
  310. }
  311. }