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