thumbnail_widget.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. int? optimizedImageHeight;
  58. int? optimizedImageWidth;
  59. @override
  60. void initState() {
  61. super.initState();
  62. assignOptimizedImageDimensions();
  63. }
  64. @override
  65. void dispose() {
  66. super.dispose();
  67. Future.delayed(const Duration(milliseconds: 10), () {
  68. // Cancel request only if the widget has been unmounted
  69. if (!mounted && widget.file!.isRemoteFile && !_hasLoadedThumbnail) {
  70. removePendingGetThumbnailRequestIfAny(widget.file!);
  71. }
  72. });
  73. }
  74. @override
  75. void didUpdateWidget(ThumbnailWidget oldWidget) {
  76. super.didUpdateWidget(oldWidget);
  77. if (widget.file!.generatedID != oldWidget.file!.generatedID) {
  78. _reset();
  79. }
  80. }
  81. ///Assigned dimension will be the size of a grid item. The size will be
  82. ///assigned to the side which is smaller in dimension.
  83. void assignOptimizedImageDimensions() {
  84. if (widget.file!.width == 0 || widget.file!.height == 0) {
  85. return;
  86. }
  87. if (widget.file!.width < widget.file!.height) {
  88. optimizedImageWidth = widget.thumbnailSize;
  89. } else {
  90. optimizedImageHeight = widget.thumbnailSize;
  91. }
  92. }
  93. @override
  94. Widget build(BuildContext context) {
  95. if (widget.file!.isRemoteFile) {
  96. _loadNetworkImage();
  97. } else {
  98. _loadLocalImage(context);
  99. }
  100. Widget? image;
  101. if (_imageProvider != null) {
  102. image = Image(
  103. image: optimizedImageHeight != null || optimizedImageWidth != null
  104. ? ResizeImage(
  105. _imageProvider!,
  106. width: optimizedImageWidth,
  107. height: optimizedImageHeight,
  108. )
  109. : _imageProvider!,
  110. fit: widget.fit,
  111. );
  112. }
  113. // todo: [2ndJuly22] pref-review if the content Widget which depends on
  114. // thumbnail fetch logic should be part of separate stateFull widget.
  115. // If yes, parent thumbnail widget can be stateless
  116. Widget? content;
  117. if (image != null) {
  118. final List<Widget> contentChildren = [image];
  119. if (FavoritesService.instance.isFavoriteCache(
  120. widget.file!,
  121. checkOnlyAlbum: widget.showFavForAlbumOnly,
  122. )) {
  123. contentChildren.add(const FavoriteOverlayIcon());
  124. }
  125. if (widget.file!.fileType == FileType.video) {
  126. contentChildren.add(const VideoOverlayIcon());
  127. } else if (widget.shouldShowLivePhotoOverlay &&
  128. (widget.file!.fileType == FileType.livePhoto ||
  129. ((widget.file!.pubMagicMetadata?.mvi ?? 0) > 0))) {
  130. contentChildren.add(const LivePhotoOverlayIcon());
  131. }
  132. if (widget.shouldShowOwnerAvatar) {
  133. if (widget.file!.ownerID != null &&
  134. widget.file!.ownerID != Configuration.instance.getUserID()) {
  135. final owner = CollectionsService.instance
  136. .getFileOwner(widget.file!.ownerID!, widget.file!.collectionID);
  137. // hide this icon if the current thumbnail is being showed as album
  138. // cover
  139. contentChildren.add(
  140. OwnerAvatarOverlayIcon(owner),
  141. );
  142. } else if (widget.file!.pubMagicMetadata!.uploaderName != null) {
  143. contentChildren.add(
  144. // Use -1 as userID for enforcing black avatar color
  145. OwnerAvatarOverlayIcon(
  146. User(
  147. id: -1,
  148. email: '',
  149. name: widget.file!.pubMagicMetadata!.uploaderName,
  150. ),
  151. ),
  152. );
  153. }
  154. }
  155. content = contentChildren.length == 1
  156. ? contentChildren.first
  157. : Stack(
  158. fit: StackFit.expand,
  159. children: contentChildren,
  160. );
  161. }
  162. final List<Widget> viewChildren = [
  163. const ThumbnailPlaceHolder(),
  164. content ?? const SizedBox(),
  165. ];
  166. if (widget.shouldShowSyncStatus && widget.file!.uploadedFileID == null) {
  167. viewChildren.add(const UnSyncedIcon());
  168. }
  169. if (kDebugMode &&
  170. widget.shouldShowSyncStatus &&
  171. widget.file!.uploadedFileID != null) {
  172. if (widget.file!.localID != null) {
  173. viewChildren.add(const DeviceIcon());
  174. } else {
  175. viewChildren.add(const CloudOnlyIcon());
  176. }
  177. }
  178. if (widget.file is TrashFile) {
  179. viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
  180. }
  181. // todo: Move this icon overlay to the collection widget.
  182. if (widget.shouldShowArchiveStatus) {
  183. viewChildren.add(const ArchiveOverlayIcon());
  184. }
  185. return Stack(
  186. fit: StackFit.expand,
  187. children: viewChildren,
  188. );
  189. }
  190. void _loadLocalImage(BuildContext context) {
  191. if (!_hasLoadedThumbnail &&
  192. !_errorLoadingLocalThumbnail &&
  193. !_isLoadingLocalThumbnail) {
  194. _isLoadingLocalThumbnail = true;
  195. final cachedSmallThumbnail =
  196. ThumbnailInMemoryLruCache.get(widget.file!, thumbnailSmallSize);
  197. if (cachedSmallThumbnail != null) {
  198. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  199. _hasLoadedThumbnail = true;
  200. } else {
  201. if (widget.diskLoadDeferDuration != null) {
  202. Future.delayed(widget.diskLoadDeferDuration!, () {
  203. if (mounted) {
  204. _getThumbnailFromDisk();
  205. }
  206. });
  207. } else {
  208. _getThumbnailFromDisk();
  209. }
  210. }
  211. }
  212. }
  213. Future _getThumbnailFromDisk() async {
  214. getThumbnailFromLocal(
  215. widget.file!,
  216. size: widget.thumbnailSize,
  217. ).then((thumbData) async {
  218. if (thumbData == null) {
  219. if (widget.file!.uploadedFileID != null) {
  220. _logger.fine("Removing localID reference for " + widget.file!.tag);
  221. widget.file!.localID = null;
  222. if (widget.file is TrashFile) {
  223. TrashDB.instance.update(widget.file as TrashFile);
  224. } else {
  225. FilesDB.instance.update(widget.file!);
  226. }
  227. _loadNetworkImage();
  228. } else {
  229. if (await doesLocalFileExist(widget.file!) == false) {
  230. _logger.info("Deleting file " + widget.file!.tag);
  231. FilesDB.instance.deleteLocalFile(widget.file!);
  232. Bus.instance.fire(
  233. LocalPhotosUpdatedEvent(
  234. [widget.file!],
  235. type: EventType.deletedFromDevice,
  236. source: "thumbFileDeleted",
  237. ),
  238. );
  239. }
  240. }
  241. return;
  242. }
  243. if (mounted) {
  244. final imageProvider = Image.memory(thumbData).image;
  245. _cacheAndRender(imageProvider);
  246. }
  247. ThumbnailInMemoryLruCache.put(
  248. widget.file!,
  249. thumbData,
  250. thumbnailSmallSize,
  251. );
  252. }).catchError((e) {
  253. _logger.warning("Could not load image: ", e);
  254. _errorLoadingLocalThumbnail = true;
  255. });
  256. }
  257. void _loadNetworkImage() {
  258. if (!_hasLoadedThumbnail &&
  259. !_errorLoadingRemoteThumbnail &&
  260. !_isLoadingRemoteThumbnail) {
  261. _isLoadingRemoteThumbnail = true;
  262. final cachedThumbnail = ThumbnailInMemoryLruCache.get(widget.file!);
  263. if (cachedThumbnail != null) {
  264. _imageProvider = Image.memory(cachedThumbnail).image;
  265. _hasLoadedThumbnail = true;
  266. return;
  267. }
  268. if (widget.serverLoadDeferDuration != null) {
  269. Future.delayed(widget.serverLoadDeferDuration!, () {
  270. if (mounted) {
  271. _getThumbnailFromServer();
  272. }
  273. });
  274. } else {
  275. _getThumbnailFromServer();
  276. }
  277. }
  278. }
  279. void _getThumbnailFromServer() async {
  280. try {
  281. final thumbnail = await getThumbnailFromServer(widget.file!);
  282. if (mounted) {
  283. final imageProvider = Image.memory(thumbnail).image;
  284. _cacheAndRender(imageProvider);
  285. }
  286. } catch (e) {
  287. if (e is RequestCancelledError) {
  288. if (mounted) {
  289. _logger.info(
  290. "Thumbnail request was aborted although it is in view, will retry",
  291. );
  292. _reset();
  293. setState(() {});
  294. }
  295. } else {
  296. _logger.severe("Could not load image " + widget.file.toString(), e);
  297. _errorLoadingRemoteThumbnail = true;
  298. }
  299. }
  300. }
  301. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  302. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  303. _logger.info("Clearing image cache");
  304. imageCache.clear();
  305. imageCache.clearLiveImages();
  306. }
  307. precacheImage(imageProvider, context).then((value) {
  308. if (mounted) {
  309. setState(() {
  310. _imageProvider = imageProvider;
  311. _hasLoadedThumbnail = true;
  312. });
  313. }
  314. });
  315. }
  316. void _reset() {
  317. _hasLoadedThumbnail = false;
  318. _isLoadingLocalThumbnail = false;
  319. _isLoadingRemoteThumbnail = false;
  320. _errorLoadingLocalThumbnail = false;
  321. _errorLoadingRemoteThumbnail = false;
  322. _imageProvider = null;
  323. }
  324. }