thumbnail_widget.dart 9.2 KB

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