cranpose-render-common 0.28.0

Scene, renderer and hit-test contracts for Cranpose backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
use std::{any::Any, rc::Rc};

use cranpose_core::{
    MemoryApplier, NodeId, RecordId,
    collections::{growth_slack::GrowthSlack, map::HashMap},
};
use cranpose_ui::{ModifierNodeSlices, Point, Rect, SubcomposeLayoutNode};

use crate::{
    NodeUpdate, SceneUpdates,
    graph::ProjectiveTransform,
    layer_transform::layer_transform_to_parent,
    scene_store::{HeadKind, Item, LayerHead, LayerRef, RecordKind, SceneStore},
};

mod dirty_records;
use dirty_records::{DirtyPlace, update_dirty_records};
mod draw_recording;
#[cfg(feature = "layer-tree")]
pub(crate) use draw_recording::draw_command_items;
use draw_recording::{
    DrawPass, DrawTarget, GroupPaint, NodeCommands, NodeDraws, OwnDraws, append_draw_nodes,
    draw_nodes, layer_node_capacity, text_item,
};
mod graph_changes;
use graph_changes::GraphChanges;
mod hit_graph;
pub(crate) use hit_graph::HitGraphState;
use hit_graph::rebuild_tracking_hits;
mod inline_leaf;
use inline_leaf::{lower_child, update_dirty_inline};
mod layer_shape;
use layer_shape::shaped_graphics_layer;
mod text_node;
mod translate_geometry;
use text_node::translate_unwrapped;
use translate_geometry::{KeptChild, TranslateGeometry, move_kept_child, translate_retained_child};
mod node_data;
use node_data::{PlacedGeometry, placed_child_geometry, read_node_data, read_placed_node_data};
mod node_layer;
use node_layer::{
    AbsOrigin, LowerContext, assign_layer, hit_test_from_slices, layer_and_node_bounds,
    layer_identity, lower_root_into, modifier_slices_have_origin_sinks, outer_commands,
    outer_draws, placing_transform, set_bounds, slices_hit_something, take_wrapped_layer,
    with_node_layer, write_node_content, write_node_layer, write_wrapper,
};
mod parent_origin;
use parent_origin::ParentOrigin;
mod translate_layer;
pub(crate) use translate_layer::TranslateScratch;
use translate_layer::{
    ItemParts, TranslatedContainer, translate_tracking_hits, translated_container,
    write_own_content_around_children,
};

struct SnapshotNodeData<'a> {
    layout_state: cranpose_ui::widgets::LayoutState,
    modifier_slices: Rc<ModifierNodeSlices>,
    children: &'a [NodeId],
    window_root: bool,
}

/// Why a scoped scene update could not be applied, forcing the caller to throw
/// the scene away and build it again from the applier.
///
/// The reason has to travel with the outcome because the shell picks the
/// scoped path from the shape of the dirty set, before this code runs, and
/// logs that choice. A frame that chose the scoped path and then rebuilt the
/// whole scene is the expensive case, and in the log it reads exactly like a
/// cheap patch -- so the fallback says so itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GraphRebuildReason {
    /// The root was dirty and its replacement layer could not be built.
    RootLayerUnavailable,
    /// A dirty subtree's replacement layer could not be built.
    DirtyLayerUnavailable,
    /// This many dirty nodes own no record in the scene, so the scoped walk
    /// never reached them. A dirty node that never made a record, or whose
    /// record left the scene this frame, cannot be patched in place.
    UnmatchedDirtyNodes(usize),
}

/// The outcome of a scoped scene update.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GraphUpdate {
    /// The dirty nodes were updated in place.
    Patched,
    /// The update could not be applied and the graph must be built again, for the given reason.
    NeedsRebuild(GraphRebuildReason),
}

/// The outcome of a scoped update together with its effect on hit testing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphUpdateReport {
    /// Whether the graph was patched or must be rebuilt.
    pub update: GraphUpdate,
    /// Whether the update changed hit geometry or handlers, so the hit targets must be collected
    /// again.
    pub hit_graph_dirty: bool,
    /// Whether the update moved a layer in its parent by the layer's own properties, as an
    /// animated graphics layer or offset moves it, which no layout pass reports.
    pub layers_moved: bool,
}

impl GraphUpdateReport {
    fn patched(changes: GraphChanges) -> Self {
        Self {
            update: GraphUpdate::Patched,
            hit_graph_dirty: changes.contains(GraphChanges::Hits),
            layers_moved: changes.contains(GraphChanges::Moves),
        }
    }

    fn needs_rebuild(reason: GraphRebuildReason) -> Self {
        Self {
            update: GraphUpdate::NeedsRebuild(reason),
            hit_graph_dirty: true,
            layers_moved: true,
        }
    }

    /// Whether the graph was patched in place.
    pub fn applied(self) -> bool {
        matches!(self.update, GraphUpdate::Patched)
    }

    /// Why the graph must be rebuilt, or `None` when it was patched.
    pub fn rebuild_reason(self) -> Option<GraphRebuildReason> {
        match self.update {
            GraphUpdate::Patched => None,
            GraphUpdate::NeedsRebuild(reason) => Some(reason),
        }
    }
}

// The room an update keeps its dirty nodes in, which the next update on the
// thread takes again.
#[derive(Default)]
pub(crate) struct DirtyRoom {
    nodes: HashMap<NodeId, NodeUpdate>,
    order: Vec<DirtyPlace>,
    ancestors: Vec<NodeId>,
}

impl DirtyRoom {
    // Gives back the room a burst of dirty nodes took.
    fn trim(&mut self) {
        self.nodes.trim_growth_slack();
        self.order.trim_growth_slack();
        self.ancestors.trim_growth_slack();
    }
}

// Gives back the room the updates of the thread took for their dirty nodes.
pub(crate) fn trim_dirty_room() {
    crate::thread_state::with(|state| {
        if let Some(mut room) = state.dirty_node_scratch.take() {
            room.trim();
            state.dirty_node_scratch.set(Some(room));
        }
    });
}

/// Builds the records of the layout tree below `root`, read from `applier`.
/// Returns `None` when `root` cannot be lowered to a layer.
pub fn build_from_applier(applier: &MemoryApplier, root: NodeId) -> Option<SceneStore> {
    let mut store = SceneStore::new();
    rebuild_from_applier(applier, root, &mut store).then_some(store)
}

// Lowers the layout tree below `root` into `store` again, its records reusing
// the store's rows and arenas. Returns `false` and leaves the store empty
// when `root` cannot be lowered to a layer.
pub(crate) fn rebuild_from_applier(
    applier: &MemoryApplier,
    root: NodeId,
    store: &mut SceneStore,
) -> bool {
    store.begin_update();
    if let Some(record) = store.root() {
        release_for_rebuild(store, record);
    }
    if !lower_root_into(applier, store, root) {
        store.clear();
        return false;
    }
    if let Some(record) = store.root() {
        store.note_content_change(record);
    }
    store.finish_update();
    true
}

// Applies `updates` to `store` in place, and reports whether the hit targets
// must be collected again or why the store must be built again.
pub(crate) fn update_from_applier(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    updates: SceneUpdates<'_>,
) -> GraphUpdateReport {
    let report = update_from_applier_inner(applier, store, updates);
    if !updates.is_empty() && report.applied() {
        store.finish_update();
    }
    report
}

// Returns a move when a node's layer change merged into new content: its
// layer is lowered again, which keeps no record of where it lay.
fn dirty_node_updates(
    updates: SceneUpdates<'_>,
    dirty: &mut HashMap<NodeId, NodeUpdate>,
) -> GraphChanges {
    dirty.clear();
    dirty.reserve(updates.len());
    let mut changes = GraphChanges::default();
    for &(id, update) in updates {
        dirty
            .entry(id)
            .and_modify(|kind| {
                let merged = kind.merge(update);
                if merged == NodeUpdate::Content && (changes_layer(*kind) || changes_layer(update))
                {
                    changes = GraphChanges::Moves;
                }
                *kind = merged;
            })
            .or_insert(update);
    }
    changes
}

fn changes_layer(update: NodeUpdate) -> bool {
    matches!(update, NodeUpdate::Layer | NodeUpdate::MovedLayer)
}

fn update_from_applier_inner(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    updates: SceneUpdates<'_>,
) -> GraphUpdateReport {
    if updates.is_empty() {
        return GraphUpdateReport::patched(GraphChanges::default());
    }
    store.begin_update();

    // The room of the frame before keeps its storage for this one.
    let mut room =
        crate::thread_state::with(|state| state.dirty_node_scratch.take()).unwrap_or_default();
    let merged = dirty_node_updates(updates, &mut room.nodes);
    let mut report = update_dirty_nodes(applier, store, &mut room);
    report.layers_moved |= merged.contains(GraphChanges::Moves);
    room.nodes.clear();
    crate::thread_state::with(|state| state.dirty_node_scratch.set(Some(room)));
    report
}

fn update_dirty_nodes(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    room: &mut DirtyRoom,
) -> GraphUpdateReport {
    let DirtyRoom {
        nodes,
        order,
        ancestors,
        ..
    } = room;
    let mut changes = match update_named_nodes(applier, store, nodes, order) {
        Ok(changes) => changes,
        Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
    };
    // A node the store holds no record of, as one placed again, lowers with
    // the nearest node above it that the store draws.
    if !nodes.is_empty() {
        name_drawn_ancestors(applier, store, nodes, ancestors);
    }
    if !nodes.is_empty() {
        changes |= match update_named_nodes(applier, store, nodes, order) {
            Ok(changes) => changes,
            Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
        };
        nodes.retain(|&node, _| is_drawn(applier, node));
    }
    if nodes.is_empty() {
        GraphUpdateReport::patched(changes)
    } else {
        GraphUpdateReport::needs_rebuild(GraphRebuildReason::UnmatchedDirtyNodes(nodes.len()))
    }
}

// Updates the root and the records of the nodes in `nodes`, taking each node
// it updates out of `nodes`.
fn update_named_nodes(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    nodes: &mut HashMap<NodeId, NodeUpdate>,
    order: &mut Vec<DirtyPlace>,
) -> Result<GraphChanges, GraphRebuildReason> {
    let root = store
        .root()
        .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
    let mut changes = GraphChanges::default();
    if let Some(root_id) = layer_identity(store.layer(root))
        && let Some(kind) = nodes.remove(&root_id)
    {
        changes = update_dirty_root(applier, store, nodes, (root, root_id, kind))?;
        if nodes.is_empty() {
            return Ok(changes);
        }
    }
    let records = update_dirty_records(applier, store, nodes, order)
        .ok_or(GraphRebuildReason::DirtyLayerUnavailable)?;
    Ok(changes | records)
}

// Updates the root, `kind` its update: a retained root layer takes it in
// place, any other root is lowered again with every node beneath it, which
// leaves no node in `nodes`. Out of line: most frames leave the root alone.
#[inline(never)]
fn update_dirty_root(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    nodes: &mut HashMap<NodeId, NodeUpdate>,
    (root, root_id, kind): (RecordId, NodeId, NodeUpdate),
) -> Result<GraphChanges, GraphRebuildReason> {
    let ancestors = TranslateAncestorContext {
        inherited: Inherited::default(),
        parent_abs: ParentOrigin::Known(&AbsOrigin::ROOT),
    };
    if kind == NodeUpdate::Draws
        && redraw_retained_layer(applier, store, root, Level::Root, ancestors.inherited)
    {
        return Ok(GraphChanges::default());
    }
    if let Some(changes) =
        try_update_retained_layer(applier, store, root, nodes, kind, Level::Root, ancestors)
    {
        return Ok(changes);
    }
    let hit_graph_dirty = rebuild_tracking_hits(store, root, |store, root| {
        release_for_rebuild(store, root);
        lower_root_into(applier, store, root_id)
    })
    .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
    store.note_content_change(root);
    nodes.clear();
    Ok(GraphChanges::hits(hit_graph_dirty))
}

// Names in place of each node in `nodes` that the store holds no record of
// the nearest node above it that the store draws, with new content, and
// drops those a subcompose node above keeps inactive, which draw nothing.
// `ancestors` is room for the nodes named.
fn name_drawn_ancestors(
    applier: &MemoryApplier,
    store: &SceneStore,
    nodes: &mut HashMap<NodeId, NodeUpdate>,
    ancestors: &mut Vec<NodeId>,
) {
    ancestors.clear();
    nodes.retain(|&node, _| {
        if store.record_of(node).is_some() {
            return true;
        }
        match climb(applier, node, |above| store.record_of(above).is_some()) {
            ClimbEnd::Stop(ancestor) => {
                ancestors.push(ancestor);
                false
            }
            ClimbEnd::Inactive => false,
            ClimbEnd::Top => true,
        }
    });
    for &ancestor in ancestors.iter() {
        nodes
            .entry(ancestor)
            .and_modify(|kind| *kind = kind.merge(NodeUpdate::Content))
            .or_insert(NodeUpdate::Content);
    }
}

fn is_drawn(applier: &MemoryApplier, node: NodeId) -> bool {
    !matches!(climb(applier, node, |_| false), ClimbEnd::Inactive)
}

// Where a climb from a node through the nodes above it ended.
enum ClimbEnd {
    // At the node the climb's `stop` picked.
    Stop(NodeId),
    // Under a subcompose node that keeps the node the climb came from among
    // its inactive children.
    Inactive,
    // Past the top.
    Top,
}

// Climbs from `node` through the nodes above it that are not virtual, up to
// the first that `stop` picks.
fn climb(applier: &MemoryApplier, node: NodeId, stop: impl Fn(NodeId) -> bool) -> ClimbEnd {
    let mut child = node;
    let mut current = node;
    while let Some(parent) = applier
        .get_ref(current)
        .ok()
        .and_then(cranpose_core::Node::parent)
    {
        let Ok(parent_node) = applier.get_ref(parent) else {
            return ClimbEnd::Top;
        };
        current = parent;
        if parent_node.is_virtual() {
            continue;
        }
        let parent_node: &dyn Any = parent_node;
        if let Some(subcompose) = parent_node.downcast_ref::<SubcomposeLayoutNode>()
            && !subcompose.with_active_children(|children| children.contains(&child))
        {
            return ClimbEnd::Inactive;
        }
        if stop(parent) {
            return ClimbEnd::Stop(parent);
        }
        child = parent;
    }
    ClimbEnd::Top
}

// What the records above a layer pass to it, besides where they lie.
#[derive(Clone, Copy, Default)]
struct Inherited {
    motion_context_animated: bool,
    translated_content_context: bool,
    parent_content_offset: Point,
}

#[derive(Clone, Copy)]
struct TranslateAncestorContext<'a> {
    inherited: Inherited,
    parent_abs: ParentOrigin<'a>,
}

// Whether a node lowers as the graph's root, the one node that may be a
// window root, which then draws at the origin.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Level {
    Root,
    Child,
}

// Whether a retained layer's node kept its place in its parent.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Position {
    Kept,
    Moved,
}

// Whether a node's layer lies in the wrapper that holds the draws chained
// before its graphics layer.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Wrapping {
    Wrapped,
    Bare,
}

fn try_update_retained_layer(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    layer: RecordId,
    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
    kind: NodeUpdate,
    level: Level,
    ancestors: TranslateAncestorContext<'_>,
) -> Option<GraphChanges> {
    match kind {
        NodeUpdate::Moved if level == Level::Child => {
            move_retained_layer(applier, store, layer, ancestors)
                .or_else(|| translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors))
        }
        // A translate keeps the layer's graphics layer: one that changed is
        // lowered again. A draws update that `redraw_retained_layer` could
        // not take comes here.
        NodeUpdate::Content | NodeUpdate::Draws | NodeUpdate::Moved => {
            translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors)
        }
        NodeUpdate::Layer => {
            update_layer_properties(applier, store, layer, level, Position::Kept, ancestors)
        }
        NodeUpdate::MovedLayer => {
            update_layer_properties(applier, store, layer, level, Position::Moved, ancestors)
        }
    }
}

// Records the draws of the node of `container` again around the children its
// layer keeps. False, with nothing written, when the node changed in more than
// its draws. It reads no window geometry above the layer.
fn redraw_retained_layer(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    container: RecordId,
    level: Level,
    inherited: Inherited,
) -> bool {
    let layer = store.layer(container);
    // The wrapper of a node's outer draws is written with its layer.
    if layer.kind() == RecordKind::Wrapper {
        return false;
    }
    let Some(node_id) = layer.node_id() else {
        return false;
    };
    read_placed_node_data(applier, node_id, level, |data| {
        let layer = store.layer(container);
        let placement = layer.origin_in_parent();
        let kept = Position::Kept;
        if !retained_layer_matches_layout(layer, &data, placement, Wrapping::Bare, kept) {
            return false;
        }
        if translated_container(
            store,
            container,
            &data.layout_state,
            &data.modifier_slices,
            inherited,
            Wrapping::Bare,
        )
        .is_none()
        {
            return false;
        }
        let parts = ItemParts::of(store, container);
        let mut list = store.lists.take();
        list.extend_from_slice(parts.children());
        let mut own = parts.own_draws();
        write_own_content_around_children(
            store,
            container,
            (&mut list, &mut own),
            &data.modifier_slices,
            data.layout_state.size(),
        );
        store.write_items(container, &list);
        own.finish(store);
        store.lists.give(list);
        parts.give_back(store);
        store.note_content_change(container);
        true
    })
    .unwrap_or(false)
}

fn move_retained_layer(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    layer: RecordId,
    ancestors: TranslateAncestorContext<'_>,
) -> Option<GraphChanges> {
    let placed = placed_child_geometry(applier, layer_identity(store.layer(layer))?)?;
    if Rect::from_size(placed.size) != store.layer(layer).node_rect() {
        return None;
    }
    let previous = HitGraphState::of(store.layer(layer));
    translate_retained_child(
        store,
        layer,
        placed.position,
        ancestors.inherited.parent_content_offset,
    );
    let moved = store.layer(layer);
    if moved.has_origin_sinks()
        && let Some(parent_abs) = ancestors.parent_abs.resolve(store)
    {
        publish_retained_window_geometry(applier, moved, parent_abs);
    }
    Some(previous.changes_against(&HitGraphState::of(moved)))
}

fn content_layer(store: &SceneStore, container: RecordId) -> Option<RecordId> {
    let layer = store.layer(container);
    let Some(node_id) = layer.wraps() else {
        return Some(container);
    };
    layer
        .children()
        .find(|child| child.kind() == RecordKind::Layer && child.node_id() == Some(node_id))
        .map(LayerRef::id)
}

fn retained_layer_matches_layout(
    layer: LayerRef<'_>,
    data: &SnapshotNodeData<'_>,
    placement: Point,
    wrapping: Wrapping,
    position: Position,
) -> bool {
    let state = &data.layout_state;
    let slices = &data.modifier_slices;
    (position == Position::Moved || state.position() == placement)
        && Rect::from_size(state.size()) == layer.node_rect()
        && slices.layer_bounds(state.size()) == layer.local_bounds()
        && state.content_offset() == layer.content_offset()
        && (slices.outer_draw_command_count() > 0) == (wrapping == Wrapping::Wrapped)
}

fn update_layer_properties(
    applier: &MemoryApplier,
    store: &mut SceneStore,
    container: RecordId,
    level: Level,
    position: Position,
    ancestors: TranslateAncestorContext<'_>,
) -> Option<GraphChanges> {
    let layer = store.layer(container);
    let node_id = layer_identity(layer)?;
    let wrapping = if layer.kind() == RecordKind::Wrapper {
        Wrapping::Wrapped
    } else {
        Wrapping::Bare
    };
    let wrapped = wrapping == Wrapping::Wrapped;
    // The wrapper of a node's outer draws holds its placement; a moved
    // wrapped node is drawn again.
    if position == Position::Moved && wrapped {
        return None;
    }
    let placement = layer.origin_in_parent();
    let changes = read_placed_node_data(applier, node_id, level, |data| {
        let target = content_layer(store, container)?;
        let slices = &data.modifier_slices;
        let state = &data.layout_state;
        if !retained_layer_matches_layout(store.layer(target), &data, placement, wrapping, position)
        {
            return None;
        }
        // The node's slices may be new in this update: they and the store's
        // note of the sinks beneath the layer say whether a node reads where
        // the layer lies.
        let reads =
            modifier_slices_have_origin_sinks(slices) || store.layer(target).has_origin_sinks();
        let context = LowerContext {
            inherited: ancestors.inherited,
            parent_abs: if reads {
                ancestors.parent_abs.resolve(store).copied()
            } else {
                None
            },
        };
        let previous = HitGraphState::of(store.layer(target));
        let child_context = with_node_layer(node_id, slices, state, context, |head, children| {
            assign_layer(store, target, head);
            children
        });
        if wrapped {
            let layer = store.layer(target);
            let transform = layer_transform_to_parent(
                layer.local_bounds(),
                Point::default(),
                layer.graphics_layer(),
            );
            store.set_placement(target, Point::default(), Some(transform));
        }
        let layer = store.layer(target);
        if layer.has_origin_sinks()
            && let Some(child_abs) = &child_context.parent_abs
        {
            for child in layer.children() {
                publish_retained_window_geometry(applier, child, child_abs);
            }
        }
        Some(previous.changes_against(&HitGraphState::of(layer)))
    })??;
    if wrapped {
        store.note_property_change(container);
    }
    Some(changes)
}

pub(crate) fn publish_space(applier: &MemoryApplier, store: &SceneStore) {
    if !crate::thread_state::with(|state| state.space_changed.replace(false)) {
        return;
    }
    publish_space_now(applier, store);
}

#[cold]
#[inline(never)]
fn publish_space_now(applier: &MemoryApplier, store: &SceneStore) {
    let Some(root_layer) = store.root_layer() else {
        return;
    };
    let root = ProjectiveTransform::identity();
    crate::space::for_each_window_eye(root_layer, root, &mut |tree, view, to_window| {
        if let Some(eye) = &tree.cells[0].scene.eye {
            eye.world.rebuild(|world| view.build_world(tree, world));
        }
        // The owner of a layer drawn on several meshes places it.
        for seen in view
            .surfaces
            .iter()
            .filter(|seen| seen.mesh == 0 && seen.layer.has_origin_sinks())
        {
            if let Some(content) = view.content_to_window(seen, to_window) {
                publish_content_geometry(applier, seen.layer, content);
            }
        }
    });
}

fn publish_content_geometry(
    applier: &MemoryApplier,
    layer: LayerRef<'_>,
    to_window: ProjectiveTransform,
) {
    if let Some(node_id) = layer.node_id() {
        read_node_data(applier, node_id, |data| {
            data.modifier_slices.publish_window_geometry(
                Point::default(),
                Some(to_window),
                data.layout_state.size(),
            );
        });
    }
    for child in layer.children() {
        if child.has_origin_sinks() && child.graphics_layer().space.is_none() {
            publish_content_geometry(applier, child, child.transform_to_parent().then(to_window));
        }
    }
}

fn publish_retained_window_geometry(
    applier: &MemoryApplier,
    layer: LayerRef<'_>,
    parent_abs: &AbsOrigin,
) {
    if !layer.has_origin_sinks() {
        return;
    }
    let child_abs = parent_abs.children_of(layer);
    if let Some(node_id) = layer.node_id() {
        let origin = layer.origin_in_parent();
        read_node_data(applier, node_id, |data| {
            data.modifier_slices.publish_window_geometry(
                Point {
                    x: parent_abs.content_origin.x + origin.x,
                    y: parent_abs.content_origin.y + origin.y,
                },
                child_abs.window_transform,
                data.layout_state.size(),
            );
        });
    }
    for child in layer.children() {
        publish_retained_window_geometry(applier, child, &child_abs);
    }
}

#[cold]
#[inline(never)]
fn note_space_change() {
    crate::thread_state::with(|state| state.space_changed.set(true));
}

fn release_for_rebuild(store: &mut SceneStore, record: RecordId) {
    store.drop_items(record);
    store.set_hit_test(record, None);
}

fn forget_dirty_subtree(
    store: &SceneStore,
    record: RecordId,
    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
) {
    if let Some(node_id) = layer_identity(store.layer(record)) {
        dirty_nodes.remove(&node_id);
    }
    remove_dirty_descendants(store, record, dirty_nodes);
}

// Takes the node of `item`, an item of a record, and every node beneath it
// out of `dirty_nodes`.
fn forget_dirty_node(
    store: &SceneStore,
    item: Item,
    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
) {
    if let Some(record) = item.as_child() {
        forget_dirty_subtree(store, record, dirty_nodes);
    }
}

fn remove_dirty_descendants(
    store: &SceneStore,
    record: RecordId,
    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
) {
    for child in store.layer(record).children() {
        if let Some(node_id) = child.node_id() {
            dirty_nodes.remove(&node_id);
        }
        remove_dirty_descendants(store, child.id(), dirty_nodes);
    }
}

// The node an item of a record draws: a child record's, `None` for the
// record's own draws and draw groups.
#[inline]
fn child_identity(store: &SceneStore, item: Item) -> Option<NodeId> {
    item.as_child()
        .and_then(|child| layer_identity(store.layer(child)))
}

#[cfg(test)]
#[path = "tests/scene_builder_tests.rs"]
mod tests;