Skip to main content

waft_widgets/widgets/
image.rs

1//! Flutter counterpart: `widgets/image.dart`.
2//!
3//! [`Image`] resolves a provider and shows what comes back; [`RawImage`] draws an image already
4//! in hand. Everything a provider needs — the cache, the decode — is below in painting, so this
5//! layer is only about listening for the frame and rebuilding when it arrives.
6//!
7//! `precacheImage` and the frame-by-frame and loading builders are not here; see `PORTING.md`.
8
9use std::rc::Rc;
10
11use waft_embedder::{ImageDecodeError, Size, TextDirection};
12use waft_foundation::{
13    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
14    FlagProperty, Handle, IntProperty, OptionRetained, Ref,
15};
16use waft_painting::{
17    Alignment, BoxFit, ImageConfiguration, ImageInfo, ImageProviderRef, ImageRepeat, ImageStream,
18    ImageStreamListener, MemoryImage,
19};
20use waft_rendering::{AnyRenderObject, RenderBox, RenderHandle, RenderImage};
21
22use crate::framework::{
23    BuildContext, IntoWidget, KeyRef, LeafRenderObjectWidget, RenderObjectWidget, State, StateData,
24    StatefulWidget, WidgetRef,
25};
26use crate::widgets::basic::{Directionality, Semantics};
27use crate::widgets::localizations::Localizations;
28use crate::widgets::media_query::MediaQuery;
29
30/// Creates an [`ImageConfiguration`] based on the given [`BuildContext`] (and optionally
31/// size).
32///
33/// This is the object that must be passed to `BoxPainter.paint` and to
34/// `ImageProvider.resolve`.
35///
36/// If this is not called from a build method, then it should be reevaluated each time the
37/// dependencies change, e.g. by calling it from `State::did_change_dependencies`, so that
38/// any changes in the environment cause the image to be re-resolved.
39///
40/// The asset bundle waits with `DefaultAssetBundle`.
41pub fn create_local_image_configuration(
42    app: &mut App,
43    context: BuildContext,
44    size: Option<Size>,
45) -> ImageConfiguration {
46    ImageConfiguration {
47        bundle: None,
48        device_pixel_ratio: Some(
49            MediaQuery::maybe_device_pixel_ratio_of(app, context).unwrap_or(1.0),
50        ),
51        locale: Localizations::maybe_locale_of(app, context),
52        text_direction: Directionality::maybe_of(app, context),
53        size,
54        platform: Some(app.platform().target_platform()),
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use std::cell::RefCell;
61    use std::rc::Rc;
62    use waft_foundation::AppCell;
63
64    use waft_embedder::TextDirection;
65
66    use super::*;
67    use crate::framework::{IntoWidget, WidgetRef};
68    use crate::test_harness::Harness;
69    use crate::widgets::basic::{Builder, SizedBox};
70    use crate::widgets::media_query::MediaQueryData;
71
72    type Seen = Rc<RefCell<Option<ImageConfiguration>>>;
73
74    /// A leaf that records the configuration its context yields.
75    fn probe(seen: &Seen, size: Option<Size>) -> WidgetRef {
76        let seen = Rc::clone(seen);
77        Builder::new(move |app, context| {
78            *seen.borrow_mut() = Some(create_local_image_configuration(app, context, size));
79            SizedBox::shrink().into_widget()
80        })
81        .into_widget()
82    }
83
84    #[test]
85    fn the_configuration_reads_the_direction_pixel_ratio_size_and_platform() {
86        let cell = AppCell::new();
87        let mut app = cell.borrow_mut();
88        let seen: Seen = Rc::default();
89        let tree = Directionality::new(
90            TextDirection::Rtl,
91            MediaQuery::new(
92                MediaQueryData::new().device_pixel_ratio(3.0),
93                probe(&seen, Some(Size::new(1.0, 2.0))),
94            )
95            .into_widget(),
96        )
97        .into_widget();
98        let harness = Harness::mount(&mut app, tree);
99        harness.pump(&mut app);
100
101        let configuration = seen.borrow_mut().take().expect("the builder ran");
102        assert_eq!(configuration.text_direction, Some(TextDirection::Rtl));
103        assert_eq!(configuration.device_pixel_ratio, Some(3.0));
104        assert_eq!(configuration.size, Some(Size::new(1.0, 2.0)));
105        assert_eq!(
106            configuration.platform,
107            Some(app.platform().target_platform())
108        );
109        assert!(configuration.bundle.is_none());
110    }
111
112    #[test]
113    fn without_ancestors_the_configuration_falls_back() {
114        let cell = AppCell::new();
115        let mut app = cell.borrow_mut();
116        let seen: Seen = Rc::default();
117        let harness = Harness::mount(&mut app, probe(&seen, None));
118        harness.pump(&mut app);
119
120        let configuration = seen.borrow_mut().take().expect("the builder ran");
121        assert_eq!(configuration.text_direction, None);
122        assert_eq!(configuration.device_pixel_ratio, Some(1.0));
123        assert_eq!(configuration.size, None);
124    }
125}
126
127/// Dart's `ImageInfo.toString`, which an image widget's dump prints.
128fn describe_image_info(info: &ImageInfo) -> String {
129    let [width, height] = info.image.size();
130    let label = info
131        .debug_label
132        .as_ref()
133        .map(|label| format!("{label} "))
134        .unwrap_or_default();
135    format!("{label}[{width}×{height}] @ {}x", info.scale)
136}
137
138/// Draws an image that is already decoded. Flutter `RawImage`.
139///
140/// Most callers want [`Image`], which finds the image first. This is the widget underneath it,
141/// and what to use when the image is already in hand.
142#[derive(Clone, Debug)]
143pub struct RawImage {
144    /// See [`Widget::key`](crate::Widget::key).
145    pub key: Option<KeyRef>,
146    /// The image to draw, or nothing while it is still on its way.
147    pub image: Option<ImageInfo>,
148    /// The width to take, or `None` to follow the image.
149    pub width: Option<f64>,
150    /// The height to take, or `None` to follow the image.
151    pub height: Option<f64>,
152    /// How opaque to draw it, from zero to one.
153    pub opacity: f64,
154    /// How to fit it into the space it is given.
155    pub fit: Option<BoxFit>,
156    /// Where it sits when it does not fill that space.
157    pub alignment: Alignment,
158    /// What fills the space it does not cover.
159    pub repeat: ImageRepeat,
160    /// Whether to mirror it in a right-to-left layout.
161    pub match_text_direction: bool,
162}
163
164impl RawImage {
165    /// Creates a [`RawImage`] showing `image`, or nothing when it is `None`.
166    pub fn new(image: Option<ImageInfo>) -> RawImage {
167        RawImage {
168            key: None,
169            image,
170            width: None,
171            height: None,
172            opacity: 1.0,
173            fit: None,
174            alignment: Alignment::CENTER,
175            repeat: ImageRepeat::NoRepeat,
176            match_text_direction: false,
177        }
178    }
179
180    /// Dart `RawImage(key:)`.
181    pub fn key(mut self, key: KeyRef) -> RawImage {
182        self.key = Some(key);
183        self
184    }
185
186    /// Dart `RawImage(width:)`.
187    pub fn width(mut self, width: f64) -> RawImage {
188        self.width = Some(width);
189        self
190    }
191
192    /// Dart `RawImage(height:)`.
193    pub fn height(mut self, height: f64) -> RawImage {
194        self.height = Some(height);
195        self
196    }
197
198    /// Dart `RawImage(opacity:)`.
199    pub fn opacity(mut self, opacity: f64) -> RawImage {
200        self.opacity = opacity;
201        self
202    }
203
204    /// Dart `RawImage(fit:)`.
205    pub fn fit(mut self, fit: BoxFit) -> RawImage {
206        self.fit = Some(fit);
207        self
208    }
209
210    /// Dart `RawImage(alignment:)`.
211    pub fn alignment(mut self, alignment: Alignment) -> RawImage {
212        self.alignment = alignment;
213        self
214    }
215
216    /// Dart `RawImage(repeat:)`.
217    pub fn repeat(mut self, repeat: ImageRepeat) -> RawImage {
218        self.repeat = repeat;
219        self
220    }
221
222    /// Dart `RawImage(matchTextDirection:)`.
223    pub fn match_text_direction(mut self, match_text_direction: bool) -> RawImage {
224        self.match_text_direction = match_text_direction;
225        self
226    }
227
228    /// The reading direction the render object needs, which is only read when mirroring.
229    fn resolved_text_direction(
230        &self,
231        app: &mut App,
232        context: BuildContext,
233    ) -> Option<TextDirection> {
234        self.match_text_direction
235            .then(|| Directionality::maybe_of(app, context))
236            .flatten()
237    }
238}
239
240impl RenderObjectWidget for RawImage {
241    type RenderObject = RenderImage;
242
243    fn key(&self) -> Option<&KeyRef> {
244        self.key.as_ref()
245    }
246
247    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
248        properties.add(DiagnosticsProperty::<String>::new(
249            "image",
250            self.image.as_ref().map(describe_image_info),
251        ));
252        properties.add(DoubleProperty::new("width", self.width).default_value(None));
253        properties.add(DoubleProperty::new("height", self.height).default_value(None));
254        properties.add(DoubleProperty::new("opacity", self.opacity).default_value(Some(1.0)));
255        properties.add(EnumProperty::<BoxFit>::new("fit", self.fit).default_value(None));
256        properties.add(
257            DiagnosticsProperty::<Alignment>::new("alignment", Some(self.alignment))
258                .default_value(None),
259        );
260        properties.add(
261            EnumProperty::new("repeat", self.repeat).default_value(Some(ImageRepeat::NoRepeat)),
262        );
263        properties.add(
264            FlagProperty::new("matchTextDirection", Some(self.match_text_direction))
265                .if_true("match text direction"),
266        );
267    }
268
269    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
270        let render = RenderImage::new(app);
271        self.update_render_object(app, context, render);
272        render.as_object()
273    }
274
275    fn update_render_object(
276        &self,
277        app: &mut App,
278        context: BuildContext,
279        render_object: RenderHandle<RenderImage>,
280    ) {
281        let text_direction = self.resolved_text_direction(app, context);
282        render_object.set_image(app, self.image.clone());
283        render_object.set_width(app, self.width);
284        render_object.set_height(app, self.height);
285        render_object.set_opacity(app, self.opacity);
286        render_object.set_fit(app, self.fit);
287        render_object.set_alignment(app, self.alignment);
288        render_object.set_repeat(app, self.repeat);
289        render_object.set_match_text_direction(app, self.match_text_direction);
290        render_object.set_text_direction(app, text_direction);
291    }
292}
293
294impl LeafRenderObjectWidget for RawImage {}
295
296/// Shows an image from a provider. Flutter `Image`.
297///
298/// The image arrives later than the widget, so nothing is drawn on the first frame unless the
299/// cache already had it — in which case it is there immediately, which is what stops a scrolling
300/// list from flickering.
301#[derive(Clone, Debug)]
302pub struct Image {
303    /// See [`Widget::key`](crate::Widget::key).
304    pub key: Option<KeyRef>,
305    /// Where the image comes from.
306    pub image: ImageProviderRef,
307    /// The width to take, or `None` to follow the image.
308    pub width: Option<f64>,
309    /// The height to take, or `None` to follow the image.
310    pub height: Option<f64>,
311    /// How opaque to draw it, from zero to one.
312    pub opacity: f64,
313    /// How to fit it into the space it is given.
314    pub fit: Option<BoxFit>,
315    /// Where it sits when it does not fill that space.
316    pub alignment: Alignment,
317    /// What fills the space it does not cover.
318    pub repeat: ImageRepeat,
319    /// Whether to mirror it in a right-to-left layout.
320    pub match_text_direction: bool,
321    /// A Semantic description of the image.
322    ///
323    /// Used to provide a description of the image to TalkBack on Android, and
324    /// VoiceOver on iOS.
325    pub semantic_label: Option<String>,
326    /// Whether to exclude this image from semantics.
327    ///
328    /// Useful for images which do not contribute meaningful information to an
329    /// application.
330    pub exclude_from_semantics: bool,
331}
332
333impl Image {
334    /// Creates an [`Image`] from any provider.
335    pub fn new(image: ImageProviderRef) -> Image {
336        Image {
337            key: None,
338            image,
339            width: None,
340            height: None,
341            opacity: 1.0,
342            fit: None,
343            alignment: Alignment::CENTER,
344            repeat: ImageRepeat::NoRepeat,
345            match_text_direction: false,
346            semantic_label: None,
347            exclude_from_semantics: false,
348        }
349    }
350
351    /// Creates an [`Image`] from encoded bytes already in memory. Flutter `Image.memory`.
352    pub fn memory(bytes: std::sync::Arc<[u8]>) -> Image {
353        Image::new(Rc::new(MemoryImage::new(bytes)) as ImageProviderRef)
354    }
355
356    /// Creates an image from static bytes, preserving their identity across rebuilds.
357    pub fn memory_static(bytes: &'static [u8]) -> Image {
358        Image::new(Rc::new(MemoryImage::from_static(bytes)) as ImageProviderRef)
359    }
360
361    /// Dart `Image(key:)`.
362    pub fn key(mut self, key: KeyRef) -> Image {
363        self.key = Some(key);
364        self
365    }
366
367    /// Dart `Image(width:)`.
368    pub fn width(mut self, width: f64) -> Image {
369        self.width = Some(width);
370        self
371    }
372
373    /// Dart `Image(height:)`.
374    pub fn height(mut self, height: f64) -> Image {
375        self.height = Some(height);
376        self
377    }
378
379    /// Dart `Image(opacity:)`.
380    pub fn opacity(mut self, opacity: f64) -> Image {
381        self.opacity = opacity;
382        self
383    }
384
385    /// Dart `Image(fit:)`.
386    pub fn fit(mut self, fit: BoxFit) -> Image {
387        self.fit = Some(fit);
388        self
389    }
390
391    /// Dart `Image(alignment:)`.
392    pub fn alignment(mut self, alignment: Alignment) -> Image {
393        self.alignment = alignment;
394        self
395    }
396
397    /// Dart `Image(repeat:)`.
398    pub fn repeat(mut self, repeat: ImageRepeat) -> Image {
399        self.repeat = repeat;
400        self
401    }
402
403    /// Dart `Image(matchTextDirection:)`.
404    pub fn match_text_direction(mut self, match_text_direction: bool) -> Image {
405        self.match_text_direction = match_text_direction;
406        self
407    }
408
409    /// Dart `Image(semanticLabel:)`.
410    ///
411    /// If [`exclude_from_semantics`](Self::exclude_from_semantics) is true, then
412    /// [`semantic_label`](Self::semantic_label) will be ignored.
413    pub fn semantic_label(mut self, semantic_label: impl Into<String>) -> Image {
414        self.semantic_label = Some(semantic_label.into());
415        self
416    }
417
418    /// Dart `Image(excludeFromSemantics:)`.
419    pub fn exclude_from_semantics(mut self, exclude_from_semantics: bool) -> Image {
420        self.exclude_from_semantics = exclude_from_semantics;
421        self
422    }
423}
424
425impl StatefulWidget for Image {
426    type State = ImageState;
427
428    fn key(&self) -> Option<&KeyRef> {
429        self.key.as_ref()
430    }
431
432    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
433        properties.add(DiagnosticsProperty::<String>::new(
434            "image",
435            Some("Instance of 'ImageProvider'".to_string()),
436        ));
437        properties.add(DoubleProperty::new("width", self.width).default_value(None));
438        properties.add(DoubleProperty::new("height", self.height).default_value(None));
439        properties.add(DoubleProperty::new("opacity", self.opacity).default_value(Some(1.0)));
440        properties.add(EnumProperty::<BoxFit>::new("fit", self.fit).default_value(None));
441        properties.add(
442            DiagnosticsProperty::<Alignment>::new("alignment", Some(self.alignment))
443                .default_value(None),
444        );
445        properties.add(
446            EnumProperty::new("repeat", self.repeat).default_value(Some(ImageRepeat::NoRepeat)),
447        );
448        properties.add(
449            FlagProperty::new("matchTextDirection", Some(self.match_text_direction))
450                .if_true("match text direction"),
451        );
452    }
453
454    fn create_state(&self) -> ImageState {
455        ImageState {
456            state: StateData::new(),
457            stream: None,
458            listener: None,
459            resolved: None,
460            error: None,
461        }
462    }
463}
464
465/// Listens for [`Image`]'s frame and rebuilds when it arrives. Flutter `_ImageState`.
466pub struct ImageState {
467    state: StateData<Image>,
468    stream: Option<Ref<ImageStream>>,
469    listener: Option<ImageStreamListener>,
470    resolved: Option<ImageInfo>,
471    error: Option<ImageDecodeError>,
472}
473
474impl ImageState {
475    /// Why the image will never arrive, if it failed.
476    ///
477    /// Dart hands a failure to `FlutterError.onError` and, if given, an error builder. Neither
478    /// is here, so this is how a caller finds out.
479    pub fn error(self: Handle<Self>, app: &App) -> Option<ImageDecodeError> {
480        app.get(self).error.clone()
481    }
482
483    /// Resolves the provider and starts listening, dropping any earlier stream.
484    ///
485    /// Resolving may answer within the call when the cache already holds the image, which is why
486    /// the listener records into the state directly rather than assuming a later frame.
487    fn resolve(self: Handle<Self>, app: &mut App, context: BuildContext) {
488        let configuration = create_local_image_configuration(app, context, None);
489        let provider = Rc::clone(&self.widget(app).image);
490        let stream = provider.resolve(app, &configuration);
491        if let Some(previous) = app.get(self).stream.handle()
492            && previous.completer(app) == stream.completer(app)
493        {
494            stream.dispose(app);
495            return;
496        }
497        self.stop_listening(app);
498        if let Some(previous) = app.get_mut(self).stream.take() {
499            previous.dispose(app);
500        }
501        app.get_mut(self).stream = Some(stream.clone());
502
503        let on_image = self;
504        let on_error = self;
505        let listener = ImageStreamListener::new(Rc::new(
506            move |app: &mut App, info: &ImageInfo, _synchronous| {
507                let info = info.clone();
508                on_image.set_state(app, move |state| {
509                    state.resolved = Some(info);
510                    state.error = None;
511                });
512            },
513        ))
514        .on_error(Rc::new(move |app: &mut App, error: &ImageDecodeError| {
515            let error = error.clone();
516            on_error.set_state(app, move |state| {
517                state.error = Some(error);
518            });
519        }));
520        app.get_mut(self).listener = Some(listener.clone());
521        stream.add_listener(app, listener);
522    }
523
524    fn stop_listening(self: Handle<Self>, app: &mut App) {
525        let (Some(stream), Some(listener)) = (
526            app.get(self).stream.handle(),
527            app.get_mut(self).listener.take(),
528        ) else {
529            return;
530        };
531        stream.remove_listener(app, &listener);
532    }
533}
534
535impl State for ImageState {
536    type Widget = Image;
537    crate::state_accessors!();
538
539    fn debug_fill_properties(
540        self: Handle<Self>,
541        app: &App,
542        properties: &mut DiagnosticPropertiesBuilder,
543    ) {
544        let state = app.get(self);
545        properties.add(DiagnosticsProperty::<String>::new(
546            "stream",
547            state.stream.as_ref().map(|_| "ImageStream".to_string()),
548        ));
549        properties.add(DiagnosticsProperty::<String>::new(
550            "pixels",
551            state.resolved.as_ref().map(describe_image_info),
552        ));
553        properties.add(DiagnosticsProperty::<String>::new(
554            "loadingProgress",
555            None::<String>,
556        ));
557        properties.add(IntProperty::<i32>::new("frameNumber", None).default_value(None));
558        properties.add(
559            DiagnosticsProperty::<bool>::new("wasSynchronouslyLoaded", None).default_value(None),
560        );
561    }
562
563    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
564        let context = self.context(app);
565        self.resolve(app, context);
566    }
567
568    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Image) {
569        if !Rc::ptr_eq(&self.widget(app).image, &old_widget.image) {
570            let context = self.context(app);
571            self.resolve(app, context);
572        }
573    }
574
575    fn dispose(self: Handle<Self>, app: &mut App) {
576        self.stop_listening(app);
577        if let Some(stream) = app.get_mut(self).stream.take() {
578            stream.dispose(app);
579        }
580        app.get_mut(self).resolved = None;
581    }
582
583    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
584        let widget = self.widget(app).clone();
585        let mut raw = RawImage::new(app.get(self).resolved.clone())
586            .opacity(widget.opacity)
587            .alignment(widget.alignment)
588            .repeat(widget.repeat)
589            .match_text_direction(widget.match_text_direction);
590        if let Some(width) = widget.width {
591            raw = raw.width(width);
592        }
593        if let Some(height) = widget.height {
594            raw = raw.height(height);
595        }
596        if let Some(fit) = widget.fit {
597            raw = raw.fit(fit);
598        }
599        let mut result = raw.into_widget();
600
601        if !widget.exclude_from_semantics {
602            result = Semantics::new()
603                .container(widget.semantic_label.is_some())
604                .image(true)
605                .label(widget.semantic_label.clone().unwrap_or_default())
606                .child(result)
607                .into_widget();
608        }
609
610        result
611    }
612}
613
614#[cfg(test)]
615mod image_widget_tests {
616    use std::cell::{Cell, RefCell};
617    use std::rc::Rc;
618    use std::time::Duration;
619    use waft_painting::ImageProvider;
620
621    use waft_embedder::test_support::solid_image;
622    use waft_embedder::{
623        ImageCodec, ImageCodecFuture, ImageFrame, ImageFrameFuture, ImageRepetition, TargetPlatform,
624    };
625    use waft_foundation::AppCell;
626    use waft_rendering::RenderImage;
627    use waft_test::TestPlatform;
628
629    use super::*;
630    use crate::framework::IntoWidget;
631    use crate::test_harness::Harness;
632    use crate::test_harness::pump_every_view;
633
634    /// A codec over pictures the test wrote out in advance.
635    struct TestCodec {
636        colours: Vec<[u8; 4]>,
637        repetition: ImageRepetition,
638        frame_duration: Duration,
639        next_index: usize,
640        /// How many frames have been asked for, which is what says when they were asked for.
641        asked: Rc<Cell<u32>>,
642        dropped: Rc<Cell<u32>>,
643        frame_gate: Option<waft_foundation::CompleterFuture<()>>,
644    }
645
646    impl Drop for TestCodec {
647        fn drop(&mut self) {
648            self.dropped.set(self.dropped.get() + 1);
649        }
650    }
651
652    impl ImageCodec for TestCodec {
653        fn frame_count(&self) -> u32 {
654            self.colours.len() as u32
655        }
656
657        fn repetition(&self) -> ImageRepetition {
658            self.repetition
659        }
660
661        fn next_frame(&mut self) -> ImageFrameFuture<'_> {
662            self.asked.set(self.asked.get() + 1);
663            let colour = self.colours[self.next_index];
664            self.next_index = (self.next_index + 1) % self.colours.len();
665            let gate = self.frame_gate.clone();
666            let duration = self.frame_duration;
667            Box::pin(async move {
668                if let Some(gate) = gate {
669                    gate.await;
670                }
671                Ok(ImageFrame {
672                    image: solid_image([30, 10], colour),
673                    duration,
674                })
675            })
676        }
677    }
678
679    /// A host that answers with a codec at once, and counts how often it was asked.
680    struct TestHost {
681        opens: RefCell<u32>,
682        colours: Vec<[u8; 4]>,
683        repetition: ImageRepetition,
684        frame_duration: Duration,
685        asked: Rc<Cell<u32>>,
686        dropped: Rc<Cell<u32>>,
687        open_gate: Option<waft_foundation::CompleterFuture<()>>,
688        frame_gate: Option<waft_foundation::CompleterFuture<()>>,
689    }
690
691    impl TestHost {
692        fn still() -> TestHost {
693            TestHost {
694                opens: RefCell::new(0),
695                colours: vec![[0, 128, 255, 255]],
696                repetition: ImageRepetition::Once,
697                frame_duration: Duration::ZERO,
698                asked: Rc::new(Cell::new(0)),
699                dropped: Rc::new(Cell::new(0)),
700                open_gate: None,
701                frame_gate: None,
702            }
703        }
704
705        fn animation() -> TestHost {
706            TestHost {
707                opens: RefCell::new(0),
708                colours: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]],
709                repetition: ImageRepetition::Forever,
710                frame_duration: Duration::from_millis(40),
711                asked: Rc::new(Cell::new(0)),
712                dropped: Rc::new(Cell::new(0)),
713                open_gate: None,
714                frame_gate: None,
715            }
716        }
717
718        /// What the host answers `Platform::open_image_codec` with.
719        fn open(&self) -> ImageCodecFuture {
720            *self.opens.borrow_mut() += 1;
721            let codec = Box::new(TestCodec {
722                colours: self.colours.clone(),
723                repetition: self.repetition,
724                frame_duration: self.frame_duration,
725                next_index: 0,
726                asked: Rc::clone(&self.asked),
727                dropped: self.dropped.clone(),
728                frame_gate: self.frame_gate.clone(),
729            }) as Box<dyn ImageCodec>;
730            let gate = self.open_gate.clone();
731            Box::pin(async move {
732                if let Some(gate) = gate {
733                    gate.await;
734                }
735                Ok(codec)
736            })
737        }
738    }
739
740    /// An [`App`] whose host decodes with `host`.
741    fn app_decoding_with(host: &Rc<TestHost>) -> Rc<AppCell> {
742        let host = Rc::clone(host);
743        let platform = TestPlatform::new()
744            .on(TargetPlatform::MacOS)
745            .with_image_codec(move |_bytes| host.open());
746        AppCell::with_platform(Rc::new(platform))
747    }
748
749    /// An [`App`] whose host has no decoder at all, which is the trait's default.
750    fn app_without_a_decoder() -> Rc<AppCell> {
751        AppCell::with_platform(Rc::new(TestPlatform::new().on(TargetPlatform::MacOS)))
752    }
753
754    /// The one image render object in the mounted tree.
755    fn mounted_image(app: &App, harness: &Harness) -> RenderHandle<RenderImage> {
756        let mut found = None;
757        let mut stack = vec![harness.render_root(app).as_object()];
758        while let Some(object) = stack.pop() {
759            if let Some(image) = object.downcast::<RenderImage>(app) {
760                found = Some(image);
761            }
762            object.visit_children(app, &mut |child| stack.push(child));
763        }
764        found.expect("the tree has an image")
765    }
766
767    fn mount_image(cell: &Rc<AppCell>, widget: WidgetRef) -> Harness {
768        let mut app = cell.borrow_mut();
769        let harness = Harness::mount(&mut app, widget);
770        harness.pump(&mut app);
771        harness
772    }
773
774    #[test]
775    fn an_image_appears_once_the_host_answers_and_takes_the_size_it_decoded() {
776        let host = Rc::new(TestHost::still());
777        let cell = app_decoding_with(&host);
778        let harness = mount_image(&cell, Image::memory_static(&b"a picture"[..]).into_widget());
779        {
780            let app = cell.borrow();
781            let image = mounted_image(&app, &harness);
782            assert!(image.image(&app).is_none(), "nothing yet");
783            assert_eq!(image.size(&app), Size::new(0.0, 0.0));
784        }
785
786        // The open and the first frame both resolve at the checkpoint, as every awaited answer
787        // does.
788        cell.checkpoint();
789        let mut app = cell.borrow_mut();
790        harness.pump(&mut app);
791
792        let image = mounted_image(&app, &harness);
793        assert!(image.image(&app).is_some(), "the frame reached the widget");
794        assert_eq!(
795            image.size(&app),
796            Size::new(30.0, 10.0),
797            "the box takes the size the host decoded"
798        );
799    }
800
801    #[test]
802    fn a_host_with_no_decoder_leaves_the_box_empty() {
803        let cell = app_without_a_decoder();
804        let harness = mount_image(&cell, Image::memory_static(&b"a picture"[..]).into_widget());
805        cell.checkpoint();
806
807        let mut app = cell.borrow_mut();
808        harness.pump(&mut app);
809        let image = mounted_image(&app, &harness);
810        assert!(image.image(&app).is_none());
811        assert_eq!(image.size(&app), Size::new(0.0, 0.0));
812    }
813
814    #[test]
815    fn two_widgets_showing_the_same_bytes_share_one_decode() {
816        let host = Rc::new(TestHost::still());
817        let cell = app_decoding_with(&host);
818        let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&b"one picture"[..]);
819        let provider: ImageProviderRef = Rc::new(MemoryImage::new(bytes));
820        mount_image(
821            &cell,
822            crate::widgets::basic::Column::new()
823                .children([
824                    Image::new(Rc::clone(&provider)).into_widget(),
825                    Image::new(provider).into_widget(),
826                ])
827                .into_widget(),
828        );
829
830        assert_eq!(
831            *host.opens.borrow(),
832            1,
833            "the cache shared the first decode with the second widget"
834        );
835    }
836
837    #[test]
838    fn an_animation_shows_a_new_frame_when_the_last_ones_time_is_up() {
839        let host = Rc::new(TestHost::animation());
840        let cell = app_decoding_with(&host);
841        let harness = mount_image(
842            &cell,
843            Image::memory_static(&b"an animation"[..]).into_widget(),
844        );
845        cell.checkpoint();
846
847        let first = {
848            let mut app = cell.borrow_mut();
849            harness.pump(&mut app);
850            mounted_image(&app, &harness)
851                .image(&app)
852                .expect("the first frame")
853                .image
854        };
855
856        // Nothing changes until the frame's own time has passed.
857        cell.elapse(Duration::from_millis(10));
858        {
859            let app = cell.borrow();
860            let showing = mounted_image(&app, &harness).image(&app).expect("a frame");
861            assert_eq!(showing.image, first, "still the first frame");
862        }
863
864        cell.elapse(Duration::from_millis(50));
865        let mut app = cell.borrow_mut();
866        harness.pump(&mut app);
867        let showing = mounted_image(&app, &harness).image(&app).expect("a frame");
868        assert_ne!(showing.image, first, "the animation moved on");
869    }
870
871    #[test]
872    fn the_frame_after_the_one_on_screen_is_asked_for_while_it_is_still_up() {
873        let host = Rc::new(TestHost::animation());
874        let cell = app_decoding_with(&host);
875        let harness = mount_image(
876            &cell,
877            Image::memory_static(&b"an animation"[..]).into_widget(),
878        );
879        cell.checkpoint();
880        {
881            let mut app = cell.borrow_mut();
882            harness.pump(&mut app);
883        }
884        cell.checkpoint();
885        // The one on screen and the one being got ready: a frame's time on screen is its own,
886        // rather than also covering the decode of the frame after it.
887        assert_eq!(
888            host.asked.get(),
889            2,
890            "asked before any of the frame's time passed"
891        );
892    }
893
894    #[test]
895    fn an_animation_nobody_is_watching_stops_between_frames() {
896        let host = Rc::new(TestHost::animation());
897        let cell = app_decoding_with(&host);
898        let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&b"an animation"[..]);
899        let provider: ImageProviderRef = Rc::new(MemoryImage::new(bytes));
900
901        let stream = {
902            let mut app = cell.borrow_mut();
903            let configuration = ImageConfiguration::EMPTY;
904            provider.resolve(&mut app, &configuration)
905        };
906        cell.checkpoint();
907
908        // A listener of our own, so the playback has someone to run for.
909        let seen: Rc<RefCell<u32>> = Rc::default();
910        let counting = Rc::clone(&seen);
911        let listener = ImageStreamListener::new(Rc::new(move |_app: &mut App, _info, _| {
912            *counting.borrow_mut() += 1;
913        }));
914        {
915            let mut app = cell.borrow_mut();
916            stream.add_listener(&mut app, listener.clone());
917        }
918        cell.elapse(Duration::from_millis(200));
919        let while_watched = *seen.borrow();
920        assert!(while_watched >= 2, "frames arrived while watched");
921
922        {
923            let mut app = cell.borrow_mut();
924            stream.remove_listener(&mut app, &listener);
925        }
926        cell.elapse(Duration::from_millis(500));
927        assert_eq!(
928            *seen.borrow(),
929            while_watched,
930            "nothing decoded once nobody was listening"
931        );
932    }
933
934    #[test]
935    fn late_open_and_frame_results_release_their_codec_after_stream_disposal() {
936        for delay_open in [true, false] {
937            let gate = waft_foundation::Completer::new();
938            let mut host = TestHost::animation();
939            if delay_open {
940                host.open_gate = Some(gate.future());
941            } else {
942                host.frame_gate = Some(gate.future());
943            }
944            let host = Rc::new(host);
945            let cell = app_decoding_with(&host);
946            let provider = MemoryImage::from_static(b"late");
947            let stream = {
948                let mut app = cell.borrow_mut();
949                provider.resolve(&mut app, &ImageConfiguration::EMPTY)
950            };
951            cell.checkpoint();
952            let completer;
953            {
954                let mut app = cell.borrow_mut();
955                completer = stream.completer(&app).unwrap();
956                let cache = waft_painting::ImageCache::instance(&mut app);
957                cache.clear(&mut app);
958                stream.dispose(&mut app);
959                pump_every_view(&mut app, Duration::ZERO);
960            }
961            let stream_handle = stream.handle();
962            drop(stream);
963            cell.checkpoint();
964            assert!(!cell.borrow().contains(stream_handle));
965            assert!(!cell.borrow().contains(completer));
966            assert_eq!(
967                host.dropped.get(),
968                0,
969                "the decode operation still owns its codec"
970            );
971            gate.complete(&mut cell.borrow_mut(), ());
972            cell.checkpoint();
973            assert_eq!(
974                host.dropped.get(),
975                1,
976                "the late result is dropped without reviving playback"
977            );
978        }
979    }
980
981    #[test]
982    fn cached_animation_disposes_its_codec_after_the_final_cache_hold_leaves() {
983        let host = Rc::new(TestHost::animation());
984        let cell = app_decoding_with(&host);
985        let stream = {
986            let mut app = cell.borrow_mut();
987            MemoryImage::from_static(b"animation").resolve(&mut app, &ImageConfiguration::EMPTY)
988        };
989        cell.checkpoint();
990        let completer;
991        {
992            let mut app = cell.borrow_mut();
993            completer = stream.completer(&app).unwrap();
994            pump_every_view(&mut app, Duration::ZERO);
995            stream.dispose(&mut app);
996            assert_eq!(
997                host.dropped.get(),
998                0,
999                "LRU retention keeps the paused codec reusable"
1000            );
1001            let cache = waft_painting::ImageCache::instance(&mut app);
1002            cache.clear(&mut app);
1003            pump_every_view(&mut app, Duration::ZERO);
1004        }
1005        cell.checkpoint();
1006        assert_eq!(host.dropped.get(), 1);
1007        assert!(!cell.borrow().contains(completer));
1008        let asked = host.asked.get();
1009        cell.elapse(Duration::from_secs(1));
1010        assert_eq!(
1011            host.asked.get(),
1012            asked,
1013            "no timer accesses the disposed playback"
1014        );
1015    }
1016
1017    #[test]
1018    fn rebuilding_static_images_reuses_the_decode_and_disposes_replaced_streams() {
1019        let host = Rc::new(TestHost::animation());
1020        let cell = app_decoding_with(&host);
1021        static DATA: [u8; 4] = *b"same";
1022        let harness = mount_image(&cell, Image::memory_static(&DATA).into_widget());
1023        cell.checkpoint();
1024        for _ in 0..8 {
1025            let mut app = cell.borrow_mut();
1026            harness.set_child(&mut app, Image::memory_static(&DATA).into_widget());
1027            harness.pump(&mut app);
1028            pump_every_view(&mut app, Duration::ZERO);
1029            drop(app);
1030            cell.checkpoint();
1031        }
1032        assert_eq!(*host.opens.borrow(), 1);
1033        {
1034            let mut app = cell.borrow_mut();
1035            harness.set_child(
1036                &mut app,
1037                crate::widgets::basic::SizedBox::shrink().into_widget(),
1038            );
1039            harness.pump(&mut app);
1040            let cache = waft_painting::ImageCache::instance(&mut app);
1041            assert_eq!(cache.live_image_count(&app), 0);
1042            cache.clear(&mut app);
1043            pump_every_view(&mut app, Duration::ZERO);
1044        }
1045        cell.checkpoint();
1046        assert_eq!(host.dropped.get(), 1);
1047    }
1048}