thumbnail_widget.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import 'package:flutter/foundation.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:logging/logging.dart';
  4. import 'package:photos/core/cache/thumbnail_in_memory_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.shouldShowLivePhotoOverlay &&
  107. (widget.file!.fileType == FileType.livePhoto ||
  108. ((widget.file!.pubMagicMetadata?.mvi ?? 0) > 0))) {
  109. contentChildren.add(const LivePhotoOverlayIcon());
  110. }
  111. if (widget.shouldShowOwnerAvatar) {
  112. if (widget.file!.ownerID != null &&
  113. widget.file!.ownerID != Configuration.instance.getUserID()) {
  114. final owner = CollectionsService.instance
  115. .getFileOwner(widget.file!.ownerID!, widget.file!.collectionID);
  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 -1 as userID for enforcing black avatar color
  124. OwnerAvatarOverlayIcon(
  125. User(
  126. id: -1,
  127. 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 (kDebugMode &&
  153. widget.shouldShowSyncStatus &&
  154. widget.file!.uploadedFileID != null) {
  155. if (widget.file!.localID != null) {
  156. viewChildren.add(const DeviceIcon());
  157. } else {
  158. viewChildren.add(const CloudOnlyIcon());
  159. }
  160. }
  161. if (widget.file is TrashFile) {
  162. viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
  163. }
  164. // todo: Move this icon overlay to the collection widget.
  165. if (widget.shouldShowArchiveStatus) {
  166. viewChildren.add(const ArchiveOverlayIcon());
  167. }
  168. return Stack(
  169. fit: StackFit.expand,
  170. children: viewChildren,
  171. );
  172. }
  173. void _loadLocalImage(BuildContext context) {
  174. if (!_hasLoadedThumbnail &&
  175. !_errorLoadingLocalThumbnail &&
  176. !_isLoadingLocalThumbnail) {
  177. _isLoadingLocalThumbnail = true;
  178. final cachedSmallThumbnail =
  179. ThumbnailInMemoryLruCache.get(widget.file!, thumbnailSmallSize);
  180. if (cachedSmallThumbnail != null) {
  181. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  182. _hasLoadedThumbnail = true;
  183. } else {
  184. if (widget.diskLoadDeferDuration != null) {
  185. Future.delayed(widget.diskLoadDeferDuration!, () {
  186. if (mounted) {
  187. _getThumbnailFromDisk();
  188. }
  189. });
  190. } else {
  191. _getThumbnailFromDisk();
  192. }
  193. }
  194. }
  195. }
  196. Future _getThumbnailFromDisk() async {
  197. getThumbnailFromLocal(
  198. widget.file!,
  199. size: widget.thumbnailSize,
  200. ).then((thumbData) async {
  201. if (thumbData == null) {
  202. if (widget.file!.uploadedFileID != null) {
  203. _logger.fine("Removing localID reference for " + widget.file!.tag);
  204. widget.file!.localID = null;
  205. if (widget.file is TrashFile) {
  206. TrashDB.instance.update(widget.file as TrashFile);
  207. } else {
  208. FilesDB.instance.update(widget.file!);
  209. }
  210. _loadNetworkImage();
  211. } else {
  212. if (await doesLocalFileExist(widget.file!) == false) {
  213. _logger.info("Deleting file " + widget.file!.tag);
  214. FilesDB.instance.deleteLocalFile(widget.file!);
  215. Bus.instance.fire(
  216. LocalPhotosUpdatedEvent(
  217. [widget.file!],
  218. type: EventType.deletedFromDevice,
  219. source: "thumbFileDeleted",
  220. ),
  221. );
  222. }
  223. }
  224. return;
  225. }
  226. if (mounted) {
  227. final imageProvider = Image.memory(thumbData).image;
  228. _cacheAndRender(imageProvider);
  229. }
  230. ThumbnailInMemoryLruCache.put(
  231. widget.file!,
  232. thumbData,
  233. thumbnailSmallSize,
  234. );
  235. }).catchError((e) {
  236. _logger.warning("Could not load image: ", e);
  237. _errorLoadingLocalThumbnail = true;
  238. });
  239. }
  240. void _loadNetworkImage() {
  241. if (!_hasLoadedThumbnail &&
  242. !_errorLoadingRemoteThumbnail &&
  243. !_isLoadingRemoteThumbnail) {
  244. _isLoadingRemoteThumbnail = true;
  245. final cachedThumbnail = ThumbnailInMemoryLruCache.get(widget.file!);
  246. if (cachedThumbnail != null) {
  247. _imageProvider = Image.memory(cachedThumbnail).image;
  248. _hasLoadedThumbnail = true;
  249. return;
  250. }
  251. if (widget.serverLoadDeferDuration != null) {
  252. Future.delayed(widget.serverLoadDeferDuration!, () {
  253. if (mounted) {
  254. _getThumbnailFromServer();
  255. }
  256. });
  257. } else {
  258. _getThumbnailFromServer();
  259. }
  260. }
  261. }
  262. void _getThumbnailFromServer() async {
  263. try {
  264. final thumbnail = await getThumbnailFromServer(widget.file!);
  265. if (mounted) {
  266. final imageProvider = Image.memory(thumbnail).image;
  267. _cacheAndRender(imageProvider);
  268. }
  269. } catch (e) {
  270. if (e is RequestCancelledError) {
  271. if (mounted) {
  272. _logger.info(
  273. "Thumbnail request was aborted although it is in view, will retry",
  274. );
  275. _reset();
  276. setState(() {});
  277. }
  278. } else {
  279. _logger.severe("Could not load image " + widget.file.toString(), e);
  280. _errorLoadingRemoteThumbnail = true;
  281. }
  282. }
  283. }
  284. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  285. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  286. _logger.info("Clearing image cache");
  287. imageCache.clear();
  288. imageCache.clearLiveImages();
  289. }
  290. precacheImage(imageProvider, context).then((value) {
  291. if (mounted) {
  292. setState(() {
  293. _imageProvider = imageProvider;
  294. _hasLoadedThumbnail = true;
  295. });
  296. }
  297. });
  298. }
  299. void _reset() {
  300. _hasLoadedThumbnail = false;
  301. _isLoadingLocalThumbnail = false;
  302. _isLoadingRemoteThumbnail = false;
  303. _errorLoadingLocalThumbnail = false;
  304. _errorLoadingRemoteThumbnail = false;
  305. _imageProvider = null;
  306. }
  307. }