thumbnail_widget.dart 9.6 KB

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