thumbnail_widget.dart 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // @dart=2.9
  2. import 'package:flutter/material.dart';
  3. import 'package:logging/logging.dart';
  4. import 'package:photos/core/cache/thumbnail_cache.dart';
  5. import 'package:photos/core/constants.dart';
  6. import 'package:photos/core/errors.dart';
  7. import 'package:photos/core/event_bus.dart';
  8. import 'package:photos/db/files_db.dart';
  9. import 'package:photos/db/trash_db.dart';
  10. import 'package:photos/events/files_updated_event.dart';
  11. import 'package:photos/events/local_photos_updated_event.dart';
  12. import 'package:photos/models/file.dart';
  13. import 'package:photos/models/file_type.dart';
  14. import 'package:photos/models/trash_file.dart';
  15. import 'package:photos/ui/viewer/file/file_icons_widget.dart';
  16. import 'package:photos/utils/file_util.dart';
  17. import 'package:photos/utils/thumbnail_util.dart';
  18. class ThumbnailWidget extends StatefulWidget {
  19. final File file;
  20. final BoxFit fit;
  21. final bool shouldShowSyncStatus;
  22. final bool shouldShowArchiveStatus;
  23. final bool shouldShowLivePhotoOverlay;
  24. final Duration diskLoadDeferDuration;
  25. final Duration serverLoadDeferDuration;
  26. ThumbnailWidget(
  27. this.file, {
  28. Key key,
  29. this.fit = BoxFit.cover,
  30. this.shouldShowSyncStatus = true,
  31. this.shouldShowLivePhotoOverlay = false,
  32. this.shouldShowArchiveStatus = false,
  33. this.diskLoadDeferDuration,
  34. this.serverLoadDeferDuration,
  35. }) : super(key: key ?? Key(file.tag()));
  36. @override
  37. State<ThumbnailWidget> createState() => _ThumbnailWidgetState();
  38. }
  39. class _ThumbnailWidgetState extends State<ThumbnailWidget> {
  40. static final _logger = Logger("ThumbnailWidget");
  41. bool _hasLoadedThumbnail = false;
  42. bool _isLoadingLocalThumbnail = false;
  43. bool _errorLoadingLocalThumbnail = false;
  44. bool _isLoadingRemoteThumbnail = false;
  45. bool _errorLoadingRemoteThumbnail = false;
  46. ImageProvider _imageProvider;
  47. @override
  48. void initState() {
  49. super.initState();
  50. }
  51. @override
  52. void dispose() {
  53. super.dispose();
  54. Future.delayed(const Duration(milliseconds: 10), () {
  55. // Cancel request only if the widget has been unmounted
  56. if (!mounted && widget.file.isRemoteFile() && !_hasLoadedThumbnail) {
  57. removePendingGetThumbnailRequestIfAny(widget.file);
  58. }
  59. });
  60. }
  61. @override
  62. void didUpdateWidget(ThumbnailWidget oldWidget) {
  63. super.didUpdateWidget(oldWidget);
  64. if (widget.file.generatedID != oldWidget.file.generatedID) {
  65. _reset();
  66. }
  67. }
  68. @override
  69. Widget build(BuildContext context) {
  70. if (widget.file.isRemoteFile()) {
  71. _loadNetworkImage();
  72. } else {
  73. _loadLocalImage(context);
  74. }
  75. Widget image;
  76. if (_imageProvider != null) {
  77. image = Image(
  78. image: _imageProvider,
  79. fit: widget.fit,
  80. );
  81. }
  82. // todo: [2ndJuly22] pref-review if the content Widget which depends on
  83. // thumbnail fetch logic should be part of separate stateFull widget.
  84. // If yes, parent thumbnail widget can be stateless
  85. Widget content;
  86. if (image != null) {
  87. final List<Widget> contentChildren = [image];
  88. if (widget.file.fileType == FileType.video) {
  89. contentChildren.add(const VideoOverlayIcon());
  90. } else if (widget.file.fileType == FileType.livePhoto &&
  91. widget.shouldShowLivePhotoOverlay) {
  92. contentChildren.add(const LivePhotoOverlayIcon());
  93. }
  94. content = contentChildren.length == 1
  95. ? contentChildren.first
  96. : Stack(
  97. fit: StackFit.expand,
  98. children: contentChildren,
  99. );
  100. }
  101. final List<Widget> viewChildren = [
  102. const ThumbnailPlaceHolder(),
  103. AnimatedOpacity(
  104. opacity: content == null ? 0 : 1.0,
  105. duration: const Duration(milliseconds: 200),
  106. child: content,
  107. )
  108. ];
  109. if (widget.shouldShowSyncStatus && widget.file.uploadedFileID == null) {
  110. viewChildren.add(const UnSyncedIcon());
  111. }
  112. if (widget.file is TrashFile) {
  113. viewChildren.add(TrashedFileOverlayText(widget.file));
  114. }
  115. // todo: Move this icon overlay to the collection widget.
  116. if (widget.shouldShowArchiveStatus) {
  117. viewChildren.add(const ArchiveOverlayIcon());
  118. }
  119. return Stack(
  120. fit: StackFit.expand,
  121. children: viewChildren,
  122. );
  123. }
  124. void _loadLocalImage(BuildContext context) {
  125. if (!_hasLoadedThumbnail &&
  126. !_errorLoadingLocalThumbnail &&
  127. !_isLoadingLocalThumbnail) {
  128. _isLoadingLocalThumbnail = true;
  129. final cachedSmallThumbnail =
  130. ThumbnailLruCache.get(widget.file, thumbnailSmallSize);
  131. if (cachedSmallThumbnail != null) {
  132. _imageProvider = Image.memory(cachedSmallThumbnail).image;
  133. _hasLoadedThumbnail = true;
  134. } else {
  135. if (widget.diskLoadDeferDuration != null) {
  136. Future.delayed(widget.diskLoadDeferDuration, () {
  137. if (mounted) {
  138. _getThumbnailFromDisk();
  139. }
  140. });
  141. } else {
  142. _getThumbnailFromDisk();
  143. }
  144. }
  145. }
  146. }
  147. Future _getThumbnailFromDisk() async {
  148. getThumbnailFromLocal(widget.file).then((thumbData) async {
  149. if (thumbData == null) {
  150. if (widget.file.uploadedFileID != null) {
  151. _logger.fine("Removing localID reference for " + widget.file.tag());
  152. widget.file.localID = null;
  153. if (widget.file is TrashFile) {
  154. TrashDB.instance.update(widget.file);
  155. } else {
  156. FilesDB.instance.update(widget.file);
  157. }
  158. _loadNetworkImage();
  159. } else {
  160. if (await doesLocalFileExist(widget.file) == false) {
  161. _logger.info("Deleting file " + widget.file.tag());
  162. FilesDB.instance.deleteLocalFile(widget.file);
  163. Bus.instance.fire(
  164. LocalPhotosUpdatedEvent(
  165. [widget.file],
  166. type: EventType.deletedFromDevice,
  167. ),
  168. );
  169. }
  170. }
  171. return;
  172. }
  173. if (thumbData != null && mounted) {
  174. final imageProvider = Image.memory(thumbData).image;
  175. _cacheAndRender(imageProvider);
  176. }
  177. ThumbnailLruCache.put(widget.file, thumbData, thumbnailSmallSize);
  178. }).catchError((e) {
  179. _logger.warning("Could not load image: ", e);
  180. _errorLoadingLocalThumbnail = true;
  181. });
  182. }
  183. void _loadNetworkImage() {
  184. if (!_hasLoadedThumbnail &&
  185. !_errorLoadingRemoteThumbnail &&
  186. !_isLoadingRemoteThumbnail) {
  187. _isLoadingRemoteThumbnail = true;
  188. final cachedThumbnail = ThumbnailLruCache.get(widget.file);
  189. if (cachedThumbnail != null) {
  190. _imageProvider = Image.memory(cachedThumbnail).image;
  191. _hasLoadedThumbnail = true;
  192. return;
  193. }
  194. if (widget.serverLoadDeferDuration != null) {
  195. Future.delayed(widget.serverLoadDeferDuration, () {
  196. if (mounted) {
  197. _getThumbnailFromServer();
  198. }
  199. });
  200. } else {
  201. _getThumbnailFromServer();
  202. }
  203. }
  204. }
  205. void _getThumbnailFromServer() async {
  206. try {
  207. final thumbnail = await getThumbnailFromServer(widget.file);
  208. if (mounted) {
  209. final imageProvider = Image.memory(thumbnail).image;
  210. _cacheAndRender(imageProvider);
  211. }
  212. } catch (e) {
  213. if (e is RequestCancelledError) {
  214. if (mounted) {
  215. _logger.info(
  216. "Thumbnail request was aborted although it is in view, will retry",
  217. );
  218. _reset();
  219. setState(() {});
  220. }
  221. } else {
  222. _logger.severe("Could not load image " + widget.file.toString(), e);
  223. _errorLoadingRemoteThumbnail = true;
  224. }
  225. }
  226. }
  227. void _cacheAndRender(ImageProvider<Object> imageProvider) {
  228. if (imageCache.currentSizeBytes > 256 * 1024 * 1024) {
  229. _logger.info("Clearing image cache");
  230. imageCache.clear();
  231. imageCache.clearLiveImages();
  232. }
  233. precacheImage(imageProvider, context).then((value) {
  234. if (mounted) {
  235. setState(() {
  236. _imageProvider = imageProvider;
  237. _hasLoadedThumbnail = true;
  238. });
  239. }
  240. });
  241. }
  242. void _reset() {
  243. _hasLoadedThumbnail = false;
  244. _isLoadingLocalThumbnail = false;
  245. _isLoadingRemoteThumbnail = false;
  246. _errorLoadingLocalThumbnail = false;
  247. _errorLoadingRemoteThumbnail = false;
  248. _imageProvider = null;
  249. }
  250. }