import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import '../data/directory_listing.dart'; import 'files_icons.dart'; import 'files_thumbnail_image.dart'; import 'files_preview.dart'; import 'files_urls.dart'; /// The logical size of a grid thumbnail. const double filesThumbnailSize = 56; /// The largest decode scale a thumbnail is allowed, so a 4x display still /// decodes a 56 dp tile to at most 224 px per side. const double filesThumbnailMaxScale = 4; /// The pixel edge a thumbnail decodes to: the tile size at the display's pixel /// ratio, bounded. The shared [PaintingBinding.imageCache] then holds a few /// hundred KiB at most per image instead of a full-size decode. int filesThumbnailDecodeSize(double devicePixelRatio) => (filesThumbnailSize * devicePixelRatio.clamp(1, filesThumbnailMaxScale)) .round(); /// A grid tile's picture: an image file's own bytes from the files endpoint, /// decoded at tile size, with the kind glyph while loading and when the fetch /// or decode fails. Non-image files show the kind glyph. class FileThumbnail extends StatefulWidget { const FileThumbnail({super.key, required this.entry, required this.endpoint}); final DirectoryEntry entry; final String endpoint; @override State createState() => _FileThumbnailState(); } class _FileThumbnailState extends State { ImageProvider? _provider; ImageProvider? _source; int? _decode; // Keep the shared image cache unchanged. Scrolled-out thumbnails release // their decoded cache entry, bounding retention to the lazily built tiles. @override void dispose() { _provider?.evict(); super.dispose(); } @override Widget build(BuildContext context) { final entry = widget.entry; final endpoint = widget.endpoint; final icon = Icon(fileIcon(entry), size: 32); if (entry.isDir || !isThumbnailFile(entry.name)) return icon; final urls = resolveFileUrls(endpoint, entry.path); if (urls == null) return icon; final decode = filesThumbnailDecodeSize( MediaQuery.devicePixelRatioOf(context), ); final ImageProvider source = kIsWeb ? NetworkImage(urls.view.toString()) : FileThumbnailImage(urls.view); if (_source != source || _decode != decode) { _provider?.evict(); _source = source; _decode = decode; _provider = ResizeImage.resizeIfNeeded(decode, decode, source); } final scheme = Theme.of(context).colorScheme; final placeholder = Container( width: filesThumbnailSize, height: filesThumbnailSize, alignment: Alignment.center, decoration: BoxDecoration( color: scheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(6), ), child: icon, ); return ClipRRect( borderRadius: BorderRadius.circular(6), child: Image( image: _provider!, width: filesThumbnailSize, height: filesThumbnailSize, fit: BoxFit.cover, semanticLabel: entry.name, frameBuilder: kIsWeb ? null : (_, child, frame, _) => frame == null ? placeholder : child, loadingBuilder: (_, child, progress) => progress == null ? child : placeholder, errorBuilder: (_, _, _) => icon, ), ); } }