thumbnail_widget.dart 8.4 KB

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