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 kept = container.children.len();
1064    write_node_content(
1065        &mut container.children,
1066        node_id,
1067        modifier_slices,
1068        size,
1069        (kept, 0),
1070        |_| {},
1071    );
1072}
1073
1074fn apply_translated_container_state(
1075    container: &mut LayerNode,
1076    modifier_slices: &ModifierNodeSlices,
1077    layout_state: &cranpose_ui::widgets::LayoutState,
1078    parent_content_offset: Point,
1079    geometry: TranslateGeometry,
1080) {
1081    container.transform_to_parent = placed_transform(
1082        container.local_bounds,
1083        layout_state.position(),
1084        &container.graphics_layer,
1085        parent_content_offset,
1086    );
1087    container.content_offset = geometry.content_offset;
1088    if container.translated_content_context {
1089        container.translated_content_offset = modifier_slices
1090            .translated_content_offset()
1091            .unwrap_or(geometry.content_offset);
1092    }
1093    modifier_slices.publish_window_geometry(
1094        geometry.top_left,
1095        geometry.window_transform,
1096        layout_state.size(),
1097    );
1098    container.origin_in_parent = layout_state.position();
1099}
1100
1101fn reconcile_translated_children(
1102    container: &mut LayerNode,
1103    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
1104    scratch: &mut TranslateScratch,
1105    children_unchanged: bool,
1106    geometry: TranslateGeometry,
1107) {
1108    if children_unchanged {
1109        for (child, (child_id, state)) in container.children.iter_mut().zip(&scratch.placed_fresh) {
1110            let RenderNode::Layer(layer) = child else {
1111                unreachable!("retained child identities were checked");
1112            };
1113            if keeps_retained_child(dirty_nodes, *child_id) {
1114                translate_retained_child(layer, state, geometry.content_offset);
1115            }
1116        }
1117        return;
1118    }
1119    let mut entering = scratch.entering.drain(..).peekable();
1120    for ((child_id, state), kept) in scratch.placed_fresh.iter().zip(scratch.kept.drain(..)) {
1121        if let Some(mut layer) = kept {
1122            if keeps_retained_child(dirty_nodes, *child_id) {
1123                translate_retained_child(&mut layer, state, geometry.content_offset);
1124            }
1125            container.children.push(RenderNode::Layer(layer));
1126        } else if let Some((_, lowered)) = entering.next_if(|(id, _)| id == child_id) {
1127            dirty_nodes.remove(child_id);
1128            remove_dirty_descendants(&lowered, dirty_nodes);
1129
1130            container.children.push(RenderNode::Layer(lowered));
1131        }
1132    }
1133}
1134
1135fn translate_layer_from_data(
1136    applier: &MemoryApplier,
1137    container: &mut LayerNode,
1138    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
1139    ancestors: TranslateAncestorContext,
1140    data: SnapshotNodeData<'_>,
1141    wrapped: bool,
1142) -> bool {
1143    let TranslateAncestorContext {
1144        inherited_motion_context_animated,
1145        update,
1146        inherited_translated_content_context,
1147        parent_content_offset,
1148        parent_abs,
1149    } = ancestors;
1150    let SnapshotNodeData {
1151        layout_state,
1152        modifier_slices,
1153        children: fresh_children,
1154        window_root,
1155    } = data;
1156    let layout_state = if window_root {
1157        layout_state.at_origin()
1158    } else {
1159        layout_state
1160    };
1161    let container_plan = match translated_container(
1162        container,
1163        &layout_state,
1164        &modifier_slices,
1165        inherited_motion_context_animated,
1166        wrapped,
1167    ) {
1168        Ok(plan) => plan,
1169        Err(reason) => return translate_bail(reason),
1170    };
1171    let TranslatedContainer {
1172        node_id,
1173        graphics_layer,
1174        local_bounds,
1175        node_bounds,
1176    } = container_plan;
1177    if container.local_bounds != local_bounds {
1178        container.local_bounds = local_bounds;
1179        container.graphics_layer.replace(graphics_layer);
1180    }
1181    container.node_bounds = node_bounds;
1182    // The container's own draws and text are recorded again around the
1183    // children it keeps: an unchanged draw reuses its recording, while
1184    // building the container anew lowered every child layer beneath it too.
1185    crate::layer_recycling::recycle_primitives(container);
1186    let mut scratch = TRANSLATE_SCRATCH.take();
1187    let children_unchanged = match translated_children(
1188        applier,
1189        container,
1190        dirty_nodes,
1191        fresh_children,
1192        &mut scratch,
1193    ) {
1194        Ok(unchanged) => unchanged,
1195        Err(reason) => {
1196            TRANSLATE_SCRATCH.set(scratch);
1197            return translate_bail(reason);
1198        }
1199    };
1200
1201    let geometry = TranslateGeometry::new(
1202        &layout_state,
1203        &container.graphics_layer,
1204        container.local_bounds,
1205        parent_abs,
1206    );
1207    let child_inherited_translated_content_context =
1208        inherited_translated_content_context || container.translated_content_context;
1209    if !children_unchanged {
1210        recycle_leaving_children(container, &mut scratch, dirty_nodes);
1211        build_entering_children(
1212            applier,
1213            container,
1214            &mut scratch,
1215            dirty_nodes,
1216            geometry,
1217            (child_inherited_translated_content_context, update),
1218        );
1219    }
1220
1221    apply_translated_container_state(
1222        container,
1223        &modifier_slices,
1224        &layout_state,
1225        parent_content_offset,
1226        geometry,
1227    );
1228
1229    reconcile_translated_children(
1230        container,
1231        dirty_nodes,
1232        &mut scratch,
1233        children_unchanged,
1234        geometry,
1235    );
1236    TRANSLATE_SCRATCH.set(scratch);
1237    write_own_content_around_children(container, node_id, &modifier_slices, layout_state.size());
1238    container.hit_test = hit_test_from_slices(&modifier_slices);
1239
1240    container.has_origin_sinks = modifier_slices_have_origin_sinks(&modifier_slices)
1241        || children_have_origin_sinks(&container.children);
1242    container.refresh_child_facts();
1243    container.note_content_change(update);
1244
1245    true
1246}
1247
1248/// Whether a retained child keeps its layer as it is and only follows its
1249/// placement: it is not dirty, or it only moved, which this placement
1250/// settles.
1251fn keeps_retained_child(dirty_nodes: &mut HashMap<NodeId, NodeUpdate>, child_id: NodeId) -> bool {
1252    match dirty_nodes.get(&child_id) {
1253        None => true,
1254        Some(NodeUpdate::Moved) => {
1255            dirty_nodes.remove(&child_id);
1256            true
1257        }
1258        Some(NodeUpdate::Content | NodeUpdate::Layer | NodeUpdate::MovedLayer) => false,
1259    }
1260}
1261
1262fn translate_retained_child(
1263    layer: &mut LayerNode,
1264    state: &cranpose_ui::widgets::LayoutState,
1265    content_offset: Point,
1266) {
1267    layer.transform_to_parent = placed_transform(
1268        layer.local_bounds,
1269        state.position(),
1270        &layer.graphics_layer,
1271        content_offset,
1272    );
1273    layer.origin_in_parent = state.position();
1274}
1275
1276#[derive(PartialEq)]
1277struct HitGraphState {
1278    hit_test: bool,
1279    has_hit_targets: bool,
1280    local_bounds: Rect,
1281    node_bounds: Option<Rect>,
1282    transform_to_parent: ProjectiveTransform,
1283    clip_rect: Option<Rect>,
1284    shape: LayerShape,
1285}
1286
1287impl HitGraphState {
1288    fn of(layer: &LayerNode) -> Self {
1289        Self {
1290            hit_test: layer.hit_test.is_some(),
1291            has_hit_targets: layer.has_hit_targets,
1292            local_bounds: layer.local_bounds,
1293            node_bounds: layer.node_bounds,
1294            transform_to_parent: layer.transform_to_parent,
1295            clip_rect: layer.clip_rect(),
1296            shape: layer.graphics_layer.shape,
1297        }
1298    }
1299
1300    fn dirty_against(&self, replacement: &Self) -> bool {
1301        self.hit_test
1302            || replacement.hit_test
1303            || ((self.has_hit_targets || replacement.has_hit_targets) && self != replacement)
1304    }
1305}
1306
1307fn release_for_rebuild(layer: &mut LayerNode) {
1308    layer.hit_test = None;
1309    crate::layer_recycling::recycle_children(layer);
1310}
1311
1312/// Takes `layer`'s node and every node beneath it out of `dirty_nodes`.
1313fn forget_dirty_subtree(layer: &LayerNode, dirty_nodes: &mut HashMap<NodeId, NodeUpdate>) {
1314    if let Some(node_id) = layer_identity(layer) {
1315        dirty_nodes.remove(&node_id);
1316    }
1317    remove_dirty_descendants(layer, dirty_nodes);
1318}
1319
1320fn remove_dirty_descendants(layer: &LayerNode, dirty_nodes: &mut HashMap<NodeId, NodeUpdate>) {
1321    for child in &layer.children {
1322        let RenderNode::Layer(child_layer) = child else {
1323            continue;
1324        };
1325        if let Some(node_id) = child_layer.node_id {
1326            dirty_nodes.remove(&node_id);
1327        }
1328        remove_dirty_descendants(child_layer, dirty_nodes);
1329    }
1330}
1331
1332#[derive(Clone, Copy)]
1333struct LowerContext {
1334    inherited_motion_context_animated: bool,
1335    inherited_translated_content_context: bool,
1336    parent_abs: Option<AbsOrigin>,
1337    parent_content_offset: Point,
1338}
1339
1340impl LowerContext {
1341    const ROOT: Self = Self {
1342        inherited_motion_context_animated: false,
1343        inherited_translated_content_context: false,
1344        parent_abs: Some(AbsOrigin::ROOT),
1345        parent_content_offset: Point { x: 0.0, y: 0.0 },
1346    };
1347
1348    fn for_children(
1349        self,
1350        slices: &ModifierNodeSlices,
1351        content_offset: Point,
1352        parent_abs: Option<AbsOrigin>,
1353    ) -> Self {
1354        Self {
1355            inherited_motion_context_animated: self.inherited_motion_context_animated
1356                || slices.motion_context_animated(),
1357            inherited_translated_content_context: self.inherited_translated_content_context
1358                || slices.translated_content_context(),
1359            parent_abs,
1360            parent_content_offset: content_offset,
1361        }
1362    }
1363}
1364
1365struct LayerHead {
1366    node_id: Option<NodeId>,
1367    wraps: Option<NodeId>,
1368    local_bounds: Rect,
1369    node_bounds: Option<Rect>,
1370    transform_to_parent: ProjectiveTransform,
1371    content_offset: Point,
1372    motion_context_animated: bool,
1373    translated_content_context: bool,
1374    translated_content_offset: Point,
1375    origin_in_parent: Point,
1376    graphics_layer: Option<GraphicsLayer>,
1377    clip_to_bounds: bool,
1378    hit_test: Option<HitTestNode>,
1379    has_origin_sinks: bool,
1380    isolation: IsolationReasons,
1381    cache_policy: CachePolicy,
1382}
1383
1384struct NodeFrame {
1385    local_bounds: Rect,
1386    node_bounds: Option<Rect>,
1387    placement: Point,
1388    content_offset: Point,
1389    translated_content_offset: Point,
1390}
1391
1392fn node_layer_head(
1393    node_id: NodeId,
1394    slices: &Rc<ModifierNodeSlices>,
1395    frame: NodeFrame,
1396    graphics_layer: Option<GraphicsLayer>,
1397    context: LowerContext,
1398) -> LayerHead {
1399    let clip_to_bounds = slices.clip_to_bounds();
1400    let translated_content_context = slices.translated_content_context();
1401    let properties = graphics_layer.as_ref().unwrap_or(&GraphicsLayer::DEFAULT);
1402    let isolation = isolation_reasons(properties);
1403    LayerHead {
1404        node_id: Some(node_id),
1405        wraps: None,
1406        local_bounds: frame.local_bounds,
1407        node_bounds: frame.node_bounds,
1408        transform_to_parent: placed_transform(
1409            frame.local_bounds,
1410            frame.placement,
1411            properties,
1412            context.parent_content_offset,
1413        ),
1414        content_offset: frame.content_offset,
1415        motion_context_animated: context.inherited_motion_context_animated
1416            || slices.motion_context_animated(),
1417        translated_content_context,
1418        translated_content_offset: if translated_content_context {
1419            frame.translated_content_offset
1420        } else {
1421            Point::default()
1422        },
1423        origin_in_parent: frame.placement,
1424        cache_policy: layer_cache_policy(properties, isolation),
1425        isolation,
1426        graphics_layer,
1427        clip_to_bounds,
1428        hit_test: hit_test_from_slices(slices),
1429        has_origin_sinks: modifier_slices_have_origin_sinks(slices),
1430    }
1431}
1432
1433fn assign_layer(layer: &mut LayerNode, head: LayerHead) {
1434    let LayerNode {
1435        node_id,
1436        wraps,
1437        local_bounds,
1438        node_bounds,
1439        transform_to_parent,
1440        content_offset,
1441        motion_context_animated,
1442        translated_content_context,
1443        translated_content_offset,
1444        origin_in_parent,
1445        graphics_layer,
1446        clip_to_bounds,
1447        hit_test,
1448        has_hit_targets,
1449        has_origin_sinks,
1450        draws_within_bounds,
1451        isolation,
1452        cache_policy,
1453        cache_hashes,
1454        content_changes,
1455        children,
1456    } = layer;
1457    if *node_id != head.node_id {
1458        *content_changes = ContentChanges::default();
1459    }
1460    *node_id = head.node_id;
1461    *wraps = head.wraps;
1462    *local_bounds = head.local_bounds;
1463    *node_bounds = head.node_bounds;
1464    *transform_to_parent = head.transform_to_parent;
1465    *content_offset = head.content_offset;
1466    *motion_context_animated = head.motion_context_animated;
1467    *translated_content_context = head.translated_content_context;
1468    *translated_content_offset = head.translated_content_offset;
1469    *origin_in_parent = head.origin_in_parent;
1470    graphics_layer.replace(head.graphics_layer);
1471    *clip_to_bounds = head.clip_to_bounds;
1472    *hit_test = head.hit_test;
1473    *has_hit_targets = false;
1474    *has_origin_sinks = head.has_origin_sinks || children_have_origin_sinks(children);
1475    *draws_within_bounds = false;
1476    *isolation = head.isolation;
1477    *cache_policy = head.cache_policy;
1478    cache_hashes.set(None);
1479    layer.refresh_child_facts();
1480}
1481
1482fn children_have_origin_sinks(children: &[RenderNode]) -> bool {
1483    children.iter().any(|child| match child {
1484        RenderNode::Layer(child_layer) => child_layer.has_origin_sinks,
1485        RenderNode::Primitive(_) | RenderNode::DrawRun(_) => false,
1486    })
1487}
1488
1489fn placed_transform(
1490    local_bounds: Rect,
1491    placement: Point,
1492    graphics_layer: &GraphicsLayer,
1493    parent_content_offset: Point,
1494) -> ProjectiveTransform {
1495    let transform = layer_transform_to_parent(local_bounds, placement, graphics_layer);
1496    if parent_content_offset == Point::default() {
1497        transform
1498    } else {
1499        transform.then(ProjectiveTransform::translation(
1500            parent_content_offset.x,
1501            parent_content_offset.y,
1502        ))
1503    }
1504}
1505
1506/// Writes a node's own draws and text around its child layers: `kept`
1507/// layers already end `list`, and `write_children` appends `written` more.
1508fn write_node_content(
1509    list: &mut Vec<RenderNode>,
1510    node_id: NodeId,
1511    slices: &ModifierNodeSlices,
1512    size: Size,
1513    (kept, written): (usize, usize),
1514    write_children: impl FnOnce(&mut Vec<RenderNode>),
1515) {
1516    let outer_count = slices.outer_draw_command_count();
1517    let commands = &slices.draw_commands()[outer_count..];
1518    list.reserve(layer_node_capacity(
1519        commands,
1520        written,
1521        slices.annotated_text().is_some(),
1522    ));
1523    let first_kept = list.len() - kept;
1524    let first_draw = list.len();
1525    append_draw_nodes(
1526        list,
1527        node_id,
1528        commands,
1529        outer_count,
1530        DrawPass::Record(DrawPlacement::Behind),
1531        size,
1532        PrimitivePhase::BeforeChildren,
1533    );
1534    if let Some(text) = text_node_from_parts(TextNodeParts {
1535        node_id,
1536        text_rect: slices.text_content_rect(size),
1537        text_style: slices.text_style(),
1538        text_layout_options: slices.text_layout_options(),
1539        text_pan: slices.text_pan_resolver(),
1540        measured_layout: slices.measured_text_layout(),
1541    }) {
1542        list.push(RenderNode::Primitive(PrimitiveEntry {
1543            phase: PrimitivePhase::BeforeChildren,
1544            node: PrimitiveNode::Text(crate::layer_recycling::boxed_text(text)),
1545        }));
1546    }
1547    // The kept layers go after the draws and text just written.
1548    list[first_kept..].rotate_left(kept);
1549    let first_draw = first_draw - kept;
1550    write_children(list);
1551    append_draw_nodes(
1552        list,
1553        node_id,
1554        commands,
1555        outer_count,
1556        DrawPass::OverlayFromOutput(first_draw),
1557        size,
1558        PrimitivePhase::AfterChildren,
1559    );
1560}
1561
1562fn write_layer_with_outer(
1563    target: &mut LayerNode,
1564    head: LayerHead,
1565    outer: Option<OuterDraws>,
1566    placement: Point,
1567    parent_content_offset: Point,
1568    write_children: impl FnOnce(&mut Vec<RenderNode>),
1569) {
1570    debug_assert!(target.children.is_empty(), "a layer is written emptied");
1571    let Some(outer) = outer else {
1572        write_children(&mut target.children);
1573        assign_layer(target, head);
1574        return;
1575    };
1576    let mut layer = crate::layer_recycling::layer_box();
1577    write_children(&mut layer.children);
1578    assign_layer(&mut layer, head);
1579    write_wrapper(target, layer, placement, outer, parent_content_offset);
1580}
1581
1582fn write_snapshot_layer(
1583    snapshot: BuildNodeSnapshot,
1584    context: LowerContext,
1585    target: &mut LayerNode,
1586) {
1587    let BuildNodeSnapshot {
1588        node_id,
1589        placement,
1590        size,
1591        content_offset,
1592        slices,
1593        graphics_layer,
1594        children,
1595    } = snapshot;
1596    let (local_bounds, node_bounds) = layer_and_node_bounds(&slices, size);
1597    let child_context = context.for_children(&slices, content_offset, None);
1598    let head = node_layer_head(
1599        node_id,
1600        &slices,
1601        NodeFrame {
1602            local_bounds,
1603            node_bounds,
1604            placement,
1605            content_offset,
1606            translated_content_offset: content_offset,
1607        },
1608        graphics_layer,
1609        context,
1610    );
1611    let outer = outer_draws(
1612        node_id,
1613        slices.draw_commands(),
1614        slices.outer_draw_command_count(),
1615        size,
1616    );
1617    write_layer_with_outer(
1618        target,
1619        head,
1620        outer,
1621        placement,
1622        context.parent_content_offset,
1623        |list| {
1624            write_node_content(list, node_id, &slices, size, (0, children.len()), |list| {
1625                for child in children {
1626                    let mut layer = crate::layer_recycling::layer_box();
1627                    write_snapshot_layer(child, child_context, &mut layer);
1628                    list.push(RenderNode::Layer(layer));
1629                }
1630            });
1631        },
1632    );
1633}
1634
1635#[derive(Clone, Copy)]
1636struct AbsOrigin {
1637    content_origin: Point,
1638    window_transform: ProjectiveTransform,
1639}
1640
1641impl AbsOrigin {
1642    const ROOT: AbsOrigin = AbsOrigin {
1643        content_origin: Point { x: 0.0, y: 0.0 },
1644        window_transform: ProjectiveTransform::identity(),
1645    };
1646
1647    fn children_of(self, layer: &LayerNode) -> AbsOrigin {
1648        let top_left = Point {
1649            x: self.content_origin.x + layer.origin_in_parent.x,
1650            y: self.content_origin.y + layer.origin_in_parent.y,
1651        };
1652        AbsOrigin {
1653            content_origin: Point {
1654                x: self.content_origin.x + layer.origin_in_parent.x + layer.content_offset.x,
1655                y: self.content_origin.y + layer.origin_in_parent.y + layer.content_offset.y,
1656            },
1657            window_transform: layer_transform_to_window(
1658                self.window_transform,
1659                top_left,
1660                layer.local_bounds,
1661                &layer.graphics_layer,
1662            ),
1663        }
1664    }
1665}
1666
1667fn read_placed_node_data<R>(
1668    applier: &MemoryApplier,
1669    node_id: NodeId,
1670    root: bool,
1671    read: impl FnOnce(SnapshotNodeData<'_>) -> R,
1672) -> Option<R> {
1673    read_node_data(applier, node_id, |mut data| {
1674        if data.window_root {
1675            if !root {
1676                return None;
1677            }
1678            data.layout_state = data.layout_state.at_origin();
1679        }
1680        note_layer_lowered();
1681        if !data.layout_state.is_placed() {
1682            return None;
1683        }
1684        Some(read(data))
1685    })?
1686}
1687
1688fn lower_root_into(applier: &MemoryApplier, node_id: NodeId, target: &mut LayerNode) -> bool {
1689    read_placed_node_data(applier, node_id, true, |data| {
1690        write_node_layer(applier, node_id, data, LowerContext::ROOT, target);
1691    })
1692    .is_some()
1693}
1694
1695fn lower_child(
1696    applier: &MemoryApplier,
1697    node_id: NodeId,
1698    context: LowerContext,
1699) -> Option<Box<LayerNode>> {
1700    read_placed_node_data(applier, node_id, false, |data| {
1701        let mut layer = crate::layer_recycling::layer_box();
1702        write_node_layer(applier, node_id, data, context, &mut layer);
1703        layer
1704    })
1705}
1706
1707fn scene_layout_state(
1708    applier: &MemoryApplier,
1709    node_id: NodeId,
1710) -> Option<cranpose_ui::widgets::LayoutState> {
1711    let node: &dyn Any = applier.get_ref(node_id).ok()?;
1712    if let Some(node) = node.downcast_ref::<LayoutNode>() {
1713        return Some(node.layout_state());
1714    }
1715    node.downcast_ref::<SubcomposeLayoutNode>()
1716        .map(SubcomposeLayoutNode::layout_state)
1717}
1718
1719fn read_node_data<R>(
1720    applier: &MemoryApplier,
1721    node_id: NodeId,
1722    read: impl FnOnce(SnapshotNodeData<'_>) -> R,
1723) -> Option<R> {
1724    let node: &dyn Any = applier.get_ref(node_id).ok()?;
1725    if let Some(node) = node.downcast_ref::<LayoutNode>() {
1726        return Some(read(SnapshotNodeData {
1727            layout_state: node.layout_state(),
1728            modifier_slices: node.modifier_slices_snapshot(),
1729            children: &node.children,
1730            window_root: node.is_window_root(),
1731        }));
1732    }
1733    let node = node.downcast_ref::<SubcomposeLayoutNode>()?;
1734    let layout_state = node.layout_state();
1735    let modifier_slices = node.modifier_slices_snapshot();
1736    Some(node.with_active_children(|children| {
1737        read(SnapshotNodeData {
1738            layout_state,
1739            modifier_slices,
1740            children,
1741            window_root: false,
1742        })
1743    }))
1744}
1745
1746fn hit_test_from_slices(slices: &Rc<ModifierNodeSlices>) -> Option<HitTestNode> {
1747    slices_hit_something(slices).then(|| HitTestNode {
1748        handlers: Rc::clone(slices),
1749    })
1750}
1751
1752/// A node's layer bounds and, when they differ from it, its own rect (see
1753/// [`LayerNode::node_bounds`]).
1754fn layer_and_node_bounds(slices: &ModifierNodeSlices, size: Size) -> (Rect, Option<Rect>) {
1755    let node_bounds = Rect::from_size(size);
1756    let layer_bounds = slices.layer_bounds(size);
1757    (
1758        layer_bounds,
1759        (layer_bounds != node_bounds).then_some(node_bounds),
1760    )
1761}
1762
1763/// Whether a node's slices make it a hit target: a pointer input or a
1764/// pointer icon.
1765fn slices_hit_something(slices: &ModifierNodeSlices) -> bool {
1766    !slices.pointer_inputs().is_empty() || slices.pointer_icon().is_some()
1767}
1768
1769fn prepare_node_layer(
1770    node_id: NodeId,
1771    slices: &Rc<ModifierNodeSlices>,
1772    layout_state: &cranpose_ui::widgets::LayoutState,
1773    context: LowerContext,
1774) -> (LayerHead, LowerContext) {
1775    let size = layout_state.size();
1776    let placement = layout_state.position();
1777    let (local_bounds, node_bounds) = layer_and_node_bounds(slices, size);
1778    let graphics_layer = graphics_layer_with_shaped_clip(
1779        slices.graphics_layer(),
1780        slices.clip_to_bounds(),
1781        slices.corner_shape(),
1782        local_bounds,
1783    );
1784    let geometry = context.parent_abs.map(|parent_abs| {
1785        TranslateGeometry::new(
1786            layout_state,
1787            graphics_layer.as_ref().unwrap_or(&GraphicsLayer::DEFAULT),
1788            local_bounds,
1789            parent_abs,
1790        )
1791    });
1792    if let Some(geometry) = geometry {
1793        slices.publish_window_geometry(geometry.top_left, geometry.window_transform, size);
1794    } else {
1795        slices.publish_pointer_input_size(size);
1796    }
1797    let content_offset = layout_state.content_offset();
1798    let child_context = context.for_children(
1799        slices,
1800        content_offset,
1801        geometry.map(TranslateGeometry::child_abs),
1802    );
1803    let head = node_layer_head(
1804        node_id,
1805        slices,
1806        NodeFrame {
1807            local_bounds,
1808            node_bounds,
1809            placement,
1810            content_offset,
1811            translated_content_offset: slices.translated_content_offset().unwrap_or(content_offset),
1812        },
1813        graphics_layer,
1814        context,
1815    );
1816    (head, child_context)
1817}
1818
1819fn write_node_layer(
1820    applier: &MemoryApplier,
1821    node_id: NodeId,
1822    data: SnapshotNodeData<'_>,
1823    context: LowerContext,
1824    target: &mut LayerNode,
1825) {
1826    let SnapshotNodeData {
1827        layout_state,
1828        modifier_slices: slices,
1829        children,
1830        window_root: _,
1831    } = data;
1832    let size = layout_state.size();
1833    let placement = layout_state.position();
1834    if cranpose_core::env_flag!("CRANPOSE_SCENE_UPDATE_DIAG") {
1835        eprintln!(
1836            "[scene-update-diag] build layer node={node_id:?} size=({:.2},{:.2}) pos=({:.2},{:.2})",
1837            size.width, size.height, placement.x, placement.y,
1838        );
1839    }
1840    let (head, child_context) = prepare_node_layer(node_id, &slices, &layout_state, context);
1841    let outer = outer_draws(
1842        node_id,
1843        slices.draw_commands(),
1844        slices.outer_draw_command_count(),
1845        size,
1846    );
1847    write_layer_with_outer(
1848        target,
1849        head,
1850        outer,
1851        placement,
1852        context.parent_content_offset,
1853        |list| {
1854            write_node_content(list, node_id, &slices, size, (0, children.len()), |list| {
1855                for &child_id in children {
1856                    if let Some(child) = lower_child(applier, child_id, child_context) {
1857                        list.push(RenderNode::Layer(child));
1858                    }
1859                }
1860            });
1861        },
1862    );
1863}
1864
1865struct RecorderSlot {
1866    generation: u64,
1867    handles: [Option<Rc<CommandRecording>>; 3],
1868    /// The allocation of a handle whose recording `acquire_storage` took,
1869    /// which the next recording the slot publishes moves into.
1870    spare: Option<Rc<CommandRecording>>,
1871}
1872
1873#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1874struct RecorderKey {
1875    node_id: NodeId,
1876    command_index: u32,
1877}
1878
1879impl From<DrawCommandId> for RecorderKey {
1880    fn from(id: DrawCommandId) -> Self {
1881        Self {
1882            node_id: id.node_id,
1883            command_index: id.command_index,
1884        }
1885    }
1886}
1887
1888thread_local! {
1889    static COMMAND_RECORDINGS: std::cell::RefCell<
1890        std::collections::HashMap<RecorderKey, RecorderSlot, cranpose_ui_graphics::FxBuildHasher>,
1891    > = std::cell::RefCell::new(std::collections::HashMap::default());
1892    static RECORDING_GENERATION: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1893}
1894
1895#[doc(hidden)]
1896pub fn clear_command_recordings_for_tests() {
1897    COMMAND_RECORDINGS.with(|map| map.borrow_mut().clear());
1898}
1899
1900fn bump_recording_generation() {
1901    let generation = RECORDING_GENERATION.with(|cell| {
1902        let next = cell.get().wrapping_add(1);
1903        cell.set(next);
1904        next
1905    });
1906    if generation.is_multiple_of(512) {
1907        COMMAND_RECORDINGS.with(|map| {
1908            map.borrow_mut()
1909                .retain(|_, slot| generation.wrapping_sub(slot.generation) <= 64);
1910        });
1911    }
1912}
1913
1914fn acquire_storage(id: DrawCommandId) -> CommandRecording {
1915    COMMAND_RECORDINGS.with(|map| {
1916        let mut map = map.borrow_mut();
1917        let Some(slot) = map.get_mut(&RecorderKey::from(id)) else {
1918            return CommandRecording::default();
1919        };
1920        for handle in &mut slot.handles {
1921            let Some(recording) = handle.as_mut().and_then(Rc::get_mut) else {
1922                continue;
1923            };
1924            let Some(storage) = recording.try_take_reusable() else {
1925                continue;
1926            };
1927            slot.spare = handle.take();
1928            return storage;
1929        }
1930        if slot.handles.iter().all(Option::is_some) {
1931            let storage = slot.handles[2]
1932                .as_mut()
1933                .and_then(Rc::get_mut)
1934                .map(std::mem::take);
1935            if let Some(storage) = storage {
1936                slot.spare = slot.handles[2].take();
1937                return storage;
1938            }
1939        }
1940        CommandRecording::default()
1941    })
1942}
1943
1944fn publish_recording(id: DrawCommandId, recording: CommandRecording) -> Rc<CommandRecording> {
1945    COMMAND_RECORDINGS.with(|map| {
1946        let mut map = map.borrow_mut();
1947        let generation = RECORDING_GENERATION.with(Cell::get);
1948        let slot = map
1949            .entry(RecorderKey::from(id))
1950            .or_insert_with(|| RecorderSlot {
1951                generation,
1952                handles: [None, None, None],
1953                spare: None,
1954            });
1955        let shared = match slot.spare.take() {
1956            Some(mut spare) => match Rc::get_mut(&mut spare) {
1957                Some(storage) => {
1958                    *storage = recording;
1959                    spare
1960                }
1961                None => Rc::new(recording),
1962            },
1963            None => Rc::new(recording),
1964        };
1965        slot.generation = generation;
1966        slot.handles[2] = slot.handles[1].take();
1967        slot.handles[1] = slot.handles[0].take();
1968        slot.handles[0] = Some(Rc::clone(&shared));
1969        shared
1970    })
1971}
1972
1973enum DrawPass<'a> {
1974    Record(DrawPlacement),
1975    OverlayFrom(std::slice::Iter<'a, RenderNode>),
1976    OverlayFromOutput(usize),
1977}
1978
1979impl DrawPass<'_> {
1980    fn placement(&self) -> DrawPlacement {
1981        match self {
1982            Self::Record(placement) => *placement,
1983            Self::OverlayFrom(_) | Self::OverlayFromOutput(_) => DrawPlacement::Overlay,
1984        }
1985    }
1986
1987    fn take_recording(
1988        &mut self,
1989        command: &DrawCommand,
1990        output: &[RenderNode],
1991    ) -> Option<Rc<CommandRecording>> {
1992        if matches!(command, DrawCommand::Overlay(_)) {
1993            return None;
1994        }
1995        let node = match self {
1996            Self::Record(_) => return None,
1997            Self::OverlayFrom(nodes) => nodes.next().expect("each behind command has a draw run"),
1998            Self::OverlayFromOutput(index) => {
1999                let node = &output[*index];
2000                *index += 1;
2001                node
2002            }
2003        };
2004        let RenderNode::DrawRun(run) = node else {
2005            unreachable!("behind commands produce draw runs");
2006        };
2007        matches!(command, DrawCommand::WithContent(_)).then(|| Rc::clone(&run.recording))
2008    }
2009}
2010
2011fn layer_node_capacity(commands: &[DrawCommand], children: usize, has_text: bool) -> usize {
2012    children
2013        + usize::from(has_text)
2014        + commands.len()
2015        + commands
2016            .iter()
2017            .filter(|command| matches!(command, DrawCommand::WithContent(_)))
2018            .count()
2019}
2020
2021fn draw_nodes(
2022    node_id: NodeId,
2023    commands: &[DrawCommand],
2024    first_command_index: usize,
2025    placement: DrawPlacement,
2026    size: Size,
2027    phase: PrimitivePhase,
2028) -> Vec<RenderNode> {
2029    let mut nodes = crate::layer_recycling::child_list(commands.len());
2030    append_draw_nodes(
2031        &mut nodes,
2032        node_id,
2033        commands,
2034        first_command_index,
2035        DrawPass::Record(placement),
2036        size,
2037        phase,
2038    );
2039    nodes
2040}
2041
2042fn append_draw_nodes(
2043    nodes: &mut Vec<RenderNode>,
2044    node_id: NodeId,
2045    commands: &[DrawCommand],
2046    first_command_index: usize,
2047    mut pass: DrawPass<'_>,
2048    size: Size,
2049    phase: PrimitivePhase,
2050) {
2051    let placement = pass.placement();
2052    for (command_index, command) in commands.iter().enumerate() {
2053        let id = DrawCommandId {
2054            node_id,
2055            command_index: (first_command_index + command_index) as u32,
2056            placement,
2057        };
2058        let (shared, segments) = if let Some(shared) = pass.take_recording(command, nodes) {
2059            let segments = shared.content_split(false);
2060            (shared, segments)
2061        } else {
2062            let Some((recording, segments)) =
2063                recording_for_placement_reusing(command, placement, size, || acquire_storage(id))
2064            else {
2065                continue;
2066            };
2067            (publish_recording(id, recording), segments)
2068        };
2069        nodes.push(RenderNode::DrawRun(DrawRunNode::for_command_shared(
2070            phase,
2071            Some(id),
2072            shared,
2073            segments,
2074        )));
2075    }
2076}
2077
2078#[doc(hidden)]
2079pub fn draw_command_nodes_for_tests(
2080    node_id: NodeId,
2081    commands: &[DrawCommand],
2082    placement: DrawPlacement,
2083    size: Size,
2084    phase: PrimitivePhase,
2085) -> Vec<RenderNode> {
2086    bump_recording_generation();
2087    draw_nodes(node_id, commands, 0, placement, size, phase)
2088}
2089
2090struct OuterDraws {
2091    behind: Vec<RenderNode>,
2092    overlay: Vec<RenderNode>,
2093}
2094
2095fn outer_draws(
2096    node_id: NodeId,
2097    draw_commands: &[DrawCommand],
2098    outer_draw_command_count: usize,
2099    size: Size,
2100) -> Option<OuterDraws> {
2101    (outer_draw_command_count > 0).then(|| {
2102        let commands = &draw_commands[..outer_draw_command_count];
2103        let behind = draw_nodes(
2104            node_id,
2105            commands,
2106            0,
2107            DrawPlacement::Behind,
2108            size,
2109            PrimitivePhase::BeforeChildren,
2110        );
2111        let mut overlay = crate::layer_recycling::child_list(commands.len());
2112        append_draw_nodes(
2113            &mut overlay,
2114            node_id,
2115            commands,
2116            0,
2117            DrawPass::OverlayFrom(behind.iter()),
2118            size,
2119            PrimitivePhase::AfterChildren,
2120        );
2121        OuterDraws { behind, overlay }
2122    })
2123}
2124
2125fn write_wrapper(
2126    wrapper: &mut LayerNode,
2127    mut layer: Box<LayerNode>,
2128    placement: Point,
2129    outer: OuterDraws,
2130    parent_content_offset: Point,
2131) {
2132    debug_assert!(wrapper.children.is_empty(), "a wrapper is written emptied");
2133    layer.transform_to_parent =
2134        layer_transform_to_parent(layer.local_bounds, Point::default(), &layer.graphics_layer);
2135    layer.origin_in_parent = Point::default();
2136    let node_rect = layer.node_rect();
2137    let graphics_layer = None;
2138    let head = LayerHead {
2139        node_id: None,
2140        wraps: layer.node_id,
2141        local_bounds: node_rect,
2142        node_bounds: None,
2143        transform_to_parent: placed_transform(
2144            node_rect,
2145            placement,
2146            &GraphicsLayer::DEFAULT,
2147            parent_content_offset,
2148        ),
2149        content_offset: Point::default(),
2150        motion_context_animated: layer.motion_context_animated,
2151        translated_content_context: false,
2152        translated_content_offset: Point::default(),
2153        origin_in_parent: placement,
2154        graphics_layer,
2155        clip_to_bounds: false,
2156        hit_test: None,
2157        has_origin_sinks: false,
2158        isolation: IsolationReasons::default(),
2159        cache_policy: CachePolicy::None,
2160    };
2161    let OuterDraws {
2162        mut behind,
2163        mut overlay,
2164    } = outer;
2165    let children = &mut wrapper.children;
2166    children.reserve(behind.len() + 1 + overlay.len());
2167    children.append(&mut behind);
2168    children.push(RenderNode::Layer(layer));
2169    children.append(&mut overlay);
2170    crate::layer_recycling::recycle_list(behind);
2171    crate::layer_recycling::recycle_list(overlay);
2172    assign_layer(wrapper, head);
2173}
2174
2175fn take_wrapped_layer(wrapper: &mut LayerNode, node_id: NodeId) -> Option<Box<LayerNode>> {
2176    let mut wrapped = None;
2177    for child in wrapper.children.drain(..) {
2178        if let RenderNode::Layer(layer) = child
2179            && layer.node_id == Some(node_id)
2180        {
2181            wrapped = Some(layer);
2182        }
2183    }
2184    wrapped
2185}
2186
2187fn layer_identity(layer: &LayerNode) -> Option<NodeId> {
2188    layer.node_id.or(layer.wraps)
2189}
2190
2191struct TextNodeParts<'a> {
2192    node_id: NodeId,
2193    /// Where the text node was placed in its layout node.
2194    text_rect: Rect,
2195    text_style: Option<&'a TextStyle>,
2196    text_layout_options: Option<TextLayoutOptions>,
2197    text_pan: Option<TextPanResolver>,
2198    measured_layout: Option<Rc<PreparedTextLayout>>,
2199}
2200
2201fn text_node_from_parts(parts: TextNodeParts<'_>) -> Option<TextPrimitiveNode> {
2202    let TextNodeParts {
2203        node_id,
2204        text_rect,
2205        text_style,
2206        text_layout_options,
2207        text_pan,
2208        measured_layout,
2209    } = parts;
2210    let prepared = measured_layout?;
2211    let default_text_style;
2212    let text_style = match text_style {
2213        Some(style) => style,
2214        None => {
2215            default_text_style = TextStyle::default();
2216            &default_text_style
2217        }
2218    };
2219    let options = text_layout_options.unwrap_or_default().normalized();
2220    let content_width = text_rect.width.max(0.0);
2221    if content_width <= 0.0 {
2222        return None;
2223    }
2224
2225    let pan_offset = text_pan
2226        .as_ref()
2227        .map_or(0.0, |resolve| resolve(content_width));
2228    let pans_horizontally = text_pan.is_some();
2229
2230    let visual_style = &prepared.visual_style;
2231    let measured_draw_width = prepared.metrics.width.max(0.0);
2232    let draw_width = if options.overflow == TextOverflow::Visible || pans_horizontally {
2233        measured_draw_width
2234    } else {
2235        measured_draw_width.min(content_width)
2236    };
2237    let alignment_offset = resolve_text_horizontal_offset(
2238        text_style,
2239        prepared.text.text.as_str(),
2240        content_width,
2241        prepared.metrics.width,
2242    );
2243    let rect = Rect {
2244        x: text_rect.x + alignment_offset - pan_offset,
2245        y: text_rect.y,
2246        width: draw_width,
2247        height: prepared.metrics.height,
2248    };
2249    let text_bounds = Rect {
2250        width: content_width,
2251        height: text_rect.height.max(0.0),
2252        ..text_rect
2253    };
2254    let font_size = visual_style.resolve_font_size(14.0);
2255    let expanded_bounds =
2256        expand_text_bounds_for_baseline_shift(text_bounds, visual_style, font_size);
2257    let clip = if options.overflow == TextOverflow::Visible && !pans_horizontally {
2258        None
2259    } else {
2260        Some(pad_clip_rect(expanded_bounds))
2261    };
2262
2263    Some(TextPrimitiveNode {
2264        node_id,
2265        rect,
2266        text: Rc::clone(&prepared.text),
2267        render_text: prepared.render_text(),
2268        text_style: std::sync::Arc::clone(visual_style),
2269        font_size,
2270        layout_options: options,
2271        clip,
2272        paint: TextPaintCache::holding(TextPaint::of(
2273            visual_style,
2274            &prepared.text.span_styles,
2275            font_size,
2276        )),
2277    })
2278}
2279
2280fn layout_box_to_snapshot(node: &LayoutBox, parent: Option<&LayoutBox>) -> BuildNodeSnapshot {
2281    let placement = parent
2282        .map(|parent_box| Point {
2283            x: node.rect.x - parent_box.rect.x - parent_box.content_offset.x,
2284            y: node.rect.y - parent_box.rect.y - parent_box.content_offset.y,
2285        })
2286        .unwrap_or_default();
2287    let mut children = Vec::with_capacity(node.children.len());
2288    for child in &node.children {
2289        children.push(layout_box_to_snapshot(child, Some(node)));
2290    }
2291    let base_graphics_layer = node.node_data.modifier_slices.graphics_layer();
2292    let has_graphics_layer = base_graphics_layer.is_some();
2293    let graphics_layer = graphics_layer_with_shaped_clip(
2294        base_graphics_layer,
2295        node.node_data.modifier_slices.clip_to_bounds(),
2296        node.node_data.modifier_slices.corner_shape(),
2297        Rect {
2298            x: 0.0,
2299            y: 0.0,
2300            width: node.rect.width,
2301            height: node.rect.height,
2302        },
2303    );
2304    let has_graphics_layer = has_graphics_layer
2305        || graphics_layer
2306            .as_ref()
2307            .is_some_and(|layer| layer.render_effect.is_some());
2308
2309    BuildNodeSnapshot {
2310        node_id: node.node_id,
2311        placement,
2312        size: Size {
2313            width: node.rect.width,
2314            height: node.rect.height,
2315        },
2316        content_offset: node.content_offset,
2317        slices: Rc::clone(&node.node_data.modifier_slices),
2318        graphics_layer: graphics_layer.filter(|_| has_graphics_layer),
2319        children,
2320    }
2321}
2322
2323fn modifier_slices_have_origin_sinks(slices: &ModifierNodeSlices) -> bool {
2324    slices.text_window_transform().is_some() || slices.viewport_window_rect().is_some()
2325}
2326
2327fn graphics_layer_with_shaped_clip(
2328    mut graphics_layer: Option<GraphicsLayer>,
2329    clip_to_bounds: bool,
2330    corner_shape: Option<RoundedCornerShape>,
2331    local_bounds: Rect,
2332) -> Option<GraphicsLayer> {
2333    if !clip_to_bounds {
2334        return graphics_layer;
2335    }
2336
2337    let Some(corner_shape) = corner_shape else {
2338        return graphics_layer;
2339    };
2340    let radii = corner_shape.resolve(local_bounds.width, local_bounds.height);
2341    if radii.top_left <= f32::EPSILON
2342        && radii.top_right <= f32::EPSILON
2343        && radii.bottom_right <= f32::EPSILON
2344        && radii.bottom_left <= f32::EPSILON
2345    {
2346        return graphics_layer;
2347    }
2348
2349    let properties = graphics_layer.get_or_insert_default();
2350    if let Some(existing) = properties.render_effect.take() {
2351        let rounded_clip = rounded_corner_alpha_mask_effect(
2352            local_bounds.width,
2353            local_bounds.height,
2354            radii,
2355            ROUNDED_CLIP_EDGE_FEATHER,
2356        );
2357        properties.render_effect = Some(existing.then(rounded_clip));
2358    } else {
2359        properties.shape = LayerShape::Rounded(corner_shape);
2360        properties.clip = true;
2361    }
2362    graphics_layer
2363}
2364
2365fn layer_cache_policy(layer: &GraphicsLayer, isolation: IsolationReasons) -> CachePolicy {
2366    if isolation.has_any() || layer_scales_or_rotates(layer) {
2367        CachePolicy::Auto
2368    } else {
2369        CachePolicy::None
2370    }
2371}
2372
2373fn isolation_reasons(layer: &GraphicsLayer) -> IsolationReasons {
2374    IsolationReasons {
2375        explicit_offscreen: layer.compositing_strategy == CompositingStrategy::Offscreen,
2376        shape_clip: layer.clip && !matches!(layer.shape, LayerShape::Rectangle),
2377        effect: layer.render_effect.is_some(),
2378        backdrop: layer.backdrop_effect.is_some(),
2379        group_opacity: layer.compositing_strategy != CompositingStrategy::ModulateAlpha
2380            && layer.alpha < 1.0,
2381        blend_mode: layer.blend_mode != cranpose_ui::BlendMode::SrcOver,
2382    }
2383}
2384
2385fn pad_clip_rect(rect: Rect) -> Rect {
2386    Rect {
2387        x: rect.x - TEXT_CLIP_PAD,
2388        y: rect.y - TEXT_CLIP_PAD,
2389        width: (rect.width + TEXT_CLIP_PAD * 2.0).max(0.0),
2390        height: (rect.height + TEXT_CLIP_PAD * 2.0).max(0.0),
2391    }
2392}
2393
2394pub fn expand_text_bounds_for_baseline_shift(
2395    text_bounds: Rect,
2396    text_style: &TextStyle,
2397    font_size: f32,
2398) -> Rect {
2399    let baseline_shift_px = text_style
2400        .span_style
2401        .baseline_shift
2402        .filter(|shift| shift.is_specified())
2403        .map_or(0.0, |shift| -(shift.0 * font_size));
2404    if baseline_shift_px == 0.0 {
2405        return text_bounds;
2406    }
2407
2408    if baseline_shift_px < 0.0 {
2409        Rect {
2410            x: text_bounds.x,
2411            y: text_bounds.y + baseline_shift_px,
2412            width: text_bounds.width,
2413            height: (text_bounds.height - baseline_shift_px).max(0.0),
2414        }
2415    } else {
2416        Rect {
2417            x: text_bounds.x,
2418            y: text_bounds.y,
2419            width: text_bounds.width,
2420            height: (text_bounds.height + baseline_shift_px).max(0.0),
2421        }
2422    }
2423}
2424
2425fn resolve_text_horizontal_offset(
2426    text_style: &TextStyle,
2427    text: &str,
2428    content_width: f32,
2429    measured_width: f32,
2430) -> f32 {
2431    let remaining = (content_width - measured_width).max(0.0);
2432    if remaining == 0.0 {
2433        return 0.0;
2434    }
2435    remaining * cranpose_ui::text::text_align_fraction(text_style, text)
2436}
2437
2438#[cfg(test)]
2439#[path = "tests/scene_builder_tests.rs"]
2440mod tests;