Skip to main content

waft_rendering/
image.rs

1//! Flutter counterpart: `rendering/image.dart` (`RenderImage`).
2//!
3//! Sizing is the interesting part: an image with no width or height given takes its own size,
4//! and one given a single dimension keeps its proportions. That is what lets a picture sit in a
5//! layout without the author having to know how big the file is.
6//!
7//! The colour blend, the nine-patch `centerSlice`, colour inversion and the filter-quality
8//! choice Dart carries are not here; see `PORTING.md`.
9
10use waft_embedder::{Offset, Size, TextDirection};
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty,
13    FlagProperty,
14};
15use waft_painting::{Alignment, BoxFit, ImageInfo, ImagePaintStyle, ImageRepeat, paint_image};
16
17use crate::box_::{BoxConstraints, RenderBox, RenderBoxData};
18use crate::object::{AnyRenderObject, RenderHandle, RenderObject, RenderObjectData};
19use crate::painting_context::PaintingContext;
20use waft_painting::ClipContext;
21
22/// Draws an image into the box it is given. Flutter `RenderImage`.
23pub struct RenderImage {
24    render_object: RenderObjectData,
25    render_box: RenderBoxData,
26    image: Option<ImageInfo>,
27    width: Option<f64>,
28    height: Option<f64>,
29    opacity: f64,
30    fit: Option<BoxFit>,
31    alignment: Alignment,
32    repeat: ImageRepeat,
33    match_text_direction: bool,
34    text_direction: Option<TextDirection>,
35}
36
37impl RenderImage {
38    /// Creates an image render object with no image yet, which lays out to nothing.
39    pub fn new(app: &mut App) -> RenderHandle<RenderImage> {
40        RenderHandle::new_box(
41            app,
42            RenderImage {
43                render_object: RenderObjectData::new(),
44                render_box: RenderBoxData::new(),
45                image: None,
46                width: None,
47                height: None,
48                opacity: 1.0,
49                fit: None,
50                alignment: Alignment::CENTER,
51                repeat: ImageRepeat::NoRepeat,
52                match_text_direction: false,
53                text_direction: None,
54            },
55        )
56    }
57
58    /// The image being drawn, if one has arrived.
59    pub fn image(self: RenderHandle<Self>, app: &App) -> Option<ImageInfo> {
60        self.get(app).image.clone()
61    }
62
63    /// Sets [`image`](Self::image).
64    ///
65    /// Laying out again is only needed while the size follows the image, which is whenever a
66    /// width or a height was left unset.
67    pub fn set_image(self: RenderHandle<Self>, app: &mut App, value: Option<ImageInfo>) {
68        if self.get(app).image == value {
69            return;
70        }
71        let follows_the_image = self.get(app).width.is_none() || self.get(app).height.is_none();
72        self.get_mut(app).image = value;
73        self.mark_needs_paint(app);
74        if follows_the_image {
75            self.mark_needs_layout(app);
76        }
77    }
78
79    /// The width to take, or `None` to follow the image.
80    pub fn width(self: RenderHandle<Self>, app: &App) -> Option<f64> {
81        self.get(app).width
82    }
83
84    /// Sets [`width`](Self::width).
85    pub fn set_width(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
86        if self.get(app).width == value {
87            return;
88        }
89        self.get_mut(app).width = value;
90        self.mark_needs_layout(app);
91    }
92
93    /// The height to take, or `None` to follow the image.
94    pub fn height(self: RenderHandle<Self>, app: &App) -> Option<f64> {
95        self.get(app).height
96    }
97
98    /// Sets [`height`](Self::height).
99    pub fn set_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
100        if self.get(app).height == value {
101            return;
102        }
103        self.get_mut(app).height = value;
104        self.mark_needs_layout(app);
105    }
106
107    /// How opaque the image is drawn, from zero to one.
108    pub fn opacity(self: RenderHandle<Self>, app: &App) -> f64 {
109        self.get(app).opacity
110    }
111
112    /// Sets [`opacity`](Self::opacity).
113    pub fn set_opacity(self: RenderHandle<Self>, app: &mut App, value: f64) {
114        if self.get(app).opacity == value {
115            return;
116        }
117        self.get_mut(app).opacity = value;
118        self.mark_needs_paint(app);
119    }
120
121    /// How the image is fitted to the box.
122    pub fn fit(self: RenderHandle<Self>, app: &App) -> Option<BoxFit> {
123        self.get(app).fit
124    }
125
126    /// Sets [`fit`](Self::fit).
127    pub fn set_fit(self: RenderHandle<Self>, app: &mut App, value: Option<BoxFit>) {
128        if self.get(app).fit == value {
129            return;
130        }
131        self.get_mut(app).fit = value;
132        self.mark_needs_paint(app);
133    }
134
135    /// Where the image sits when it does not fill the box.
136    pub fn alignment(self: RenderHandle<Self>, app: &App) -> Alignment {
137        self.get(app).alignment
138    }
139
140    /// Sets [`alignment`](Self::alignment).
141    pub fn set_alignment(self: RenderHandle<Self>, app: &mut App, value: Alignment) {
142        if self.get(app).alignment == value {
143            return;
144        }
145        self.get_mut(app).alignment = value;
146        self.mark_needs_paint(app);
147    }
148
149    /// What fills the space the image does not cover.
150    pub fn repeat(self: RenderHandle<Self>, app: &App) -> ImageRepeat {
151        self.get(app).repeat
152    }
153
154    /// Sets [`repeat`](Self::repeat).
155    pub fn set_repeat(self: RenderHandle<Self>, app: &mut App, value: ImageRepeat) {
156        if self.get(app).repeat == value {
157            return;
158        }
159        self.get_mut(app).repeat = value;
160        self.mark_needs_paint(app);
161    }
162
163    /// Whether the image is mirrored in a right-to-left layout, as a directional arrow is.
164    pub fn match_text_direction(self: RenderHandle<Self>, app: &App) -> bool {
165        self.get(app).match_text_direction
166    }
167
168    /// Sets [`match_text_direction`](Self::match_text_direction).
169    pub fn set_match_text_direction(self: RenderHandle<Self>, app: &mut App, value: bool) {
170        if self.get(app).match_text_direction == value {
171            return;
172        }
173        self.get_mut(app).match_text_direction = value;
174        self.mark_needs_paint(app);
175    }
176
177    /// The reading direction, which only matters with
178    /// [`match_text_direction`](Self::match_text_direction).
179    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> Option<TextDirection> {
180        self.get(app).text_direction
181    }
182
183    /// Sets [`text_direction`](Self::text_direction).
184    pub fn set_text_direction(
185        self: RenderHandle<Self>,
186        app: &mut App,
187        value: Option<TextDirection>,
188    ) {
189        if self.get(app).text_direction == value {
190            return;
191        }
192        self.get_mut(app).text_direction = value;
193        self.mark_needs_paint(app);
194    }
195
196    /// The size this box takes under `constraints`. Dart's `_sizeForConstraints`.
197    ///
198    /// A width and a height both given make the size exact. Otherwise the image's own size is
199    /// constrained while its proportions are kept, which is what makes one given dimension
200    /// derive the other.
201    fn size_for_constraints(
202        self: RenderHandle<Self>,
203        app: &App,
204        constraints: BoxConstraints,
205    ) -> Size {
206        let held = self.get(app);
207        let constraints = BoxConstraints::tight_for(held.width, held.height).enforce(constraints);
208        let Some(image) = &held.image else {
209            return constraints.smallest();
210        };
211        constraints.constrain_size_and_attempt_to_preserve_aspect_ratio(image.size())
212    }
213
214    /// The style `paint_image` is called with, assembled from this object's fields.
215    fn paint_style(self: RenderHandle<Self>, app: &App) -> ImagePaintStyle {
216        let held = self.get(app);
217        let scale = held.image.as_ref().map_or(1.0, |image| image.scale);
218        ImagePaintStyle {
219            scale,
220            opacity: held.opacity,
221            fit: held.fit,
222            alignment: held.alignment,
223            repeat: held.repeat,
224            flip_horizontally: held.match_text_direction
225                && held.text_direction == Some(TextDirection::Rtl),
226        }
227    }
228}
229
230impl RenderObject for RenderImage {
231    crate::render_object_accessors!();
232
233    fn debug_fill_properties(
234        self: RenderHandle<Self>,
235        app: &App,
236        properties: &mut DiagnosticPropertiesBuilder,
237    ) {
238        let this = self.get(app);
239        let image = this.image.as_ref().map(|info| {
240            let [width, height] = info.image.size();
241            format!("[{width}\u{00D7}{height}]")
242        });
243        properties.add(DiagnosticsProperty::<String>::new("image", image));
244        properties.add(DoubleProperty::new("width", this.width).default_value(None));
245        properties.add(DoubleProperty::new("height", this.height).default_value(None));
246        properties.add(EnumProperty::<BoxFit>::new("fit", this.fit).default_value(None));
247        properties.add(
248            DiagnosticsProperty::<Alignment>::new("alignment", Some(this.alignment))
249                .default_value(None),
250        );
251        properties.add(
252            EnumProperty::<ImageRepeat>::new("repeat", Some(this.repeat))
253                .default_value(Some(ImageRepeat::NoRepeat)),
254        );
255        properties.add(
256            FlagProperty::new("matchTextDirection", Some(this.match_text_direction))
257                .if_true("match text direction"),
258        );
259        properties.add(
260            EnumProperty::<TextDirection>::new("textDirection", this.text_direction)
261                .default_value(None),
262        );
263    }
264
265    fn visit_children(
266        self: RenderHandle<Self>,
267        _app: &App,
268        _visitor: &mut dyn FnMut(AnyRenderObject),
269    ) {
270        // An image has no children.
271    }
272
273    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
274        let constraints = self.constraints(app);
275        let size = self.size_for_constraints(app, constraints);
276        self.set_size(app, size);
277    }
278
279    fn paint(
280        self: RenderHandle<Self>,
281        app: &mut App,
282        context: &mut PaintingContext,
283        offset: Offset,
284    ) {
285        let Some(image) = self.get(app).image.clone() else {
286            return;
287        };
288        let size = self.size(app);
289        let style = self.paint_style(app);
290        paint_image(context.canvas(), offset & size, &image.image, &style);
291    }
292}
293
294impl RenderBox for RenderImage {
295    crate::render_box_accessors!();
296
297    /// Dart returns zero for every intrinsic when a dimension is unset, because an image with no
298    /// constraint has no preferred size of its own to report.
299    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
300        self.compute_max_intrinsic_width(app, height)
301    }
302
303    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
304        debug_assert!(height >= 0.0);
305        if self.get(app).width.is_none() && self.get(app).height.is_none() {
306            return 0.0;
307        }
308        self.size_for_constraints(app, BoxConstraints::tight_for(None, Some(height)))
309            .width()
310    }
311
312    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
313        self.compute_max_intrinsic_height(app, width)
314    }
315
316    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
317        debug_assert!(width >= 0.0);
318        if self.get(app).width.is_none() && self.get(app).height.is_none() {
319            return 0.0;
320        }
321        self.size_for_constraints(app, BoxConstraints::tight_for(Some(width), None))
322            .height()
323    }
324
325    fn compute_dry_layout(
326        self: RenderHandle<Self>,
327        app: &mut App,
328        constraints: BoxConstraints,
329    ) -> Size {
330        self.size_for_constraints(app, constraints)
331    }
332
333    /// An image absorbs a hit anywhere in its box, as every painted box does.
334    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
335        true
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use crate::testing::{EnginePhase, ignoring_hash_codes, layout_with};
342    use waft_embedder::test_support::solid_image;
343    use waft_foundation::AppCell;
344    use waft_painting::AlignmentGeometry;
345
346    use super::*;
347
348    /// `image_test.dart`: "Image sizing", its dump. `invertColors` and `filterQuality` wait for
349    /// the colour inversion and sampling choices; see `PORTING.md`.
350    #[test]
351    fn an_image_dump_shows_its_size_and_alignment() {
352        let cell = AppCell::new();
353        let mut app = cell.borrow_mut();
354        let image = solid_image([10, 10], [255, 0, 0, 255]);
355        let render = RenderImage::new(&mut app);
356        render.set_image(&mut app, Some(ImageInfo::new(image)));
357        let constraints = BoxConstraints::new()
358            .min_width(25.0)
359            .min_height(25.0)
360            .max_width(100.0)
361            .max_height(100.0);
362        layout_with(
363            &mut app,
364            render.as_box(),
365            Some(constraints),
366            AlignmentGeometry::CENTER,
367            EnginePhase::Layout,
368        );
369        assert_eq!(
370            ignoring_hash_codes(&render.as_object().to_string_deep(&app)),
371            "RenderImage#00000 relayoutBoundary=up2 NEEDS-PAINT\n\
372             \u{20}  parentData: <none> (can use size)\n\
373             \u{20}  constraints: BoxConstraints(25.0<=w<=100.0, 25.0<=h<=100.0)\n\
374             \u{20}  size: Size(25.0, 25.0)\n\
375             \u{20}  image: [10\u{00D7}10]\n\
376             \u{20}  alignment: Alignment.center\n"
377        );
378    }
379
380    /// A forty-by-twenty image, so a change of proportion is unmistakable.
381    fn wide_image(scale: f64) -> ImageInfo {
382        ImageInfo::new(solid_image([40, 20], [255, 0, 0, 255])).scale(scale)
383    }
384
385    fn loose(width: f64, height: f64) -> BoxConstraints {
386        BoxConstraints::loose(Size::new(width, height))
387    }
388
389    #[test]
390    fn an_image_that_has_not_arrived_takes_no_room() {
391        let cell = AppCell::new();
392        let mut app = cell.borrow_mut();
393        let render = RenderImage::new(&mut app);
394        assert_eq!(
395            render.compute_dry_layout(&mut app, loose(100.0, 100.0)),
396            Size::new(0.0, 0.0)
397        );
398    }
399
400    #[test]
401    fn an_image_with_no_size_given_takes_its_own() {
402        let cell = AppCell::new();
403        let mut app = cell.borrow_mut();
404        let render = RenderImage::new(&mut app);
405        render.set_image(&mut app, Some(wide_image(1.0)));
406        assert_eq!(
407            render.compute_dry_layout(&mut app, loose(1000.0, 1000.0)),
408            Size::new(40.0, 20.0)
409        );
410    }
411
412    #[test]
413    fn a_scaled_image_takes_fewer_points_than_it_has_pixels() {
414        let cell = AppCell::new();
415        let mut app = cell.borrow_mut();
416        let render = RenderImage::new(&mut app);
417        // A two-times asset: the same pixels over half the points.
418        render.set_image(&mut app, Some(wide_image(2.0)));
419        assert_eq!(
420            render.compute_dry_layout(&mut app, loose(1000.0, 1000.0)),
421            Size::new(20.0, 10.0)
422        );
423    }
424
425    #[test]
426    fn one_given_dimension_derives_the_other_from_the_proportions() {
427        let cell = AppCell::new();
428        let mut app = cell.borrow_mut();
429        let render = RenderImage::new(&mut app);
430        render.set_image(&mut app, Some(wide_image(1.0)));
431
432        render.set_width(&mut app, Some(80.0));
433        assert_eq!(
434            render.compute_dry_layout(&mut app, loose(1000.0, 1000.0)),
435            Size::new(80.0, 40.0)
436        );
437
438        render.set_width(&mut app, None);
439        render.set_height(&mut app, Some(5.0));
440        assert_eq!(
441            render.compute_dry_layout(&mut app, loose(1000.0, 1000.0)),
442            Size::new(10.0, 5.0)
443        );
444    }
445
446    #[test]
447    fn both_dimensions_given_make_the_size_exact() {
448        let cell = AppCell::new();
449        let mut app = cell.borrow_mut();
450        let render = RenderImage::new(&mut app);
451        render.set_image(&mut app, Some(wide_image(1.0)));
452        render.set_width(&mut app, Some(7.0));
453        render.set_height(&mut app, Some(9.0));
454        assert_eq!(
455            render.compute_dry_layout(&mut app, loose(1000.0, 1000.0)),
456            Size::new(7.0, 9.0)
457        );
458    }
459
460    #[test]
461    fn a_box_too_small_for_the_image_constrains_it() {
462        let cell = AppCell::new();
463        let mut app = cell.borrow_mut();
464        let render = RenderImage::new(&mut app);
465        render.set_image(&mut app, Some(wide_image(1.0)));
466        // Half the width available, so the proportions carry the height down with it.
467        assert_eq!(
468            render.compute_dry_layout(&mut app, loose(20.0, 1000.0)),
469            Size::new(20.0, 10.0)
470        );
471    }
472
473    #[test]
474    fn an_image_with_no_dimension_given_reports_no_intrinsic_size() {
475        let cell = AppCell::new();
476        let mut app = cell.borrow_mut();
477        let render = RenderImage::new(&mut app);
478        render.set_image(&mut app, Some(wide_image(1.0)));
479        // Dart's rule: without a width or a height there is no preferred size to report.
480        assert_eq!(render.compute_max_intrinsic_width(&mut app, 100.0), 0.0);
481        assert_eq!(render.compute_max_intrinsic_height(&mut app, 100.0), 0.0);
482
483        render.set_width(&mut app, Some(80.0));
484        assert_eq!(render.compute_max_intrinsic_height(&mut app, 80.0), 40.0);
485    }
486}