crcbl-ui 0.20.0

Crucible immediate-mode GUI
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
//! Taffy's low-level traits, implemented over this frame's nodes and the
//! persistent store.
//!
//! [`LayoutTree`] is a borrow of [`super::Ui`]'s parts for one layout pass:
//! the frame's nodes are the tree Taffy traverses, their [`NodeStyle`]s are
//! the styles it reads, and the store is where each node's cache and unrounded
//! layout live, so a cache hit next frame finds what this frame wrote.
//!
//! The dispatch in [`LayoutPartialTree::compute_child_layout`] is the one
//! `taffy::TaffyTree` makes for the same two layout modes: a hidden run hides,
//! `display: none` hides, a node with children is a flex container and a node
//! without is a leaf measured by its content.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use taffy::{
    AvailableSpace, Cache, CacheTree, Layout, LayoutFlexboxContainer, LayoutInput, LayoutOutput,
    LayoutPartialTree, NodeId, RoundTree, RunMode, Size, TraversePartialTree, TraverseTree,
    compute_cached_layout, compute_flexbox_layout, compute_hidden_layout, compute_leaf_layout,
};

use super::ellipsis::KeptCut;
use super::paragraph::{inline_runs, measure_runs};
use super::store::NodeStore;
use super::style::{Display, NodeStyle, WhiteSpace};
use super::{Content, FrameNode};
use crate::font::Font;
use crate::font::layout::{TextLayout, wrap_width};
use crate::text::{FontAtlas, LINE_HEIGHT};
use crate::widget::NATURAL_FONT_SIZE;

/// Which width a text measurement was asked under.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum WidthBucket {
    MinContent,
    MaxContent,
    /// The bits of [`wrap_width`] of the width: whole pixels, the widths lines
    /// are broken at, so every width in one bucket measures exactly the same.
    Definite(u32),
    /// Every width at once: text that measures the same under any of them.
    Any,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct MeasureKey {
    /// The span's content hash: its text, and every style field that sizes it.
    text: u64,
    width: WidthBucket,
}

/// How many layouts a text's measurements are held for after the last one
/// that built or measured it.
///
/// **Longer than any frame's layouts**: a game that draws each label as a
/// begin-frame, layout and emit cycle of its own on one [`super::Ui`] lays out
/// once per label, so a label drawn every frame comes back within one frame's
/// labels, and is held across frames as long as a frame draws fewer labels
/// than this. **Short enough that a churning label**,
/// a timer whose text is new every layout, leaves no more dead texts behind
/// than this and one [`SWEEP_EVERY`] between sweeps.
pub(super) const RETENTION_CYCLES: u64 = 1024;

/// How many layouts pass between sweeps for texts older than
/// [`RETENTION_CYCLES`]. A sweep visits every text held, so a frame of one
/// layout per label sweeps once per this many labels rather than once per
/// label.
pub(super) const SWEEP_EVERY: u64 = 64;

/// The most texts held after a layout, whatever their age: the bound on a UI
/// whose text churns faster than [`RETENTION_CYCLES`] can let it go, such as
/// many timers at once.
///
/// Room for one churning label's whole window and the layouts between sweeps,
/// so a single one never reaches it. Each text holds a few sizes, at most
/// [`WIDTHS_KEPT`] definite widths and a wrapped layout at each, and at most
/// one `nowrap` layout and [`CUTS_KEPT`] cuts of it, so this bounds the
/// cache's memory.
pub(super) const TEXTS_KEPT: usize = 2048;

/// How many texts a layout that finds more than [`TEXTS_KEPT`] keeps: the
/// newest. Below the cap by a quarter of it, so the eviction, which visits
/// every text, runs at most once per that many new texts — each one measured,
/// which costs far more than its share of the eviction.
pub(super) const TEXTS_AFTER_EVICTION: usize = TEXTS_KEPT / 4 * 3;

/// The most definite widths one text's measurements are held at; a new one
/// past it drops the one measured first. A steady layout asks a wrapping text
/// at one or two, so this holds a box moving between a few widths, while a
/// box dragged through every width does not grow its text's entry without
/// bound.
pub(super) const WIDTHS_KEPT: usize = 8;

/// The most cuts one `nowrap` text is held at, each at its own width; a new
/// one past it drops the one kept first. A layout cuts a text at as many
/// widths as it has ellipsis spans of that text in boxes of different widths,
/// so this holds a few such spans' cuts at once, each found again next frame,
/// while a box dragged through every width does not grow its text's entry
/// without bound.
pub(super) const CUTS_KEPT: usize = 4;

const _: () = assert!(TEXTS_KEPT as u64 > RETENTION_CYCLES + SWEEP_EVERY);

/// Text measurements, keyed by (text and its font, size and line height, width
/// bucket), on Clay's measure-cache pattern.
///
/// A flex pass asks a leaf for its min-content and max-content size and again
/// at its final width, and a text span answers all three from one
/// measurement here.
///
/// **A text's measurements outlive the layout that built it**, so a UI that
/// lays out one label per cycle finds each label's measurements again next
/// frame: they are held while some layout in the last [`RETENTION_CYCLES`]
/// built a span of that text, or measured it, and dropped at a sweep after
/// that. Never more than [`TEXTS_KEPT`] texts are held after a layout; past
/// it, the ones built or measured longest ago go first. Holding a measurement
/// longer is never wrong: it is found by content hash, and a `nowrap` layout
/// is checked against its text, font and size before it is used.
///
/// Text in a parsed font is laid out by [`TextLayout`]: its max-content size
/// unbroken, its min-content size broken at every space, and at a definite
/// width broken to fit it. **Text that measures the same under every width is
/// measured once**, in one bucket for them all: text in the bitmap font, which
/// never wraps, and `white-space: nowrap` text, laid out unbroken under every
/// width. A paragraph is measured the same way, under the hash of its runs, by
/// its line breaker in `inline.rs`.
///
/// **A `nowrap` span's layout is kept with its size**, so cutting it to fit
/// ([`super::ellipsis`]) and drawing it shape nothing again: one layout per
/// `nowrap` span's text in a parsed font, held as long as its sizes are. **So is
/// each cut** an ellipsis span's text was cut to fit with, and the width it
/// was cut at, up to [`CUTS_KEPT`] widths, so a steady frame cuts none of its
/// spans again, even spans of one text in boxes of different widths. **A wrapped
/// span's layout is kept at each definite width it is held at**, so drawing
/// it at a width it was measured or drawn at shapes nothing again.
#[derive(Clone, Debug, Default)]
pub(crate) struct MeasureCache {
    texts: HashMap<u64, Held>,
    /// How many layouts have ended: what [`Held::used`] is stamped with.
    cycle: u64,
    /// Measurements answered from `texts`.
    pub hits: u64,
    /// Measurements that went to the font.
    pub misses: u64,
}

impl MeasureCache {
    /// `text`'s natural size in `style`, under a `width` constraint: in
    /// `font`, or in the bitmap font when that is `None`.
    fn text(
        &mut self,
        atlas: &FontAtlas,
        font: Option<&Font>,
        text: &str,
        content_hash: u64,
        style: &NodeStyle,
        width: AvailableSpace,
    ) -> Size<f32> {
        let bucket = match (font, style.white_space) {
            (None, _) | (Some(_), WhiteSpace::NoWrap) => WidthBucket::Any,
            (Some(_), WhiteSpace::Normal) => bucket(width),
        };
        let key = MeasureKey {
            text: content_hash,
            width: bucket,
        };
        self.entry(key, || match font {
            None => {
                let scale = style.font_size / NATURAL_FONT_SIZE;
                Measured::size(Size {
                    width: atlas.text_width(text, scale),
                    height: atlas.line_count(text) as f32 * LINE_HEIGHT * scale,
                })
            }
            Some(font) => {
                let (size, line_height) = (style.font_size, style.text_line_height(font));
                let wrap = match (style.white_space, width) {
                    (WhiteSpace::NoWrap, _) => {
                        let layout = TextLayout::nowrap(font, text, size, line_height);
                        return Measured {
                            size: size_of(&layout),
                            layout: Some(Arc::new(layout)),
                            cuts: Vec::new(),
                        };
                    }
                    (WhiteSpace::Normal, AvailableSpace::Definite(width)) => {
                        let layout = TextLayout::new(font, text, size, line_height, Some(width));
                        return Measured::wrapped(layout);
                    }
                    (WhiteSpace::Normal, AvailableSpace::MaxContent) => None,
                    (WhiteSpace::Normal, AvailableSpace::MinContent) => Some(0.0),
                };
                Measured::size(size_of(&TextLayout::new(
                    font,
                    text,
                    size,
                    line_height,
                    wrap,
                )))
            }
        })
        .size
    }

    /// The layout a `white-space: nowrap` span of content `content_hash` was
    /// measured from — `text` laid out by [`TextLayout::nowrap`] in `font` at
    /// `size` and `line_height` — when one is held.
    ///
    /// The layout is checked against each of them rather than trusted to the hash,
    /// so a held one is never another text's, nor the same text's in another
    /// font, fallback faces and all, or at another size or line height.
    pub fn nowrap_layout(
        &self,
        content_hash: u64,
        font: &Font,
        text: &str,
        size: f32,
        line_height: f32,
    ) -> Option<&Arc<TextLayout>> {
        self.nowrap(content_hash, font, text, size, line_height)?
            .layout
            .as_ref()
    }

    /// The cut kept for a `white-space: nowrap` span of content
    /// `content_hash` cut at `width`, when one is: only beside a layout of
    /// `text` in `font` at `size` and `line_height`, checked as
    /// [`MeasureCache::nowrap_layout`] checks it, and only at the same width,
    /// to the bit.
    pub fn kept_cut(
        &self,
        content_hash: u64,
        font: &Font,
        text: &str,
        size: f32,
        line_height: f32,
        width: f32,
    ) -> Option<&KeptCut> {
        self.nowrap(content_hash, font, text, size, line_height)?
            .cuts
            .iter()
            .find(|cut| cut.width == width.to_bits())
    }

    /// Keeps `cut` beside the layout of the `nowrap` span of content
    /// `content_hash`, a cut at a width [`MeasureCache::kept_cut`] found none
    /// at; past [`CUTS_KEPT`], in place of the one kept first. Does nothing
    /// when no layout is held for it, so a cut is never kept that
    /// [`MeasureCache::kept_cut`] could not check. Checks only that a layout
    /// is held, not that it is this cut's text's: the caller has already found
    /// it with [`MeasureCache::nowrap_layout`].
    pub fn keep_cut(&mut self, content_hash: u64, cut: KeptCut) {
        let key = MeasureKey {
            text: content_hash,
            width: WidthBucket::Any,
        };
        if let Some(entry) = self.held_mut(key)
            && entry.layout.is_some()
        {
            if entry.cuts.len() >= CUTS_KEPT {
                entry.cuts.remove(0);
            }
            entry.cuts.push(cut);
        }
    }

    /// The layout a `white-space: normal` span of content `content_hash` is
    /// drawn from at content-box `width`: `text` in `font` at `size` and
    /// `line_height`, broken as [`TextLayout::new`] breaks it at `width`.
    ///
    /// The one held in `width`'s bucket when it lays out each of them, checked as
    /// [`MeasureCache::nowrap_layout`] checks it; the bucket is the
    /// [`wrap_width`] every width in it is broken at, so that layout is the
    /// one `width` would give. Otherwise laid out now and held there, unless
    /// the bucket holds another measurement under the same hash.
    pub fn wrapped_layout(
        &mut self,
        content_hash: u64,
        font: &Font,
        text: &str,
        size: f32,
        line_height: f32,
        width: f32,
    ) -> Arc<TextLayout> {
        let key = MeasureKey {
            text: content_hash,
            width: bucket(AvailableSpace::Definite(width)),
        };
        let held = self.held(key);
        if let Some(layout) = held.and_then(|held| held.layout.as_ref())
            && layout.lays_out(font, text, size, line_height)
        {
            return Arc::clone(layout);
        }
        let layout = Arc::new(TextLayout::new(font, text, size, line_height, Some(width)));
        if held.is_none() {
            self.entry(key, || Measured {
                size: size_of(&layout),
                layout: Some(Arc::clone(&layout)),
                cuts: Vec::new(),
            });
        }
        layout
    }

    /// The entry of the `nowrap` span of content `content_hash`, when it
    /// holds a layout of `text` in `font` — the same fallback faces and all —
    /// at `size` and `line_height`: checked against each of them rather than
    /// trusted to the hash, so it is never another text's.
    fn nowrap(
        &self,
        content_hash: u64,
        font: &Font,
        text: &str,
        size: f32,
        line_height: f32,
    ) -> Option<&Measured> {
        let key = MeasureKey {
            text: content_hash,
            width: WidthBucket::Any,
        };
        self.held(key).filter(|entry| {
            entry
                .layout
                .as_ref()
                .is_some_and(|layout| layout.lays_out(font, text, size, line_height))
        })
    }

    /// The measurement held for content `content_hash` under `width`, or
    /// `measure`'s, held from now on.
    pub fn cached(
        &mut self,
        content_hash: u64,
        width: AvailableSpace,
        measure: impl FnOnce() -> Size<f32>,
    ) -> Size<f32> {
        let key = MeasureKey {
            text: content_hash,
            width: bucket(width),
        };
        self.entry(key, || Measured::size(measure())).size
    }

    /// The entry held under `key`, or `measure`'s, held from now on.
    fn entry(&mut self, key: MeasureKey, measure: impl FnOnce() -> Measured) -> &Measured {
        let held = self.texts.entry(key.text).or_default();
        held.used = self.cycle;
        if key.width == WidthBucket::Any {
            if held.any.is_some() {
                self.hits += 1;
            } else {
                self.misses += 1;
            }
            return held.any.get_or_insert_with(measure);
        }
        let measured = &mut held.widths;
        if let Some(at) = measured.iter().position(|(width, _)| *width == key.width) {
            self.hits += 1;
            return &measured[at].1;
        }
        self.misses += 1;
        let definite =
            |(width, _): &(WidthBucket, Measured)| matches!(width, WidthBucket::Definite(_));
        if matches!(key.width, WidthBucket::Definite(_))
            && measured.iter().filter(|entry| definite(entry)).count() >= WIDTHS_KEPT
            && let Some(first) = measured.iter().position(definite)
        {
            measured.remove(first);
        }
        measured.push((key.width, measure()));
        &measured[measured.len() - 1].1
    }

    /// The entry held under `key`, if one is.
    fn held(&self, key: MeasureKey) -> Option<&Measured> {
        let held = self.texts.get(&key.text)?;
        if key.width == WidthBucket::Any {
            return held.any.as_ref();
        }
        held.widths
            .iter()
            .find_map(|(width, measured)| (*width == key.width).then_some(measured))
    }

    /// The entry held under `key`, if one is, to change.
    fn held_mut(&mut self, key: MeasureKey) -> Option<&mut Measured> {
        let held = self.texts.get_mut(&key.text)?;
        if key.width == WidthBucket::Any {
            return held.any.as_mut();
        }
        held.widths
            .iter_mut()
            .find_map(|(width, measured)| (*width == key.width).then_some(measured))
    }

    /// Ends a layout that built the spans and paragraphs whose content hashes
    /// are `live`: stamps their texts as used now, every [`SWEEP_EVERY`]
    /// layouts drops the texts unused for [`RETENTION_CYCLES`], and drops the
    /// longest unused ones past [`TEXTS_KEPT`].
    ///
    /// Visits each of `live`, and every text held only at a sweep or past the
    /// cap, so a frame of many small layouts does not visit the whole cache
    /// each layout.
    pub fn end_cycle(&mut self, live: &HashSet<u64>) {
        let cycle = self.cycle;
        for hash in live {
            if let Some(held) = self.texts.get_mut(hash) {
                held.used = cycle;
            }
        }
        if cycle.is_multiple_of(SWEEP_EVERY) || self.texts.len() > TEXTS_KEPT {
            self.texts
                .retain(|_, held| cycle - held.used < RETENTION_CYCLES);
        }
        if self.texts.len() > TEXTS_KEPT {
            self.evict_oldest(TEXTS_AFTER_EVICTION);
        }
        self.cycle += 1;
    }

    /// Drops the texts used longest ago until `keep` are held, ties between
    /// texts used at the same layout broken in the map's order.
    fn evict_oldest(&mut self, keep: usize) {
        let excess = self.texts.len().saturating_sub(keep);
        if excess == 0 {
            return;
        }
        let mut used: Vec<u64> = self.texts.values().map(|held| held.used).collect();
        // The oldest stamp a kept text may have: `excess` texts are older or
        // as old.
        let (_, &mut threshold, _) = used.select_nth_unstable(excess - 1);
        let older = used.iter().filter(|&&stamp| stamp < threshold).count();
        let mut at_threshold = excess - older;
        self.texts.retain(|_, held| {
            if held.used < threshold {
                false
            } else if held.used == threshold && at_threshold > 0 {
                at_threshold -= 1;
                false
            } else {
                true
            }
        });
    }

    /// How many different strings have measurements held.
    #[cfg(test)]
    pub fn texts(&self) -> usize {
        self.texts.len()
    }

    /// Whether any measurement of content `content_hash` is held.
    #[cfg(test)]
    pub fn holds(&self, content_hash: u64) -> bool {
        self.texts.contains_key(&content_hash)
    }

    /// How many cuts are kept for the `nowrap` text of content `content_hash`.
    #[cfg(all(test, feature = "parsed-font"))]
    pub fn cuts(&self, content_hash: u64) -> usize {
        self.texts
            .get(&content_hash)
            .and_then(|held| held.any.as_ref())
            .map_or(0, |measured| measured.cuts.len())
    }

    /// How many measurements are held, under every width of every text.
    #[cfg(all(test, feature = "parsed-font"))]
    pub fn measurements(&self) -> usize {
        self.texts
            .values()
            .map(|held| usize::from(held.any.is_some()) + held.widths.len())
            .sum()
    }
}

/// One text's measurements, and when it was last used.
#[derive(Clone, Debug, Default)]
struct Held {
    /// The layout that last built a span of this text or measured it: the
    /// [`MeasureCache::cycle`] it ran in.
    used: u64,
    /// Its one measurement under every width, for text that measures the
    /// same under all of them: held in place, so a `nowrap` span's layout is
    /// one lookup away.
    any: Option<Measured>,
    /// Its measurement under each other width it was asked under, in the
    /// order they were measured.
    widths: Vec<(WidthBucket, Measured)>,
}

/// One measurement held.
#[derive(Clone, Debug)]
struct Measured {
    size: Size<f32>,
    /// What a span in a parsed font was measured from: its text laid out by
    /// [`TextLayout::nowrap`] for a `nowrap` span, or by [`TextLayout::new`]
    /// at a definite width for a wrapped one. `None` for every other
    /// measurement.
    layout: Option<Arc<TextLayout>>,
    /// What `layout`'s text was cut to under `text-overflow: ellipsis` at
    /// each width it is kept at, in the order they were kept; empty until it
    /// is cut, and for every measurement without a layout.
    cuts: Vec<KeptCut>,
}

impl Measured {
    /// A measurement with no layout kept.
    const fn size(size: Size<f32>) -> Self {
        Self {
            size,
            layout: None,
            cuts: Vec::new(),
        }
    }

    /// A wrapped span's measurement at a definite width, keeping the layout
    /// it was measured from.
    fn wrapped(layout: TextLayout) -> Self {
        Self {
            size: size_of(&layout),
            layout: Some(Arc::new(layout)),
            cuts: Vec::new(),
        }
    }
}

/// The bucket a measurement under `width` is held in, for content that
/// measures differently under different widths.
fn bucket(width: AvailableSpace) -> WidthBucket {
    match width {
        AvailableSpace::MinContent => WidthBucket::MinContent,
        AvailableSpace::MaxContent => WidthBucket::MaxContent,
        AvailableSpace::Definite(width) => WidthBucket::Definite(wrap_width(width).to_bits()),
    }
}

/// The box `layout` needs, as Taffy takes a size.
fn size_of(layout: &TextLayout) -> Size<f32> {
    let measured = layout.measure();
    Size {
        width: measured.x,
        height: measured.y,
    }
}

/// One layout pass's view of a [`super::Ui`].
pub(crate) struct LayoutTree<'a> {
    pub nodes: &'a mut [FrameNode],
    /// Every node's children, flattened: a node's are
    /// `children[child_start..child_start + child_count]`.
    pub children: &'a [NodeId],
    pub store: &'a mut NodeStore,
    pub text: &'a str,
    pub measure: &'a mut MeasureCache,
    pub atlas: &'a FontAtlas,
}

impl LayoutTree<'_> {
    fn node(&self, id: NodeId) -> &FrameNode {
        &self.nodes[usize::from(id)]
    }

    fn cache(&mut self, id: NodeId) -> &mut Cache {
        let slot = self.nodes[usize::from(id)].slot;
        &mut self.store.get_mut(slot).cache
    }
}

impl TraversePartialTree for LayoutTree<'_> {
    type ChildIter<'a>
        = core::iter::Copied<core::slice::Iter<'a, NodeId>>
    where
        Self: 'a;

    fn child_ids(&self, parent: NodeId) -> Self::ChildIter<'_> {
        let node = self.node(parent);
        self.children[node.child_start..node.child_start + node.child_count]
            .iter()
            .copied()
    }

    fn child_count(&self, parent: NodeId) -> usize {
        self.node(parent).child_count
    }

    fn get_child_id(&self, parent: NodeId, index: usize) -> NodeId {
        self.children[self.node(parent).child_start + index]
    }
}

impl TraverseTree for LayoutTree<'_> {}

impl LayoutPartialTree for LayoutTree<'_> {
    type CoreContainerStyle<'a>
        = &'a NodeStyle
    where
        Self: 'a;

    type CustomIdent = String;

    fn get_core_container_style(&self, node: NodeId) -> Self::CoreContainerStyle<'_> {
        &self.node(node).style
    }

    fn set_unrounded_layout(&mut self, node: NodeId, layout: &Layout) {
        let slot = self.node(node).slot;
        self.store.get_mut(slot).unrounded = *layout;
    }

    fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
        if inputs.run_mode == RunMode::PerformHiddenLayout {
            return compute_hidden_layout(self, node);
        }
        compute_cached_layout(self, node, inputs, |tree, node, inputs| {
            let index = usize::from(node);
            match (
                tree.nodes[index].style.display,
                tree.nodes[index].child_count,
            ) {
                (Display::None, _) => compute_hidden_layout(tree, node),
                (Display::Flex, 1..) => compute_flexbox_layout(tree, node, inputs),
                (Display::Flex, 0) => {
                    let LayoutTree {
                        nodes,
                        text,
                        measure,
                        atlas,
                        ..
                    } = tree;
                    let frame = &nodes[index];
                    compute_leaf_layout(
                        inputs,
                        &frame.style,
                        // Nothing in the subset is a `calc()`.
                        |_, _| 0.0,
                        |known, available| {
                            // The width the node is given, else the space it
                            // may take: what a wrapped line breaks at.
                            let width = known
                                .width
                                .map_or(available.width, AvailableSpace::Definite);
                            let natural = match frame.content {
                                // A run is laid out by its paragraph.
                                Content::Block | Content::Run { .. } => Size::ZERO,
                                Content::Text { start, end } => measure.text(
                                    atlas,
                                    frame.font.as_ref(),
                                    &text[start..end],
                                    frame.content_hash,
                                    &frame.style,
                                    width,
                                ),
                                Content::Paragraph => {
                                    measure.cached(frame.content_hash, width, || {
                                        let (_, runs) = inline_runs(nodes, text, index);
                                        measure_runs(&runs, frame.style.white_space, width, atlas)
                                    })
                                }
                                Content::Image(image) => Size {
                                    width: image.width as f32,
                                    height: image.height as f32,
                                },
                            };
                            Size {
                                width: known.width.unwrap_or(natural.width),
                                height: known.height.unwrap_or(natural.height),
                            }
                        },
                    )
                }
            }
        })
    }
}

impl CacheTree for LayoutTree<'_> {
    fn cache_get(&mut self, node: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
        self.cache(node).get(input)
    }

    fn cache_store(&mut self, node: NodeId, input: &LayoutInput, output: LayoutOutput) {
        self.cache(node).store(input, output);
    }

    fn cache_clear(&mut self, node: NodeId) {
        self.cache(node).clear();
    }
}

impl LayoutFlexboxContainer for LayoutTree<'_> {
    type FlexboxContainerStyle<'a>
        = &'a NodeStyle
    where
        Self: 'a;

    type FlexboxItemStyle<'a>
        = &'a NodeStyle
    where
        Self: 'a;

    fn get_flexbox_container_style(&self, node: NodeId) -> Self::FlexboxContainerStyle<'_> {
        &self.node(node).style
    }

    fn get_flexbox_child_style(&self, child: NodeId) -> Self::FlexboxItemStyle<'_> {
        &self.node(child).style
    }
}

impl RoundTree for LayoutTree<'_> {
    fn get_unrounded_layout(&self, node: NodeId) -> Layout {
        self.store.get(self.node(node).slot).unrounded
    }

    fn set_final_layout(&mut self, node: NodeId, layout: &Layout) {
        self.nodes[usize::from(node)].layout = *layout;
    }
}