Skip to main content

pax_std/media/
native_image.rs

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