thumbnail_widget.dart 11 KB

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