Skip to main content

cranpose_render_common/
scene_builder.rs

1use std::{any::Any, cell::Cell, rc::Rc};
2
3use cranpose_core::{
4    MemoryApplier, NodeId,
5    collections::map::{HashMap, HashSet},
6};
7use cranpose_ui::{
8    DrawCommand, LayoutBox, LayoutNode, ModifierNodeSlices, Point, PreparedTextLayout, Rect, Size,
9    SubcomposeLayoutNode, TextLayoutOptions, TextOverflow, TextPanResolver, text::TextStyle,
10};
11use cranpose_ui_graphics::{
12    CommandRecording, CompositingStrategy, GraphicsLayer, LayerShape, RoundedCornerShape,
13    rounded_corner_alpha_mask_effect,
14};
15
16use crate::{
17    SceneUpdates,
18    graph::{
19        CachePolicy, ContentChanges, DrawCommandId, DrawRunNode, HitTestNode, IsolationReasons,
20        LayerNode, PrimitiveEntry, PrimitiveNode, PrimitivePhase, ProjectiveTransform, RenderGraph,
21        RenderNode, TextPrimitiveNode,
22    },
23    layer_transform::{
24        layer_scales_or_rotates, layer_transform_to_parent, layer_transform_to_window,
25    },
26    style_shared::{DrawPlacement, recording_for_placement_reusing},
27    text_paint::{TextPaint, TextPaintCache},
28};
29
30const TEXT_CLIP_PAD: f32 = 1.0;
31const ROUNDED_CLIP_EDGE_FEATHER: f32 = 1.0;
32
33#[derive(Clone, Default)]
34struct BuildNodeSnapshot {
35    node_id: NodeId,
36    placement: Point,
37    size: Size,
38    content_offset: Point,
39    /// The node's modifier slices, shared: its draw commands, handlers and
40    /// text are read from them rather than copied out.
41    slices: Rc<ModifierNodeSlices>,
42    graphics_layer: Option<GraphicsLayer>,
43    children: Vec<Self>,
44}
45
46struct SnapshotNodeData<'a> {
47    layout_state: cranpose_ui::widgets::LayoutState,
48    modifier_slices: Rc<ModifierNodeSlices>,
49    children: &'a [NodeId],
50    window_root: bool,
51}
52
53/// Why a scoped scene update could not be applied, forcing the caller to throw
54/// the render graph away and build it again from the applier.
55///
56/// The reason has to travel with the outcome because the shell picks the
57/// scoped path from the shape of the dirty set, before this code runs, and
58/// logs that choice. A frame that chose the scoped path and then rebuilt the
59/// whole scene is the expensive case, and in the log it reads exactly like a
60/// cheap patch -- so the fallback says so itself.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum GraphRebuildReason {
63    /// The root was dirty and its replacement layer could not be built.
64    RootLayerUnavailable,
65    /// A dirty subtree's replacement layer could not be built.
66    DirtyLayerUnavailable,
67    /// This many dirty nodes own no layer in the render graph, so the scoped
68    /// walk never reached them. A node enters the graph only as a `LayerNode`;
69    /// a dirty node that never produced one -- or whose layer left the graph
70    /// this frame -- cannot be patched in place.
71    UnmatchedDirtyNodes(usize),
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum GraphUpdate {
76    Patched,
77    NeedsRebuild(GraphRebuildReason),
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct GraphUpdateReport {
82    pub update: GraphUpdate,
83    pub hit_graph_dirty: bool,
84}
85
86impl GraphUpdateReport {
87    pub fn applied(self) -> bool {
88        matches!(self.update, GraphUpdate::Patched)
89    }
90
91    pub fn rebuild_reason(self) -> Option<GraphRebuildReason> {
92        match self.update {
93            GraphUpdate::Patched => None,
94            GraphUpdate::NeedsRebuild(reason) => Some(reason),
95        }
96    }
97}
98
99#[cfg(test)]
100thread_local! {
101    static LOWERED_LAYER_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
102}
103
104fn note_layer_lowered() {
105    #[cfg(test)]
106    LOWERED_LAYER_COUNT.with(|count| count.set(count.get() + 1));
107}
108
109#[cfg(test)]
110fn reset_lowered_layer_count() {
111    LOWERED_LAYER_COUNT.with(|count| count.set(0));
112}
113
114#[cfg(test)]
115fn lowered_layer_count() -> usize {
116    LOWERED_LAYER_COUNT.with(Cell::get)
117}
118
119pub fn build_graph_from_layout_tree(root: &LayoutBox, _scale: f32) -> RenderGraph {
120    bump_recording_generation();
121    let root_snapshot = layout_box_to_snapshot(root, None);
122    let mut graph = RenderGraph::new(LayerNode::default());
123    write_snapshot_layer(root_snapshot, LowerContext::ROOT, &mut graph.root);
124    graph
125}
126
127pub fn build_graph_from_applier(
128    applier: &MemoryApplier,
129    root: NodeId,
130    _scale: f32,
131) -> Option<RenderGraph> {
132    bump_recording_generation();
133    let mut graph = RenderGraph::new(LayerNode::default());
134    lower_root_into(applier, root, &mut graph.root).then_some(graph)
135}
136
137/// Builds `root`'s graph again, its layers taking the allocations of
138/// `previous`, the graph it replaces.
139pub fn rebuild_graph_from_applier(
140    applier: &MemoryApplier,
141    root: NodeId,
142    scale: f32,
143    previous: Option<RenderGraph>,
144) -> Option<RenderGraph> {
145    let graph = match previous {
146        Some(mut graph) => {
147            release_for_rebuild(&mut graph.root);
148            bump_recording_generation();
149            graph.update += 1;
150            graph.root.note_content_change(graph.update);
151            lower_root_into(applier, root, &mut graph.root).then_some(graph)
152        }
153        None => build_graph_from_applier(applier, root, scale),
154    };
155    crate::layer_recycling::release();
156    graph
157}
158
159pub fn update_graph_from_applier(
160    applier: &MemoryApplier,
161    graph: &mut RenderGraph,
162    updates: SceneUpdates<'_>,
163    scale: f32,
164) -> bool {
165    update_graph_from_applier_report(applier, graph, updates, scale).applied()
166}
167
168pub fn update_graph_from_applier_report(
169    applier: &MemoryApplier,
170    graph: &mut RenderGraph,
171    updates: SceneUpdates<'_>,
172    _scale: f32,
173) -> GraphUpdateReport {
174    let report = update_graph_from_applier_report_inner(applier, graph, updates);
175    crate::layer_recycling::release();
176    if let GraphUpdate::NeedsRebuild(reason) = report.update
177        && cranpose_core::env_flag!("CRANPOSE_SCENE_UPDATE_DIAG")
178    {
179        eprintln!(
180            "[scene-update-diag] scoped update abandoned, whole scene rebuilt: {reason:?} dirty={}",
181            updates.content.len() + updates.layers.len() + updates.moved.len()
182        );
183    }
184    report
185}
186
187#[derive(Clone, Copy)]
188enum NodeUpdate {
189    Content,
190    Layer,
191    /// The node moved in its parent and kept its size: its layer moves and
192    /// keeps what it drew.
193    Moved,
194    /// The node moved and its layer properties changed: its layer moves,
195    /// takes the new properties and keeps what it drew.
196    MovedLayer,
197}
198
199/// Each dirty node with the update it needs: content wins over the others,
200/// and a moved node whose layer properties changed too moves with them.
201fn dirty_node_updates(updates: SceneUpdates<'_>) -> HashMap<NodeId, NodeUpdate> {
202    let mut dirty = HashMap::with_capacity_and_hasher(
203        updates.moved.len() + updates.layers.len() + updates.content.len(),
204        Default::default(),
205    );
206    dirty.extend(updates.moved.iter().map(|&id| (id, NodeUpdate::Moved)));
207    for &id in updates.layers {
208        let kind = match dirty.get(&id) {
209            Some(NodeUpdate::Moved) => NodeUpdate::MovedLayer,
210            _ => NodeUpdate::Layer,
211        };
212        dirty.insert(id, kind);
213    }
214    dirty.extend(updates.content.iter().map(|&id| (id, NodeUpdate::Content)));
215    dirty
216}
217
218fn update_graph_from_applier_report_inner(
219    applier: &MemoryApplier,
220    graph: &mut RenderGraph,
221    updates: SceneUpdates<'_>,
222) -> GraphUpdateReport {
223    if updates.is_empty() {
224        return GraphUpdateReport {
225            update: GraphUpdate::Patched,
226            hit_graph_dirty: false,
227        };
228    }
229    bump_recording_generation();
230    graph.update += 1;
231    let update = graph.update;
232
233    if cranpose_core::env_flag!("CRANPOSE_SCENE_UPDATE_DIAG") {
234        eprintln!("[scene-update-diag] dirty={updates:?}");
235    }
236
237    let mut remaining_dirty_nodes = dirty_node_updates(updates);
238    if let Some(root_id) = layer_identity(&graph.root)
239        && let Some(kind) = remaining_dirty_nodes.remove(&root_id)
240    {
241        if let Some(hit_graph_dirty) = try_update_retained_layer(
242            applier,
243            &mut graph.root,
244            &mut remaining_dirty_nodes,
245            kind,
246            true,
247            TranslateAncestorContext {
248                inherited_motion_context_animated: false,
249                update,
250                inherited_translated_content_context: false,
251                parent_content_offset: Point::default(),
252                parent_abs: AbsOrigin::ROOT,
253            },
254        ) {
255            if remaining_dirty_nodes.is_empty() {
256                return GraphUpdateReport {
257                    update: GraphUpdate::Patched,
258                    hit_graph_dirty,
259                };
260            }
261            let inherited = graph.root.translated_content_context;
262            let root_children = AbsOrigin::ROOT.children_of(&graph.root);
263            let ancestry = dirty_ancestry(applier, &remaining_dirty_nodes);
264            let walked = replace_dirty_layers_from_applier(
265                applier,
266                &mut graph.root,
267                root_children,
268                DirtyWalk {
269                    nodes: &mut remaining_dirty_nodes,
270                    ancestry: &ancestry,
271                },
272                inherited,
273                update,
274            );
275            return GraphUpdateReport {
276                update: classify_walk(applier, walked.is_some(), &mut remaining_dirty_nodes),
277                hit_graph_dirty: hit_graph_dirty || walked.is_none_or(|r| r.hit_graph_dirty),
278            };
279        }
280
281        let previous = HitGraphState::of(&graph.root);
282        release_for_rebuild(&mut graph.root);
283        if !lower_root_into(applier, root_id, &mut graph.root) {
284            return GraphUpdateReport {
285                update: GraphUpdate::NeedsRebuild(GraphRebuildReason::RootLayerUnavailable),
286                hit_graph_dirty: true,
287            };
288        }
289        let hit_graph_dirty = previous.dirty_against(&HitGraphState::of(&graph.root));
290        graph.root.note_content_change(update);
291
292        return GraphUpdateReport {
293            update: GraphUpdate::Patched,
294            hit_graph_dirty,
295        };
296    }
297
298    let inherited_translated_content_context = graph.root.translated_content_context;
299    let root_children = AbsOrigin::ROOT.children_of(&graph.root);
300    let ancestry = dirty_ancestry(applier, &remaining_dirty_nodes);
301    let Some(report) = replace_dirty_layers_from_applier(
302        applier,
303        &mut graph.root,
304        root_children,
305        DirtyWalk {
306            nodes: &mut remaining_dirty_nodes,
307            ancestry: &ancestry,
308        },
309        inherited_translated_content_context,
310        update,
311    ) else {
312        return GraphUpdateReport {
313            update: GraphUpdate::NeedsRebuild(GraphRebuildReason::DirtyLayerUnavailable),
314            hit_graph_dirty: true,
315        };
316    };
317
318    match classify_walk(applier, true, &mut remaining_dirty_nodes) {
319        GraphUpdate::Patched => GraphUpdateReport {
320            update: GraphUpdate::Patched,
321            hit_graph_dirty: report.hit_graph_dirty,
322        },
323        update => GraphUpdateReport {
324            update,
325            hit_graph_dirty: true,
326        },
327    }
328}
329
330/// The update a walk made. A dirty node the walk did not find needs the whole
331/// scene built again, unless no layer draws it.
332fn classify_walk(
333    applier: &MemoryApplier,
334    walked: bool,
335    remaining_dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
336) -> GraphUpdate {
337    if !walked {
338        return GraphUpdate::NeedsRebuild(GraphRebuildReason::DirtyLayerUnavailable);
339    }
340    remaining_dirty_nodes.retain(|&node, _| is_drawn(applier, node));
341    if !remaining_dirty_nodes.is_empty() {
342        GraphUpdate::NeedsRebuild(GraphRebuildReason::UnmatchedDirtyNodes(
343            remaining_dirty_nodes.len(),
344        ))
345    } else {
346        GraphUpdate::Patched
347    }
348}
349
350/// Whether the scene draws `node`: each subcompose node above it draws the
351/// slot `node` is in. A slot a lazy list keeps for reuse, or composes before
352/// it shows it, stays in the applier's tree without being drawn, and its
353/// nodes still change.
354fn is_drawn(applier: &MemoryApplier, node: NodeId) -> bool {
355    let mut child = node;
356    let mut current = node;
357    while let Some(parent) = applier
358        .get_ref(current)
359        .ok()
360        .and_then(cranpose_core::Node::parent)
361    {
362        let Ok(parent_node) = applier.get_ref(parent) else {
363            return true;
364        };
365        current = parent;
366        if parent_node.is_virtual() {
367            continue;
368        }
369        let parent_node: &dyn Any = parent_node;
370        if let Some(subcompose) = parent_node.downcast_ref::<SubcomposeLayoutNode>()
371            && !subcompose.with_active_children(|children| children.contains(&child))
372        {
373            return false;
374        }
375        child = parent;
376    }
377    true
378}
379
380#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
381struct ReplaceDirtyLayersReport {
382    updated: bool,
383    hit_graph_dirty: bool,
384}
385
386/// The dirty nodes a scene update has yet to find, and every node above
387/// them in the applier: a layer is lowered from its node's subtree, so a
388/// layer whose node is in neither holds no dirty layer.
389struct DirtyWalk<'a> {
390    nodes: &'a mut HashMap<NodeId, NodeUpdate>,
391    ancestry: &'a HashSet<NodeId>,
392}
393
394impl DirtyWalk<'_> {
395    fn reborrow(&mut self) -> DirtyWalk<'_> {
396        DirtyWalk {
397            nodes: self.nodes,
398            ancestry: self.ancestry,
399        }
400    }
401
402    /// Whether the subtree of a layer with `identity` may hold a dirty
403    /// layer: always for a layer without a node.
404    fn may_hold(&self, identity: Option<NodeId>) -> bool {
405        identity.is_none_or(|id| self.ancestry.contains(&id))
406    }
407}
408
409/// The applier ancestors of every node in `dirty`.
410fn dirty_ancestry(applier: &MemoryApplier, dirty: &HashMap<NodeId, NodeUpdate>) -> HashSet<NodeId> {
411    let mut ancestry = HashSet::default();
412    for &node in dirty.keys() {
413        let mut current = node;
414        while let Some(parent) = applier
415            .get_ref(current)
416            .ok()
417            .and_then(cranpose_core::Node::parent)
418        {
419            if !ancestry.insert(parent) {
420                break;
421            }
422            current = parent;
423        }
424    }
425    ancestry
426}
427
428fn replace_dirty_layers_from_applier(
429    applier: &MemoryApplier,
430    parent: &mut LayerNode,
431    parent_children: AbsOrigin,
432    mut dirty: DirtyWalk<'_>,
433    inherited_translated_content_context: bool,
434    update: u64,
435) -> Option<ReplaceDirtyLayersReport> {
436    if dirty.nodes.is_empty() {
437        return Some(ReplaceDirtyLayersReport::default());
438    }
439
440    let child_inherited_translated_content_context =
441        inherited_translated_content_context || parent.translated_content_context;
442    let mut report = ReplaceDirtyLayersReport::default();
443
444    for child in &mut parent.children {
445        if dirty.nodes.is_empty() {
446            break;
447        }
448        let RenderNode::Layer(child_layer) = child else {
449            continue;
450        };
451
452        let identity = layer_identity(child_layer);
453        if let Some(kind) = identity.and_then(|id| dirty.nodes.remove(&id)) {
454            if let Some(hit_graph_dirty) = try_update_retained_layer(
455                applier,
456                child_layer,
457                dirty.nodes,
458                kind,
459                false,
460                TranslateAncestorContext {
461                    inherited_motion_context_animated: parent.motion_context_animated,
462                    update,
463                    inherited_translated_content_context:
464                        child_inherited_translated_content_context,
465                    parent_content_offset: parent.content_offset,
466                    parent_abs: parent_children,
467                },
468            ) {
469                report.hit_graph_dirty |= hit_graph_dirty;
470                report.updated = true;
471                let child_children = parent_children.children_of(child_layer);
472                let child_report = replace_dirty_layers_from_applier(
473                    applier,
474                    child_layer,
475                    child_children,
476                    dirty.reborrow(),
477                    child_inherited_translated_content_context,
478                    update,
479                )?;
480                report.hit_graph_dirty |= child_report.hit_graph_dirty;
481                continue;
482            }
483            let node_id = layer_identity(child_layer).expect("dirty layer must have a node id");
484
485            let previous = HitGraphState::of(child_layer);
486            // Nodes that leave this subtree are gone from the scene: nothing
487            // remains to update for them, and a dirty one would otherwise go
488            // unmatched and rebuild the whole scene.
489            remove_dirty_descendants(child_layer, dirty.nodes);
490            release_for_rebuild(child_layer);
491            let context = LowerContext {
492                inherited_motion_context_animated: parent.motion_context_animated,
493                inherited_translated_content_context: child_inherited_translated_content_context,
494                parent_abs: Some(parent_children),
495                parent_content_offset: parent.content_offset,
496            };
497            read_placed_node_data(applier, node_id, false, |data| {
498                write_node_layer(applier, node_id, data, context, child_layer);
499            })?;
500            report.hit_graph_dirty |= previous.dirty_against(&HitGraphState::of(child_layer));
501            remove_dirty_descendants(child_layer, dirty.nodes);
502
503            child_layer.note_content_change(update);
504            report.updated = true;
505            continue;
506        }
507
508        if !dirty.may_hold(identity) {
509            continue;
510        }
511        let child_children = parent_children.children_of(child_layer);
512        let child_report = replace_dirty_layers_from_applier(
513            applier,
514            child_layer,
515            child_children,
516            dirty.reborrow(),
517            child_inherited_translated_content_context,
518            update,
519        )?;
520        report.updated |= child_report.updated;
521        report.hit_graph_dirty |= child_report.hit_graph_dirty;
522    }
523
524    if report.updated {
525        parent.refresh_child_facts();
526        // A layer's own sinks are not kept apart from its children's, so a
527        // child that stopped publishing leaves the flag set, which only keeps
528        // the scroll fast path off; a child that started must set it.
529        parent.has_origin_sinks |= children_have_origin_sinks(&parent.children);
530        parent.note_content_change(update);
531    }
532
533    Some(report)
534}
535
536fn translate_bail(reason: &str) -> bool {
537    if cranpose_core::env_flag!("CRANPOSE_SCENE_UPDATE_DIAG") {
538        eprintln!("[scene-update-diag] translate bail: {reason}");
539    }
540    false
541}
542
543#[derive(Clone, Copy)]
544struct TranslateAncestorContext {
545    inherited_motion_context_animated: bool,
546    /// The scene update in progress.
547    update: u64,
548    inherited_translated_content_context: bool,
549    parent_content_offset: Point,
550    parent_abs: AbsOrigin,
551}
552
553fn try_update_retained_layer(
554    applier: &MemoryApplier,
555    layer: &mut LayerNode,
556    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
557    kind: NodeUpdate,
558    root: bool,
559    ancestors: TranslateAncestorContext,
560) -> Option<bool> {
561    match kind {
562        NodeUpdate::Moved if !root => {
563            move_retained_layer(applier, layer, ancestors.parent_content_offset).or_else(|| {
564                try_translate_scrolled_layer(applier, layer, dirty_nodes, ancestors).then_some(true)
565            })
566        }
567        NodeUpdate::Content | NodeUpdate::Moved => {
568            try_translate_scrolled_layer(applier, layer, dirty_nodes, ancestors).then_some(true)
569        }
570        NodeUpdate::Layer => update_layer_properties(applier, layer, root, false, ancestors),
571        NodeUpdate::MovedLayer => update_layer_properties(applier, layer, root, true, ancestors),
572    }
573}
574
575/// Moves the layer of a node that only moved in its parent, keeping what it
576/// drew, and returns whether hit geometry changed. `None` when the layer
577/// cannot keep its content: its size changed, or its subtree publishes
578/// window origins.
579fn move_retained_layer(
580    applier: &MemoryApplier,
581    layer: &mut LayerNode,
582    parent_content_offset: Point,
583) -> Option<bool> {
584    if layer.has_origin_sinks {
585        return None;
586    }
587    let state = scene_layout_state(applier, layer_identity(layer)?)?;
588    if !state.is_placed() || Rect::from_size(state.size()) != layer.node_rect() {
589        return None;
590    }
591    let previous = HitGraphState::of(layer);
592    translate_retained_child(layer, &state, parent_content_offset);
593    Some(previous.dirty_against(&HitGraphState::of(layer)))
594}
595
596fn content_layer_mut(container: &mut LayerNode) -> Option<&mut LayerNode> {
597    let Some(node_id) = container.wraps else {
598        return Some(container);
599    };
600    container.children.iter_mut().find_map(|child| match child {
601        RenderNode::Layer(layer) if layer.node_id == Some(node_id) => Some(&mut **layer),
602        _ => None,
603    })
604}
605
606/// Whether `layer` still fits its node's layout, so new layer properties
607/// can update it in place: at `placement`, unless the node `moved`.
608fn retained_layer_matches_layout(
609    layer: &LayerNode,
610    data: &SnapshotNodeData<'_>,
611    placement: Point,
612    wrapped: bool,
613    moved: bool,
614) -> bool {
615    let state = &data.layout_state;
616    let slices = &data.modifier_slices;
617    (moved || state.position() == placement)
618        && Rect::from_size(state.size()) == layer.node_rect()
619        && slices.layer_bounds(state.size()) == layer.local_bounds
620        && state.content_offset() == layer.content_offset
621        && (slices.outer_draw_command_count() > 0) == wrapped
622}
623
624fn update_layer_properties(
625    applier: &MemoryApplier,
626    container: &mut LayerNode,
627    root: bool,
628    moved: bool,
629    ancestors: TranslateAncestorContext,
630) -> Option<bool> {
631    let node_id = layer_identity(container)?;
632    let wrapped = container.wraps.is_some();
633    // The wrapper of a node's outer draws holds its placement; a moved
634    // wrapped node is drawn again.
635    if moved && wrapped {
636        return None;
637    }
638    let placement = container.origin_in_parent;
639    let hit_graph_dirty = read_placed_node_data(applier, node_id, root, |data| {
640        let target = content_layer_mut(container)?;
641        let slices = &data.modifier_slices;
642        let state = &data.layout_state;
643        if !retained_layer_matches_layout(target, &data, placement, wrapped, moved) {
644            return None;
645        }
646        let context = LowerContext {
647            inherited_motion_context_animated: ancestors.inherited_motion_context_animated,
648            inherited_translated_content_context: ancestors.inherited_translated_content_context,
649            parent_abs: Some(ancestors.parent_abs),
650            parent_content_offset: ancestors.parent_content_offset,
651        };
652        let previous = HitGraphState::of(target);
653        let (head, child_context) = prepare_node_layer(node_id, slices, state, context);
654        assign_layer(target, head);
655        if wrapped {
656            target.transform_to_parent = layer_transform_to_parent(
657                target.local_bounds,
658                Point::default(),
659                &target.graphics_layer,
660            );
661            target.origin_in_parent = Point::default();
662        }
663        if target.has_origin_sinks
664            && let Some(child_abs) = child_context.parent_abs
665        {
666            for child in &target.children {
667                if let RenderNode::Layer(child) = child {
668                    publish_retained_window_geometry(applier, child, child_abs);
669                }
670            }
671        }
672        Some(previous.dirty_against(&HitGraphState::of(target)))
673    })??;
674    if wrapped {
675        container.refresh_child_facts();
676        container.has_origin_sinks = children_have_origin_sinks(&container.children);
677        container.forget_own_raster_cache_hashes();
678    }
679    Some(hit_graph_dirty)
680}
681
682fn publish_retained_window_geometry(
683    applier: &MemoryApplier,
684    layer: &LayerNode,
685    parent_abs: AbsOrigin,
686) {
687    if !layer.has_origin_sinks {
688        return;
689    }
690    let child_abs = parent_abs.children_of(layer);
691    if let Some(node_id) = layer.node_id {
692        read_node_data(applier, node_id, |data| {
693            data.modifier_slices.publish_window_geometry(
694                Point {
695                    x: parent_abs.content_origin.x + layer.origin_in_parent.x,
696                    y: parent_abs.content_origin.y + layer.origin_in_parent.y,
697                },
698                child_abs.window_transform,
699                data.layout_state.size(),
700            );
701        });
702    }
703    for child in &layer.children {
704        if let RenderNode::Layer(child) = child {
705            publish_retained_window_geometry(applier, child, child_abs);
706        }
707    }
708}
709
710fn try_translate_scrolled_layer(
711    applier: &MemoryApplier,
712    container: &mut LayerNode,
713    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
714    ancestors: TranslateAncestorContext,
715) -> bool {
716    let Some(node_id) = layer_identity(container) else {
717        return translate_bail("no node id");
718    };
719    read_node_data(applier, node_id, |data| {
720        if container.wraps.is_none() {
721            return translate_layer_from_data(
722                applier,
723                container,
724                dirty_nodes,
725                ancestors,
726                data,
727                false,
728            );
729        }
730        let outer_count = data.modifier_slices.outer_draw_command_count();
731        if outer_count == 0 {
732            return translate_bail("outer draws removed");
733        }
734        let size = data.layout_state.size();
735        let placement = data.layout_state.position();
736        let slices = Rc::clone(&data.modifier_slices);
737        let Some(inner) = content_layer_mut(container) else {
738            return translate_bail("wrapped layer missing");
739        };
740        if !translate_layer_from_data(applier, inner, dirty_nodes, ancestors, data, true) {
741            return false;
742        }
743        let outer = outer_draws(node_id, slices.draw_commands(), outer_count, size)
744            .expect("outer command count is nonzero");
745        let layer =
746            take_wrapped_layer(container, node_id).expect("the wrapped layer was found above");
747        write_wrapper(
748            container,
749            layer,
750            placement,
751            outer,
752            ancestors.parent_content_offset,
753        );
754        container.note_content_change(ancestors.update);
755        true
756    })
757    .unwrap_or_else(|| translate_bail("container snapshot read failed"))
758}
759
760/// What a container keeps its children under: its node, its graphics layer
761/// and its bounds at its current size.
762struct TranslatedContainer {
763    node_id: NodeId,
764    graphics_layer: Option<GraphicsLayer>,
765    local_bounds: Rect,
766    node_bounds: Option<Rect>,
767}
768
769fn translated_container(
770    container: &LayerNode,
771    layout_state: &cranpose_ui::widgets::LayoutState,
772    modifier_slices: &ModifierNodeSlices,
773    inherited_motion_context_animated: bool,
774    wrapped: bool,
775) -> Result<TranslatedContainer, &'static str> {
776    if cranpose_core::env_flag!("CRANPOSE_DISABLE_SCROLL_TRANSLATE") {
777        return Err("fast path disabled by ablation switch");
778    }
779    let Some(node_id) = container.node_id else {
780        return Err("no node id");
781    };
782    if !layout_state.is_placed() {
783        return Err("container unplaced");
784    }
785    let outer_count = modifier_slices.outer_draw_command_count();
786    if (outer_count > 0 && !wrapped)
787        || (inherited_motion_context_animated || modifier_slices.motion_context_animated())
788            != container.motion_context_animated
789        || modifier_slices.translated_content_context() != container.translated_content_context
790    {
791        return Err("container outer draws or translated context changed");
792    }
793    let clip_to_bounds = modifier_slices.clip_to_bounds();
794    if clip_to_bounds != container.clip_to_bounds {
795        return Err("container clip changed");
796    }
797    // A resized container keeps its children: only its bounds and the clip
798    // shaped to them follow its size. Any other change to its graphics layer
799    // may change what its children inherit.
800    let shaped = |bounds: Rect| {
801        graphics_layer_with_shaped_clip(
802            modifier_slices.graphics_layer(),
803            clip_to_bounds,
804            modifier_slices.corner_shape(),
805            bounds,
806        )
807    };
808    if shaped(container.local_bounds)
809        .as_ref()
810        .unwrap_or(&GraphicsLayer::DEFAULT)
811        != &*container.graphics_layer
812    {
813        return Err("container graphics layer changed");
814    }
815    let (local_bounds, node_bounds) = layer_and_node_bounds(modifier_slices, layout_state.size());
816    Ok(TranslatedContainer {
817        node_id,
818        graphics_layer: shaped(local_bounds),
819        local_bounds,
820        node_bounds,
821    })
822}
823
824/// What a scroll step reconciles a container's children in, kept between
825/// steps so a step allocates nothing of its own. Every list is empty
826/// between steps, so it holds no layer.
827#[derive(Default)]
828struct TranslateScratch {
829    /// The placed children, in their new order.
830    placed_fresh: Vec<(NodeId, cranpose_ui::widgets::LayoutState)>,
831    old_index_by_id: HashMap<NodeId, usize>,
832    /// The container's previous children by their index, until each is
833    /// kept or recycled.
834    retained: Vec<Option<Box<LayerNode>>>,
835    /// The previous children that stay, in their new order; `None` where a
836    /// child enters.
837    kept: Vec<Option<Box<LayerNode>>>,
838    /// The children built for the step, in their new order.
839    entering: Vec<(NodeId, Box<LayerNode>)>,
840}
841
842thread_local! {
843    static TRANSLATE_SCRATCH: Cell<TranslateScratch> = Cell::new(TranslateScratch::default());
844}
845
846/// Fills `scratch` with `container`'s placed children and the index of its
847/// previous ones, and returns whether they are the same children in the
848/// same order.
849fn translated_children(
850    applier: &MemoryApplier,
851    container: &LayerNode,
852    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
853    fresh_children: &[NodeId],
854    scratch: &mut TranslateScratch,
855) -> Result<bool, &'static str> {
856    let placed_fresh = &mut scratch.placed_fresh;
857    placed_fresh.clear();
858    for child_id in fresh_children {
859        let Some(state) = scene_layout_state(applier, *child_id) else {
860            continue;
861        };
862        if !state.is_placed() {
863            continue;
864        }
865        placed_fresh.push((*child_id, state));
866    }
867    let children_unchanged = container.children.len() == placed_fresh.len()
868        && container
869        .children
870        .iter()
871        .zip(placed_fresh.iter())
872        .all(|(child, (id, _))| {
873            matches!(child, RenderNode::Layer(layer) if layer_identity(layer) == Some(*id))
874        });
875    let old_index_by_id = &mut scratch.old_index_by_id;
876    old_index_by_id.clear();
877    if !children_unchanged {
878        for (index, child) in container.children.iter().enumerate() {
879            let RenderNode::Layer(layer) = child else {
880                return Err("child without node id");
881            };
882            let Some(id) = layer_identity(layer) else {
883                return Err("child without node id");
884            };
885            old_index_by_id.insert(id, index);
886        }
887    }
888    check_retained_children(
889        container,
890        dirty_nodes,
891        &scratch.placed_fresh,
892        children_unchanged,
893        &scratch.old_index_by_id,
894    )?;
895    Ok(children_unchanged)
896}
897
898/// Checks that every child kept as it is still fits its layer. A moved child
899/// that no longer fits is drawn again: it becomes a content update.
900fn check_retained_children(
901    container: &LayerNode,
902    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
903    placed_fresh: &[(NodeId, cranpose_ui::widgets::LayoutState)],
904    children_unchanged: bool,
905    old_index_by_id: &HashMap<NodeId, usize>,
906) -> Result<(), &'static str> {
907    for (fresh_index, (child_id, state)) in placed_fresh.iter().enumerate() {
908        let old_index = if children_unchanged {
909            fresh_index
910        } else if let Some(index) = old_index_by_id.get(child_id) {
911            *index
912        } else {
913            continue;
914        };
915        let RenderNode::Layer(layer) = &container.children[old_index] else {
916            return Err("retained child slot is not a layer");
917        };
918        let fits = !layer.has_origin_sinks && Rect::from_size(state.size()) == layer.node_rect();
919        match dirty_nodes.get_mut(child_id) {
920            Some(NodeUpdate::Content | NodeUpdate::Layer) => {}
921            Some(kind @ (NodeUpdate::Moved | NodeUpdate::MovedLayer)) => {
922                if !fits {
923                    *kind = NodeUpdate::Content;
924                }
925            }
926            None if layer.has_origin_sinks => {
927                return Err("child subtree publishes window origins");
928            }
929            None if !fits => return Err("child resized"),
930            None => {}
931        }
932    }
933    Ok(())
934}
935
936#[derive(Clone, Copy)]
937struct TranslateGeometry {
938    content_offset: Point,
939    window_transform: ProjectiveTransform,
940    top_left: Point,
941    child_origin: Point,
942}
943
944impl TranslateGeometry {
945    fn new(
946        layout_state: &cranpose_ui::widgets::LayoutState,
947        graphics_layer: &GraphicsLayer,
948        local_bounds: Rect,
949        parent_abs: AbsOrigin,
950    ) -> Self {
951        let content_offset = layout_state.content_offset();
952        let top_left = Point {
953            x: parent_abs.content_origin.x + layout_state.position().x,
954            y: parent_abs.content_origin.y + layout_state.position().y,
955        };
956        let window_transform = layer_transform_to_window(
957            parent_abs.window_transform,
958            top_left,
959            local_bounds,
960            graphics_layer,
961        );
962        Self {
963            content_offset,
964            window_transform,
965            top_left,
966            child_origin: Point {
967                x: top_left.x + content_offset.x,
968                y: top_left.y + content_offset.y,
969            },
970        }
971    }
972
973    fn child_abs(self) -> AbsOrigin {
974        AbsOrigin {
975            content_origin: self.child_origin,
976            window_transform: self.window_transform,
977        }
978    }
979}
980
981/// Moves `container`'s previous children that stay into `scratch.kept`, in
982/// their new order, and the subtrees of those that leave into the layer
983/// pool, so the entering children are built in their allocations.
984/// Recycles the children that leave `container`. Their nodes leave the
985/// dirty set with them: nothing remains to update for a node the scene no
986/// longer shows, and one left dirty would go unmatched and rebuild the whole
987/// scene.
988fn recycle_leaving_children(
989    container: &mut LayerNode,
990    scratch: &mut TranslateScratch,
991    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
992) {
993    let TranslateScratch {
994        placed_fresh,
995        old_index_by_id,
996        retained,
997        kept,
998        ..
999    } = scratch;
1000    retained.clear();
1001    retained.extend(container.children.drain(..).map(|child| match child {
1002        RenderNode::Layer(layer) => Some(layer),
1003        RenderNode::Primitive(_) | RenderNode::DrawRun(_) => None,
1004    }));
1005    kept.clear();
1006    kept.extend(placed_fresh.iter().map(|(child_id, _)| {
1007        old_index_by_id
1008            .get(child_id)
1009            .and_then(|index| retained[*index].take())
1010    }));
1011    for leaving in retained.drain(..).flatten() {
1012        forget_dirty_subtree(&leaving, dirty_nodes);
1013        crate::layer_recycling::recycle(leaving);
1014    }
1015}
1016
1017/// Builds the children that enter `container`. They are built from the
1018/// applier's current state, so their nodes leave the dirty set: the walk
1019/// beneath would otherwise build each of them a second time.
1020fn build_entering_children(
1021    applier: &MemoryApplier,
1022    container: &LayerNode,
1023    scratch: &mut TranslateScratch,
1024    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
1025    geometry: TranslateGeometry,
1026    inherited: (bool, u64),
1027) {
1028    let (child_inherited_translated_content_context, update) = inherited;
1029    let entering = &mut scratch.entering;
1030    entering.clear();
1031    for (child_id, _) in &scratch.placed_fresh {
1032        if scratch.old_index_by_id.contains_key(child_id) {
1033            continue;
1034        }
1035        let context = LowerContext {
1036            inherited_motion_context_animated: container.motion_context_animated,
1037            inherited_translated_content_context: child_inherited_translated_content_context,
1038            parent_abs: Some(geometry.child_abs()),
1039            parent_content_offset: geometry.content_offset,
1040        };
1041        let Some(mut lowered) = lower_child(applier, *child_id, context) else {
1042            continue;
1043        };
1044        lowered.note_content_change(update);
1045        forget_dirty_subtree(&lowered, dirty_nodes);
1046        entering.push((*child_id, lowered));
1047    }
1048}
1049
1050/// Records `container`'s own draws and text around the child layers its list
1051/// holds, in the order [`write_node_content`] writes a layer.
1052fn write_own_content_around_children(
1053    container: &mut LayerNode,
1054    node_id: NodeId,
1055    modifier_slices: &ModifierNodeSlices,
1056    size: Size,
1057) {
1058    if modifier_slices.draw_commands()[modifier_slices.outer_draw_command_count()..].is_empty()
1059        && modifier_slices.annotated_text().is_none()
1060    {
1061        return;
1062    }
1063    let mut layers = std::mem::replace(
1064        &mut container.children,
1065        crate::layer_recycling::child_list(0),
1066    );
1067    write_node_content(
1068        &mut container.children,
1069        node_id,
1070        modifier_slices,
1071        size,
1072        layers.len(),
1073        |list| list.append(&mut layers),
1074    );
1075    crate::layer_recycling::recycle_list(layers);
1076}
1077
1078fn apply_translated_container_state(
1079    container: &mut LayerNode,
1080    modifier_slices: &ModifierNodeSlices,
1081    layout_state: &cranpose_ui::widgets::LayoutState,
1082    parent_content_offset: Point,
1083    geometry: TranslateGeometry,
1084) {
1085    container.transform_to_parent = placed_transform(
1086        container.local_bounds,
1087        layout_state.position(),
1088        &container.graphics_layer,
1089        parent_content_offset,
1090    );
1091    container.content_offset = geometry.content_offset;
1092    if container.translated_content_context {
1093        container.translated_content_offset = modifier_slices
1094            .translated_content_offset()
1095            .unwrap_or(geometry.content_offset);
1096    }
1097    modifier_slices.publish_window_geometry(
1098        geometry.top_left,
1099        geometry.window_transform,
1100        layout_state.size(),
1101    );
1102    container.origin_in_parent = layout_state.position();
1103}
1104
1105fn reconcile_translated_children(
1106    container: &mut LayerNode,
1107    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
1108    scratch: &mut TranslateScratch,
1109    children_unchanged: bool,
1110    geometry: TranslateGeometry,
1111) {
1112    if children_unchanged {
1113        for (child, (child_id, state)) in container.children.iter_mut().zip(&scratch.placed_fresh) {
1114            let RenderNode::Layer(layer) = child else {
1115                unreachable!("retained child identities were checked");
1116            };
1117            if keeps_retained_child(dirty_nodes, *child_id) {
1118                translate_retained_child(layer, state, geometry.content_offset);
1119            }
1120        }
1121        return;
1122    }
1123    let mut entering = scratch.entering.drain(..).peekable();
1124    for ((child_id, state), kept) in scratch.placed_fresh.iter().zip(scratch.kept.drain(..)) {
1125        if let Some(mut layer) = kept {
1126            if keeps_retained_child(dirty_nodes, *child_id) {
1127                translate_retained_child(&mut layer, state, geometry.content_offset);
1128            }
1129            container.children.push(RenderNode::Layer(layer));
1130        } else if let Some((_, lowered)) = entering.next_if(|(id, _)| id == child_id) {
1131            dirty_nodes.remove(child_id);
1132            remove_dirty_descendants(&lowered, dirty_nodes);
1133
1134            container.children.push(RenderNode::Layer(lowered));
1135        }
1136    }
1137}
1138
1139fn translate_layer_from_data(
1140    applier: &MemoryApplier,
1141    container: &mut LayerNode,
1142    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
1143    ancestors: TranslateAncestorContext,
1144    data: SnapshotNodeData<'_>,
1145    wrapped: bool,
1146) -> bool {
1147    let TranslateAncestorContext {
1148        inherited_motion_context_animated,
1149        update,
1150        inherited_translated_content_context,
1151        parent_content_offset,
1152        parent_abs,
1153    } = ancestors;
1154    let SnapshotNodeData {
1155        layout_state,
1156        modifier_slices,
1157        children: fresh_children,
1158        window_root,
1159    } = data;
1160    let layout_state = if window_root {
1161        layout_state.at_origin()
1162    } else {
1163        layout_state
1164    };
1165    let container_plan = match translated_container(
1166        container,
1167        &layout_state,
1168        &modifier_slices,
1169        inherited_motion_context_animated,
1170        wrapped,
1171    ) {
1172        Ok(plan) => plan,
1173        Err(reason) => return translate_bail(reason),
1174    };
1175    let TranslatedContainer {
1176        node_id,
1177        graphics_layer,
1178        local_bounds,
1179        node_bounds,
1180    } = container_plan;
1181    if container.local_bounds != local_bounds {
1182        container.local_bounds = local_bounds;
1183        container.graphics_layer.replace(graphics_layer);
1184    }
1185    container.node_bounds = node_bounds;
1186    // The container's own draws and text are recorded again around the
1187    // children it keeps: an unchanged draw reuses its recording, while
1188    // building the container anew lowered every child layer beneath it too.
1189    crate::layer_recycling::recycle_primitives(container);
1190    let mut scratch = TRANSLATE_SCRATCH.take();
1191    let children_unchanged = match translated_children(
1192        applier,
1193        container,
1194        dirty_nodes,
1195        fresh_children,
1196        &mut scratch,
1197    ) {
1198        Ok(unchanged) => unchanged,
1199        Err(reason) => {
1200            TRANSLATE_SCRATCH.set(scratch);
1201            return translate_bail(reason);
1202        }
1203    };
1204
1205    let geometry = TranslateGeometry::new(
1206        &layout_state,
1207        &container.graphics_layer,
1208        container.local_bounds,
1209        parent_abs,
1210    );
1211    let child_inherited_translated_content_context =
1212        inherited_translated_content_context || container.translated_content_context;
1213    if !children_unchanged {
1214        recycle_leaving_children(container, &mut scratch, dirty_nodes);
1215        build_entering_children(
1216            applier,
1217            container,
1218            &mut scratch,
1219            dirty_nodes,
1220            geometry,
1221            (child_inherited_translated_content_context, update),
1222        );
1223    }
1224
1225    apply_translated_container_state(
1226        container,
1227        &modifier_slices,
1228        &layout_state,
1229        parent_content_offset,
1230        geometry,
1231    );
1232
1233    reconcile_translated_children(
1234        container,
1235        dirty_nodes,
1236        &mut scratch,
1237        children_unchanged,
1238        geometry,
1239    );
1240    TRANSLATE_SCRATCH.set(scratch);
1241    write_own_content_around_children(container, node_id, &modifier_slices, layout_state.size());
1242    container.hit_test = hit_test_from_slices(&modifier_slices);
1243
1244    container.has_origin_sinks = modifier_slices_have_origin_sinks(&modifier_slices)
1245        || children_have_origin_sinks(&container.children);
1246    container.refresh_child_facts();
1247    container.note_content_change(update);
1248
1249    true
1250}
1251
1252/// Whether a retained child keeps its layer as it is and only follows its
1253/// placement: it is not dirty, or it only moved, which this placement
1254/// settles.
1255fn keeps_retained_child(dirty_nodes: &mut HashMap<NodeId, NodeUpdate>, child_id: NodeId) -> bool {
1256    match dirty_nodes.get(&child_id) {
1257        None => true,
1258        Some(NodeUpdate::Moved) => {
1259            dirty_nodes.remove(&child_id);
1260            true
1261        }
1262        Some(NodeUpdate::Content | NodeUpdate::Layer | NodeUpdate::MovedLayer) => false,
1263    }
1264}
1265
1266fn translate_retained_child(
1267    layer: &mut LayerNode,
1268    state: &cranpose_ui::widgets::LayoutState,
1269    content_offset: Point,
1270) {
1271    layer.transform_to_parent = placed_transform(
1272        layer.local_bounds,
1273        state.position(),
1274        &layer.graphics_layer,
1275        content_offset,
1276    );
1277    layer.origin_in_parent = state.position();
1278}
1279
1280#[derive(PartialEq)]
1281struct HitGraphState {
1282    hit_test: bool,
1283    has_hit_targets: bool,
1284    local_bounds: Rect,
1285    node_bounds: Option<Rect>,
1286    transform_to_parent: ProjectiveTransform,
1287    clip_rect: Option<Rect>,
1288    shape: LayerShape,
1289}
1290
1291impl HitGraphState {
1292    fn of(layer: &LayerNode) -> Self {
1293        Self {
1294            hit_test: layer.hit_test.is_some(),
1295            has_hit_targets: layer.has_hit_targets,
1296            local_bounds: layer.local_bounds,
1297            node_bounds: layer.node_bounds,
1298            transform_to_parent: layer.transform_to_parent,
1299            clip_rect: layer.clip_rect(),
1300            shape: layer.graphics_layer.shape,
1301        }
1302    }
1303
1304    fn dirty_against(&self, replacement: &Self) -> bool {
1305        self.hit_test
1306            || replacement.hit_test
1307            || ((self.has_hit_targets || replacement.has_hit_targets) && self != replacement)
1308    }
1309}
1310
1311fn release_for_rebuild(layer: &mut LayerNode) {
1312    layer.hit_test = None;
1313    crate::layer_recycling::recycle_children(layer);
1314}
1315
1316/// Takes `layer`'s node and every node beneath it out of `dirty_nodes`.
1317fn forget_dirty_subtree(layer: &LayerNode, dirty_nodes: &mut HashMap<NodeId, NodeUpdate>) {
1318    if let Some(node_id) = layer_identity(layer) {
1319        dirty_nodes.remove(&node_id);
1320    }
1321    remove_dirty_descendants(layer, dirty_nodes);
1322}
1323
1324fn remove_dirty_descendants(layer: &LayerNode, dirty_nodes: &mut HashMap<NodeId, NodeUpdate>) {
1325    for child in &layer.children {
1326        let RenderNode::Layer(child_layer) = child else {
1327            continue;
1328        };
1329        if let Some(node_id) = child_layer.node_id {
1330            dirty_nodes.remove(&node_id);
1331        }
1332        remove_dirty_descendants(child_layer, dirty_nodes);
1333    }
1334}
1335
1336#[derive(Clone, Copy)]
1337struct LowerContext {
1338    inherited_motion_context_animated: bool,
1339    inherited_translated_content_context: bool,
1340    parent_abs: Option<AbsOrigin>,
1341    parent_content_offset: Point,
1342}
1343
1344impl LowerContext {
1345    const ROOT: Self = Self {
1346        inherited_motion_context_animated: false,
1347        inherited_translated_content_context: false,
1348        parent_abs: Some(AbsOrigin::ROOT),
1349        parent_content_offset: Point { x: 0.0, y: 0.0 },
1350    };
1351
1352    fn for_children(
1353        self,
1354        slices: &ModifierNodeSlices,
1355        content_offset: Point,
1356        parent_abs: Option<AbsOrigin>,
1357    ) -> Self {
1358        Self {
1359            inherited_motion_context_animated: self.inherited_motion_context_animated
1360                || slices.motion_context_animated(),
1361            inherited_translated_content_context: self.inherited_translated_content_context
1362                || slices.translated_content_context(),
1363            parent_abs,
1364            parent_content_offset: content_offset,
1365        }
1366    }
1367}
1368
1369struct LayerHead {
1370    node_id: Option<NodeId>,
1371    wraps: Option<NodeId>,
1372    local_bounds: Rect,
1373    node_bounds: Option<Rect>,
1374    transform_to_parent: ProjectiveTransform,
1375    content_offset: Point,
1376    motion_context_animated: bool,
1377    translated_content_context: bool,
1378    translated_content_offset: Point,
1379    origin_in_parent: Point,
1380    graphics_layer: Option<GraphicsLayer>,
1381    clip_to_bounds: bool,
1382    hit_test: Option<HitTestNode>,
1383    has_origin_sinks: bool,
1384    isolation: IsolationReasons,
1385    cache_policy: CachePolicy,
1386}
1387
1388struct NodeFrame {
1389    local_bounds: Rect,
1390    node_bounds: Option<Rect>,
1391    placement: Point,
1392    content_offset: Point,
1393    translated_content_offset: Point,
1394}
1395
1396fn node_layer_head(
1397    node_id: NodeId,
1398    slices: &Rc<ModifierNodeSlices>,
1399    frame: NodeFrame,
1400    graphics_layer: Option<GraphicsLayer>,
1401    context: LowerContext,
1402) -> LayerHead {
1403    let clip_to_bounds = slices.clip_to_bounds();
1404    let translated_content_context = slices.translated_content_context();
1405    let properties = graphics_layer.as_ref().unwrap_or(&GraphicsLayer::DEFAULT);
1406    let isolation = isolation_reasons(properties);
1407    LayerHead {
1408        node_id: Some(node_id),
1409        wraps: None,
1410        local_bounds: frame.local_bounds,
1411        node_bounds: frame.node_bounds,
1412        transform_to_parent: placed_transform(
1413            frame.local_bounds,
1414            frame.placement,
1415            properties,
1416            context.parent_content_offset,
1417        ),
1418        content_offset: frame.content_offset,
1419        motion_context_animated: context.inherited_motion_context_animated
1420            || slices.motion_context_animated(),
1421        translated_content_context,
1422        translated_content_offset: if translated_content_context {
1423            frame.translated_content_offset
1424        } else {
1425            Point::default()
1426        },
1427        origin_in_parent: frame.placement,
1428        cache_policy: layer_cache_policy(properties, isolation),
1429        isolation,
1430        graphics_layer,
1431        clip_to_bounds,
1432        hit_test: hit_test_from_slices(slices),
1433        has_origin_sinks: modifier_slices_have_origin_sinks(slices),
1434    }
1435}
1436
1437fn assign_layer(layer: &mut LayerNode, head: LayerHead) {
1438    let LayerNode {
1439        node_id,
1440        wraps,
1441        local_bounds,
1442        node_bounds,
1443        transform_to_parent,
1444        content_offset,
1445        motion_context_animated,
1446        translated_content_context,
1447        translated_content_offset,
1448        origin_in_parent,
1449        graphics_layer,
1450        clip_to_bounds,
1451        hit_test,
1452        has_hit_targets,
1453        has_origin_sinks,
1454        draws_within_bounds,
1455        isolation,
1456        cache_policy,
1457        cache_hashes,
1458        content_changes,
1459        children,
1460    } = layer;
1461    if *node_id != head.node_id {
1462        *content_changes = ContentChanges::default();
1463    }
1464    *node_id = head.node_id;
1465    *wraps = head.wraps;
1466    *local_bounds = head.local_bounds;
1467    *node_bounds = head.node_bounds;
1468    *transform_to_parent = head.transform_to_parent;
1469    *content_offset = head.content_offset;
1470    *motion_context_animated = head.motion_context_animated;
1471    *translated_content_context = head.translated_content_context;
1472    *translated_content_offset = head.translated_content_offset;
1473    *origin_in_parent = head.origin_in_parent;
1474    graphics_layer.replace(head.graphics_layer);
1475    *clip_to_bounds = head.clip_to_bounds;
1476    *hit_test = head.hit_test;
1477    *has_hit_targets = false;
1478    *has_origin_sinks = head.has_origin_sinks || children_have_origin_sinks(children);
1479    *draws_within_bounds = false;
1480    *isolation = head.isolation;
1481    *cache_policy = head.cache_policy;
1482    cache_hashes.set(None);
1483    layer.refresh_child_facts();
1484}
1485
1486fn children_have_origin_sinks(children: &[RenderNode]) -> bool {
1487    children.iter().any(|child| match child {
1488        RenderNode::Layer(child_layer) => child_layer.has_origin_sinks,
1489        RenderNode::Primitive(_) | RenderNode::DrawRun(_) => false,
1490    })
1491}
1492
1493fn placed_transform(
1494    local_bounds: Rect,
1495    placement: Point,
1496    graphics_layer: &GraphicsLayer,
1497    parent_content_offset: Point,
1498) -> ProjectiveTransform {
1499    let transform = layer_transform_to_parent(local_bounds, placement, graphics_layer);
1500    if parent_content_offset == Point::default() {
1501        transform
1502    } else {
1503        transform.then(ProjectiveTransform::translation(
1504            parent_content_offset.x,
1505            parent_content_offset.y,
1506        ))
1507    }
1508}
1509
1510fn write_node_content(
1511    list: &mut Vec<RenderNode>,
1512    node_id: NodeId,
1513    slices: &ModifierNodeSlices,
1514    size: Size,
1515    child_count: usize,
1516    write_children: impl FnOnce(&mut Vec<RenderNode>),
1517) {
1518    let outer_count = slices.outer_draw_command_count();
1519    let commands = &slices.draw_commands()[outer_count..];
1520    list.reserve(layer_node_capacity(
1521        commands,
1522        child_count,
1523        slices.annotated_text().is_some(),
1524    ));
1525    let first_draw = list.len();
1526    append_draw_nodes(
1527        list,
1528        node_id,
1529        commands,
1530        outer_count,
1531        DrawPass::Record(DrawPlacement::Behind),
1532        size,
1533        PrimitivePhase::BeforeChildren,
1534    );
1535    if let Some(text) = text_node_from_parts(TextNodeParts {
1536        node_id,
1537        text_rect: slices.text_content_rect(size),
1538        text_style: slices.text_style(),
1539        text_layout_options: slices.text_layout_options(),
1540        text_pan: slices.text_pan_resolver(),
1541        measured_layout: slices.measured_text_layout(),
1542    }) {
1543        list.push(RenderNode::Primitive(PrimitiveEntry {
1544            phase: PrimitivePhase::BeforeChildren,
1545            node: PrimitiveNode::Text(crate::layer_recycling::boxed_text(text)),
1546        }));
1547    }
1548    write_children(list);
1549    append_draw_nodes(
1550        list,
1551        node_id,
1552        commands,
1553        outer_count,
1554        DrawPass::OverlayFromOutput(first_draw),
1555        size,
1556        PrimitivePhase::AfterChildren,
1557    );
1558}
1559
1560fn write_layer_with_outer(
1561    target: &mut LayerNode,
1562    head: LayerHead,
1563    outer: Option<OuterDraws>,
1564    placement: Point,
1565    parent_content_offset: Point,
1566    write_children: impl FnOnce(&mut Vec<RenderNode>),
1567) {
1568    debug_assert!(target.children.is_empty(), "a layer is written emptied");
1569    let Some(outer) = outer else {
1570        write_children(&mut target.children);
1571        assign_layer(target, head);
1572        return;
1573    };
1574    let mut layer = crate::layer_recycling::layer_box();
1575    write_children(&mut layer.children);
1576    assign_layer(&mut layer, head);
1577    write_wrapper(target, layer, placement, outer, parent_content_offset);
1578}
1579
1580fn write_snapshot_layer(
1581    snapshot: BuildNodeSnapshot,
1582    context: LowerContext,
1583    target: &mut LayerNode,
1584) {
1585    let BuildNodeSnapshot {
1586        node_id,
1587        placement,
1588        size,
1589        content_offset,
1590        slices,
1591        graphics_layer,
1592        children,
1593    } = snapshot;
1594    let (local_bounds, node_bounds) = layer_and_node_bounds(&slices, size);
1595    let child_context = context.for_children(&slices, content_offset, None);
1596    let head = node_layer_head(
1597        node_id,
1598        &slices,
1599        NodeFrame {
1600            local_bounds,
1601            node_bounds,
1602            placement,
1603            content_offset,
1604            translated_content_offset: content_offset,
1605        },
1606        graphics_layer,
1607        context,
1608    );
1609    let outer = outer_draws(
1610        node_id,
1611        slices.draw_commands(),
1612        slices.outer_draw_command_count(),
1613        size,
1614    );
1615    write_layer_with_outer(
1616        target,
1617        head,
1618        outer,
1619        placement,
1620        context.parent_content_offset,
1621        |list| {
1622            write_node_content(list, node_id, &slices, size, children.len(), |list| {
1623                for child in children {
1624                    let mut layer = crate::layer_recycling::layer_box();
1625                    write_snapshot_layer(child, child_context, &mut layer);
1626                    list.push(RenderNode::Layer(layer));
1627                }
1628            });
1629        },
1630    );
1631}
1632
1633#[derive(Clone, Copy)]
1634struct AbsOrigin {
1635    content_origin: Point,
1636    window_transform: ProjectiveTransform,
1637}
1638
1639impl AbsOrigin {
1640    const ROOT: AbsOrigin = AbsOrigin {
1641        content_origin: Point { x: 0.0, y: 0.0 },
1642        window_transform: ProjectiveTransform::identity(),
1643    };
1644
1645    fn children_of(self, layer: &LayerNode) -> AbsOrigin {
1646        let top_left = Point {
1647            x: self.content_origin.x + layer.origin_in_parent.x,
1648            y: self.content_origin.y + layer.origin_in_parent.y,
1649        };
1650        AbsOrigin {
1651            content_origin: Point {
1652                x: self.content_origin.x + layer.origin_in_parent.x + layer.content_offset.x,
1653                y: self.content_origin.y + layer.origin_in_parent.y + layer.content_offset.y,
1654            },
1655            window_transform: layer_transform_to_window(
1656                self.window_transform,
1657                top_left,
1658                layer.local_bounds,
1659                &layer.graphics_layer,
1660            ),
1661        }
1662    }
1663}
1664
1665fn read_placed_node_data<R>(
1666    applier: &MemoryApplier,
1667    node_id: NodeId,
1668    root: bool,
1669    read: impl FnOnce(SnapshotNodeData<'_>) -> R,
1670) -> Option<R> {
1671    read_node_data(applier, node_id, |mut data| {
1672        if data.window_root {
1673            if !root {
1674                return None;
1675            }
1676            data.layout_state = data.layout_state.at_origin();
1677        }
1678        note_layer_lowered();
1679        if !data.layout_state.is_placed() {
1680            return None;
1681        }
1682        Some(read(data))
1683    })?
1684}
1685
1686fn lower_root_into(applier: &MemoryApplier, node_id: NodeId, target: &mut LayerNode) -> bool {
1687    read_placed_node_data(applier, node_id, true, |data| {
1688        write_node_layer(applier, node_id, data, LowerContext::ROOT, target);
1689    })
1690    .is_some()
1691}
1692
1693fn lower_child(
1694    applier: &MemoryApplier,
1695    node_id: NodeId,
1696    context: LowerContext,
1697) -> Option<Box<LayerNode>> {
1698    read_placed_node_data(applier, node_id, false, |data| {
1699        let mut layer = crate::layer_recycling::layer_box();
1700        write_node_layer(applier, node_id, data, context, &mut layer);
1701        layer
1702    })
1703}
1704
1705fn scene_layout_state(
1706    applier: &MemoryApplier,
1707    node_id: NodeId,
1708) -> Option<cranpose_ui::widgets::LayoutState> {
1709    let node: &dyn Any = applier.get_ref(node_id).ok()?;
1710    if let Some(node) = node.downcast_ref::<LayoutNode>() {
1711        return Some(node.layout_state());
1712    }
1713    node.downcast_ref::<SubcomposeLayoutNode>()
1714        .map(SubcomposeLayoutNode::layout_state)
1715}
1716
1717fn read_node_data<R>(
1718    applier: &MemoryApplier,
1719    node_id: NodeId,
1720    read: impl FnOnce(SnapshotNodeData<'_>) -> R,
1721) -> Option<R> {
1722    let node: &dyn Any = applier.get_ref(node_id).ok()?;
1723    if let Some(node) = node.downcast_ref::<LayoutNode>() {
1724        return Some(read(SnapshotNodeData {
1725            layout_state: node.layout_state(),
1726            modifier_slices: node.modifier_slices_snapshot(),
1727            children: &node.children,
1728            window_root: node.is_window_root(),
1729        }));
1730    }
1731    let node = node.downcast_ref::<SubcomposeLayoutNode>()?;
1732    let layout_state = node.layout_state();
1733    let modifier_slices = node.modifier_slices_snapshot();
1734    Some(node.with_active_children(|children| {
1735        read(SnapshotNodeData {
1736            layout_state,
1737            modifier_slices,
1738            children,
1739            window_root: false,
1740        })
1741    }))
1742}
1743
1744fn hit_test_from_slices(slices: &Rc<ModifierNodeSlices>) -> Option<HitTestNode> {
1745    slices_hit_something(slices).then(|| HitTestNode {
1746        handlers: Rc::clone(slices),
1747    })
1748}
1749
1750/// A node's layer bounds and, when they differ from it, its own rect (see
1751/// [`LayerNode::node_bounds`]).
1752fn layer_and_node_bounds(slices: &ModifierNodeSlices, size: Size) -> (Rect, Option<Rect>) {
1753    let node_bounds = Rect::from_size(size);
1754    let layer_bounds = slices.layer_bounds(size);
1755    (
1756        layer_bounds,
1757        (layer_bounds != node_bounds).then_some(node_bounds),
1758    )
1759}
1760
1761/// Whether a node's slices make it a hit target: a pointer input or a
1762/// pointer icon.
1763fn slices_hit_something(slices: &ModifierNodeSlices) -> bool {
1764    !slices.pointer_inputs().is_empty() || slices.pointer_icon().is_some()
1765}
1766
1767fn prepare_node_layer(
1768    node_id: NodeId,
1769    slices: &Rc<ModifierNodeSlices>,
1770    layout_state: &cranpose_ui::widgets::LayoutState,
1771    context: LowerContext,
1772) -> (LayerHead, LowerContext) {
1773    let size = layout_state.size();
1774    let placement = layout_state.position();
1775    let (local_bounds, node_bounds) = layer_and_node_bounds(slices, size);
1776    let graphics_layer = graphics_layer_with_shaped_clip(
1777        slices.graphics_layer(),
1778        slices.clip_to_bounds(),
1779        slices.corner_shape(),
1780        local_bounds,
1781    );
1782    let geometry = context.parent_abs.map(|parent_abs| {
1783        TranslateGeometry::new(
1784            layout_state,
1785            graphics_layer.as_ref().unwrap_or(&GraphicsLayer::DEFAULT),
1786            local_bounds,
1787            parent_abs,
1788        )
1789    });
1790    if let Some(geometry) = geometry {
1791        slices.publish_window_geometry(geometry.top_left, geometry.window_transform, size);
1792    } else {
1793        slices.publish_pointer_input_size(size);
1794    }
1795    let content_offset = layout_state.content_offset();
1796    let child_context = context.for_children(
1797        slices,
1798        content_offset,
1799        geometry.map(TranslateGeometry::child_abs),
1800    );
1801    let head = node_layer_head(
1802        node_id,
1803        slices,
1804        NodeFrame {
1805            local_bounds,
1806            node_bounds,
1807            placement,
1808            content_offset,
1809            translated_content_offset: slices.translated_content_offset().unwrap_or(content_offset),
1810        },
1811        graphics_layer,
1812        context,
1813    );
1814    (head, child_context)
1815}
1816
1817fn write_node_layer(
1818    applier: &MemoryApplier,
1819    node_id: NodeId,
1820    data: SnapshotNodeData<'_>,
1821    context: LowerContext,
1822    target: &mut LayerNode,
1823) {
1824    let SnapshotNodeData {
1825        layout_state,
1826        modifier_slices: slices,
1827        children,
1828        window_root: _,
1829    } = data;
1830    let size = layout_state.size();
1831    let placement = layout_state.position();
1832    if cranpose_core::env_flag!("CRANPOSE_SCENE_UPDATE_DIAG") {
1833        eprintln!(
1834            "[scene-update-diag] build layer node={node_id:?} size=({:.2},{:.2}) pos=({:.2},{:.2})",
1835            size.width, size.height, placement.x, placement.y,
1836        );
1837    }
1838    let (head, child_context) = prepare_node_layer(node_id, &slices, &layout_state, context);
1839    let outer = outer_draws(
1840        node_id,
1841        slices.draw_commands(),
1842        slices.outer_draw_command_count(),
1843        size,
1844    );
1845    write_layer_with_outer(
1846        target,
1847        head,
1848        outer,
1849        placement,
1850        context.parent_content_offset,
1851        |list| {
1852            write_node_content(list, node_id, &slices, size, children.len(), |list| {
1853                for &child_id in children {
1854                    if let Some(child) = lower_child(applier, child_id, child_context) {
1855                        list.push(RenderNode::Layer(child));
1856                    }
1857                }
1858            });
1859        },
1860    );
1861}
1862
1863struct RecorderSlot {
1864    generation: u64,
1865    handles: [Option<Rc<CommandRecording>>; 3],
1866    /// The allocation of a handle whose recording `acquire_storage` took,
1867    /// which the next recording the slot publishes moves into.
1868    spare: Option<Rc<CommandRecording>>,
1869}
1870
1871#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1872struct RecorderKey {
1873    node_id: NodeId,
1874    command_index: u32,
1875}
1876
1877impl From<DrawCommandId> for RecorderKey {
1878    fn from(id: DrawCommandId) -> Self {
1879        Self {
1880            node_id: id.node_id,
1881            command_index: id.command_index,
1882        }
1883    }
1884}
1885
1886thread_local! {
1887    static COMMAND_RECORDINGS: std::cell::RefCell<
1888        std::collections::HashMap<RecorderKey, RecorderSlot, cranpose_ui_graphics::FxBuildHasher>,
1889    > = std::cell::RefCell::new(std::collections::HashMap::default());
1890    static RECORDING_GENERATION: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1891}
1892
1893#[doc(hidden)]
1894pub fn clear_command_recordings_for_tests() {
1895    COMMAND_RECORDINGS.with(|map| map.borrow_mut().clear());
1896}
1897
1898fn bump_recording_generation() {
1899    let generation = RECORDING_GENERATION.with(|cell| {
1900        let next = cell.get().wrapping_add(1);
1901        cell.set(next);
1902        next
1903    });
1904    if generation.is_multiple_of(512) {
1905        COMMAND_RECORDINGS.with(|map| {
1906            map.borrow_mut()
1907                .retain(|_, slot| generation.wrapping_sub(slot.generation) <= 64);
1908        });
1909    }
1910}
1911
1912fn acquire_storage(id: DrawCommandId) -> CommandRecording {
1913    COMMAND_RECORDINGS.with(|map| {
1914        let mut map = map.borrow_mut();
1915        let Some(slot) = map.get_mut(&RecorderKey::from(id)) else {
1916            return CommandRecording::default();
1917        };
1918        for handle in &mut slot.handles {
1919            let Some(recording) = handle.as_mut().and_then(Rc::get_mut) else {
1920                continue;
1921            };
1922            let Some(storage) = recording.try_take_reusable() else {
1923                continue;
1924            };
1925            slot.spare = handle.take();
1926            return storage;
1927        }
1928        if slot.handles.iter().all(Option::is_some) {
1929            let storage = slot.handles[2]
1930                .as_mut()
1931                .and_then(Rc::get_mut)
1932                .map(std::mem::take);
1933            if let Some(storage) = storage {
1934                slot.spare = slot.handles[2].take();
1935                return storage;
1936            }
1937        }
1938        CommandRecording::default()
1939    })
1940}
1941
1942fn publish_recording(id: DrawCommandId, recording: CommandRecording) -> Rc<CommandRecording> {
1943    COMMAND_RECORDINGS.with(|map| {
1944        let mut map = map.borrow_mut();
1945        let generation = RECORDING_GENERATION.with(Cell::get);
1946        let slot = map
1947            .entry(RecorderKey::from(id))
1948            .or_insert_with(|| RecorderSlot {
1949                generation,
1950                handles: [None, None, None],
1951                spare: None,
1952            });
1953        let shared = match slot.spare.take() {
1954            Some(mut spare) => match Rc::get_mut(&mut spare) {
1955                Some(storage) => {
1956                    *storage = recording;
1957                    spare
1958                }
1959                None => Rc::new(recording),
1960            },
1961            None => Rc::new(recording),
1962        };
1963        slot.generation = generation;
1964        slot.handles[2] = slot.handles[1].take();
1965        slot.handles[1] = slot.handles[0].take();
1966        slot.handles[0] = Some(Rc::clone(&shared));
1967        shared
1968    })
1969}
1970
1971enum DrawPass<'a> {
1972    Record(DrawPlacement),
1973    OverlayFrom(std::slice::Iter<'a, RenderNode>),
1974    OverlayFromOutput(usize),
1975}
1976
1977impl DrawPass<'_> {
1978    fn placement(&self) -> DrawPlacement {
1979        match self {
1980            Self::Record(placement) => *placement,
1981            Self::OverlayFrom(_) | Self::OverlayFromOutput(_) => DrawPlacement::Overlay,
1982        }
1983    }
1984
1985    fn take_recording(
1986        &mut self,
1987        command: &DrawCommand,
1988        output: &[RenderNode],
1989    ) -> Option<Rc<CommandRecording>> {
1990        if matches!(command, DrawCommand::Overlay(_)) {
1991            return None;
1992        }
1993        let node = match self {
1994            Self::Record(_) => return None,
1995            Self::OverlayFrom(nodes) => nodes.next().expect("each behind command has a draw run"),
1996            Self::OverlayFromOutput(index) => {
1997                let node = &output[*index];
1998                *index += 1;
1999                node
2000            }
2001        };
2002        let RenderNode::DrawRun(run) = node else {
2003            unreachable!("behind commands produce draw runs");
2004        };
2005        matches!(command, DrawCommand::WithContent(_)).then(|| Rc::clone(&run.recording))
2006    }
2007}
2008
2009fn layer_node_capacity(commands: &[DrawCommand], children: usize, has_text: bool) -> usize {
2010    children
2011        + usize::from(has_text)
2012        + commands.len()
2013        + commands
2014            .iter()
2015            .filter(|command| matches!(command, DrawCommand::WithContent(_)))
2016            .count()
2017}
2018
2019fn draw_nodes(
2020    node_id: NodeId,
2021    commands: &[DrawCommand],
2022    first_command_index: usize,
2023    placement: DrawPlacement,
2024    size: Size,
2025    phase: PrimitivePhase,
2026) -> Vec<RenderNode> {
2027    let mut nodes = crate::layer_recycling::child_list(commands.len());
2028    append_draw_nodes(
2029        &mut nodes,
2030        node_id,
2031        commands,
2032        first_command_index,
2033        DrawPass::Record(placement),
2034        size,
2035        phase,
2036    );
2037    nodes
2038}
2039
2040fn append_draw_nodes(
2041    nodes: &mut Vec<RenderNode>,
2042    node_id: NodeId,
2043    commands: &[DrawCommand],
2044    first_command_index: usize,
2045    mut pass: DrawPass<'_>,
2046    size: Size,
2047    phase: PrimitivePhase,
2048) {
2049    let placement = pass.placement();
2050    for (command_index, command) in commands.iter().enumerate() {
2051        let id = DrawCommandId {
2052            node_id,
2053            command_index: (first_command_index + command_index) as u32,
2054            placement,
2055        };
2056        let (shared, segments) = if let Some(shared) = pass.take_recording(command, nodes) {
2057            let segments = shared.content_split(false);
2058            (shared, segments)
2059        } else {
2060            let Some((recording, segments)) =
2061                recording_for_placement_reusing(command, placement, size, || acquire_storage(id))
2062            else {
2063                continue;
2064            };
2065            (publish_recording(id, recording), segments)
2066        };
2067        nodes.push(RenderNode::DrawRun(DrawRunNode::for_command_shared(
2068            phase,
2069            Some(id),
2070            shared,
2071            segments,
2072        )));
2073    }
2074}
2075
2076#[doc(hidden)]
2077pub fn draw_command_nodes_for_tests(
2078    node_id: NodeId,
2079    commands: &[DrawCommand],
2080    placement: DrawPlacement,
2081    size: Size,
2082    phase: PrimitivePhase,
2083) -> Vec<RenderNode> {
2084    bump_recording_generation();
2085    draw_nodes(node_id, commands, 0, placement, size, phase)
2086}
2087
2088struct OuterDraws {
2089    behind: Vec<RenderNode>,
2090    overlay: Vec<RenderNode>,
2091}
2092
2093fn outer_draws(
2094    node_id: NodeId,
2095    draw_commands: &[DrawCommand],
2096    outer_draw_command_count: usize,
2097    size: Size,
2098) -> Option<OuterDraws> {
2099    (outer_draw_command_count > 0).then(|| {
2100        let commands = &draw_commands[..outer_draw_command_count];
2101        let behind = draw_nodes(
2102            node_id,
2103            commands,
2104            0,
2105            DrawPlacement::Behind,
2106            size,
2107            PrimitivePhase::BeforeChildren,
2108        );
2109        let mut overlay = crate::layer_recycling::child_list(commands.len());
2110        append_draw_nodes(
2111            &mut overlay,
2112            node_id,
2113            commands,
2114            0,
2115            DrawPass::OverlayFrom(behind.iter()),
2116            size,
2117            PrimitivePhase::AfterChildren,
2118        );
2119        OuterDraws { behind, overlay }
2120    })
2121}
2122
2123fn write_wrapper(
2124    wrapper: &mut LayerNode,
2125    mut layer: Box<LayerNode>,
2126    placement: Point,
2127    outer: OuterDraws,
2128    parent_content_offset: Point,
2129) {
2130    debug_assert!(wrapper.children.is_empty(), "a wrapper is written emptied");
2131    layer.transform_to_parent =
2132        layer_transform_to_parent(layer.local_bounds, Point::default(), &layer.graphics_layer);
2133    layer.origin_in_parent = Point::default();
2134    let node_rect = layer.node_rect();
2135    let graphics_layer = None;
2136    let head = LayerHead {
2137        node_id: None,
2138        wraps: layer.node_id,
2139        local_bounds: node_rect,
2140        node_bounds: None,
2141        transform_to_parent: placed_transform(
2142            node_rect,
2143            placement,
2144            &GraphicsLayer::DEFAULT,
2145            parent_content_offset,
2146        ),
2147        content_offset: Point::default(),
2148        motion_context_animated: layer.motion_context_animated,
2149        translated_content_context: false,
2150        translated_content_offset: Point::default(),
2151        origin_in_parent: placement,
2152        graphics_layer,
2153        clip_to_bounds: false,
2154        hit_test: None,
2155        has_origin_sinks: false,
2156        isolation: IsolationReasons::default(),
2157        cache_policy: CachePolicy::None,
2158    };
2159    let OuterDraws {
2160        mut behind,
2161        mut overlay,
2162    } = outer;
2163    let children = &mut wrapper.children;
2164    children.reserve(behind.len() + 1 + overlay.len());
2165    children.append(&mut behind);
2166    children.push(RenderNode::Layer(layer));
2167    children.append(&mut overlay);
2168    crate::layer_recycling::recycle_list(behind);
2169    crate::layer_recycling::recycle_list(overlay);
2170    assign_layer(wrapper, head);
2171}
2172
2173fn take_wrapped_layer(wrapper: &mut LayerNode, node_id: NodeId) -> Option<Box<LayerNode>> {
2174    let mut wrapped = None;
2175    for child in wrapper.children.drain(..) {
2176        if let RenderNode::Layer(layer) = child
2177            && layer.node_id == Some(node_id)
2178        {
2179            wrapped = Some(layer);
2180        }
2181    }
2182    wrapped
2183}
2184
2185fn layer_identity(layer: &LayerNode) -> Option<NodeId> {
2186    layer.node_id.or(layer.wraps)
2187}
2188
2189struct TextNodeParts<'a> {
2190    node_id: NodeId,
2191    /// Where the text node was placed in its layout node.
2192    text_rect: Rect,
2193    text_style: Option<&'a TextStyle>,
2194    text_layout_options: Option<TextLayoutOptions>,
2195    text_pan: Option<TextPanResolver>,
2196    measured_layout: Option<Rc<PreparedTextLayout>>,
2197}
2198
2199fn text_node_from_parts(parts: TextNodeParts<'_>) -> Option<TextPrimitiveNode> {
2200    let TextNodeParts {
2201        node_id,
2202        text_rect,
2203        text_style,
2204        text_layout_options,
2205        text_pan,
2206        measured_layout,
2207    } = parts;
2208    let prepared = measured_layout?;
2209    let default_text_style;
2210    let text_style = match text_style {
2211        Some(style) => style,
2212        None => {
2213            default_text_style = TextStyle::default();
2214            &default_text_style
2215        }
2216    };
2217    let options = text_layout_options.unwrap_or_default().normalized();
2218    let content_width = text_rect.width.max(0.0);
2219    if content_width <= 0.0 {
2220        return None;
2221    }
2222
2223    let pan_offset = text_pan
2224        .as_ref()
2225        .map_or(0.0, |resolve| resolve(content_width));
2226    let pans_horizontally = text_pan.is_some();
2227
2228    let visual_style = &prepared.visual_style;
2229    let measured_draw_width = prepared.metrics.width.max(0.0);
2230    let draw_width = if options.overflow == TextOverflow::Visible || pans_horizontally {
2231        measured_draw_width
2232    } else {
2233        measured_draw_width.min(content_width)
2234    };
2235    let alignment_offset = resolve_text_horizontal_offset(
2236        text_style,
2237        prepared.text.text.as_str(),
2238        content_width,
2239        prepared.metrics.width,
2240    );
2241    let rect = Rect {
2242        x: text_rect.x + alignment_offset - pan_offset,
2243        y: text_rect.y,
2244        width: draw_width,
2245        height: prepared.metrics.height,
2246    };
2247    let text_bounds = Rect {
2248        width: content_width,
2249        height: text_rect.height.max(0.0),
2250        ..text_rect
2251    };
2252    let font_size = visual_style.resolve_font_size(14.0);
2253    let expanded_bounds =
2254        expand_text_bounds_for_baseline_shift(text_bounds, visual_style, font_size);
2255    let clip = if options.overflow == TextOverflow::Visible && !pans_horizontally {
2256        None
2257    } else {
2258        Some(pad_clip_rect(expanded_bounds))
2259    };
2260
2261    Some(TextPrimitiveNode {
2262        node_id,
2263        rect,
2264        text: Rc::clone(&prepared.text),
2265        render_text: prepared.render_text(),
2266        text_style: std::sync::Arc::clone(visual_style),
2267        font_size,
2268        layout_options: options,
2269        clip,
2270        paint: TextPaintCache::holding(TextPaint::of(
2271            visual_style,
2272            &prepared.text.span_styles,
2273            font_size,
2274        )),
2275    })
2276}
2277
2278fn layout_box_to_snapshot(node: &LayoutBox, parent: Option<&LayoutBox>) -> BuildNodeSnapshot {
2279    let placement = parent
2280        .map(|parent_box| Point {
2281            x: node.rect.x - parent_box.rect.x - parent_box.content_offset.x,
2282            y: node.rect.y - parent_box.rect.y - parent_box.content_offset.y,
2283        })
2284        .unwrap_or_default();
2285    let mut children = Vec::with_capacity(node.children.len());
2286    for child in &node.children {
2287        children.push(layout_box_to_snapshot(child, Some(node)));
2288    }
2289    let base_graphics_layer = node.node_data.modifier_slices.graphics_layer();
2290    let has_graphics_layer = base_graphics_layer.is_some();
2291    let graphics_layer = graphics_layer_with_shaped_clip(
2292        base_graphics_layer,
2293        node.node_data.modifier_slices.clip_to_bounds(),
2294        node.node_data.modifier_slices.corner_shape(),
2295        Rect {
2296            x: 0.0,
2297            y: 0.0,
2298            width: node.rect.width,
2299            height: node.rect.height,
2300        },
2301    );
2302    let has_graphics_layer = has_graphics_layer
2303        || graphics_layer
2304            .as_ref()
2305            .is_some_and(|layer| layer.render_effect.is_some());
2306
2307    BuildNodeSnapshot {
2308        node_id: node.node_id,
2309        placement,
2310        size: Size {
2311            width: node.rect.width,
2312            height: node.rect.height,
2313        },
2314        content_offset: node.content_offset,
2315        slices: Rc::clone(&node.node_data.modifier_slices),
2316        graphics_layer: graphics_layer.filter(|_| has_graphics_layer),
2317        children,
2318    }
2319}
2320
2321fn modifier_slices_have_origin_sinks(slices: &ModifierNodeSlices) -> bool {
2322    slices.text_window_transform().is_some() || slices.viewport_window_rect().is_some()
2323}
2324
2325fn graphics_layer_with_shaped_clip(
2326    mut graphics_layer: Option<GraphicsLayer>,
2327    clip_to_bounds: bool,
2328    corner_shape: Option<RoundedCornerShape>,
2329    local_bounds: Rect,
2330) -> Option<GraphicsLayer> {
2331    if !clip_to_bounds {
2332        return graphics_layer;
2333    }
2334
2335    let Some(corner_shape) = corner_shape else {
2336        return graphics_layer;
2337    };
2338    let radii = corner_shape.resolve(local_bounds.width, local_bounds.height);
2339    if radii.top_left <= f32::EPSILON
2340        && radii.top_right <= f32::EPSILON
2341        && radii.bottom_right <= f32::EPSILON
2342        && radii.bottom_left <= f32::EPSILON
2343    {
2344        return graphics_layer;
2345    }
2346
2347    let properties = graphics_layer.get_or_insert_default();
2348    if let Some(existing) = properties.render_effect.take() {
2349        let rounded_clip = rounded_corner_alpha_mask_effect(
2350            local_bounds.width,
2351            local_bounds.height,
2352            radii,
2353            ROUNDED_CLIP_EDGE_FEATHER,
2354        );
2355        properties.render_effect = Some(existing.then(rounded_clip));
2356    } else {
2357        properties.shape = LayerShape::Rounded(corner_shape);
2358        properties.clip = true;
2359    }
2360    graphics_layer
2361}
2362
2363fn layer_cache_policy(layer: &GraphicsLayer, isolation: IsolationReasons) -> CachePolicy {
2364    if isolation.has_any() || layer_scales_or_rotates(layer) {
2365        CachePolicy::Auto
2366    } else {
2367        CachePolicy::None
2368    }
2369}
2370
2371fn isolation_reasons(layer: &GraphicsLayer) -> IsolationReasons {
2372    IsolationReasons {
2373        explicit_offscreen: layer.compositing_strategy == CompositingStrategy::Offscreen,
2374        shape_clip: layer.clip && !matches!(layer.shape, LayerShape::Rectangle),
2375        effect: layer.render_effect.is_some(),
2376        backdrop: layer.backdrop_effect.is_some(),
2377        group_opacity: layer.compositing_strategy != CompositingStrategy::ModulateAlpha
2378            && layer.alpha < 1.0,
2379        blend_mode: layer.blend_mode != cranpose_ui::BlendMode::SrcOver,
2380    }
2381}
2382
2383fn pad_clip_rect(rect: Rect) -> Rect {
2384    Rect {
2385        x: rect.x - TEXT_CLIP_PAD,
2386        y: rect.y - TEXT_CLIP_PAD,
2387        width: (rect.width + TEXT_CLIP_PAD * 2.0).max(0.0),
2388        height: (rect.height + TEXT_CLIP_PAD * 2.0).max(0.0),
2389    }
2390}
2391
2392pub fn expand_text_bounds_for_baseline_shift(
2393    text_bounds: Rect,
2394    text_style: &TextStyle,
2395    font_size: f32,
2396) -> Rect {
2397    let baseline_shift_px = text_style
2398        .span_style
2399        .baseline_shift
2400        .filter(|shift| shift.is_specified())
2401        .map_or(0.0, |shift| -(shift.0 * font_size));
2402    if baseline_shift_px == 0.0 {
2403        return text_bounds;
2404    }
2405
2406    if baseline_shift_px < 0.0 {
2407        Rect {
2408            x: text_bounds.x,
2409            y: text_bounds.y + baseline_shift_px,
2410            width: text_bounds.width,
2411            height: (text_bounds.height - baseline_shift_px).max(0.0),
2412        }
2413    } else {
2414        Rect {
2415            x: text_bounds.x,
2416            y: text_bounds.y,
2417            width: text_bounds.width,
2418            height: (text_bounds.height + baseline_shift_px).max(0.0),
2419        }
2420    }
2421}
2422
2423fn resolve_text_horizontal_offset(
2424    text_style: &TextStyle,
2425    text: &str,
2426    content_width: f32,
2427    measured_width: f32,
2428) -> f32 {
2429    let remaining = (content_width - measured_width).max(0.0);
2430    if remaining == 0.0 {
2431        return 0.0;
2432    }
2433    remaining * cranpose_ui::text::text_align_fraction(text_style, text)
2434}
2435
2436#[cfg(test)]
2437#[path = "tests/scene_builder_tests.rs"]
2438mod tests;