thumbnail_widget.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. assignOptimizedImageDimensions();
  62. super.initState();
  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. AnimatedOpacity(
  165. opacity: content == null ? 0 : 1.0,
  166. duration: const Duration(milliseconds: 200),
  167. child: content,
  168. )
  169. ];
  170. if (widget.shouldShowSyncStatus && widget.file!.uploadedFileID == null) {
  171. viewChildren.add(const UnSyncedIcon());
  172. }
  173. if (kDebugMode &&
  174. widget.shouldShowSyncStatus &&
  175. widget.file!.uploadedFileID != null) {
  176. if (widget.file!.localID != null) {
  177. viewChildren.add(const DeviceIcon());
  178. } else {
  179. viewChildren.add(const CloudOnlyIcon());
  180. }
  181. }
  182. if (widget.file is TrashFile) {
  183. viewChildren.add(TrashedFileOverlayText(widget.file as TrashFile));
  184. }
  185. // todo: Move this icon overlay to the collection widget.
  186. if (widget.shouldShowArchiveStatus) {
  187. viewChildren.add(const ArchiveOverlayIcon());
  188. }
  189. return Stack(
  190. fit: StackFit.expand,
  191. children: viewChildren,
  192. );
  193. }
  194. void _loadLocalImage(BuildContext context) {
  195. if (!_hasLoadedThumbnail &&
  196. !_errorLoadingLocalThumbnail &&
  197. !_isLoadingLocalThumbnail) {
  198. _isLoadingLocalThumbnail = true;
  199. final cachedSmallThumbnail =
  200. ThumbnailInMemoryLruCache.get(widget.file!, thumbnailSmallSize);
  201. if (cachedSmallThumbnail != null) {
  202. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  203. _hasLoadedThumbnail = true;
  204. } else {
  205. if (widget.diskLoadDeferDuration != null) {
  206. Future.delayed(widget.diskLoadDeferDuration!, () {
  207. if (mounted) {
  208. _getThumbnailFromDisk();
  209. }
  210. });
  211. } else {
  212. _getThumbnailFromDisk();
  213. }
  214. }
  215. }
  216. }
  217. Future _getThumbnailFromDisk() async {
  218. getThumbnailFromLocal(
  219. widget.file!,
  220. size: widget.thumbnailSize,
  221. ).then((thumbData) async {
  222. if (thumbData == null) {
  223. if (widget.file!.uploadedFileID != null) {
  224. _logger.fine("Removing localID reference for " + widget.file!.tag);
  225. widget.file!.localID = null;
  226. if (widget.file is TrashFile) {
  227. TrashDB.instance.update(widget.file as TrashFile);
  228. } else {
  229. FilesDB.instance.update(widget.file!);
  230. }
  231. _loadNetworkImage();
  232. } else {
  233. if (await doesLocalFileExist(widget.file!) == false) {
  234. _logger.info("Deleting file " + widget.file!.tag);
  235. FilesDB.instance.deleteLocalFile(widget.file!);
  236. Bus.instance.fire(
  237. LocalPhotosUpdatedEvent(
  238. [widget.file!],
  239. type: EventType.deletedFromDevice,
  240. source: "thumbFileDeleted",
  241. ),
  242. );
  243. }
  244. }
  245. return;
  246. }
  247. if (mounted) {
  248. final imageProvider = Image.memory(thumbData).image;
  249. _cacheAndRender(imageProvider);
  250. }
  251. ThumbnailInMemoryLruCache.put(
  252. widget.file!,
  253. thumbData,
  254. thumbnailSmallSize,
  255. );
  256. }).catchError((e) {
  257. _logger.warning("Could not load image: ", e);
  258. _errorLoadingLocalThumbnail = true;
  259. });
  260. }
  261. void _loadNetworkImage() {
  262. if (!_hasLoadedThumbnail &&
  263. !_errorLoadingRemoteThumbnail &&
  264. !_isLoadingRemoteThumbnail) {
  265. _isLoadingRemoteThumbnail = true;
  266. final cachedThumbnail = ThumbnailInMemoryLruCache.get(widget.file!);
  267. if (cachedThumbnail != null) {
  268. _imageProvider = Image.memory(cachedThumbnail).image;
  269. _hasLoadedThumbnail = true;
  270. return;
  271. }
  272. if (widget.serverLoadDeferDuration != null) {
  273. Future.delayed(widget.serverLoadDeferDuration!, () {
  274. if (mounted) {
  275. _getThumbnailFromServer();
  276. }
  277. });
  278. } else {
  279. _getThumbnailFromServer();
  280. }
  281. }
  282. }
  283. void _getThumbnailFromServer() async {
  284. try {
  285. final thumbnail = await getThumbnailFromServer(widget.file!);
  286. if (mounted) {
  287. final imageProvider = Image.memory(thumbnail).image;
  288. _cacheAndRender(imageProvider);
  289. }
  290. } catch (e) {
  291. if (e is RequestCancelledError) {
  292. if (mounted) {
  293. _logger.info(
  294. "Thumbnail request was aborted although it is in view, will retry",
  295. );
  296. _reset();
  297. setState(() {});
  298. }
  299. } else {
  300. _logger.severe("Could not load image " + widget.file.toString(), e);
  301. _errorLoadingRemoteThumbnail = true;
  302. }
  303. }
  304. }
  305. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  306. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  307. _logger.info("Clearing image cache");
  308. imageCache.clear();
  309. imageCache.clearLiveImages();
  310. }
  311. precacheImage(imageProvider, context).then((value) {
  312. if (mounted) {
  313. setState(() {
  314. _imageProvider = imageProvider;
  315. _hasLoadedThumbnail = true;
  316. });
  317. }
  318. });
  319. }
  320. void _reset() {
  321. _hasLoadedThumbnail = false;
  322. _isLoadingLocalThumbnail = false;
  323. _isLoadingRemoteThumbnail = false;
  324. _errorLoadingLocalThumbnail = false;
  325. _errorLoadingRemoteThumbnail = false;
  326. _imageProvider = null;
  327. }
  328. }