1use pax_engine::api::LocalProperty;
2use std::iter;
3use std::rc::Rc;
4
5use crate::common::{canvas_surface_transform, native_surface_opacity, patch_if_needed};
6use kurbo::{Affine, BezPath, RoundedRect, Shape};
7use pax_engine::*;
8use pax_message::{AnyCreatePatch, FramePatch};
9use pax_runtime::api::{bez_path_to_svg_path_data, Layer, Property, RenderContext};
10use pax_runtime::{
11 bind_content_measurement_effect, resolve_axis_autosize, sync_content_autosize_with_axes,
12 BaseInstance, ContentMeasurementGeometry, ExpandedNode, InstanceFlags, InstanceNode,
13 InstantiationArgs, RuntimeContext,
14};
15use_RefCell!();
16use pax_runtime::api::{borrow, borrow_mut, use_RefCell};
17
18fn mark_canvas_descendants_dirty(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
19 for child in expanded_node.children.get().iter() {
20 if borrow!(child.instance_node).base().flags().layer == Layer::Canvas {
21 context.mark_canvas_node_dirty(child.id);
22 context.set_canvas_dirty(child.occlusion.get().render_layer_id);
23 }
24 mark_canvas_descendants_dirty(child, context);
25 }
26}
27
28#[pax]
36#[engine_import_path("pax_engine")]
37#[primitive("pax_std::core::frame::FrameInstance")]
38#[custom(Default)]
39pub struct Frame {
40 pub autosize: Property<bool>,
42 pub autosize_x: Property<Option<bool>>,
44 pub autosize_y: Property<Option<bool>>,
46 pub _clip_content: Property<bool>,
48 pub corner_radius: Property<f64>,
50}
51
52impl Default for Frame {
53 fn default() -> Self {
54 Self {
55 autosize: Property::new(false),
56 autosize_x: Property::new(None),
57 autosize_y: Property::new(None),
58 _clip_content: Property::new(true),
59 corner_radius: Property::new(0.0),
60 }
61 }
62}
63
64pub struct FrameInstance {
66 base: BaseInstance,
67}
68
69impl FrameInstance {
70 fn clip_path_in_space(expanded_node: &ExpandedNode, transform: Affine) -> Option<BezPath> {
71 expanded_node.with_properties_unwrapped(|frame: &mut Frame| {
72 frame._clip_content.local().get().then(|| {
73 frame_clip_path(
74 expanded_node.transform_and_bounds.get().bounds,
75 frame.corner_radius.local().get(),
76 transform,
77 )
78 })
79 })
80 }
81}
82
83fn frame_clip_path(bounds: (f64, f64), corner_radius: f64, transform: Affine) -> BezPath {
84 let (width, height) = bounds;
85 let max_radius = 0.5 * width.max(0.0).min(height.max(0.0));
86 let radius = corner_radius.clamp(0.0, max_radius);
87 transform * RoundedRect::new(0.0, 0.0, width, height, radius).to_path(0.1)
88}
89
90impl InstanceNode for FrameInstance {
91 fn supports_alpha_source_render(&self) -> bool {
92 true
93 }
94
95 fn instantiate(args: InstantiationArgs) -> Rc<Self>
96 where
97 Self: Sized,
98 {
99 Rc::new(Self {
100 base: BaseInstance::new(
101 args,
102 InstanceFlags {
103 invisible_to_slot: false,
104 invisible_to_raycasting: true,
105 layer: Layer::DontCare,
106 is_component: false,
107 is_slot: false,
108 },
109 ),
110 })
111 }
112
113 fn requires_non_reactive_update(&self, expanded_node: &ExpandedNode) -> bool {
114 !expanded_node.content_measurement_bound.get()
115 }
116
117 fn update(self: Rc<Self>, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
118 if expanded_node.content_measurement_bound.get() {
119 return;
120 }
121 let ctx = expanded_node.get_node_context(context);
122 let (autosize, autosize_x, autosize_y) =
123 expanded_node.with_properties_unwrapped(|frame: &mut Frame| {
124 (
125 frame.autosize.local(),
126 frame.autosize_x.local(),
127 frame.autosize_y.local(),
128 )
129 });
130 let deps = [
131 autosize.untyped(),
132 autosize_x.untyped(),
133 autosize_y.untyped(),
134 ];
135 bind_content_measurement_effect(
136 expanded_node,
137 &ctx,
138 "frame autosize",
139 ContentMeasurementGeometry::Placed,
140 &deps,
141 move |node, node_ctx| {
142 sync_content_autosize_with_axes(
143 node,
144 node_ctx,
145 resolve_axis_autosize(autosize.get(), autosize_x.get(), true),
146 resolve_axis_autosize(autosize.get(), autosize_y.get(), true),
147 );
148 },
149 );
150 }
151
152 fn resolve_effect_clip_path(&self, expanded_node: &ExpandedNode) -> Option<BezPath> {
153 Self::clip_path_in_space(
154 expanded_node,
155 Affine::from(expanded_node.transform_and_bounds.get().transform),
156 )
157 }
158
159 fn handle_pre_render(
160 &self,
161 expanded_node: &ExpandedNode,
162 rtc: &Rc<RuntimeContext>,
163 rcs: &mut dyn RenderContext,
164 ) {
165 let layer_id = rcs
169 .alpha_source_layer()
170 .unwrap_or(expanded_node.occlusion.get().render_layer_id);
171
172 if rcs.alpha_source_layer().is_none() && !rtc.is_canvas_dirty(&layer_id) {
173 return;
174 }
175
176 let Some(transformed_bez_path) =
179 Self::clip_path_in_space(expanded_node, canvas_surface_transform(expanded_node, rtc))
180 else {
181 return;
182 };
183
184 if !rcs.begin_node(
187 layer_id,
188 expanded_node.id.to_u32(),
189 expanded_node.occlusion.get().z_index,
190 0,
191 ) {
192 return;
193 }
194 rcs.save(layer_id);
196 rcs.clip(layer_id, transformed_bez_path);
197 let _ = rcs.end_node(layer_id, expanded_node.id.to_u32());
198 }
199
200 fn handle_post_render(
201 &self,
202 expanded_node: &ExpandedNode,
203 rtc: &Rc<RuntimeContext>,
204 rcs: &mut dyn RenderContext,
205 ) {
206 if !expanded_node
207 .with_properties_unwrapped(|frame: &mut Frame| frame._clip_content.local().get())
208 {
209 return;
210 }
211
212 let layer_id = rcs
213 .alpha_source_layer()
214 .unwrap_or(expanded_node.occlusion.get().render_layer_id);
215
216 if rcs.alpha_source_layer().is_none() && !rtc.is_canvas_dirty(&layer_id) {
217 return;
218 }
219
220 rcs.restore(layer_id);
222 }
223
224 fn handle_mount(
225 self: Rc<Self>,
226 expanded_node: &Rc<ExpandedNode>,
227 context: &Rc<RuntimeContext>,
228 ) {
229 let id = expanded_node.id.clone();
230 if !expanded_node.is_render_source() {
231 context.enqueue_native_message(pax_message::NativeMessage::FrameCreate(
232 AnyCreatePatch {
233 id: id.to_u32(),
234 parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
235 render_layer_id: 0,
236 },
237 ));
238 }
239
240 let env = Rc::clone(&expanded_node.stack);
242 let children = borrow!(self.base().get_instance_children());
243 let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
244
245 let this_frame_prop = LocalProperty::new(Some(expanded_node.id));
247 let new_children =
248 expanded_node.generate_children(children_with_envs, context, &this_frame_prop, true);
249 expanded_node.children.set(new_children);
250
251 if expanded_node.is_render_source() {
253 return;
254 }
255
256 let weak_self_ref = Rc::downgrade(&expanded_node);
258 let cloned_context = Rc::clone(context);
259 let last_patch = Rc::new(RefCell::new(FramePatch {
260 id: id.to_u32(),
261 ..Default::default()
262 }));
263
264 let deps: Vec<_> = borrow!(expanded_node.properties_scope)
265 .values()
266 .cloned()
267 .map(|v| v.get_untyped_property().clone())
268 .chain([
269 expanded_node.transform_and_bounds.untyped(),
270 expanded_node.computed_opacity.untyped(),
271 expanded_node.occlusion.untyped(),
272 ])
273 .collect();
274
275 expanded_node
276 .changed_listener
277 .replace_with(LocalProperty::computed(
278 move || {
279 let Some(expanded_node) = weak_self_ref.upgrade() else {
280 return;
281 };
282 let id = expanded_node.id.to_u32();
283 let mut old_state = borrow_mut!(last_patch);
284
285 let mut patch = FramePatch {
286 id,
287 ..Default::default()
288 };
289 expanded_node.with_properties_unwrapped(|properties: &mut Frame| {
290 let computed_tab = expanded_node.transform_and_bounds.get();
291 let (width, height) = computed_tab.bounds;
292 let corner_radius = properties.corner_radius.local().get();
293 let max_radius = 0.5 * width.max(0.0).min(height.max(0.0));
294 let clamped_radius = corner_radius.clamp(0.0, max_radius);
295 let clip_path = if properties._clip_content.local().get()
296 && clamped_radius > f64::EPSILON
297 {
298 let rect = RoundedRect::new(0.0, 0.0, width, height, clamped_radius);
299 let bez_path = Affine::from(computed_tab.transform) * rect.to_path(0.1);
300 bez_path_to_svg_path_data(&bez_path)
301 } else {
302 String::new()
303 };
304
305 let updates = [
306 patch_if_needed(
307 &mut old_state.clip_content,
308 &mut patch.clip_content,
309 properties._clip_content.local().get(),
310 ),
311 patch_if_needed(
312 &mut old_state.corner_radius,
313 &mut patch.corner_radius,
314 corner_radius,
315 ),
316 patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
317 patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
318 patch_if_needed(
319 &mut old_state.transform,
320 &mut patch.transform,
321 computed_tab.transform.coeffs().to_vec(),
322 ),
323 patch_if_needed(
324 &mut old_state.clip_path,
325 &mut patch.clip_path,
326 clip_path,
327 ),
328 patch_if_needed(
329 &mut old_state.opacity,
330 &mut patch.opacity,
331 native_surface_opacity(&expanded_node, &cloned_context),
332 ),
333 patch_if_needed(
334 &mut old_state.parent_frame,
335 &mut patch.parent_frame,
336 expanded_node.parent_frame.get().map(|v| v.to_u32()),
337 ),
338 patch_if_needed(
339 &mut old_state.z_index,
340 &mut patch.z_index,
341 expanded_node.occlusion.get().z_index,
342 ),
343 ];
344
345 if updates.into_iter().any(|v| v == true) {
346 cloned_context.enqueue_native_message(
347 pax_message::NativeMessage::FrameUpdate(patch),
348 );
349 mark_canvas_descendants_dirty(&expanded_node, &cloned_context);
350 }
351 });
352 },
353 &deps,
354 ));
355 }
356
357 fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
358 let id = expanded_node.id.clone();
359 expanded_node
361 .changed_listener
362 .replace_with(LocalProperty::default());
363 if !expanded_node.is_render_source() {
364 context.enqueue_native_message(pax_message::NativeMessage::FrameDelete(id.to_u32()));
365 }
366 }
367
368 fn resolve_debug(
369 &self,
370 f: &mut std::fmt::Formatter,
371 expanded_node: Option<&ExpandedNode>,
372 ) -> std::fmt::Result {
373 match expanded_node {
374 Some(expanded_node) => expanded_node
375 .with_properties_unwrapped(|_f: &mut Frame| f.debug_struct("Frame").finish()),
376 None => f.debug_struct("Frame").finish_non_exhaustive(),
377 }
378 }
379
380 fn base(&self) -> &BaseInstance {
381 &self.base
382 }
383
384 fn clips_content(&self, expanded_node: &ExpandedNode) -> bool {
385 expanded_node
386 .with_properties_unwrapped(|props: &mut Frame| props._clip_content.local().get())
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 #[test]
395 fn frame_clip_tracks_its_surface_without_reapplying_the_scroller_offset() {
396 let scroller_world = Affine::translate((32.0, 80.0)) * Affine::scale(1.5);
397 let tile_in_scroller = Affine::translate((288.0, 140.0));
398 let tile_world = scroller_world * tile_in_scroller;
399 let bounds = (288.0, 140.0);
400 for radius in [0.0, 18.0, 500.0] {
401 let world_path = frame_clip_path(bounds, radius, tile_world);
402 let surface_path =
403 frame_clip_path(bounds, radius, scroller_world.inverse() * tile_world);
404 let expected = frame_clip_path(bounds, radius, tile_in_scroller);
405 assert_eq!(surface_path.bounding_box(), expected.bounding_box());
406 assert_eq!(
407 (scroller_world * surface_path).bounding_box(),
408 world_path.bounding_box()
409 );
410 }
411 }
412}