thumbnail_widget.dart 11 KB

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