trim method
Called between paints with the entire viewport's required URI set.
Borrowed handles must not escape the paint turn. Drop dependent pictures
through beforeRelease before the selected cache handles are disposed.
Implementation
void trim({
required Set<String> retaining,
required void Function(Set<String>) beforeRelease,
}) {
if (_disposed) return;
for (final key in retaining) {
if (_images.containsKey(key)) _lastUsed[key] = ++_accessClock;
}
if (_decodedPixelBytes <= retentionBytes) return;
final candidates =
_images.keys.where((key) => !retaining.contains(key)).toList()
..sort((a, b) => (_lastUsed[a] ?? 0).compareTo(_lastUsed[b] ?? 0));
var remaining = _decodedPixelBytes;
final victims = <String, ImageInfo>{};
for (final key in candidates) {
if (remaining <= retentionBytes) break;
final info = _images[key]!;
victims[key] = info;
remaining -= _imageBytes(info);
}
if (victims.isEmpty) return;
beforeRelease(Set.unmodifiable(victims.keys));
for (final entry in victims.entries) {
final key = entry.key;
// Cleanup can release and reload the same URI. Its new resource was not
// part of this eviction decision or the dependent-picture cleanup.
if (!identical(_images[key], entry.value)) continue;
final info = _images.remove(key);
if (info == null) continue;
_lastUsed.remove(key);
_decodedPixelBytes -= _imageBytes(info);
info.dispose();
_changed(key);
}
}