Skip to main content

waft_painting/
image_stream.rs

1//! Flutter counterpart: `painting/image_stream.dart`.
2//!
3//! An image arrives later than the widget that wants it, so a widget holds a stream and is
4//! called back when a frame is ready. The stream is the listening half and the completer is
5//! the resolving half, exactly as in Dart; a provider hands out the completer and the cache
6//! keeps it, so several widgets showing the same image share one decode.
7//!
8//! Cache retention and listener lifetime follow Flutter; animation playback is composed with
9//! the completer and is disposed through its cleanup hook.
10
11use std::fmt::{self, Debug};
12use std::rc::Rc;
13
14use waft_embedder::{Image, ImageDecodeError};
15use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
16
17/// A decoded image and how to read it. Flutter `ImageInfo`.
18///
19/// The scale is what turns pixels into logical points: an image drawn from a two-times asset
20/// carries a scale of two and paints at half its pixel size, which is what makes the same asset
21/// look right on displays of different densities.
22#[derive(Clone, Debug, PartialEq)]
23pub struct ImageInfo {
24    /// The decoded image itself.
25    pub image: Image,
26    /// Linear pixels per logical point; one means the image draws at its pixel size.
27    pub scale: f64,
28    /// A name for error messages, such as the asset the image came from.
29    pub debug_label: Option<String>,
30}
31
32impl ImageInfo {
33    /// Creates an [`ImageInfo`] at the natural scale.
34    pub fn new(image: Image) -> ImageInfo {
35        ImageInfo {
36            image,
37            scale: 1.0,
38            debug_label: None,
39        }
40    }
41
42    /// Dart `ImageInfo(scale:)`.
43    pub fn scale(mut self, scale: f64) -> ImageInfo {
44        self.scale = scale;
45        self
46    }
47
48    /// Dart `ImageInfo(debugLabel:)`.
49    pub fn debug_label(mut self, label: impl Into<String>) -> ImageInfo {
50        self.debug_label = Some(label.into());
51        self
52    }
53
54    /// How much memory the decoded image occupies, which is what the cache budgets by.
55    pub fn size_bytes(&self) -> usize {
56        let [width, height] = self.image.size();
57        width as usize * height as usize * 4
58    }
59
60    /// The image's size in logical points, which is its pixel size divided by its scale.
61    pub fn size(&self) -> waft_embedder::Size {
62        let [width, height] = self.image.size();
63        waft_embedder::Size::new(
64            f64::from(width) / self.scale,
65            f64::from(height) / self.scale,
66        )
67    }
68}
69
70/// Called when a frame is ready. `synchronous` is true when the image was already there and the
71/// call happened inside `add_listener` rather than later.
72pub type ImageListener = Rc<ImageCallback>;
73
74type ImageCallback = dyn Fn(&mut App, &ImageInfo, bool);
75
76/// Called when an image will never arrive.
77pub type ImageErrorListener = Rc<ImageErrorCallback>;
78
79type ImageErrorCallback = dyn Fn(&mut App, &ImageDecodeError);
80
81/// Called as an image's bytes arrive, before it is whole.
82pub type ImageChunkListener = Rc<ImageChunkCallback>;
83
84type ImageChunkCallback = dyn Fn(&mut App, &ImageChunkEvent);
85
86/// An immutable notification of image bytes that have been incrementally loaded. Flutter
87/// `ImageChunkEvent`.
88///
89/// A provider that reads a body in pieces reports one after each piece, as a network image does
90/// for its bytes over the wire; a file image, as Flutter's, reports none. The expected total is what lets a listener show
91/// how far along the load is; it is not the decoded image's size.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub struct ImageChunkEvent {
94    /// The bytes received so far.
95    pub cumulative_bytes_loaded: usize,
96    /// How many bytes the whole image is expected to take, when the source said.
97    pub expected_total_bytes: Option<usize>,
98}
99
100/// What a caller wants to hear about an image. Flutter `ImageStreamListener`.
101///
102/// Without an error listener a failure is silent here, where Dart's would reach
103/// `FlutterError.onError`; a caller that wants to show something in place of a broken image
104/// supplies one.
105#[derive(Clone)]
106pub struct ImageStreamListener {
107    /// Called for each frame, including one that had already arrived.
108    pub on_image: ImageListener,
109    /// Called as each piece of the image's bytes arrives.
110    pub on_chunk: Option<ImageChunkListener>,
111    /// Called instead when the image failed.
112    pub on_error: Option<ImageErrorListener>,
113}
114
115/// Callback identities without owning them, for a subscription that removes itself.
116pub(crate) struct WeakImageStreamListener {
117    on_image: std::rc::Weak<ImageCallback>,
118    on_chunk: Option<std::rc::Weak<ImageChunkCallback>>,
119    on_error: Option<std::rc::Weak<ImageErrorCallback>>,
120}
121
122impl WeakImageStreamListener {
123    pub(crate) fn upgrade(&self) -> Option<ImageStreamListener> {
124        Some(ImageStreamListener {
125            on_image: self.on_image.upgrade()?,
126            on_chunk: match &self.on_chunk {
127                Some(callback) => Some(callback.upgrade()?),
128                None => None,
129            },
130            on_error: match &self.on_error {
131                Some(callback) => Some(callback.upgrade()?),
132                None => None,
133            },
134        })
135    }
136}
137
138impl ImageStreamListener {
139    pub(crate) fn downgrade(&self) -> WeakImageStreamListener {
140        WeakImageStreamListener {
141            on_image: Rc::downgrade(&self.on_image),
142            on_chunk: self.on_chunk.as_ref().map(Rc::downgrade),
143            on_error: self.on_error.as_ref().map(Rc::downgrade),
144        }
145    }
146
147    /// Creates a listener that only wants the image.
148    pub fn new(on_image: ImageListener) -> ImageStreamListener {
149        ImageStreamListener {
150            on_image,
151            on_chunk: None,
152            on_error: None,
153        }
154    }
155
156    /// Dart `ImageStreamListener(onChunk:)`.
157    pub fn on_chunk(mut self, on_chunk: ImageChunkListener) -> ImageStreamListener {
158        self.on_chunk = Some(on_chunk);
159        self
160    }
161
162    /// Dart `ImageStreamListener(onError:)`.
163    pub fn on_error(mut self, on_error: ImageErrorListener) -> ImageStreamListener {
164        self.on_error = Some(on_error);
165        self
166    }
167
168    /// Whether every callback is the same as `other`'s, which is how a listener is found again
169    /// to remove it.
170    fn is(&self, other: &ImageStreamListener) -> bool {
171        Rc::ptr_eq(&self.on_image, &other.on_image)
172            && match (&self.on_chunk, &other.on_chunk) {
173                (None, None) => true,
174                (Some(left), Some(right)) => Rc::ptr_eq(left, right),
175                _ => false,
176            }
177            && match (&self.on_error, &other.on_error) {
178                (None, None) => true,
179                (Some(left), Some(right)) => Rc::ptr_eq(left, right),
180                _ => false,
181            }
182    }
183}
184
185impl Debug for ImageStreamListener {
186    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187        formatter
188            .debug_struct("ImageStreamListener")
189            .field("on_error", &self.on_error.is_some())
190            .finish()
191    }
192}
193
194/// Keeps a completer usable without listening to animation frames.
195///
196/// Call `dispose` exactly once to release logical retention. Arena retention separately keeps
197/// the receiver allocated while disposal invokes callbacks, as a Dart reference would.
198#[must_use = "dispose the keep-alive handle when its owner releases the completer"]
199pub struct ImageStreamCompleterHandle {
200    completer: Ref<ImageStreamCompleter>,
201}
202
203impl ImageStreamCompleterHandle {
204    /// Releases this keep-alive and disposes the completer if it has no listeners or other holds.
205    pub fn dispose(self, app: &mut App) {
206        let completer = self.completer.handle();
207        debug_assert!(!app.is_disposed(completer));
208        debug_assert!(app.get(completer).keep_alive_handles > 0);
209        app.get_mut(completer).keep_alive_handles -= 1;
210        completer.maybe_dispose(app);
211    }
212}
213
214/// The resolving half of an image: holds the frame once it exists and tells the listeners.
215///
216/// Flutter `ImageStreamCompleter`. A listener added after the image has arrived is called
217/// straight away, which is what lets a widget built later show a cached image in its first
218/// frame instead of flashing empty.
219#[derive(Default)]
220pub struct ImageStreamCompleter {
221    listeners: Vec<ImageStreamListener>,
222    current_image: Option<ImageInfo>,
223    current_error: Option<ImageDecodeError>,
224    on_watched: Option<WatchedCallback>,
225    keep_alive_handles: usize,
226    on_last_listener_removed: Vec<Listener>,
227    on_disposed: Option<Listener>,
228}
229
230/// Told whether anyone is listening now, when that answer changes.
231pub type WatchedCallback = Rc<dyn Fn(&mut App, bool)>;
232
233impl ImageStreamCompleter {
234    /// Creates a completer with no image yet.
235    pub fn new(app: &mut App) -> Ref<ImageStreamCompleter> {
236        app.create(ImageStreamCompleter::default())
237    }
238
239    /// Holds this completer without subscribing to its frames.
240    pub fn keep_alive(self: Handle<Self>, app: &mut App) -> ImageStreamCompleterHandle {
241        debug_assert!(!app.is_disposed(self));
242        app.get_mut(self).keep_alive_handles += 1;
243        ImageStreamCompleterHandle {
244            completer: self.keep(app),
245        }
246    }
247
248    /// Registers cleanup when the last frame listener leaves. Callbacks are cleared afterward.
249    pub fn add_on_last_listener_removed_callback(
250        self: Handle<Self>,
251        app: &mut App,
252        callback: Listener,
253    ) {
254        debug_assert!(!app.is_disposed(self));
255        app.get_mut(self).on_last_listener_removed.push(callback);
256    }
257
258    /// Unregisters a previously installed last-listener callback.
259    pub fn remove_on_last_listener_removed_callback(
260        self: Handle<Self>,
261        app: &mut App,
262        callback: &Listener,
263    ) {
264        let callbacks = &mut app.get_mut(self).on_last_listener_removed;
265        if let Some(index) = callbacks.iter().position(|held| held == callback) {
266            callbacks.remove(index);
267        }
268    }
269
270    /// Installs the composed playback's resource cleanup.
271    pub(crate) fn set_on_disposed(self: Handle<Self>, app: &mut App, callback: Listener) {
272        debug_assert!(app.get(self).on_disposed.is_none());
273        app.get_mut(self).on_disposed = Some(callback);
274    }
275
276    /// Releases resources once neither listeners nor keep-alive handles need this completer.
277    pub fn maybe_dispose(self: Handle<Self>, app: &mut App) {
278        if app.is_disposed(self)
279            || !app.get(self).listeners.is_empty()
280            || app.get(self).keep_alive_handles != 0
281        {
282            return;
283        }
284        let data = app.get_mut(self);
285        data.current_image = None;
286        data.current_error = None;
287        data.on_watched = None;
288        data.on_last_listener_removed.clear();
289        let cleanup = data.on_disposed.take();
290        app.mark_disposed(self);
291        if let Some(cleanup) = cleanup {
292            cleanup.call(app);
293        }
294    }
295
296    /// The frame this completer holds, if one has arrived.
297    pub fn current_image(self: Handle<Self>, app: &App) -> Option<ImageInfo> {
298        app.get(self).current_image.clone()
299    }
300
301    /// Why this image will never arrive, if it failed.
302    pub fn current_error(self: Handle<Self>, app: &App) -> Option<ImageDecodeError> {
303        app.get(self).current_error.clone()
304    }
305
306    /// How many listeners are waiting, which is what tells the cache whether anyone still wants
307    /// this image.
308    pub fn listener_count(self: Handle<Self>, app: &App) -> usize {
309        app.get(self).listeners.len()
310    }
311
312    /// Watches whether anyone is listening, so work nobody is waiting for can be stopped.
313    ///
314    /// Called with true when the first listener arrives and false when the last one leaves. An
315    /// animation uses this to stop between frames while it is off screen and pick up again when
316    /// it comes back; Dart's completer overrides its listener methods to the same end.
317    pub fn set_on_watched(self: Handle<Self>, app: &mut App, on_watched: WatchedCallback) {
318        let watched = !app.get(self).listeners.is_empty();
319        app.get_mut(self).on_watched = Some(Rc::clone(&on_watched));
320        if watched {
321            on_watched(app, true);
322        }
323    }
324
325    /// Adds a listener, calling it at once if the image or the failure is already here.
326    pub fn add_listener(self: Handle<Self>, app: &mut App, listener: ImageStreamListener) {
327        debug_assert!(!app.is_disposed(self));
328        let was_watched = !app.get(self).listeners.is_empty();
329        app.get_mut(self).listeners.push(listener.clone());
330        if !was_watched {
331            self.report_watched(app, true);
332        }
333        if let Some(image) = app.get(self).current_image.clone() {
334            (listener.on_image)(app, &image, true);
335            return;
336        }
337        if let Some(error) = app.get(self).current_error.clone()
338            && let Some(on_error) = &listener.on_error
339        {
340            on_error(app, &error);
341        }
342    }
343
344    /// Removes a listener added with [`add_listener`](Self::add_listener).
345    pub fn remove_listener(self: Handle<Self>, app: &mut App, listener: &ImageStreamListener) {
346        debug_assert!(!app.is_disposed(self));
347        let listeners = &mut app.get_mut(self).listeners;
348        if let Some(index) = listeners.iter().position(|held| held.is(listener)) {
349            listeners.remove(index);
350        }
351        if listeners.is_empty() {
352            for callback in app.get(self).on_last_listener_removed.clone() {
353                callback.call(app);
354            }
355            app.get_mut(self).on_last_listener_removed.clear();
356            self.report_watched(app, false);
357            self.maybe_dispose(app);
358        }
359    }
360
361    fn report_watched(self: Handle<Self>, app: &mut App, watched: bool) {
362        let Some(on_watched) = app.get(self).on_watched.clone() else {
363            return;
364        };
365        on_watched(app, watched);
366    }
367
368    /// Hands a frame to every listener and keeps it for listeners still to come.
369    pub fn set_image(self: Handle<Self>, app: &mut App, image: ImageInfo) {
370        debug_assert!(!app.is_disposed(self));
371        app.get_mut(self).current_image = Some(image.clone());
372        app.get_mut(self).current_error = None;
373        // A copy, so a listener that adds or removes one while being called does not disturb
374        // this pass — the same rule the change notifiers follow.
375        for listener in app.get(self).listeners.clone() {
376            (listener.on_image)(app, &image, false);
377        }
378    }
379
380    /// Tells every listener with a chunk callback about bytes that arrived. Flutter
381    /// `reportImageChunkEvent`.
382    pub fn report_image_chunk_event(self: Handle<Self>, app: &mut App, event: ImageChunkEvent) {
383        debug_assert!(!app.is_disposed(self));
384        if app.get(self).listeners.is_empty() {
385            return;
386        }
387        // A copy, so a listener that adds or removes one while being called does not disturb
388        // this pass.
389        let listeners: Vec<ImageChunkListener> = app
390            .get(self)
391            .listeners
392            .iter()
393            .filter_map(|listener| listener.on_chunk.clone())
394            .collect();
395        for listener in listeners {
396            listener(app, &event);
397        }
398    }
399
400    /// Tells every listener that the image failed, and keeps the failure for later listeners.
401    pub fn report_error(self: Handle<Self>, app: &mut App, error: ImageDecodeError) {
402        debug_assert!(!app.is_disposed(self));
403        app.get_mut(self).current_error = Some(error.clone());
404        for listener in app.get(self).listeners.clone() {
405            if let Some(on_error) = &listener.on_error {
406                on_error(app, &error);
407            }
408        }
409    }
410}
411
412/// The listening half of an image. Flutter `ImageStream`.
413///
414/// A stream exists before its completer does, because a provider may have to look in the cache
415/// or start a decode first. Listeners added in the meantime are held here and handed over when
416/// [`set_completer`](Self::set_completer) arrives.
417#[derive(Default)]
418pub struct ImageStream {
419    completer: Option<Ref<ImageStreamCompleter>>,
420    listeners: Vec<ImageStreamListener>,
421}
422
423impl ImageStream {
424    /// Creates a stream with no completer yet.
425    pub fn new(app: &mut App) -> Ref<ImageStream> {
426        app.create(ImageStream::default())
427    }
428
429    /// The completer, once one has been assigned.
430    ///
431    /// Two streams for the same image share a completer, which is how the cache makes one decode
432    /// serve every widget showing it. Comparing these is how a widget tells whether the image it
433    /// resolved to has actually changed.
434    pub fn completer(self: Handle<Self>, app: &App) -> Option<Handle<ImageStreamCompleter>> {
435        app.get(self).completer.handle()
436    }
437
438    /// Releases the stream and unregisters its listeners. The resolving consumer owns this call.
439    pub fn dispose(self: Handle<Self>, app: &mut App) {
440        let listeners = std::mem::take(&mut app.get_mut(self).listeners);
441        if let Some(completer) = app.get_mut(self).completer.take() {
442            for listener in listeners {
443                completer.remove_listener(app, &listener);
444            }
445            completer.maybe_dispose(app);
446            drop(completer);
447        }
448        app.mark_disposed(self);
449    }
450
451    /// Assigns the completer, handing it every listener added while there was none.
452    ///
453    /// # Panics
454    ///
455    /// Panics if a completer was already assigned, as Dart's assert does; a stream resolves once.
456    pub fn set_completer(self: Handle<Self>, app: &mut App, completer: Ref<ImageStreamCompleter>) {
457        assert!(
458            app.get(self).completer.is_none(),
459            "an ImageStream takes its completer once"
460        );
461        let kept = completer.clone();
462        let completer = completer.handle();
463        app.get_mut(self).completer = Some(kept);
464        for listener in app.get(self).listeners.clone() {
465            completer.add_listener(app, listener);
466        }
467    }
468
469    /// Adds a listener now, or holds it until the completer arrives.
470    pub fn add_listener(self: Handle<Self>, app: &mut App, listener: ImageStreamListener) {
471        app.get_mut(self).listeners.push(listener.clone());
472        if let Some(completer) = self.completer(app) {
473            completer.add_listener(app, listener);
474        }
475    }
476
477    /// Removes a listener, whether it is waiting here or already on the completer.
478    pub fn remove_listener(self: Handle<Self>, app: &mut App, listener: &ImageStreamListener) {
479        let listeners = &mut app.get_mut(self).listeners;
480        if let Some(index) = listeners.iter().position(|held| held.is(listener)) {
481            listeners.remove(index);
482            if let Some(completer) = self.completer(app) {
483                completer.remove_listener(app, listener);
484            }
485        }
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use std::cell::RefCell;
492
493    use waft_embedder::test_support::solid_image;
494    use waft_foundation::AppCell;
495
496    use super::*;
497
498    /// A listener that records what it was told, so a test can assert on the order.
499    #[derive(Default)]
500    struct Record {
501        images: RefCell<Vec<(f64, bool)>>,
502        errors: RefCell<Vec<ImageDecodeError>>,
503    }
504
505    fn listener(record: &Rc<Record>) -> ImageStreamListener {
506        let images = Rc::clone(record);
507        let errors = Rc::clone(record);
508        ImageStreamListener::new(Rc::new(move |_app: &mut App, info: &ImageInfo, sync| {
509            images.images.borrow_mut().push((info.scale, sync));
510        }))
511        .on_error(Rc::new(move |_app: &mut App, error: &ImageDecodeError| {
512            errors.errors.borrow_mut().push(error.clone());
513        }))
514    }
515
516    fn an_image() -> ImageInfo {
517        ImageInfo::new(solid_image([4, 2], [255, 0, 0, 255])).scale(2.0)
518    }
519
520    #[test]
521    fn an_image_reaches_the_listeners_waiting_for_it() {
522        let cell = AppCell::new();
523        let mut app = cell.borrow_mut();
524        let completer = ImageStreamCompleter::new(&mut app);
525        let record = Rc::new(Record::default());
526        completer.add_listener(&mut app, listener(&record));
527
528        completer.set_image(&mut app, an_image());
529
530        assert_eq!(record.images.borrow().as_slice(), &[(2.0, false)]);
531    }
532
533    #[test]
534    fn a_listener_added_after_the_image_hears_about_it_at_once() {
535        let cell = AppCell::new();
536        let mut app = cell.borrow_mut();
537        let completer = ImageStreamCompleter::new(&mut app);
538        completer.set_image(&mut app, an_image());
539
540        let record = Rc::new(Record::default());
541        completer.add_listener(&mut app, listener(&record));
542
543        // Reported as synchronous, which is what lets a widget paint in the frame it was built.
544        assert_eq!(record.images.borrow().as_slice(), &[(2.0, true)]);
545    }
546
547    #[test]
548    fn a_removed_listener_hears_nothing_further() {
549        let cell = AppCell::new();
550        let mut app = cell.borrow_mut();
551        let completer = ImageStreamCompleter::new(&mut app);
552        let keep_alive = completer.keep_alive(&mut app);
553        let record = Rc::new(Record::default());
554        let listener = listener(&record);
555        completer.add_listener(&mut app, listener.clone());
556        completer.remove_listener(&mut app, &listener);
557
558        completer.set_image(&mut app, an_image());
559
560        assert!(record.images.borrow().is_empty());
561        assert_eq!(completer.listener_count(&app), 0);
562        keep_alive.dispose(&mut app);
563    }
564
565    #[test]
566    fn a_failure_reaches_the_error_listeners_and_the_late_ones() {
567        let cell = AppCell::new();
568        let mut app = cell.borrow_mut();
569        let completer = ImageStreamCompleter::new(&mut app);
570        let waiting = Rc::new(Record::default());
571        completer.add_listener(&mut app, listener(&waiting));
572
573        completer.report_error(&mut app, ImageDecodeError::UnknownFormat);
574
575        let late = Rc::new(Record::default());
576        completer.add_listener(&mut app, listener(&late));
577
578        assert_eq!(
579            waiting.errors.borrow().as_slice(),
580            &[ImageDecodeError::UnknownFormat]
581        );
582        assert_eq!(
583            late.errors.borrow().as_slice(),
584            &[ImageDecodeError::UnknownFormat],
585            "a listener added after the failure still learns of it"
586        );
587    }
588
589    #[test]
590    fn listeners_added_before_a_completer_are_handed_over_with_it() {
591        let cell = AppCell::new();
592        let mut app = cell.borrow_mut();
593        let stream = ImageStream::new(&mut app);
594        let record = Rc::new(Record::default());
595        stream.add_listener(&mut app, listener(&record));
596        assert!(stream.completer(&app).is_none());
597
598        let completer = ImageStreamCompleter::new(&mut app);
599        completer.set_image(&mut app, an_image());
600        stream.set_completer(&mut app, completer.clone());
601
602        assert_eq!(record.images.borrow().as_slice(), &[(2.0, true)]);
603        assert_eq!(completer.listener_count(&app), 1);
604    }
605
606    #[test]
607    fn a_listener_removed_before_the_completer_never_reaches_it() {
608        let cell = AppCell::new();
609        let mut app = cell.borrow_mut();
610        let stream = ImageStream::new(&mut app);
611        let record = Rc::new(Record::default());
612        let listener = listener(&record);
613        stream.add_listener(&mut app, listener.clone());
614        stream.remove_listener(&mut app, &listener);
615
616        let completer = ImageStreamCompleter::new(&mut app);
617        stream.set_completer(&mut app, completer.clone());
618        completer.set_image(&mut app, an_image());
619
620        assert!(record.images.borrow().is_empty());
621    }
622
623    #[test]
624    fn an_image_reports_its_logical_size_and_what_it_costs_to_hold() {
625        let info = ImageInfo::new(solid_image([4, 2], [0, 0, 255, 255])).scale(2.0);
626        assert_eq!(info.size(), waft_embedder::Size::new(2.0, 1.0));
627        assert_eq!(info.size_bytes(), 4 * 2 * 4);
628    }
629    #[test]
630    fn a_listener_can_dispose_its_stream_during_frame_delivery() {
631        let cell = AppCell::new();
632        let mut app = cell.borrow_mut();
633        let stream = ImageStream::new(&mut app);
634        let completer = ImageStreamCompleter::new(&mut app);
635        stream.set_completer(&mut app, completer.clone());
636        let listener = {
637            let stream = stream.handle();
638            ImageStreamListener::new(Rc::new(move |app, _, _| {
639                stream.dispose(app);
640            }))
641        };
642        stream.add_listener(&mut app, listener);
643        completer.set_image(&mut app, an_image());
644        assert!(app.is_disposed(&completer));
645        assert!(completer.current_image(&app).is_none());
646        let (stream_handle, completer_handle) = (stream.handle(), completer.handle());
647        drop((stream, completer));
648        drop(app);
649        cell.checkpoint();
650        let app = cell.borrow();
651        assert!(!app.contains(stream_handle));
652        assert!(!app.contains(completer_handle));
653    }
654}