Skip to main content

pax_std/media/
image.rs

1use kurbo::{Affine, Rect, Shape};
2use pax_engine::*;
3use pax_runtime::api::{borrow_mut, use_RefCell};
4use pax_runtime::{api::Property, api::RenderContext, ExpandedNodeIdentifier};
5use std::collections::HashSet;
6
7use_RefCell!();
8use pax_message::ImagePatch;
9use pax_runtime::{
10    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
11};
12use std::rc::Rc;
13
14use crate::common::{begin_bounded_canvas_node, patch_if_needed};
15
16/// A GPU/canvas-rendered image decoded by the active chassis.
17///
18/// `Image` draws into the node bounds and participates in the same canvas
19/// rendering path as vectors. Use `NativeImage` when a platform-native image
20/// element is preferable.
21#[pax]
22#[engine_import_path("pax_engine")]
23#[primitive("pax_std::media::image::ImageInstance")]
24pub struct Image {
25    /// Image source: empty, URL, or raw RGBA data.
26    pub source: Property<ImageSource>,
27    /// How the image should fit into this node's bounds.
28    pub fit: Property<ImageFit>,
29}
30
31/// Source data for an `Image`.
32///
33/// In Pax templates, a string in an `ImageSource` context is shorthand for
34/// [`ImageSource::Url`]:
35///
36/// ```pax
37/// <Image source="assets/spaceship.png" />
38/// <Image source={avatar_url} />
39/// ```
40///
41/// [`ImageSource::Url`] and [`ImageSource::Data`] remain available as explicit
42/// constructor forms. Unlike the list shorthands used by compound Pax types,
43/// the URL shorthand has no positional ("magic index") fields: the entire
44/// string is the URL or chassis-relative asset path.
45#[pax]
46#[derive(PartialEq)]
47#[engine_import_path("pax_engine")]
48#[custom(CoercionRules)]
49pub enum ImageSource {
50    /// No image.
51    #[default]
52    Empty,
53    /// Image loaded from a URL/path understood by the chassis.
54    Url(String),
55    /// Raw RGBA image data: width, height, and bytes where `len = width * height * 4`.
56    Data(usize, usize, Vec<u8>),
57}
58
59impl CoercionRules for ImageSource {
60    fn try_coerce(value: PaxValue) -> Result<Self, String> {
61        match value {
62            PaxValue::String(url) => Ok(Self::Url(url)),
63            PaxValue::Enum(contents) => {
64                let (enum_name, variant_name, values) = *contents;
65                if enum_name != "ImageSource" {
66                    return Err(format!(
67                        "expected ImageSource enum value, got {enum_name}::{variant_name}"
68                    ));
69                }
70
71                let expected_arity = match variant_name.as_str() {
72                    "Empty" => 0,
73                    "Url" => 1,
74                    "Data" => 3,
75                    _ => {
76                        return Err(format!(
77                            "failed to coerce ImageSource: unknown variant {variant_name:?}"
78                        ))
79                    }
80                };
81                if values.len() != expected_arity {
82                    return Err(format!(
83                        "ImageSource::{variant_name} expects {expected_arity} argument(s), got {}",
84                        values.len()
85                    ));
86                }
87
88                let mut values = values.into_iter();
89                match variant_name.as_str() {
90                    "Empty" => Ok(Self::Empty),
91                    "Url" => Ok(Self::Url(String::try_coerce(values.next().unwrap())?)),
92                    "Data" => Ok(Self::Data(
93                        usize::try_coerce(values.next().unwrap())?,
94                        usize::try_coerce(values.next().unwrap())?,
95                        Vec::<u8>::try_coerce(values.next().unwrap())?,
96                    )),
97                    _ => unreachable!(),
98                }
99            }
100            PaxValue::Option(value) => match *value {
101                Some(value) => Self::try_coerce(value),
102                None => Err("None can't be coerced into ImageSource".to_string()),
103            },
104            value => Err(format!("{value:?} can't be coerced into ImageSource")),
105        }
106    }
107}
108
109#[cfg(test)]
110mod image_source_coercion_tests {
111    use super::*;
112
113    #[test]
114    fn string_coerces_to_url() {
115        assert_eq!(
116            ImageSource::try_coerce(PaxValue::String("assets/photo.png".to_string())).unwrap(),
117            ImageSource::Url("assets/photo.png".to_string())
118        );
119    }
120
121    #[test]
122    fn explicit_variants_remain_supported() {
123        let url = PaxValue::Enum(Box::new((
124            "ImageSource".to_string(),
125            "Url".to_string(),
126            vec![PaxValue::String(
127                "https://example.com/photo.png".to_string(),
128            )],
129        )));
130        assert_eq!(
131            ImageSource::try_coerce(url).unwrap(),
132            ImageSource::Url("https://example.com/photo.png".to_string())
133        );
134
135        let empty = PaxValue::Enum(Box::new((
136            "ImageSource".to_string(),
137            "Empty".to_string(),
138            vec![],
139        )));
140        assert_eq!(ImageSource::try_coerce(empty).unwrap(), ImageSource::Empty);
141
142        let data = PaxValue::Enum(Box::new((
143            "ImageSource".to_string(),
144            "Data".to_string(),
145            vec![
146                1usize.to_pax_value(),
147                1usize.to_pax_value(),
148                vec![255u8, 128, 64, 255].to_pax_value(),
149            ],
150        )));
151        assert_eq!(
152            ImageSource::try_coerce(data).unwrap(),
153            ImageSource::Data(1, 1, vec![255, 128, 64, 255])
154        );
155    }
156}
157
158// Runtime instance backing `<Image>`.
159pub struct ImageInstance {
160    base: BaseInstance,
161    needs_to_load_data: Rc<RefCell<HashSet<ExpandedNodeIdentifier>>>,
162    initial_load: RefCell<HashSet<ExpandedNodeIdentifier>>,
163}
164
165impl InstanceNode for ImageInstance {
166    fn instantiate(args: InstantiationArgs) -> Rc<Self>
167    where
168        Self: Sized,
169    {
170        Rc::new(Self {
171            base: BaseInstance::new(
172                args,
173                InstanceFlags {
174                    invisible_to_slot: false,
175                    invisible_to_raycasting: false,
176                    layer: pax_runtime::api::Layer::Canvas,
177                    is_component: false,
178                    is_slot: false,
179                },
180            ),
181            needs_to_load_data: Default::default(),
182            initial_load: Default::default(),
183        })
184    }
185
186    fn handle_mount(
187        self: Rc<Self>,
188        expanded_node: &Rc<ExpandedNode>,
189        context: &Rc<RuntimeContext>,
190    ) {
191        let id = expanded_node.id.to_u32();
192
193        // send update message when relevant properties change
194        let weak_self_ref = Rc::downgrade(&expanded_node);
195        let last_patch = Rc::new(RefCell::new(ImagePatch {
196            id,
197            ..Default::default()
198        }));
199
200        let source =
201            expanded_node.with_properties_unwrapped(|props: &mut Image| props.source.clone());
202
203        let tab = expanded_node.transform_and_bounds.clone();
204        let deps = [tab.untyped()];
205        let cloned_context = context.clone();
206        let occlusion = expanded_node.occlusion.clone();
207        let expanded_node_id = expanded_node.id;
208
209        let tab_changed = Property::computed(
210            move || {
211                cloned_context.mark_canvas_node_dirty(expanded_node_id);
212                cloned_context.set_canvas_dirty(occlusion.get().render_layer_id);
213            },
214            &deps,
215        );
216
217        let cloned_context = context.clone();
218        let deps = [source.untyped()];
219        let needs_to_load_data = Rc::clone(&self.needs_to_load_data);
220        let source_changed = Property::computed(
221            move || {
222                let Some(expanded_node) = weak_self_ref.upgrade() else {
223                    return;
224                };
225                let mut old_state = borrow_mut!(last_patch);
226
227                let mut patch = ImagePatch {
228                    id,
229                    ..Default::default()
230                };
231                expanded_node.with_properties_unwrapped(|props: &mut Image| {
232                    let source = props.source.get();
233                    match source {
234                        ImageSource::Empty => (),
235                        ImageSource::Url(url) => {
236                            let update = patch_if_needed(&mut old_state.path, &mut patch.path, url);
237
238                            if update {
239                                cloned_context.enqueue_native_message(
240                                    pax_message::NativeMessage::ImageLoad(patch),
241                                );
242                            }
243                        }
244                        ImageSource::Data(_width, _height, _data) => {
245                            // insert to notify during render it needs to reload
246                            borrow_mut!(needs_to_load_data).insert(expanded_node.id.clone());
247                        }
248                    }
249                });
250                cloned_context.mark_canvas_node_dirty(expanded_node.id);
251                cloned_context.set_canvas_dirty(expanded_node.occlusion.get().render_layer_id)
252            },
253            &deps,
254        );
255
256        let deps = [source_changed.untyped(), tab_changed.untyped()];
257        expanded_node
258            .changed_listener
259            .replace_with(Property::computed(
260                move || {
261                    source_changed.get();
262                    tab_changed.get();
263                },
264                &deps,
265            ))
266    }
267
268    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, _context: &Rc<RuntimeContext>) {
269        let id = expanded_node.id.clone();
270        expanded_node
271            .changed_listener
272            .replace_with(Property::default());
273        borrow_mut!(self.needs_to_load_data).remove(&id);
274    }
275
276    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
277        let tab = expanded_node.transform_and_bounds.get();
278        let rect = Rect::new(0.0, 0.0, tab.bounds.0, tab.bounds.1);
279        Some(Affine::from(tab.transform) * rect.into_path(0.01))
280    }
281
282    fn render(
283        &self,
284        expanded_node: &ExpandedNode,
285        rtc: &Rc<RuntimeContext>,
286        rc: &mut dyn RenderContext,
287    ) {
288        let node_dirty = rtc.is_canvas_node_dirty(&expanded_node.id);
289        let initial_load_complete = self.initial_load.borrow().contains(&expanded_node.id);
290
291        if !node_dirty && initial_load_complete {
292            return;
293        }
294
295        let Some(scope) = begin_bounded_canvas_node(rc, expanded_node, rtc) else {
296            return;
297        };
298
299        let (container_width, container_height) = scope.bounds;
300        let mut did_draw = false;
301
302        expanded_node.with_properties_unwrapped(|props: &mut Image| {
303            let image_size_and_load_path = props.source.read(|source| {
304                match source {
305                    ImageSource::Empty => return None,
306                    ImageSource::Url(url) => {
307                        let Some((image_width, image_height)) = rc.get_image_size(&url) else {
308                            // image not loaded yet
309                            return None;
310                        };
311                        Some((image_width, image_height, url.to_string()))
312                    }
313                    &ImageSource::Data(width, height, ref data) => {
314                        let mut last_images = borrow_mut!(self.needs_to_load_data);
315                        let unique_ident = format!("raw-image-ref-{}", expanded_node.id.to_u32());
316                        if last_images.contains(&expanded_node.id) {
317                            let mut data_of_correct_len = vec![0; width * height * 4];
318                            data_of_correct_len[0..data.len()].copy_from_slice(&data);
319                            rc.load_image(&unique_ident, &data_of_correct_len, width, height);
320                            last_images.remove(&expanded_node.id);
321                        }
322                        Some((width, height, unique_ident))
323                    }
324                }
325            });
326
327            let Some((image_width, image_height, path)) = image_size_and_load_path else {
328                return;
329            };
330
331            let (image_width, image_height) = (image_width as f64, image_height as f64);
332            let stretch_w = container_width / image_width;
333            let stretch_h = container_height / image_height;
334            let (width, height) = match props.fit.get() {
335                ImageFit::Fill => {
336                    let stretch = stretch_h.max(stretch_w);
337                    (image_width * stretch, image_height * stretch)
338                }
339                ImageFit::Fit => {
340                    let stretch = stretch_h.min(stretch_w);
341                    (image_width * stretch, image_height * stretch)
342                }
343                ImageFit::Stretch => (container_width, container_height),
344            };
345            let x = (container_width - width) / 2.0;
346            let y = (container_height - height) / 2.0;
347            let transformed_bounds = kurbo::Rect::new(x, y, x + width, y + height);
348            let clip_path = kurbo::Rect::new(0.0, 0.0, container_width, container_height);
349            rc.save(scope.layer_id);
350            rc.transform(scope.layer_id, scope.surface_transform);
351            rc.clip(scope.layer_id, clip_path.into_path(0.01));
352            rc.draw_image(scope.layer_id, &path, transformed_bounds);
353            rc.restore(scope.layer_id);
354            did_draw = true;
355            self.initial_load
356                .borrow_mut()
357                .insert(expanded_node.id.clone());
358        });
359        if did_draw && rc.end_node(scope.layer_id, scope.node_id) {
360            rtc.clear_canvas_node_dirty(&expanded_node.id);
361        } else {
362            let _ = rc.end_node(scope.layer_id, scope.node_id);
363        }
364    }
365
366    fn base(&self) -> &BaseInstance {
367        &self.base
368    }
369
370    fn resolve_debug(
371        &self,
372        f: &mut std::fmt::Formatter,
373        _expanded_node: Option<&pax_runtime::ExpandedNode>,
374    ) -> std::fmt::Result {
375        f.debug_struct("Image").finish_non_exhaustive()
376    }
377}
378
379/// Image fit/layout options.
380#[pax]
381#[derive(PartialEq)]
382#[engine_import_path("pax_engine")]
383pub enum ImageFit {
384    /// Scale the image to fill its bounds, possibly clipping part of the image.
385    Fill,
386    /// Scale the image to fit within its bounds without clipping, possibly leaving empty space.
387    #[default]
388    Fit,
389    /// Stretch the image to exactly match the container.
390    Stretch,
391}