Skip to main content

cranpose_render_common/
scene_builder.rs

1use std::{any::Any, rc::Rc};
2
3use cranpose_core::{
4    MemoryApplier, NodeId, RecordId,
5    collections::{growth_slack::GrowthSlack, map::HashMap},
6};
7use cranpose_ui::{ModifierNodeSlices, Point, Rect, SubcomposeLayoutNode};
8
9use crate::{
10    NodeUpdate, SceneUpdates,
11    graph::ProjectiveTransform,
12    layer_transform::layer_transform_to_parent,
13    scene_store::{HeadKind, Item, LayerHead, LayerRef, RecordKind, SceneStore},
14};
15
16mod dirty_records;
17use dirty_records::{DirtyPlace, update_dirty_records};
18mod draw_recording;
19#[cfg(feature = "layer-tree")]
20pub(crate) use draw_recording::draw_command_items;
21use draw_recording::{
22    DrawPass, DrawTarget, GroupPaint, NodeCommands, NodeDraws, OwnDraws, append_draw_nodes,
23    draw_nodes, layer_node_capacity, text_item,
24};
25mod graph_changes;
26use graph_changes::GraphChanges;
27mod hit_graph;
28pub(crate) use hit_graph::HitGraphState;
29use hit_graph::rebuild_tracking_hits;
30mod inline_leaf;
31use inline_leaf::{lower_child, update_dirty_inline};
32mod layer_shape;
33use layer_shape::shaped_graphics_layer;
34mod text_node;
35mod translate_geometry;
36use text_node::translate_unwrapped;
37use translate_geometry::{KeptChild, TranslateGeometry, move_kept_child, translate_retained_child};
38mod node_data;
39use node_data::{PlacedGeometry, placed_child_geometry, read_node_data, read_placed_node_data};
40mod node_layer;
41use node_layer::{
42    AbsOrigin, LowerContext, assign_layer, hit_test_from_slices, layer_and_node_bounds,
43    layer_identity, lower_root_into, modifier_slices_have_origin_sinks, outer_commands,
44    outer_draws, placing_transform, set_bounds, slices_hit_something, take_wrapped_layer,
45    with_node_layer, write_node_content, write_node_layer, write_wrapper,
46};
47mod translate_layer;
48pub(crate) use translate_layer::TranslateScratch;
49use translate_layer::{
50    ItemParts, TranslatedContainer, translate_tracking_hits, translated_container,
51    write_own_content_around_children,
52};
53
54struct SnapshotNodeData<'a> {
55    layout_state: cranpose_ui::widgets::LayoutState,
56    modifier_slices: Rc<ModifierNodeSlices>,
57    children: &'a [NodeId],
58    window_root: bool,
59}
60
61/// Why a scoped scene update could not be applied, forcing the caller to throw
62/// the scene away and build it again from the applier.
63///
64/// The reason has to travel with the outcome because the shell picks the
65/// scoped path from the shape of the dirty set, before this code runs, and
66/// logs that choice. A frame that chose the scoped path and then rebuilt the
67/// whole scene is the expensive case, and in the log it reads exactly like a
68/// cheap patch -- so the fallback says so itself.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum GraphRebuildReason {
71    /// The root was dirty and its replacement layer could not be built.
72    RootLayerUnavailable,
73    /// A dirty subtree's replacement layer could not be built.
74    DirtyLayerUnavailable,
75    /// This many dirty nodes own no record in the scene, so the scoped walk
76    /// never reached them. A dirty node that never made a record, or whose
77    /// record left the scene this frame, cannot be patched in place.
78    UnmatchedDirtyNodes(usize),
79}
80
81/// The outcome of a scoped scene update.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum GraphUpdate {
84    /// The dirty nodes were updated in place.
85    Patched,
86    /// The update could not be applied and the graph must be built again, for the given reason.
87    NeedsRebuild(GraphRebuildReason),
88}
89
90/// The outcome of a scoped update together with its effect on hit testing.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub struct GraphUpdateReport {
93    /// Whether the graph was patched or must be rebuilt.
94    pub update: GraphUpdate,
95    /// Whether the update changed hit geometry or handlers, so the hit targets must be collected
96    /// again.
97    pub hit_graph_dirty: bool,
98    /// Whether the update moved a layer in its parent by the layer's own properties, as an
99    /// animated graphics layer or offset moves it, which no layout pass reports.
100    pub layers_moved: bool,
101}
102
103impl GraphUpdateReport {
104    fn patched(changes: GraphChanges) -> Self {
105        Self {
106            update: GraphUpdate::Patched,
107            hit_graph_dirty: changes.contains(GraphChanges::Hits),
108            layers_moved: changes.contains(GraphChanges::Moves),
109        }
110    }
111
112    fn needs_rebuild(reason: GraphRebuildReason) -> Self {
113        Self {
114            update: GraphUpdate::NeedsRebuild(reason),
115            hit_graph_dirty: true,
116            layers_moved: true,
117        }
118    }
119
120    /// Whether the graph was patched in place.
121    pub fn applied(self) -> bool {
122        matches!(self.update, GraphUpdate::Patched)
123    }
124
125    /// Why the graph must be rebuilt, or `None` when it was patched.
126    pub fn rebuild_reason(self) -> Option<GraphRebuildReason> {
127        match self.update {
128            GraphUpdate::Patched => None,
129            GraphUpdate::NeedsRebuild(reason) => Some(reason),
130        }
131    }
132}
133
134// The room an update keeps its dirty nodes in, which the next update on the
135// thread takes again.
136#[derive(Default)]
137pub(crate) struct DirtyRoom {
138    nodes: HashMap<NodeId, NodeUpdate>,
139    order: Vec<DirtyPlace>,
140    ancestors: Vec<NodeId>,
141}
142
143impl DirtyRoom {
144    // Gives back the room a burst of dirty nodes took.
145    fn trim(&mut self) {
146        self.nodes.trim_growth_slack();
147        self.order.trim_growth_slack();
148        self.ancestors.trim_growth_slack();
149    }
150}
151
152// Gives back the room the updates of the thread took for their dirty nodes.
153pub(crate) fn trim_dirty_room() {
154    crate::thread_state::with(|state| {
155        if let Some(mut room) = state.dirty_node_scratch.take() {
156            room.trim();
157            state.dirty_node_scratch.set(Some(room));
158        }
159    });
160}
161
162/// Builds the records of the layout tree below `root`, read from `applier`.
163/// Returns `None` when `root` cannot be lowered to a layer.
164pub fn build_from_applier(applier: &MemoryApplier, root: NodeId) -> Option<SceneStore> {
165    let mut store = SceneStore::new();
166    rebuild_from_applier(applier, root, &mut store).then_some(store)
167}
168
169// Lowers the layout tree below `root` into `store` again, its records reusing
170// the store's rows and arenas. Returns `false` and leaves the store empty
171// when `root` cannot be lowered to a layer.
172pub(crate) fn rebuild_from_applier(
173    applier: &MemoryApplier,
174    root: NodeId,
175    store: &mut SceneStore,
176) -> bool {
177    store.begin_update();
178    if let Some(record) = store.root() {
179        release_for_rebuild(store, record);
180    }
181    if !lower_root_into(applier, store, root) {
182        store.clear();
183        return false;
184    }
185    if let Some(record) = store.root() {
186        store.note_content_change(record);
187    }
188    store.finish_update();
189    true
190}
191
192// Applies `updates` to `store` in place, and reports whether the hit targets
193// must be collected again or why the store must be built again.
194pub(crate) fn update_from_applier(
195    applier: &MemoryApplier,
196    store: &mut SceneStore,
197    updates: SceneUpdates<'_>,
198) -> GraphUpdateReport {
199    let report = update_from_applier_inner(applier, store, updates);
200    if !updates.is_empty() && report.applied() {
201        store.finish_update();
202    }
203    report
204}
205
206// Returns a move when a node's layer change merged into new content: its
207// layer is lowered again, which keeps no record of where it lay.
208fn dirty_node_updates(
209    updates: SceneUpdates<'_>,
210    dirty: &mut HashMap<NodeId, NodeUpdate>,
211) -> GraphChanges {
212    dirty.clear();
213    dirty.reserve(updates.len());
214    let mut changes = GraphChanges::default();
215    for &(id, update) in updates {
216        dirty
217            .entry(id)
218            .and_modify(|kind| {
219                let merged = kind.merge(update);
220                if merged == NodeUpdate::Content && (changes_layer(*kind) || changes_layer(update))
221                {
222                    changes = GraphChanges::Moves;
223                }
224                *kind = merged;
225            })
226            .or_insert(update);
227    }
228    changes
229}
230
231fn changes_layer(update: NodeUpdate) -> bool {
232    matches!(update, NodeUpdate::Layer | NodeUpdate::MovedLayer)
233}
234
235fn update_from_applier_inner(
236    applier: &MemoryApplier,
237    store: &mut SceneStore,
238    updates: SceneUpdates<'_>,
239) -> GraphUpdateReport {
240    if updates.is_empty() {
241        return GraphUpdateReport::patched(GraphChanges::default());
242    }
243    store.begin_update();
244
245    // The room of the frame before keeps its storage for this one.
246    let mut room =
247        crate::thread_state::with(|state| state.dirty_node_scratch.take()).unwrap_or_default();
248    let merged = dirty_node_updates(updates, &mut room.nodes);
249    let mut report = update_dirty_nodes(applier, store, &mut room);
250    report.layers_moved |= merged.contains(GraphChanges::Moves);
251    room.nodes.clear();
252    crate::thread_state::with(|state| state.dirty_node_scratch.set(Some(room)));
253    report
254}
255
256fn update_dirty_nodes(
257    applier: &MemoryApplier,
258    store: &mut SceneStore,
259    room: &mut DirtyRoom,
260) -> GraphUpdateReport {
261    let DirtyRoom {
262        nodes,
263        order,
264        ancestors,
265        ..
266    } = room;
267    let mut changes = match update_named_nodes(applier, store, nodes, order) {
268        Ok(changes) => changes,
269        Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
270    };
271    // A node the store holds no record of, as one placed again, lowers with
272    // the nearest node above it that the store draws.
273    if !nodes.is_empty() {
274        name_drawn_ancestors(applier, store, nodes, ancestors);
275    }
276    if !nodes.is_empty() {
277        changes |= match update_named_nodes(applier, store, nodes, order) {
278            Ok(changes) => changes,
279            Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
280        };
281        nodes.retain(|&node, _| is_drawn(applier, node));
282    }
283    if nodes.is_empty() {
284        GraphUpdateReport::patched(changes)
285    } else {
286        GraphUpdateReport::needs_rebuild(GraphRebuildReason::UnmatchedDirtyNodes(nodes.len()))
287    }
288}
289
290// Updates the root and the records of the nodes in `nodes`, taking each node
291// it updates out of `nodes`.
292fn update_named_nodes(
293    applier: &MemoryApplier,
294    store: &mut SceneStore,
295    nodes: &mut HashMap<NodeId, NodeUpdate>,
296    order: &mut Vec<DirtyPlace>,
297) -> Result<GraphChanges, GraphRebuildReason> {
298    let root = store
299        .root()
300        .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
301    let mut changes = GraphChanges::default();
302    if let Some(root_id) = layer_identity(store.layer(root))
303        && let Some(kind) = nodes.remove(&root_id)
304    {
305        changes = update_dirty_root(applier, store, nodes, (root, root_id, kind))?;
306        if nodes.is_empty() {
307            return Ok(changes);
308        }
309    }
310    let records = update_dirty_records(applier, store, nodes, order)
311        .ok_or(GraphRebuildReason::DirtyLayerUnavailable)?;
312    Ok(changes | records)
313}
314
315// Updates the root, `kind` its update: a retained root layer takes it in
316// place, any other root is lowered again with every node beneath it, which
317// leaves no node in `nodes`. Out of line: most frames leave the root alone.
318#[inline(never)]
319fn update_dirty_root(
320    applier: &MemoryApplier,
321    store: &mut SceneStore,
322    nodes: &mut HashMap<NodeId, NodeUpdate>,
323    (root, root_id, kind): (RecordId, NodeId, NodeUpdate),
324) -> Result<GraphChanges, GraphRebuildReason> {
325    let ancestors = TranslateAncestorContext {
326        inherited: Inherited::default(),
327        parent_abs: AbsOrigin::ROOT,
328    };
329    if kind == NodeUpdate::Draws
330        && redraw_retained_layer(applier, store, root, Level::Root, ancestors.inherited)
331    {
332        return Ok(GraphChanges::default());
333    }
334    if let Some(changes) =
335        try_update_retained_layer(applier, store, root, nodes, kind, Level::Root, ancestors)
336    {
337        return Ok(changes);
338    }
339    let hit_graph_dirty = rebuild_tracking_hits(store, root, |store, root| {
340        release_for_rebuild(store, root);
341        lower_root_into(applier, store, root_id)
342    })
343    .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
344    store.note_content_change(root);
345    nodes.clear();
346    Ok(GraphChanges::hits(hit_graph_dirty))
347}
348
349// Names in place of each node in `nodes` that the store holds no record of
350// the nearest node above it that the store draws, with new content, and
351// drops those a subcompose node above keeps inactive, which draw nothing.
352// `ancestors` is room for the nodes named.
353fn name_drawn_ancestors(
354    applier: &MemoryApplier,
355    store: &SceneStore,
356    nodes: &mut HashMap<NodeId, NodeUpdate>,
357    ancestors: &mut Vec<NodeId>,
358) {
359    ancestors.clear();
360    nodes.retain(|&node, _| {
361        if store.record_of(node).is_some() {
362            return true;
363        }
364        match climb(applier, node, |above| store.record_of(above).is_some()) {
365            ClimbEnd::Stop(ancestor) => {
366                ancestors.push(ancestor);
367                false
368            }
369            ClimbEnd::Inactive => false,
370            ClimbEnd::Top => true,
371        }
372    });
373    for &ancestor in ancestors.iter() {
374        nodes
375            .entry(ancestor)
376            .and_modify(|kind| *kind = kind.merge(NodeUpdate::Content))
377            .or_insert(NodeUpdate::Content);
378    }
379}
380
381fn is_drawn(applier: &MemoryApplier, node: NodeId) -> bool {
382    !matches!(climb(applier, node, |_| false), ClimbEnd::Inactive)
383}
384
385// Where a climb from a node through the nodes above it ended.
386enum ClimbEnd {
387    // At the node the climb's `stop` picked.
388    Stop(NodeId),
389    // Under a subcompose node that keeps the node the climb came from among
390    // its inactive children.
391    Inactive,
392    // Past the top.
393    Top,
394}
395
396// Climbs from `node` through the nodes above it that are not virtual, up to
397// the first that `stop` picks.
398fn climb(applier: &MemoryApplier, node: NodeId, stop: impl Fn(NodeId) -> bool) -> ClimbEnd {
399    let mut child = node;
400    let mut current = node;
401    while let Some(parent) = applier
402        .get_ref(current)
403        .ok()
404        .and_then(cranpose_core::Node::parent)
405    {
406        let Ok(parent_node) = applier.get_ref(parent) else {
407            return ClimbEnd::Top;
408        };
409        current = parent;
410        if parent_node.is_virtual() {
411            continue;
412        }
413        let parent_node: &dyn Any = parent_node;
414        if let Some(subcompose) = parent_node.downcast_ref::<SubcomposeLayoutNode>()
415            && !subcompose.with_active_children(|children| children.contains(&child))
416        {
417            return ClimbEnd::Inactive;
418        }
419        if stop(parent) {
420            return ClimbEnd::Stop(parent);
421        }
422        child = parent;
423    }
424    ClimbEnd::Top
425}
426
427// What the records above a layer pass to it, besides where they lie.
428#[derive(Clone, Copy, Default)]
429struct Inherited {
430    motion_context_animated: bool,
431    translated_content_context: bool,
432    parent_content_offset: Point,
433}
434
435#[derive(Clone, Copy)]
436struct TranslateAncestorContext {
437    inherited: Inherited,
438    parent_abs: AbsOrigin,
439}
440
441// Whether a node lowers as the graph's root, the one node that may be a
442// window root, which then draws at the origin.
443#[derive(Clone, Copy, PartialEq, Eq)]
444enum Level {
445    Root,
446    Child,
447}
448
449// Whether a retained layer's node kept its place in its parent.
450#[derive(Clone, Copy, PartialEq, Eq)]
451enum Position {
452    Kept,
453    Moved,
454}
455
456// Whether a node's layer lies in the wrapper that holds the draws chained
457// before its graphics layer.
458#[derive(Clone, Copy, PartialEq, Eq)]
459enum Wrapping {
460    Wrapped,
461    Bare,
462}
463
464fn try_update_retained_layer(
465    applier: &MemoryApplier,
466    store: &mut SceneStore,
467    layer: RecordId,
468    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
469    kind: NodeUpdate,
470    level: Level,
471    ancestors: TranslateAncestorContext,
472) -> Option<GraphChanges> {
473    match kind {
474        NodeUpdate::Moved if level == Level::Child => {
475            move_retained_layer(applier, store, layer, ancestors)
476                .or_else(|| translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors))
477        }
478        // A translate keeps the layer's graphics layer: one that changed is
479        // lowered again. A draws update that `redraw_retained_layer` could
480        // not take comes here.
481        NodeUpdate::Content | NodeUpdate::Draws | NodeUpdate::Moved => {
482            translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors)
483        }
484        NodeUpdate::Layer => {
485            update_layer_properties(applier, store, layer, level, Position::Kept, ancestors)
486        }
487        NodeUpdate::MovedLayer => {
488            update_layer_properties(applier, store, layer, level, Position::Moved, ancestors)
489        }
490    }
491}
492
493// Records the draws of the node of `container` again around the children its
494// layer keeps. False, with nothing written, when the node changed in more than
495// its draws. It reads no window geometry above the layer.
496fn redraw_retained_layer(
497    applier: &MemoryApplier,
498    store: &mut SceneStore,
499    container: RecordId,
500    level: Level,
501    inherited: Inherited,
502) -> bool {
503    let layer = store.layer(container);
504    // The wrapper of a node's outer draws is written with its layer.
505    if layer.kind() == RecordKind::Wrapper {
506        return false;
507    }
508    let Some(node_id) = layer.node_id() else {
509        return false;
510    };
511    read_placed_node_data(applier, node_id, level, |data| {
512        let layer = store.layer(container);
513        let placement = layer.origin_in_parent();
514        let kept = Position::Kept;
515        if !retained_layer_matches_layout(layer, &data, placement, Wrapping::Bare, kept) {
516            return false;
517        }
518        if translated_container(
519            store,
520            container,
521            &data.layout_state,
522            &data.modifier_slices,
523            inherited,
524            Wrapping::Bare,
525        )
526        .is_none()
527        {
528            return false;
529        }
530        let parts = ItemParts::of(store, container);
531        let mut list = store.lists.take();
532        list.extend_from_slice(parts.children());
533        let mut own = parts.own_draws();
534        write_own_content_around_children(
535            store,
536            container,
537            (&mut list, &mut own),
538            &data.modifier_slices,
539            data.layout_state.size(),
540        );
541        store.write_items(container, &list);
542        own.finish(store);
543        store.lists.give(list);
544        parts.give_back(store);
545        store.note_content_change(container);
546        true
547    })
548    .unwrap_or(false)
549}
550
551fn move_retained_layer(
552    applier: &MemoryApplier,
553    store: &mut SceneStore,
554    layer: RecordId,
555    ancestors: TranslateAncestorContext,
556) -> Option<GraphChanges> {
557    let placed = placed_child_geometry(applier, layer_identity(store.layer(layer))?)?;
558    if Rect::from_size(placed.size) != store.layer(layer).node_rect() {
559        return None;
560    }
561    let previous = HitGraphState::of(store.layer(layer));
562    translate_retained_child(
563        store,
564        layer,
565        placed.position,
566        ancestors.inherited.parent_content_offset,
567    );
568    let moved = store.layer(layer);
569    if moved.has_origin_sinks() {
570        publish_retained_window_geometry(applier, moved, ancestors.parent_abs);
571    }
572    Some(previous.changes_against(&HitGraphState::of(moved)))
573}
574
575fn content_layer(store: &SceneStore, container: RecordId) -> Option<RecordId> {
576    let layer = store.layer(container);
577    let Some(node_id) = layer.wraps() else {
578        return Some(container);
579    };
580    layer
581        .children()
582        .find(|child| child.kind() == RecordKind::Layer && child.node_id() == Some(node_id))
583        .map(LayerRef::id)
584}
585
586fn retained_layer_matches_layout(
587    layer: LayerRef<'_>,
588    data: &SnapshotNodeData<'_>,
589    placement: Point,
590    wrapping: Wrapping,
591    position: Position,
592) -> bool {
593    let state = &data.layout_state;
594    let slices = &data.modifier_slices;
595    (position == Position::Moved || state.position() == placement)
596        && Rect::from_size(state.size()) == layer.node_rect()
597        && slices.layer_bounds(state.size()) == layer.local_bounds()
598        && state.content_offset() == layer.content_offset()
599        && (slices.outer_draw_command_count() > 0) == (wrapping == Wrapping::Wrapped)
600}
601
602fn update_layer_properties(
603    applier: &MemoryApplier,
604    store: &mut SceneStore,
605    container: RecordId,
606    level: Level,
607    position: Position,
608    ancestors: TranslateAncestorContext,
609) -> Option<GraphChanges> {
610    let layer = store.layer(container);
611    let node_id = layer_identity(layer)?;
612    let wrapping = if layer.kind() == RecordKind::Wrapper {
613        Wrapping::Wrapped
614    } else {
615        Wrapping::Bare
616    };
617    let wrapped = wrapping == Wrapping::Wrapped;
618    // The wrapper of a node's outer draws holds its placement; a moved
619    // wrapped node is drawn again.
620    if position == Position::Moved && wrapped {
621        return None;
622    }
623    let placement = layer.origin_in_parent();
624    let changes = read_placed_node_data(applier, node_id, level, |data| {
625        let target = content_layer(store, container)?;
626        let slices = &data.modifier_slices;
627        let state = &data.layout_state;
628        if !retained_layer_matches_layout(store.layer(target), &data, placement, wrapping, position)
629        {
630            return None;
631        }
632        let context = LowerContext::beneath(ancestors);
633        let previous = HitGraphState::of(store.layer(target));
634        let child_context = with_node_layer(node_id, slices, state, context, |head, children| {
635            assign_layer(store, target, head);
636            children
637        });
638        if wrapped {
639            let layer = store.layer(target);
640            let transform = layer_transform_to_parent(
641                layer.local_bounds(),
642                Point::default(),
643                layer.graphics_layer(),
644            );
645            store.set_placement(target, Point::default(), Some(transform));
646        }
647        let layer = store.layer(target);
648        if layer.has_origin_sinks()
649            && let Some(child_abs) = child_context.parent_abs
650        {
651            for child in layer.children() {
652                publish_retained_window_geometry(applier, child, child_abs);
653            }
654        }
655        Some(previous.changes_against(&HitGraphState::of(layer)))
656    })??;
657    if wrapped {
658        store.note_property_change(container);
659    }
660    Some(changes)
661}
662
663pub(crate) fn publish_space(applier: &MemoryApplier, store: &SceneStore) {
664    if !crate::thread_state::with(|state| state.space_changed.replace(false)) {
665        return;
666    }
667    publish_space_now(applier, store);
668}
669
670#[cold]
671#[inline(never)]
672fn publish_space_now(applier: &MemoryApplier, store: &SceneStore) {
673    let Some(root_layer) = store.root_layer() else {
674        return;
675    };
676    let root = ProjectiveTransform::identity();
677    crate::space::for_each_window_eye(root_layer, root, &mut |tree, view, to_window| {
678        if let Some(eye) = &tree.cells[0].scene.eye {
679            eye.world.rebuild(|world| view.build_world(tree, world));
680        }
681        // The owner of a layer drawn on several meshes places it.
682        for seen in view
683            .surfaces
684            .iter()
685            .filter(|seen| seen.mesh == 0 && seen.layer.has_origin_sinks())
686        {
687            if let Some(content) = view.content_to_window(seen, to_window) {
688                publish_content_geometry(applier, seen.layer, content);
689            }
690        }
691    });
692}
693
694fn publish_content_geometry(
695    applier: &MemoryApplier,
696    layer: LayerRef<'_>,
697    to_window: ProjectiveTransform,
698) {
699    if let Some(node_id) = layer.node_id() {
700        read_node_data(applier, node_id, |data| {
701            data.modifier_slices.publish_window_geometry(
702                Point::default(),
703                Some(to_window),
704                data.layout_state.size(),
705            );
706        });
707    }
708    for child in layer.children() {
709        if child.has_origin_sinks() && child.graphics_layer().space.is_none() {
710            publish_content_geometry(applier, child, child.transform_to_parent().then(to_window));
711        }
712    }
713}
714
715fn publish_retained_window_geometry(
716    applier: &MemoryApplier,
717    layer: LayerRef<'_>,
718    parent_abs: AbsOrigin,
719) {
720    if !layer.has_origin_sinks() {
721        return;
722    }
723    let child_abs = parent_abs.children_of(layer);
724    if let Some(node_id) = layer.node_id() {
725        let origin = layer.origin_in_parent();
726        read_node_data(applier, node_id, |data| {
727            data.modifier_slices.publish_window_geometry(
728                Point {
729                    x: parent_abs.content_origin.x + origin.x,
730                    y: parent_abs.content_origin.y + origin.y,
731                },
732                child_abs.window_transform,
733                data.layout_state.size(),
734            );
735        });
736    }
737    for child in layer.children() {
738        publish_retained_window_geometry(applier, child, child_abs);
739    }
740}
741
742#[cold]
743#[inline(never)]
744fn note_space_change() {
745    crate::thread_state::with(|state| state.space_changed.set(true));
746}
747
748fn release_for_rebuild(store: &mut SceneStore, record: RecordId) {
749    store.drop_items(record);
750    store.set_hit_test(record, None);
751}
752
753fn forget_dirty_subtree(
754    store: &SceneStore,
755    record: RecordId,
756    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
757) {
758    if let Some(node_id) = layer_identity(store.layer(record)) {
759        dirty_nodes.remove(&node_id);
760    }
761    remove_dirty_descendants(store, record, dirty_nodes);
762}
763
764// Takes the node of `item`, an item of a record, and every node beneath it
765// out of `dirty_nodes`.
766fn forget_dirty_node(
767    store: &SceneStore,
768    item: Item,
769    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
770) {
771    if let Some(record) = item.as_child() {
772        forget_dirty_subtree(store, record, dirty_nodes);
773    }
774}
775
776fn remove_dirty_descendants(
777    store: &SceneStore,
778    record: RecordId,
779    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
780) {
781    for child in store.layer(record).children() {
782        if let Some(node_id) = child.node_id() {
783            dirty_nodes.remove(&node_id);
784        }
785        remove_dirty_descendants(store, child.id(), dirty_nodes);
786    }
787}
788
789// The node an item of a record draws: a child record's, `None` for the
790// record's own draws and draw groups.
791#[inline]
792fn child_identity(store: &SceneStore, item: Item) -> Option<NodeId> {
793    item.as_child()
794        .and_then(|child| layer_identity(store.layer(child)))
795}
796
797#[cfg(test)]
798#[path = "tests/scene_builder_tests.rs"]
799mod tests;