Skip to main content

cranpose_render_common/scene_store/
store.rs

1// The records a renderer draws: a tree of layout nodes' layers, wrappers,
2// draw groups and leaves, each a row of fixed-size records with its items in
3// one span, its other properties and its draws in side arenas.
4
5use std::{
6    rc::Rc,
7    sync::atomic::{AtomicU16, Ordering},
8};
9
10use cranpose_core::{NodeId, RecordId, RecordRef, SceneUpdate, StoreId};
11use cranpose_ui::{GraphicsLayer, Rect};
12use cranpose_ui_graphics::CommandRecording;
13
14use super::{
15    ChildOrder, Facts, GeoRecord, HashCache, Item, ItemKind, ItemLists, Journal, JournalEntry,
16    JournalRead, LayerProps, LayerRef, NodeRecords, Reach, RecordEvent, RecordEvents, RecordFlags,
17    RecordKind, RecordNode, ShapeChunks, ShapeRun, Slab, Span, SpanPool, TreeRecord, WarmRecord,
18    recordings::Recordings,
19};
20#[cfg(feature = "window-damage")]
21use super::{ReachState, own_marks};
22#[cfg(feature = "layer-tree")]
23use crate::graph::LayerNode;
24use crate::graph::{
25    DrawCommandId, DrawPrimitiveNode, DrawRunNode, ProjectiveTransform, TextPrimitiveNode,
26};
27
28/// The scene a renderer draws and the hit targets come from.
29pub struct SceneStore {
30    // The store's identity among the renderers' stores.
31    id: StoreId,
32    pub(super) tree: Vec<TreeRecord>,
33    pub(super) geo: Vec<GeoRecord>,
34    pub(super) warm: Vec<WarmRecord>,
35    pub(super) generations: Vec<u32>,
36    // The generation a new row starts at: past every one a cleared store
37    // or a cut row gave out.
38    pub(super) generation_floor: u32,
39    pub(super) free_rows: Vec<u32>,
40    pub(super) items: SpanPool<Item>,
41    #[cfg(feature = "window-damage")]
42    pub(super) marks: own_marks::Marks,
43    pub(super) props: Slab<LayerProps>,
44    pub(super) graphics_layers: Slab<GraphicsLayer>,
45    pub(super) transforms: Slab<ProjectiveTransform>,
46    pub(super) draws: Slab<DrawPrimitiveNode>,
47    pub(super) texts: Slab<TextPrimitiveNode>,
48    pub(super) runs: Slab<DrawRunNode>,
49    pub(super) shape_runs: Slab<ShapeRun>,
50    pub(super) shape_chunks: ShapeChunks,
51    pub(super) hashes: HashCache,
52    pub(super) facts: Facts,
53    pub(super) node_records: NodeRecords,
54    pub(crate) lists: ItemLists,
55    root: Option<RecordId>,
56    update: SceneUpdate,
57    pub(super) journal: Journal,
58    pub(super) order: ChildOrder,
59    pub(crate) recordings: Recordings,
60}
61
62/// One state of one store: what it held after one of its updates.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub struct SceneVersion {
65    store: StoreId,
66    update: SceneUpdate,
67}
68
69impl SceneVersion {
70    /// The update the store had made.
71    pub fn update(self) -> SceneUpdate {
72        self.update
73    }
74}
75
76/// What a new record starts as.
77#[derive(Clone, Copy, Debug)]
78pub struct RecordSeed {
79    /// What the record draws for.
80    pub kind: RecordKind,
81    /// The layout node the record draws for, `None` for an overlay that
82    /// draws for none.
83    pub node: Option<NodeId>,
84    /// The record that holds it, `None` for the root.
85    pub parent: Option<RecordId>,
86}
87
88fn next_store_id() -> StoreId {
89    static NEXT: AtomicU16 = AtomicU16::new(1);
90    loop {
91        if let Some(id) = StoreId::new(NEXT.fetch_add(1, Ordering::Relaxed)) {
92            return id;
93        }
94    }
95}
96
97impl Default for SceneStore {
98    fn default() -> Self {
99        Self::new()
100    }
101}
102
103impl SceneStore {
104    /// An empty store.
105    pub fn new() -> Self {
106        Self {
107            id: next_store_id(),
108            tree: Vec::new(),
109            geo: Vec::new(),
110            warm: Vec::new(),
111            generations: Vec::new(),
112            generation_floor: 0,
113            free_rows: Vec::new(),
114            items: SpanPool::default(),
115            #[cfg(feature = "window-damage")]
116            marks: own_marks::Marks::default(),
117            props: Slab::default(),
118            graphics_layers: Slab::default(),
119            transforms: Slab::default(),
120            draws: Slab::default(),
121            texts: Slab::default(),
122            runs: Slab::default(),
123            shape_runs: Slab::default(),
124            shape_chunks: ShapeChunks::default(),
125            hashes: HashCache::default(),
126            facts: Facts::default(),
127            node_records: NodeRecords::default(),
128            lists: ItemLists::default(),
129            root: None,
130            update: SceneUpdate::default(),
131            journal: Journal::default(),
132            order: ChildOrder::default(),
133            recordings: Recordings::default(),
134        }
135    }
136
137    /// The store's identity among the renderers' stores.
138    #[inline]
139    pub fn id(&self) -> StoreId {
140        self.id
141    }
142
143    /// The store's identity and latest update.
144    pub fn version(&self) -> SceneVersion {
145        SceneVersion {
146            store: self.id,
147            update: self.update,
148        }
149    }
150
151    /// The root record, `None` before the first build.
152    pub fn root(&self) -> Option<RecordId> {
153        self.root
154    }
155
156    /// The latest scene update.
157    pub fn update(&self) -> SceneUpdate {
158        self.update
159    }
160
161    /// Starts a scene update and returns its number.
162    pub fn begin_update(&mut self) -> SceneUpdate {
163        self.recordings.begin_update();
164        self.update = self.update.next();
165        self.journal.begin(self.update, self.tree.len());
166        self.update
167    }
168
169    /// Whether `id` changed itself or moved in the latest `updates` updates.
170    #[inline]
171    pub fn changed_within(&self, id: RecordId, updates: u32) -> bool {
172        let row = &self.tree[id.index()];
173        self.update.since(row.content_rev) < updates || self.update.since(row.place_rev) < updates
174    }
175
176    // Lists the record at `index` among those the update changed, unless a
177    // stamp of the update shows it listed.
178    #[inline]
179    fn touch(&mut self, index: usize) {
180        let tree = &self.tree[index];
181        if self.journal.follows_stamps()
182            && tree.content_rev != self.update
183            && tree.place_rev != self.update
184        {
185            self.journal.stamp(RecordRef {
186                id: RecordId::from_index(index).expect("a row is a record"),
187                generation: self.generations[index],
188            });
189        }
190    }
191
192    /// Keeps the changes of the kinds in `events` for the store's readers
193    /// from the next update on, in place of those it kept.
194    pub fn follow(&mut self, events: RecordEvents) {
195        if self.journal.followed() != events {
196            self.journal.follow(events);
197            self.mark_for_redraws();
198        }
199    }
200
201    // Whether a reader follows where the update in progress redraws.
202    #[cfg(feature = "window-damage")]
203    #[inline]
204    pub(super) fn follows_redrawn_reach(&self) -> bool {
205        self.journal.wants_redrawn_reach(self.update)
206    }
207
208    // Works out the marks that wait once a reader follows where records
209    // redraw, so it compares the next redraws with the store as it is now.
210    #[cfg(feature = "window-damage")]
211    fn mark_for_redraws(&mut self) {
212        if self.follows_redrawn_reach() {
213            own_marks::refresh_lost(self);
214        }
215    }
216
217    #[cfg(not(feature = "window-damage"))]
218    #[inline]
219    fn mark_for_redraws(&mut self) {}
220
221    /// The changes of the store's records in the updates after `read`, the
222    /// version of the store a reader read last. Lost for no version, a
223    /// version of another store or one older than the store keeps.
224    pub fn changes_since(&self, read: Option<SceneVersion>) -> JournalRead<'_> {
225        match read {
226            Some(read) if read.store == self.id => self.journal.since(read.update, self.update),
227            _ => JournalRead::Lost,
228        }
229    }
230
231    /// The records the updates after `read` made, changed or moved, while
232    /// the store follows [`RecordEvents::STAMPS`]; a record may come more
233    /// than once. `None` for no version, a version of another store or one
234    /// older than the store keeps, or when an update stamped more records
235    /// than the store keeps.
236    pub fn stamps_since(&self, read: Option<SceneVersion>) -> Option<&[RecordRef]> {
237        let read = read.filter(|read| read.store == self.id)?;
238        self.journal.stamps_since(read.update, self.update)
239    }
240
241    /// Whether an update after `read`, the version of the store a reader
242    /// read last, changed a record. True for no version, a version of
243    /// another store or one the store was cleared after.
244    pub fn changed_since(&self, read: Option<SceneVersion>) -> bool {
245        match read {
246            Some(read) if read.store == self.id => self.journal.changed_since(read.update),
247            _ => true,
248        }
249    }
250
251    // Notes the change of `event` for `id` and logs it as the record is
252    // now, when a reader follows it.
253    #[inline]
254    pub(super) fn log(&mut self, event: RecordEvent, id: RecordId) {
255        self.journal.note_change(self.update);
256        if self.journal.wants(event, self.update) {
257            self.log_entry(event, id);
258        }
259    }
260
261    fn log_entry(&mut self, event: RecordEvent, id: RecordId) {
262        let index = id.index();
263        self.journal.log(JournalEntry {
264            update: self.update,
265            event,
266            record: RecordRef {
267                id,
268                generation: self.generations[index],
269            },
270            parent: self.tree[index].parent.map(|parent| RecordRef {
271                id: parent,
272                generation: self.generations[parent.index()],
273            }),
274            node: self.warm[index].node.map(RecordNode::id),
275        });
276    }
277
278    /// Ends the update in progress: logs the records whose children it put
279    /// in another order and the own draws it redrew. Readers read the store
280    /// after it.
281    pub fn finish_update(&mut self) {
282        super::child_order::settle(self);
283        #[cfg(feature = "window-damage")]
284        own_marks::settle(self);
285    }
286
287    /// Gives back the room the store's arrays hold past their records and
288    /// draws: the room a burst took, such as a first build's or a long
289    /// list's. The store's owner calls it at rest, when no frame waits, as
290    /// a frame would take the room again. Returns whether most rows stay
291    /// free past records made after them, room that only a store cleared
292    /// and built anew gives back.
293    pub fn trim(&mut self) -> bool {
294        super::growth_slack::trim(self)
295    }
296
297    // Leaves the own draws of the record at `index` to be compared with what
298    // they were at the end of the update. While no reader follows where
299    // records redraw, the record's marks wait at once.
300    #[expect(
301        clippy::inline_always,
302        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
303    )]
304    #[inline(always)]
305    #[cfg(feature = "window-damage")]
306    pub(super) fn redraw_pending(&mut self, index: usize) {
307        if !self.follows_redrawn_reach() {
308            own_marks::lose(self, index);
309            return;
310        }
311        let flags = &mut self.tree[index].flags;
312        if !flags.contains(RecordFlags::REDRAW_PENDING) {
313            *flags = flags.with(RecordFlags::REDRAW_PENDING);
314            self.marks.redrawn.push(RecordRef {
315                id: RecordId::from_index(index).expect("a row is a record"),
316                generation: self.generations[index],
317            });
318        }
319    }
320
321    // Without window damage a record keeps no marks, and logs each redraw
322    // without its reach.
323    #[cfg(not(feature = "window-damage"))]
324    #[inline]
325    pub(super) fn redraw_pending(&mut self, index: usize) {
326        self.log(
327            RecordEvent::Redrawn(Reach::Unknown),
328            RecordId::from_index(index).expect("a row is a record"),
329        );
330    }
331
332    #[cfg(feature = "window-damage")]
333    pub(super) fn reach(&self, index: usize) -> Reach {
334        match self.tree[index].reach_state {
335            ReachState::Empty => Reach::Empty,
336            ReachState::Finite => Reach::Finite(self.geo[index].reach),
337            ReachState::Unknown => Reach::Unknown,
338        }
339    }
340
341    #[cfg(feature = "window-damage")]
342    pub(super) fn set_reach(&mut self, index: usize, reach: Reach) {
343        let (state, rect) = match reach {
344            Reach::Empty => (ReachState::Empty, Rect::default()),
345            Reach::Finite(rect) => (ReachState::Finite, rect),
346            Reach::Unknown => (ReachState::Unknown, Rect::default()),
347        };
348        self.tree[index].reach_state = state;
349        self.geo[index].reach = rect;
350    }
351
352    // Leaves the containment and the reach of the record at `index` and of
353    // the ancestors that follow from them to be worked out again. Most often
354    // an earlier change in the update left the record so already.
355    #[cfg(feature = "window-damage")]
356    #[inline]
357    pub(super) fn stale(&mut self, index: usize) {
358        if !self.tree[index].flags.contains(RecordFlags::REACH_STALE)
359            || super::facts::keeps_contained(self, index)
360        {
361            self.stale_climb(index);
362        }
363    }
364
365    // Without window damage no reader asks for reach or containment.
366    #[cfg(not(feature = "window-damage"))]
367    #[inline]
368    pub(super) fn stale(&mut self, _index: usize) {}
369
370    #[cfg(feature = "window-damage")]
371    #[inline(never)]
372    fn stale_climb(&mut self, index: usize) {
373        super::facts::forget_contained(self, index);
374        self.reach_stale(index);
375    }
376
377    // Leaves the reach of the record at `index` and of its ancestors to be
378    // worked out again, stopping at the first that waits for it already.
379    #[cfg(feature = "window-damage")]
380    fn reach_stale(&mut self, index: usize) {
381        let mut current = Some(index);
382        while let Some(index) = current {
383            let flags = &mut self.tree[index].flags;
384            if flags.contains(RecordFlags::REACH_STALE) {
385                break;
386            }
387            *flags = flags.with(RecordFlags::REACH_STALE);
388            current = self.tree[index].parent.map(RecordId::index);
389        }
390    }
391
392    /// Works out the reach of every record whose reach a change beneath it
393    /// left to be worked out again, as [`LayerRef::reach`] reads it.
394    #[cfg(feature = "window-damage")]
395    pub fn refresh_reach(&mut self) {
396        own_marks::refresh_lost(self);
397        if let Some(root) = self.root {
398            super::reach::refresh(self, root);
399        }
400    }
401
402    // Leaves the containment of the record at `index` and of its parent,
403    // which reads what the record draws, to be worked out again.
404    #[inline]
405    pub(super) fn stale_with_parent(&mut self, index: usize) {
406        self.stale(index);
407        if let Some(parent) = self.tree[index].parent {
408            self.stale(parent.index());
409        }
410    }
411
412    /// A store that holds `root` and the tree beneath it as records.
413    #[cfg(feature = "layer-tree")]
414    pub fn from_layer(root: &LayerNode) -> Self {
415        let mut store = Self::new();
416        store.describe(root);
417        store
418    }
419
420    /// Writes `root` and the tree beneath it as records in place of what the
421    /// store held, in a new update. Records of the same kind and node at the
422    /// same place stay, so the update changes only what differs.
423    #[cfg(feature = "layer-tree")]
424    pub fn describe(&mut self, root: &LayerNode) {
425        self.begin_update();
426        super::spec::write_root(self, root);
427        self.finish_update();
428    }
429
430    /// The record `id` as its readers see it.
431    #[inline]
432    pub fn layer(&self, id: RecordId) -> LayerRef<'_> {
433        LayerRef::new(self, id)
434    }
435
436    /// The root record as its readers see it.
437    pub fn root_layer(&self) -> Option<LayerRef<'_>> {
438        self.root.map(|root| self.layer(root))
439    }
440
441    /// Estimated heap memory the store holds, in bytes, for memory reports.
442    pub fn heap_bytes(&self) -> usize {
443        super::heap_bytes::store_heap_bytes(self)
444    }
445
446    /// How many records and draws the store holds: each record counts once,
447    /// each primitive of a draw run on its own.
448    pub fn node_count(&self) -> usize {
449        self.record_count()
450            + self.draws.values().count()
451            + self.texts.values().count()
452            + self.runs.values().map(DrawRunNode::len).sum::<usize>()
453            + self.shape_item_count()
454    }
455
456    /// How many records the store holds.
457    pub fn record_count(&self) -> usize {
458        self.tree.len() - self.free_rows.len()
459    }
460
461    /// Removes every record.
462    pub fn clear(&mut self) {
463        self.tree.clear();
464        self.geo.clear();
465        self.warm.clear();
466        // A record made after the clear takes a generation past every one
467        // given out before, so no handle taken before names it. The floor
468        // already counts the rows an update cut from the end.
469        if let Some(&last) = self.generations.iter().max() {
470            self.generation_floor = self.generation_floor.max(last.wrapping_add(1));
471        }
472        self.generations.clear();
473        self.free_rows = Vec::new();
474        self.items.clear();
475        #[cfg(feature = "window-damage")]
476        self.marks.clear();
477        self.props.clear();
478        self.graphics_layers.clear();
479        self.transforms.clear();
480        self.draws.clear();
481        self.texts.clear();
482        self.runs.clear();
483        self.clear_shapes();
484        self.hashes.clear();
485        self.facts.clear();
486        self.node_records.clear();
487        self.root = None;
488        // The store takes an update of its own, which no reader read: a
489        // reader of an earlier version finds its changes lost.
490        self.update = self.update.next();
491        self.journal.clear(self.update);
492    }
493
494    /// Makes a record from `seed`, changed in the update in progress, with no
495    /// items, at the origin of its parent and of zero size. Its ancestors
496    /// take the update as their subtree's; the caller adds it to its
497    /// parent's items.
498    pub fn insert(&mut self, seed: RecordSeed) -> RecordId {
499        let update = self.update;
500        let tree = TreeRecord {
501            parent: seed.parent,
502            items: Span::default(),
503            kind: seed.kind,
504            #[cfg(feature = "window-damage")]
505            reach_state: ReachState::Empty,
506            flags: RecordFlags::default(),
507            content_rev: update,
508            place_rev: update,
509            subtree_rev: update,
510            transform: None,
511        };
512        let warm = WarmRecord {
513            node: seed.node.map(RecordNode::of),
514            props: None,
515            graphics_layer: None,
516            content_offset: [0.0; 2],
517            #[cfg(feature = "window-damage")]
518            own_marks: Span::default(),
519        };
520        let id = match self.free_rows.pop() {
521            Some(row) => {
522                let index = row as usize;
523                self.tree[index] = tree;
524                self.geo[index] = GeoRecord::default();
525                self.warm[index] = warm;
526                RecordId::from_index(index).expect("a freed row was a record")
527            }
528            None => {
529                self.tree.push(tree);
530                self.geo.push(GeoRecord::default());
531                self.warm.push(warm);
532                self.generations.push(self.generation_floor);
533                RecordId::from_index(self.tree.len() - 1).expect("fewer than 2^32 records")
534            }
535        };
536        self.facts.open_row(id.index());
537        self.node_records.claim(id, seed.kind, seed.node);
538        match seed.parent {
539            Some(parent) => self.note_subtree_change(Some(parent)),
540            None => self.root = Some(id),
541        }
542        self.stale_with_parent(id.index());
543        #[cfg(feature = "window-damage")]
544        own_marks::pend_inserted(self, id.index());
545        self.log(RecordEvent::Inserted, id);
546        if self.journal.follows_stamps() {
547            self.journal.stamp(self.record_ref(id));
548        }
549        id
550    }
551
552    // Out of line: inlined into `remove_item`, a removal most updates never
553    // make takes room in the code that drops each replaced draw.
554    /// Removes `id`, its draws, its properties and every record beneath it.
555    #[inline(never)]
556    pub fn remove_subtree(&mut self, id: RecordId) {
557        self.log(RecordEvent::Removed, id);
558        let index = id.index();
559        self.node_records
560            .release(id, self.tree[index].kind, self.node(id));
561        if let Some(parent) = self.tree[index].parent {
562            self.stale(parent.index());
563        }
564        let span = self.tree[index].items;
565        for position in 0..span.len() {
566            let item = self.items.span(span)[position];
567            self.remove_item(item);
568        }
569        // A free row names no span, so a trim packs the live spans alone.
570        self.items.free_span(span);
571        self.tree[index].items = Span::default();
572        #[cfg(feature = "window-damage")]
573        self.marks
574            .pool
575            .free_span(std::mem::take(&mut self.warm[index].own_marks));
576        self.hashes.remove(index);
577        self.drop_props(index);
578        if let Some(transform) = self.tree[index].transform.take() {
579            self.transforms.remove(transform.index());
580        }
581        self.generations[index] = self.generations[index].wrapping_add(1);
582        self.free_rows
583            .push(u32::try_from(index).expect("fewer than 2^32 records"));
584        if self.root == Some(id) {
585            self.root = None;
586        }
587    }
588
589    /// Removes what `item` holds: a child record's subtree or a draw.
590    pub fn remove_item(&mut self, item: Item) {
591        match item.kind() {
592            ItemKind::Child => {
593                if let Some(child) = item.as_child() {
594                    self.remove_subtree(child);
595                }
596            }
597            ItemKind::Draw => {
598                self.draws.remove(item.index());
599            }
600            ItemKind::Text => {
601                self.texts.remove(item.index());
602            }
603            ItemKind::Run => {
604                if let Some(run) = self.runs.take(item.index()) {
605                    self.keep_released(run.command, &run.recording);
606                }
607            }
608            ItemKind::Shape => self.remove_shapes(item.index()),
609        }
610    }
611
612    /// A handle to `id` that tells a later holder whether the row went to
613    /// another record since.
614    #[inline]
615    pub fn record_ref(&self, id: RecordId) -> RecordRef {
616        RecordRef {
617            id,
618            generation: self.generations[id.index()],
619        }
620    }
621
622    /// The record `held` names, while its row still holds that record.
623    #[inline]
624    pub fn resolve(&self, held: RecordRef) -> Option<RecordId> {
625        (self.generations.get(held.id.index()) == Some(&held.generation)).then_some(held.id)
626    }
627
628    /// The items of `id` in draw order.
629    #[inline]
630    pub fn items(&self, id: RecordId) -> &[Item] {
631        self.items.span(self.tree[id.index()].items)
632    }
633
634    // Writes the items of `id` for the scene builder, which notes the
635    // change itself.
636    pub(crate) fn write_items(&mut self, id: RecordId, items: &[Item]) {
637        self.replace_items(id, items);
638        self.stale(id.index());
639    }
640
641    // Replaces the items of `id` with `items` and logs the change, leaving
642    // its containment and reach to the caller. Returns whether the items
643    // differ from the ones it held.
644    pub(super) fn replace_items(&mut self, id: RecordId, items: &[Item]) -> bool {
645        let index = id.index();
646        let old = self.items.span(self.tree[index].items);
647        // Draws written in place of removed ones of the same kinds take
648        // their handles: the items read as before.
649        if old == items {
650            return false;
651        }
652        if !super::facts::same_children(old, items) {
653            super::facts::forget_children(self, index);
654        }
655        super::facts::forget_own(self, index);
656        let noted = self.journal.follows(RecordEvent::Changed);
657        if noted {
658            let record = self.record_ref(id);
659            self.order.note(record, old);
660        }
661        self.tree[index].items = self.items.write(self.tree[index].items, items);
662        self.touch(index);
663        // A reader that follows these changes learns them when the update
664        // ends, from the order of the children and the redrawn own draws.
665        // Any other write of items is a change of its own.
666        if !noted {
667            self.journal.note_change(self.update);
668        }
669        true
670    }
671
672    /// Adds a draw primitive for an item.
673    pub fn add_draw(&mut self, draw: DrawPrimitiveNode) -> Item {
674        Item::new(ItemKind::Draw, self.draws.insert(draw))
675    }
676
677    /// Adds a text for an item.
678    pub fn add_text(&mut self, text: TextPrimitiveNode) -> Item {
679        Item::new(ItemKind::Text, self.texts.insert(text))
680    }
681
682    /// Adds a draw run for an item.
683    pub fn add_run(&mut self, run: DrawRunNode) -> Item {
684        Item::new(ItemKind::Run, self.runs.insert(run))
685    }
686
687    /// The draw primitive of a draw item.
688    #[inline]
689    pub fn draw(&self, item: Item) -> &DrawPrimitiveNode {
690        &self.draws[item.index()]
691    }
692
693    /// The text of a text item.
694    #[inline]
695    pub fn text(&self, item: Item) -> &TextPrimitiveNode {
696        &self.texts[item.index()]
697    }
698
699    // The text of a text item, to change in place by the scene builder,
700    // which notes the change of the record that holds it.
701    pub(crate) fn text_mut(&mut self, item: Item) -> &mut TextPrimitiveNode {
702        &mut self.texts[item.index()]
703    }
704
705    /// The draw run of a run item.
706    #[inline]
707    pub fn run(&self, item: Item) -> &DrawRunNode {
708        &self.runs[item.index()]
709    }
710
711    // The draw run of a run item, to draw again in place.
712    #[inline]
713    pub(crate) fn run_mut(&mut self, item: Item) -> &mut DrawRunNode {
714        &mut self.runs[item.index()]
715    }
716
717    // Puts `recording` in place of the recording of the run `item`.
718    pub(crate) fn swap_run_recording(&mut self, item: Item, recording: Rc<CommandRecording>) {
719        let run = &mut self.runs[item.index()];
720        // A run handed the recording it draws lets go of nothing.
721        if Rc::ptr_eq(&run.recording, &recording) {
722            return;
723        }
724        let command = run.command;
725        let old = std::mem::replace(&mut run.recording, recording);
726        self.keep_released(command, &old);
727    }
728
729    // Keeps `recording`, which `command` recorded and which the store lets
730    // go of, for the command's next recording once no reader holds it.
731    fn keep_released(&mut self, command: Option<DrawCommandId>, recording: &Rc<CommandRecording>) {
732        if let Some(id) = command {
733            self.recordings.keep(id, recording);
734        }
735    }
736
737    /// What `id` draws for.
738    #[inline]
739    pub fn kind(&self, id: RecordId) -> RecordKind {
740        self.tree[id.index()].kind
741    }
742
743    /// The layout node `id` draws for.
744    #[inline]
745    pub fn node(&self, id: RecordId) -> Option<NodeId> {
746        self.warm[id.index()].node.map(RecordNode::id)
747    }
748
749    /// The record that holds `id`.
750    #[inline]
751    pub fn parent(&self, id: RecordId) -> Option<RecordId> {
752        self.tree[id.index()].parent
753    }
754
755    // The record `node` draws through: its layer or its leaf.
756    pub(crate) fn record_of(&self, node: NodeId) -> Option<RecordId> {
757        self.node_records.get(node)
758    }
759
760    // The node whose record holds the records of `node`: the one to draw
761    // again for the records of `node` to leave. `None` when no record draws
762    // for `node` or its record is the root.
763    pub(crate) fn drawn_parent(&self, node: NodeId) -> Option<NodeId> {
764        let mut record = self.record_of(node)?;
765        loop {
766            record = self.parent(record)?;
767            if let Some(parent) = self.node(record)
768                && parent != node
769            {
770                return Some(parent);
771            }
772        }
773    }
774
775    /// The flags of `id`.
776    #[inline]
777    pub fn flags(&self, id: RecordId) -> RecordFlags {
778        self.tree[id.index()].flags
779    }
780
781    // Writes the flags of `id` for the scene builder, which notes the
782    // change itself; `false` when they stay.
783    pub(crate) fn write_flags(&mut self, id: RecordId, flags: RecordFlags) -> bool {
784        let changed = self.write_flag_row(id.index(), flags);
785        if changed {
786            self.stale_with_parent(id.index());
787        }
788        changed
789    }
790
791    /// The size of the node rect of `id`.
792    #[inline]
793    pub fn node_rect(&self, id: RecordId) -> Rect {
794        self.geo[id.index()].node_rect()
795    }
796
797    // Writes the node rect size of `id` for the scene builder, which notes
798    // the change itself; `false` when it stays.
799    #[inline]
800    pub(crate) fn write_size(&mut self, id: RecordId, width: f32, height: f32) -> bool {
801        let index = id.index();
802        let size = [width, height];
803        if super::records::same_pair(self.geo[index].size, size) {
804            return false;
805        }
806        self.geo[index].size = size;
807        self.stale_with_parent(index);
808        true
809    }
810
811    /// Sets what `id` draws for and the layout node it draws for, and
812    /// returns whether either changed. A [`RecordKind::Leaf`] holds no layer
813    /// properties and no child layers.
814    #[inline]
815    pub fn set_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) -> bool {
816        let index = id.index();
817        let changed =
818            self.tree[index].kind != kind || self.warm[index].node != node.map(RecordNode::of);
819        if changed {
820            self.change_kind(id, kind, node);
821        }
822        changed
823    }
824
825    #[inline(never)]
826    fn change_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) {
827        let index = id.index();
828        self.log(RecordEvent::Released, id);
829        self.node_records
830            .release(id, self.tree[index].kind, self.node(id));
831        self.node_records.claim(id, kind, node);
832        self.tree[index].kind = kind;
833        self.warm[index].node = node.map(RecordNode::of);
834        self.stale_with_parent(index);
835        self.log(RecordEvent::Claimed, id);
836        self.touch(index);
837    }
838
839    // Removes every item of `id` for the scene builder, which notes the
840    // change itself.
841    pub(crate) fn drop_items(&mut self, id: RecordId) {
842        let index = id.index();
843        let span = self.tree[index].items;
844        if !super::facts::same_children(self.items.span(span), &[]) {
845            super::facts::forget_children(self, index);
846        }
847        for position in 0..span.len() {
848            let item = self.items.span(span)[position];
849            self.remove_item(item);
850        }
851        self.items.free_span(span);
852        self.tree[index].items = Span::default();
853        super::facts::forget_own(self, index);
854        self.stale(index);
855        if span.len() != 0 {
856            self.touch(index);
857        }
858    }
859
860    /// Notes that the update in progress changed what `id` draws: its own
861    /// draws, properties or children. Its ancestors take the update as their
862    /// subtree's.
863    pub fn note_content_change(&mut self, id: RecordId) {
864        let update = self.update;
865        let index = id.index();
866        self.redraw_pending(index);
867        self.stale(index);
868        super::facts::forget_own(self, index);
869        self.touch(index);
870        let tree = &mut self.tree[index];
871        tree.content_rev = update;
872        let raise = tree.subtree_rev != update;
873        self.note_content_run(index);
874        if raise {
875            self.raise_subtree_revs(id);
876        }
877    }
878
879    /// Notes that the update in progress changed the properties of `id`
880    /// without changing what it draws: its hashes go, while a raster cache
881    /// keyed on its content does not count the update as a content change.
882    pub fn note_property_change(&mut self, id: RecordId) {
883        let update = self.update;
884        let index = id.index();
885        if self.tree[index].content_rev != update {
886            self.log(RecordEvent::Changed, id);
887        }
888        self.touch(index);
889        let tree = &mut self.tree[index];
890        tree.content_rev = update;
891        tree.subtree_rev = update;
892        let parent = tree.parent;
893        self.note_subtree_change(parent);
894    }
895
896    // Notes that the update in progress moved the record at `index`, or its
897    // content within it. Its ancestors take the update as their subtree's.
898    #[inline]
899    pub(super) fn moved(&mut self, index: usize) {
900        if self.tree[index].place_rev != self.update {
901            self.touch(index);
902            self.tree[index].place_rev = self.update;
903            self.log(
904                RecordEvent::Moved,
905                RecordId::from_index(index).expect("a row is a record"),
906            );
907            self.note_subtree_change(self.tree[index].parent);
908        }
909    }
910
911    // Raises the subtree revision of `from` and its ancestors to the update
912    // in progress, and leaves their hashes to be worked out again, stopping
913    // at the first ancestor that holds the update already.
914    #[inline]
915    pub(super) fn note_subtree_change(&mut self, from: Option<RecordId>) {
916        if let Some(record) = from
917            && self.tree[record.index()].subtree_rev != self.update
918        {
919            self.raise_subtree_revs(record);
920        }
921    }
922
923    #[inline(never)]
924    fn raise_subtree_revs(&mut self, from: RecordId) {
925        let update = self.update;
926        let mut current = Some(from);
927        while let Some(record) = current {
928            let index = record.index();
929            let tree = &mut self.tree[index];
930            if tree.subtree_rev == update {
931                break;
932            }
933            tree.subtree_rev = update;
934            current = tree.parent;
935            self.note_content_run(index);
936        }
937    }
938
939    // Counts the update in progress in the content run of the record at
940    // `index`, which `LayerRef::content_churns` reads.
941    #[cfg(feature = "window-damage")]
942    #[inline]
943    fn note_content_run(&mut self, index: usize) {
944        if self.tree[index].flags.contains(RecordFlags::HAS_PROPS)
945            && let Some(props) = self.warm[index].props
946        {
947            self.props[props.index()].content_run.note(self.update);
948        }
949    }
950
951    // Without window damage no reader asks whether a record's content churns.
952    #[cfg(not(feature = "window-damage"))]
953    #[inline]
954    fn note_content_run(&mut self, _index: usize) {}
955
956    /// The update that last changed what `id` itself draws.
957    pub fn content_rev(&self, id: RecordId) -> SceneUpdate {
958        self.tree[id.index()].content_rev
959    }
960}