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