thumbnail_widget.dart 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // Use uploadName hashCode as userID so that different uploader
  123. // get avatar color
  124. OwnerAvatarOverlayIcon(
  125. User(
  126. id: widget.file.pubMagicMetadata.uploaderName.hashCode,
  127. email: owner.email,
  128. name: widget.file.pubMagicMetadata.uploaderName,
  129. ),
  130. ),
  131. );
  132. }
  133. }
  134. content = contentChildren.length == 1
  135. ? contentChildren.first
  136. : Stack(
  137. fit: StackFit.expand,
  138. children: contentChildren,
  139. );
  140. }
  141. final List<Widget> viewChildren = [
  142. const ThumbnailPlaceHolder(),
  143. AnimatedOpacity(
  144. opacity: content == null ? 0 : 1.0,
  145. duration: const Duration(milliseconds: 200),
  146. child: content,
  147. )
  148. ];
  149. if (widget.shouldShowSyncStatus && widget.file.uploadedFileID == null) {
  150. viewChildren.add(const UnSyncedIcon());
  151. }
  152. if (widget.file is TrashFile) {
  153. viewChildren.add(TrashedFileOverlayText(widget.file));
  154. }
  155. // todo: Move this icon overlay to the collection widget.
  156. if (widget.shouldShowArchiveStatus) {
  157. viewChildren.add(const ArchiveOverlayIcon());
  158. }
  159. return Stack(
  160. fit: StackFit.expand,
  161. children: viewChildren,
  162. );
  163. }
  164. void _loadLocalImage(BuildContext context) {
  165. if (!_hasLoadedThumbnail &&
  166. !_errorLoadingLocalThumbnail &&
  167. !_isLoadingLocalThumbnail) {
  168. _isLoadingLocalThumbnail = true;
  169. final cachedSmallThumbnail =
  170. ThumbnailLruCache.get(widget.file, thumbnailSmallSize);
  171. if (cachedSmallThumbnail != null) {
  172. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  173. _hasLoadedThumbnail = true;
  174. } else {
  175. if (widget.diskLoadDeferDuration != null) {
  176. Future.delayed(widget.diskLoadDeferDuration, () {
  177. if (mounted) {
  178. _getThumbnailFromDisk();
  179. }
  180. });
  181. } else {
  182. _getThumbnailFromDisk();
  183. }
  184. }
  185. }
  186. }
  187. Future _getThumbnailFromDisk() async {
  188. getThumbnailFromLocal(
  189. widget.file,
  190. size: widget.thumbnailSize,
  191. ).then((thumbData) async {
  192. if (thumbData == null) {
  193. if (widget.file.uploadedFileID != null) {
  194. _logger.fine("Removing localID reference for " + widget.file.tag);
  195. widget.file.localID = null;
  196. if (widget.file is TrashFile) {
  197. TrashDB.instance.update(widget.file);
  198. } else {
  199. FilesDB.instance.update(widget.file);
  200. }
  201. _loadNetworkImage();
  202. } else {
  203. if (await doesLocalFileExist(widget.file) == false) {
  204. _logger.info("Deleting file " + widget.file.tag);
  205. FilesDB.instance.deleteLocalFile(widget.file);
  206. Bus.instance.fire(
  207. LocalPhotosUpdatedEvent(
  208. [widget.file],
  209. type: EventType.deletedFromDevice,
  210. source: "thumbFileDeleted",
  211. ),
  212. );
  213. }
  214. }
  215. return;
  216. }
  217. if (thumbData != null && mounted) {
  218. final imageProvider = Image.memory(thumbData).image;
  219. _cacheAndRender(imageProvider);
  220. }
  221. ThumbnailLruCache.put(widget.file, thumbData, thumbnailSmallSize);
  222. }).catchError((e) {
  223. _logger.warning("Could not load image: ", e);
  224. _errorLoadingLocalThumbnail = true;
  225. });
  226. }
  227. void _loadNetworkImage() {
  228. if (!_hasLoadedThumbnail &&
  229. !_errorLoadingRemoteThumbnail &&
  230. !_isLoadingRemoteThumbnail) {
  231. _isLoadingRemoteThumbnail = true;
  232. final cachedThumbnail = ThumbnailLruCache.get(widget.file);
  233. if (cachedThumbnail != null) {
  234. _imageProvider = Image.memory(cachedThumbnail).image;
  235. _hasLoadedThumbnail = true;
  236. return;
  237. }
  238. if (widget.serverLoadDeferDuration != null) {
  239. Future.delayed(widget.serverLoadDeferDuration, () {
  240. if (mounted) {
  241. _getThumbnailFromServer();
  242. }
  243. });
  244. } else {
  245. _getThumbnailFromServer();
  246. }
  247. }
  248. }
  249. void _getThumbnailFromServer() async {
  250. try {
  251. final thumbnail = await getThumbnailFromServer(widget.file);
  252. if (mounted) {
  253. final imageProvider = Image.memory(thumbnail).image;
  254. _cacheAndRender(imageProvider);
  255. }
  256. } catch (e) {
  257. if (e is RequestCancelledError) {
  258. if (mounted) {
  259. _logger.info(
  260. "Thumbnail request was aborted although it is in view, will retry",
  261. );
  262. _reset();
  263. setState(() {});
  264. }
  265. } else {
  266. _logger.severe("Could not load image " + widget.file.toString(), e);
  267. _errorLoadingRemoteThumbnail = true;
  268. }
  269. }
  270. }
  271. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  272. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  273. _logger.info("Clearing image cache");
  274. imageCache.clear();
  275. imageCache.clearLiveImages();
  276. }
  277. precacheImage(imageProvider, context).then((value) {
  278. if (mounted) {
  279. setState(() {
  280. _imageProvider = imageProvider;
  281. _hasLoadedThumbnail = true;
  282. });
  283. }
  284. });
  285. }
  286. void _reset() {
  287. _hasLoadedThumbnail = false;
  288. _isLoadingLocalThumbnail = false;
  289. _isLoadingRemoteThumbnail = false;
  290. _errorLoadingLocalThumbnail = false;
  291. _errorLoadingRemoteThumbnail = false;
  292. _imageProvider = null;
  293. }
  294. }