thumbnail_widget.dart 9.8 KB

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