Skip to main content

pax_std/media/
native_image.rs

1use pax_message::AnyCreatePatch;
2use pax_runtime::api::{Layer, Property};
3use pax_runtime::{
4    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
5};
6use_RefCell!();
7use pax_engine::pax;
8use pax_runtime::api::*;
9
10use std::rc::Rc;
11
12use crate::common::{native_surface_opacity, patch_if_needed};
13use crate::ImageFit;
14
15/// A platform-native image.  This will be managed by Pax's compositor as a platform-specific
16/// host for an image, for example a DOM `<img>` element on the web, or a UIImageView on iOS.
17/// `NativeImage` is an alternative to using `pax_std::media::Image`, with various trade-offs,
18/// where the latter is managed as a GPU texture and drawn on a canvas surface.
19#[pax]
20#[engine_import_path("pax_engine")]
21#[primitive("pax_std::media::native_image::NativeImageInstance")]
22pub struct NativeImage {
23    /// Image URL/path understood by the chassis.
24    pub url: Property<String>,
25    /// How the image should fit into this node's bounds.
26    pub fit: Property<ImageFit>,
27}
28
29// Runtime instance backing `<NativeImage>`.
30pub struct NativeImageInstance {
31    base: BaseInstance,
32}
33
34impl InstanceNode for NativeImageInstance {
35    fn instantiate(args: InstantiationArgs) -> Rc<Self>
36    where
37        Self: Sized,
38    {
39        Rc::new(Self {
40            base: BaseInstance::new(
41                args,
42                InstanceFlags {
43                    invisible_to_slot: false,
44                    invisible_to_raycasting: false,
45                    layer: Layer::Native,
46                    is_component: false,
47                    is_slot: false,
48                },
49            ),
50        })
51    }
52
53    fn handle_mount(
54        self: Rc<Self>,
55        expanded_node: &Rc<ExpandedNode>,
56        context: &Rc<RuntimeContext>,
57    ) {
58        let id = expanded_node.id.to_u32();
59        context.enqueue_native_message(pax_message::NativeMessage::NativeImageCreate(
60            AnyCreatePatch {
61                id,
62                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
63                render_layer_id: 0,
64            },
65        ));
66        let weak_self_ref = Rc::downgrade(&expanded_node);
67        let context = Rc::clone(context);
68        let last_patch = Rc::new(RefCell::new(NativeImagePatch {
69            id,
70            ..Default::default()
71        }));
72
73        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
74            .values()
75            .cloned()
76            .map(|v| v.get_untyped_property().clone())
77            .chain([
78                expanded_node.transform_and_bounds.untyped(),
79                expanded_node.computed_opacity.untyped(),
80                expanded_node.occlusion.untyped(),
81            ])
82            .collect();
83        expanded_node
84            .changed_listener
85            .replace_with(Property::computed(
86                move || {
87                    let Some(expanded_node) = weak_self_ref.upgrade() else {
88                        return;
89                    };
90                    let mut old_state = borrow_mut!(last_patch);
91
92                    let mut patch = NativeImagePatch {
93                        id,
94                        ..Default::default()
95                    };
96                    expanded_node.with_properties_unwrapped(|properties: &mut NativeImage| {
97                        let computed_tab = expanded_node.transform_and_bounds.get();
98                        let (width, height) = computed_tab.bounds;
99                        let updates = [
100                            patch_if_needed(
101                                &mut old_state.url,
102                                &mut patch.url,
103                                properties.url.get(),
104                            ),
105                            patch_if_needed(
106                                &mut old_state.fit,
107                                &mut patch.fit,
108                                match properties.fit.get() {
109                                    ImageFit::Fill => "cover",
110                                    ImageFit::Fit => "contain",
111                                    ImageFit::Stretch => "fill",
112                                }
113                                .to_string(),
114                            ),
115                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
116                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
117                            patch_if_needed(
118                                &mut old_state.parent_frame,
119                                &mut patch.parent_frame,
120                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
121                            ),
122                            patch_if_needed(
123                                &mut old_state.z_index,
124                                &mut patch.z_index,
125                                expanded_node.occlusion.get().z_index,
126                            ),
127                            patch_if_needed(
128                                &mut old_state.transform,
129                                &mut patch.transform,
130                                computed_tab.transform.coeffs().to_vec(),
131                            ),
132                            patch_if_needed(
133                                &mut old_state.opacity,
134                                &mut patch.opacity,
135                                native_surface_opacity(&expanded_node, &context),
136                            ),
137                        ];
138                        if updates.into_iter().any(|v| v == true) {
139                            context.enqueue_native_message(
140                                pax_message::NativeMessage::NativeImageUpdate(patch),
141                            );
142                        }
143                    });
144                    ()
145                },
146                &deps,
147            ));
148    }
149
150    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
151        let id = expanded_node.id.clone();
152        expanded_node
153            .changed_listener
154            .replace_with(Property::default());
155        context.enqueue_native_message(pax_message::NativeMessage::NativeImageDelete(id.to_u32()));
156    }
157
158    fn base(&self) -> &BaseInstance {
159        &self.base
160    }
161
162    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
163        false
164    }
165
166    fn resolve_debug(
167        &self,
168        f: &mut std::fmt::Formatter,
169        _expanded_node: Option<&ExpandedNode>,
170    ) -> std::fmt::Result {
171        f.debug_struct("NativeImage").finish_non_exhaustive()
172    }
173}