image_cache.dart 23.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Dan Field's avatar
Dan Field committed
5
import 'dart:developer';
Dan Field's avatar
Dan Field committed
6
import 'dart:ui' show hashValues;
Dan Field's avatar
Dan Field committed
7 8

import 'package:flutter/foundation.dart';
9
import 'package:flutter/scheduler.dart';
Dan Field's avatar
Dan Field committed
10

11
import 'image_stream.dart';
12

13
const int _kDefaultSize = 1000;
14
const int _kDefaultSizeBytes = 100 << 20; // 100 MiB
15

16
/// Class for caching images.
17
///
18 19
/// Implements a least-recently-used cache of up to 1000 images, and up to 100
/// MB. The maximum size can be adjusted using [maximumSize] and
Dan Field's avatar
Dan Field committed
20 21
/// [maximumSizeBytes].
///
22
/// The cache also holds a list of 'live' references. An image is considered
Dan Field's avatar
Dan Field committed
23 24 25 26
/// live if its [ImageStreamCompleter]'s listener count has never dropped to
/// zero after adding at least one listener. The cache uses
/// [ImageStreamCompleter.addOnLastListenerRemovedCallback] to determine when
/// this has happened.
27
///
28 29 30
/// The [putIfAbsent] method is the main entry-point to the cache API. It
/// returns the previously cached [ImageStreamCompleter] for the given key, if
/// available; if not, it calls the given callback to obtain it first. In either
31
/// case, the key is moved to the 'most recently used' position.
32
///
Dan Field's avatar
Dan Field committed
33 34
/// A caller can determine whether an image is already in the cache by using
/// [containsKey], which will return true if the image is tracked by the cache
35
/// in a pending or completed state. More fine grained information is available
Dan Field's avatar
Dan Field committed
36 37
/// by using the [statusForKey] method.
///
38 39
/// Generally this class is not used directly. The [ImageProvider] class and its
/// subclasses automatically handle the caching of images.
40 41 42
///
/// A shared instance of this cache is retained by [PaintingBinding] and can be
/// obtained via the [imageCache] top-level property in the [painting] library.
43
///
44
/// {@tool snippet}
45 46
///
/// This sample shows how to supply your own caching logic and replace the
Dan Field's avatar
Dan Field committed
47
/// global [imageCache] variable.
48 49 50 51 52 53 54
///
/// ```dart
/// /// This is the custom implementation of [ImageCache] where we can override
/// /// the logic.
/// class MyImageCache extends ImageCache {
///   @override
///   void clear() {
55
///     print('Clearing cache!');
56 57 58 59 60 61 62 63 64 65 66 67
///     super.clear();
///   }
/// }
///
/// class MyWidgetsBinding extends WidgetsFlutterBinding {
///   @override
///   ImageCache createImageCache() => MyImageCache();
/// }
///
/// void main() {
///   // The constructor sets global variables.
///   MyWidgetsBinding();
68
///   runApp(const MyApp());
69 70 71
/// }
///
/// class MyApp extends StatelessWidget {
72 73
///   const MyApp({Key? key}) : super(key: key);
///
74 75 76 77 78 79 80
///   @override
///   Widget build(BuildContext context) {
///     return Container();
///   }
/// }
/// ```
/// {@end-tool}
81
class ImageCache {
82
  final Map<Object, _PendingImage> _pendingImages = <Object, _PendingImage>{};
83
  final Map<Object, _CachedImage> _cache = <Object, _CachedImage>{};
Dan Field's avatar
Dan Field committed
84 85 86 87
  /// ImageStreamCompleters with at least one listener. These images may or may
  /// not fit into the _pendingImages or _cache objects.
  ///
  /// Unlike _cache, the [_CachedImage] for this may have a null byte size.
88
  final Map<Object, _LiveImage> _liveImages = <Object, _LiveImage>{};
89

90 91 92 93
  /// Maximum number of entries to store in the cache.
  ///
  /// Once this many entries have been cached, the least-recently-used entry is
  /// evicted when adding a new entry.
94 95
  int get maximumSize => _maximumSize;
  int _maximumSize = _kDefaultSize;
96 97 98 99 100
  /// Changes the maximum cache size.
  ///
  /// If the new size is smaller than the current number of elements, the
  /// extraneous elements are evicted immediately. Setting this to zero and then
  /// returning it to its original value will therefore immediately clear the
101
  /// cache.
102
  set maximumSize(int value) {
103 104 105 106
    assert(value != null);
    assert(value >= 0);
    if (value == maximumSize)
      return;
107
    TimelineTask? timelineTask;
Dan Field's avatar
Dan Field committed
108
    if (!kReleaseMode) {
109
      timelineTask = TimelineTask()..start(
Dan Field's avatar
Dan Field committed
110 111 112 113
        'ImageCache.setMaximumSize',
        arguments: <String, dynamic>{'value': value},
      );
    }
114 115
    _maximumSize = value;
    if (maximumSize == 0) {
116
      clear();
117
    } else {
Dan Field's avatar
Dan Field committed
118 119 120
      _checkCacheSize(timelineTask);
    }
    if (!kReleaseMode) {
121
      timelineTask!.finish();
122 123
    }
  }
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  /// The current number of cached entries.
  int get currentSize => _cache.length;

  /// Maximum size of entries to store in the cache in bytes.
  ///
  /// Once more than this amount of bytes have been cached, the
  /// least-recently-used entry is evicted until there are fewer than the
  /// maximum bytes.
  int get maximumSizeBytes => _maximumSizeBytes;
  int _maximumSizeBytes = _kDefaultSizeBytes;
  /// Changes the maximum cache bytes.
  ///
  /// If the new size is smaller than the current size in bytes, the
  /// extraneous elements are evicted immediately. Setting this to zero and then
  /// returning it to its original value will therefore immediately clear the
  /// cache.
  set maximumSizeBytes(int value) {
    assert(value != null);
    assert(value >= 0);
    if (value == _maximumSizeBytes)
      return;
146
    TimelineTask? timelineTask;
Dan Field's avatar
Dan Field committed
147 148 149 150 151 152
    if (!kReleaseMode) {
      timelineTask = TimelineTask()..start(
        'ImageCache.setMaximumSizeBytes',
        arguments: <String, dynamic>{'value': value},
      );
    }
153 154
    _maximumSizeBytes = value;
    if (_maximumSizeBytes == 0) {
155
      clear();
156
    } else {
Dan Field's avatar
Dan Field committed
157 158 159
      _checkCacheSize(timelineTask);
    }
    if (!kReleaseMode) {
160
      timelineTask!.finish();
161 162 163 164 165 166 167
    }
  }

  /// The current size of cached entries in bytes.
  int get currentSizeBytes => _currentSizeBytes;
  int _currentSizeBytes = 0;

Dan Field's avatar
Dan Field committed
168
  /// Evicts all pending and keepAlive entries from the cache.
169 170 171
  ///
  /// This is useful if, for instance, the root asset bundle has been updated
  /// and therefore new images must be obtained.
172 173 174
  ///
  /// Images which have not finished loading yet will not be removed from the
  /// cache, and when they complete they will be inserted as normal.
Dan Field's avatar
Dan Field committed
175 176 177 178 179 180
  ///
  /// This method does not clear live references to images, since clearing those
  /// would not reduce memory pressure. Such images still have listeners in the
  /// application code, and will still remain resident in memory.
  ///
  /// To clear live references, use [clearLiveImages].
181
  void clear() {
Dan Field's avatar
Dan Field committed
182 183 184 185 186
    if (!kReleaseMode) {
      Timeline.instantSync(
        'ImageCache.clear',
        arguments: <String, dynamic>{
          'pendingImages': _pendingImages.length,
Dan Field's avatar
Dan Field committed
187 188
          'keepAliveImages': _cache.length,
          'liveImages': _liveImages.length,
Dan Field's avatar
Dan Field committed
189 190 191 192
          'currentSizeInBytes': _currentSizeBytes,
        },
      );
    }
193 194 195
    for (final _CachedImage image in _cache.values) {
      image.dispose();
    }
196
    _cache.clear();
197
    _pendingImages.clear();
198 199 200 201
    _currentSizeBytes = 0;
  }

  /// Evicts a single entry from the cache, returning true if successful.
Dan Field's avatar
Dan Field committed
202
  ///
Dan Field's avatar
Dan Field committed
203
  /// Pending images waiting for completion are removed as well, returning true
Dan Field's avatar
Dan Field committed
204 205 206
  /// if successful. When a pending image is removed the listener on it is
  /// removed as well to prevent it from adding itself to the cache if it
  /// eventually completes.
207
  ///
Dan Field's avatar
Dan Field committed
208 209 210 211 212 213 214 215 216 217 218
  /// If this method removes a pending image, it will also remove
  /// the corresponding live tracking of the image, since it is no longer clear
  /// if the image will ever complete or have any listeners, and failing to
  /// remove the live reference could leave the cache in a state where all
  /// subsequent calls to [putIfAbsent] will return an [ImageStreamCompleter]
  /// that will never complete.
  ///
  /// If this method removes a completed image, it will _not_ remove the live
  /// reference to the image, which will only be cleared when the listener
  /// count on the completer drops to zero. To clear live image references,
  /// whether completed or not, use [clearLiveImages].
219
  ///
Dan Field's avatar
Dan Field committed
220
  /// The `key` must be equal to an object used to cache an image in
221 222 223 224 225
  /// [ImageCache.putIfAbsent].
  ///
  /// If the key is not immediately available, as is common, consider using
  /// [ImageProvider.evict] to call this method indirectly instead.
  ///
Dan Field's avatar
Dan Field committed
226 227 228 229 230 231 232 233 234
  /// The `includeLive` argument determines whether images that still have
  /// listeners in the tree should be evicted as well. This parameter should be
  /// set to true in cases where the image may be corrupted and needs to be
  /// completely discarded by the cache. It should be set to false when calls
  /// to evict are trying to relieve memory pressure, since an image with a
  /// listener will not actually be evicted from memory, and subsequent attempts
  /// to load it will end up allocating more memory for the image again. The
  /// argument must not be null.
  ///
235 236
  /// See also:
  ///
237
  ///  * [ImageProvider], for providing images to the [Image] widget.
Dan Field's avatar
Dan Field committed
238 239 240 241 242 243 244 245
  bool evict(Object key, { bool includeLive = true }) {
    assert(includeLive != null);
    if (includeLive) {
      // Remove from live images - the cache will not be able to mark
      // it as complete, and it might be getting evicted because it
      // will never complete, e.g. it was loaded in a FakeAsync zone.
      // In such a case, we need to make sure subsequent calls to
      // putIfAbsent don't return this image that may never complete.
246
      final _LiveImage? image = _liveImages.remove(key);
247
      image?.dispose();
Dan Field's avatar
Dan Field committed
248
    }
249
    final _PendingImage? pendingImage = _pendingImages.remove(key);
250
    if (pendingImage != null) {
Dan Field's avatar
Dan Field committed
251 252
      if (!kReleaseMode) {
        Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{
253
          'type': 'pending',
Dan Field's avatar
Dan Field committed
254 255
        });
      }
256 257 258
      pendingImage.removeListener();
      return true;
    }
259
    final _CachedImage? image = _cache.remove(key);
260
    if (image != null) {
Dan Field's avatar
Dan Field committed
261 262
      if (!kReleaseMode) {
        Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{
Dan Field's avatar
Dan Field committed
263
          'type': 'keepAlive',
264
          'sizeInBytes': image.sizeBytes,
Dan Field's avatar
Dan Field committed
265 266
        });
      }
267
      _currentSizeBytes -= image.sizeBytes!;
268
      image.dispose();
269 270
      return true;
    }
Dan Field's avatar
Dan Field committed
271 272 273 274 275
    if (!kReleaseMode) {
      Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{
        'type': 'miss',
      });
    }
276
    return false;
277 278
  }

Dan Field's avatar
Dan Field committed
279 280 281 282 283
  /// Updates the least recently used image cache with this image, if it is
  /// less than the [maximumSizeBytes] of this cache.
  ///
  /// Resizes the cache as appropriate to maintain the constraints of
  /// [maximumSize] and [maximumSizeBytes].
284
  void _touch(Object key, _CachedImage image, TimelineTask? timelineTask) {
285
    assert(timelineTask != null);
286
    if (image.sizeBytes != null && image.sizeBytes! <= maximumSizeBytes && maximumSize > 0) {
287
      _currentSizeBytes += image.sizeBytes!;
Dan Field's avatar
Dan Field committed
288 289
      _cache[key] = image;
      _checkCacheSize(timelineTask);
290 291
    } else {
      image.dispose();
Dan Field's avatar
Dan Field committed
292 293 294
    }
  }

295
  void _trackLiveImage(Object key, ImageStreamCompleter completer, int? sizeBytes) {
Dan Field's avatar
Dan Field committed
296 297 298 299 300
    // Avoid adding unnecessary callbacks to the completer.
    _liveImages.putIfAbsent(key, () {
      // Even if no callers to ImageProvider.resolve have listened to the stream,
      // the cache is listening to the stream and will remove itself once the
      // image completes to move it from pending to keepAlive.
301 302 303 304 305 306 307 308 309
      // Even if the cache size is 0, we still add this tracker, which will add
      // a keep alive handle to the stream.
      return _LiveImage(
        completer,
        () {
          _liveImages.remove(key);
        },
      );
    }).sizeBytes ??= sizeBytes;
Dan Field's avatar
Dan Field committed
310 311
  }

312 313
  /// Returns the previously cached [ImageStream] for the given key, if available;
  /// if not, calls the given callback to obtain it first. In either case, the
314
  /// key is moved to the 'most recently used' position.
315
  ///
316
  /// The arguments must not be null. The `loader` cannot return null.
317 318 319 320 321
  ///
  /// In the event that the loader throws an exception, it will be caught only if
  /// `onError` is also provided. When an exception is caught resolving an image,
  /// no completers are cached and `null` is returned instead of a new
  /// completer.
322
  ImageStreamCompleter? putIfAbsent(Object key, ImageStreamCompleter Function() loader, { ImageErrorListener? onError }) {
323 324
    assert(key != null);
    assert(loader != null);
325 326
    TimelineTask? timelineTask;
    TimelineTask? listenerTask;
Dan Field's avatar
Dan Field committed
327 328 329 330 331 332 333 334
    if (!kReleaseMode) {
      timelineTask = TimelineTask()..start(
        'ImageCache.putIfAbsent',
        arguments: <String, dynamic>{
          'key': key.toString(),
        },
      );
    }
335
    ImageStreamCompleter? result = _pendingImages[key]?.completer;
336
    // Nothing needs to be done because the image hasn't loaded yet.
Dan Field's avatar
Dan Field committed
337 338
    if (result != null) {
      if (!kReleaseMode) {
339
        timelineTask!.finish(arguments: <String, dynamic>{'result': 'pending'});
Dan Field's avatar
Dan Field committed
340
      }
341
      return result;
Dan Field's avatar
Dan Field committed
342
    }
343 344
    // Remove the provider from the list so that we can move it to the
    // recently used position below.
Dan Field's avatar
Dan Field committed
345 346
    // Don't use _touch here, which would trigger a check on cache size that is
    // not needed since this is just moving an existing cache entry to the head.
347
    final _CachedImage? image = _cache.remove(key);
348
    if (image != null) {
Dan Field's avatar
Dan Field committed
349
      if (!kReleaseMode) {
350
        timelineTask!.finish(arguments: <String, dynamic>{'result': 'keepAlive'});
Dan Field's avatar
Dan Field committed
351
      }
Dan Field's avatar
Dan Field committed
352 353
      // The image might have been keptAlive but had no listeners (so not live).
      // Make sure the cache starts tracking it as live again.
354 355 356 357 358
      _trackLiveImage(
        key,
        image.completer,
        image.sizeBytes,
      );
359 360
      _cache[key] = image;
      return image.completer;
361
    }
Dan Field's avatar
Dan Field committed
362

363
    final _LiveImage? liveImage = _liveImages[key];
Dan Field's avatar
Dan Field committed
364
    if (liveImage != null) {
365 366 367 368 369 370 371 372
      _touch(
        key,
        _CachedImage(
          liveImage.completer,
          sizeBytes: liveImage.sizeBytes,
        ),
        timelineTask,
      );
Dan Field's avatar
Dan Field committed
373
      if (!kReleaseMode) {
374
        timelineTask!.finish(arguments: <String, dynamic>{'result': 'keepAlive'});
Dan Field's avatar
Dan Field committed
375 376 377 378
      }
      return liveImage.completer;
    }

379 380
    try {
      result = loader();
381
      _trackLiveImage(key, result, null);
382
    } catch (error, stackTrace) {
Dan Field's avatar
Dan Field committed
383
      if (!kReleaseMode) {
384
        timelineTask!.finish(arguments: <String, dynamic>{
Dan Field's avatar
Dan Field committed
385 386 387 388 389
          'result': 'error',
          'error': error.toString(),
          'stackTrace': stackTrace.toString(),
        });
      }
390 391 392 393 394 395 396
      if (onError != null) {
        onError(error, stackTrace);
        return null;
      } else {
        rethrow;
      }
    }
Dan Field's avatar
Dan Field committed
397 398 399 400

    if (!kReleaseMode) {
      listenerTask = TimelineTask(parent: timelineTask)..start('listener');
    }
Dan Field's avatar
Dan Field committed
401 402 403
    // If we're doing tracing, we need to make sure that we don't try to finish
    // the trace entry multiple times if we get re-entrant calls from a multi-
    // frame provider here.
Dan Field's avatar
Dan Field committed
404
    bool listenedOnce = false;
Dan Field's avatar
Dan Field committed
405 406 407 408 409

    // We shouldn't use the _pendingImages map if the cache is disabled, but we
    // will have to listen to the image at least once so we don't leak it in
    // the live image tracking.
    // If the cache is disabled, this variable will be set.
410 411
    _PendingImage? untrackedPendingImage;
    void listener(ImageInfo? info, bool syncCall) {
412 413
      int? sizeBytes;
      if (info != null) {
414
        sizeBytes = info.sizeBytes;
415 416 417 418 419
        info.dispose();
      }
      final _CachedImage image = _CachedImage(
        result!,
        sizeBytes: sizeBytes,
420
      );
Dan Field's avatar
Dan Field committed
421

422 423
      _trackLiveImage(key, result, sizeBytes);

424 425 426
      // Only touch if the cache was enabled when resolve was initially called.
      if (untrackedPendingImage == null) {
        _touch(key, image, listenerTask);
427 428
      } else {
        image.dispose();
429 430
      }

431 432 433 434
      final _PendingImage? pendingImage = untrackedPendingImage ?? _pendingImages.remove(key);
      if (pendingImage != null) {
        pendingImage.removeListener();
      }
Dan Field's avatar
Dan Field committed
435
      if (!kReleaseMode && !listenedOnce) {
436
        listenerTask!.finish(arguments: <String, dynamic>{
Dan Field's avatar
Dan Field committed
437
          'syncCall': syncCall,
438
          'sizeInBytes': sizeBytes,
Dan Field's avatar
Dan Field committed
439
        });
440
        timelineTask!.finish(arguments: <String, dynamic>{
Dan Field's avatar
Dan Field committed
441 442 443
          'currentSizeBytes': currentSizeBytes,
          'currentSize': currentSize,
        });
444
      }
Dan Field's avatar
Dan Field committed
445
      listenedOnce = true;
446
    }
Dan Field's avatar
Dan Field committed
447 448

    final ImageStreamListener streamListener = ImageStreamListener(listener);
449
    if (maximumSize > 0 && maximumSizeBytes > 0) {
450
      _pendingImages[key] = _PendingImage(result, streamListener);
Dan Field's avatar
Dan Field committed
451 452
    } else {
      untrackedPendingImage = _PendingImage(result, streamListener);
453
    }
Dan Field's avatar
Dan Field committed
454 455 456
    // Listener is removed in [_PendingImage.removeListener].
    result.addListener(streamListener);

457
    return result;
458
  }
459

Dan Field's avatar
Dan Field committed
460 461 462 463 464 465 466 467 468
  /// The [ImageCacheStatus] information for the given `key`.
  ImageCacheStatus statusForKey(Object key) {
    return ImageCacheStatus._(
      pending: _pendingImages.containsKey(key),
      keepAlive: _cache.containsKey(key),
      live: _liveImages.containsKey(key),
    );
  }

469 470 471 472 473
  /// Returns whether this `key` has been previously added by [putIfAbsent].
  bool containsKey(Object key) {
    return _pendingImages[key] != null || _cache[key] != null;
  }

Dan Field's avatar
Dan Field committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
  /// The number of live images being held by the [ImageCache].
  ///
  /// Compare with [ImageCache.currentSize] for keepAlive images.
  int get liveImageCount => _liveImages.length;

  /// The number of images being tracked as pending in the [ImageCache].
  ///
  /// Compare with [ImageCache.currentSize] for keepAlive images.
  int get pendingImageCount => _pendingImages.length;

  /// Clears any live references to images in this cache.
  ///
  /// An image is considered live if its [ImageStreamCompleter] has never hit
  /// zero listeners after adding at least one listener. The
  /// [ImageStreamCompleter.addOnLastListenerRemovedCallback] is used to
  /// determine when this has happened.
  ///
  /// This is called after a hot reload to evict any stale references to image
  /// data for assets that have changed. Calling this method does not relieve
  /// memory pressure, since the live image caching only tracks image instances
  /// that are also being held by at least one other object.
  void clearLiveImages() {
496
    for (final _LiveImage image in _liveImages.values) {
497
      image.dispose();
498
    }
Dan Field's avatar
Dan Field committed
499 500 501
    _liveImages.clear();
  }

502 503
  // Remove images from the cache until both the length and bytes are below
  // maximum, or the cache is empty.
504
  void _checkCacheSize(TimelineTask? timelineTask) {
Dan Field's avatar
Dan Field committed
505
    final Map<String, dynamic> finishArgs = <String, dynamic>{};
506
    TimelineTask? checkCacheTask;
Dan Field's avatar
Dan Field committed
507 508 509 510 511 512
    if (!kReleaseMode) {
      checkCacheTask = TimelineTask(parent: timelineTask)..start('checkCacheSize');
      finishArgs['evictedKeys'] = <String>[];
      finishArgs['currentSize'] = currentSize;
      finishArgs['currentSizeBytes'] = currentSizeBytes;
    }
513 514
    while (_currentSizeBytes > _maximumSizeBytes || _cache.length > _maximumSize) {
      final Object key = _cache.keys.first;
515 516
      final _CachedImage image = _cache[key]!;
      _currentSizeBytes -= image.sizeBytes!;
517
      image.dispose();
518
      _cache.remove(key);
Dan Field's avatar
Dan Field committed
519
      if (!kReleaseMode) {
520
        (finishArgs['evictedKeys'] as List<String>).add(key.toString());
Dan Field's avatar
Dan Field committed
521 522 523 524 525
      }
    }
    if (!kReleaseMode) {
      finishArgs['endSize'] = currentSize;
      finishArgs['endSizeBytes'] = currentSizeBytes;
526
      checkCacheTask!.finish(arguments: finishArgs);
527 528 529 530 531 532 533
    }
    assert(_currentSizeBytes >= 0);
    assert(_cache.length <= maximumSize);
    assert(_currentSizeBytes <= maximumSizeBytes);
  }
}

Dan Field's avatar
Dan Field committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
/// Information about how the [ImageCache] is tracking an image.
///
/// A [pending] image is one that has not completed yet. It may also be tracked
/// as [live] because something is listening to it.
///
/// A [keepAlive] image is being held in the cache, which uses Least Recently
/// Used semantics to determine when to evict an image. These images are subject
/// to eviction based on [ImageCache.maximumSizeBytes] and
/// [ImageCache.maximumSize]. It may be [live], but not [pending].
///
/// A [live] image is being held until its [ImageStreamCompleter] has no more
/// listeners. It may also be [pending] or [keepAlive].
///
/// An [untracked] image is not being cached.
///
/// To obtain an [ImageCacheStatus], use [ImageCache.statusForKey] or
/// [ImageProvider.obtainCacheStatus].
551
@immutable
Dan Field's avatar
Dan Field committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
class ImageCacheStatus {
  const ImageCacheStatus._({
    this.pending = false,
    this.keepAlive = false,
    this.live = false,
  }) : assert(!pending || !keepAlive);

  /// An image that has been submitted to [ImageCache.putIfAbsent], but
  /// not yet completed.
  final bool pending;

  /// An image that has been submitted to [ImageCache.putIfAbsent], has
  /// completed, fits based on the sizing rules of the cache, and has not been
  /// evicted.
  ///
  /// Such images will be kept alive even if [live] is false, as long
  /// as they have not been evicted from the cache based on its sizing rules.
  final bool keepAlive;

  /// An image that has been submitted to [ImageCache.putIfAbsent] and has at
  /// least one listener on its [ImageStreamCompleter].
  ///
  /// Such images may also be [keepAlive] if they fit in the cache based on its
  /// sizing rules. They may also be [pending] if they have not yet resolved.
  final bool live;

  /// An image that is tracked in some way by the [ImageCache], whether
  /// [pending], [keepAlive], or [live].
  bool get tracked => pending || keepAlive || live;

  /// An image that either has not been submitted to
  /// [ImageCache.putIfAbsent] or has otherwise been evicted from the
  /// [keepAlive] and [live] caches.
  bool get untracked => !pending && !keepAlive && !live;

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) {
      return false;
    }
    return other is ImageCacheStatus
        && other.pending == pending
        && other.keepAlive == keepAlive
        && other.live == live;
  }

  @override
  int get hashCode => hashValues(pending, keepAlive, live);

  @override
  String toString() => '${objectRuntimeType(this, 'ImageCacheStatus')}(pending: $pending, live: $live, keepAlive: $keepAlive)';
}

605 606 607 608 609 610 611 612 613 614
/// Base class for [_CachedImage] and [_LiveImage].
///
/// Exists primarily so that a [_LiveImage] cannot be added to the
/// [ImageCache._cache].
abstract class _CachedImageBase {
  _CachedImageBase(
    this.completer, {
    this.sizeBytes,
  }) : assert(completer != null),
       handle = completer.keepAlive();
615 616

  final ImageStreamCompleter completer;
617
  int? sizeBytes;
618 619 620 621 622 623 624
  ImageStreamCompleterHandle? handle;

  @mustCallSuper
  void dispose() {
    assert(handle != null);
    // Give any interested parties a chance to listen to the stream before we
    // potentially dispose it.
625
    SchedulerBinding.instance!.addPostFrameCallback((Duration timeStamp) {
626 627 628 629 630
      assert(handle != null);
      handle?.dispose();
      handle = null;
    });
  }
631
}
632

633 634 635 636
class _CachedImage extends _CachedImageBase {
  _CachedImage(ImageStreamCompleter completer, {int? sizeBytes})
      : super(completer, sizeBytes: sizeBytes);
}
637

638 639 640 641 642 643 644 645 646
class _LiveImage extends _CachedImageBase {
  _LiveImage(ImageStreamCompleter completer, VoidCallback handleRemove, {int? sizeBytes})
      : super(completer, sizeBytes: sizeBytes) {
    _handleRemove = () {
      handleRemove();
      dispose();
    };
    completer.addOnLastListenerRemovedCallback(_handleRemove);
  }
647

648 649 650 651 652 653
  late VoidCallback _handleRemove;

  @override
  void dispose() {
    completer.removeOnLastListenerRemovedCallback(_handleRemove);
    super.dispose();
654
  }
655 656 657

  @override
  String toString() => describeIdentity(this);
658
}
659 660 661 662 663

class _PendingImage {
  _PendingImage(this.completer, this.listener);

  final ImageStreamCompleter completer;
664
  final ImageStreamListener listener;
665 666 667 668 669

  void removeListener() {
    completer.removeListener(listener);
  }
}