thumbnail_widget.dart 10 KB

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