thumbnail_widget.dart 8.6 KB

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