lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
use std::{
  cell::{Cell, OnceCell, RefCell},
  sync::{Arc, Weak},
};

#[cfg(test)]
use crate::layout::layout_result::SubtreeHolds;
use crate::{
  core::layout_dirty::LayoutWatch,
  layout::{Constraints, layout_result::LayoutResult},
};

/// Up to two layout results of one node, most recently used first.
///
/// The front entry is the layout the node was last laid out as or served
/// from, so its constraints are the ones the node's parent last gave it.
pub struct LayoutCache {
  // The first entry stays inline: every laid-out node holds one, and a box for
  // it was as many allocations in a first layout. Only a node laid out under
  // other constraints as well pays for the box with the two result slots.
  inner: RefCell<CachedLayouts>,
  // Inline: a rebuilt tree validates every node, and a box here was as many
  // allocations. Without the RefCell it costs Node no more than the box did.
  validated: Cell<Option<ValidatedLayout>>,
  // Made on first use (`Self::watch`): building an element tree allocated one
  // per node, and its builders marked each, before anything could observe it.
  // A mark on a watch not made yet is dropped (`Self::mark_watch`): the watch
  // starts at a generation newer than any mark before it, which is what the
  // mark would have left, and nothing holds it to be notified.
  watch: OnceCell<Arc<LayoutWatch>>,
  pub(crate) tracking_generation: Cell<u64>,
  pub(crate) inspected_generation: Cell<u64>,
  pub(crate) guards_generation: Cell<u64>,
  // A clear belongs to each node consuming the shared element handle.
  override_clear_generation: Cell<u64>,
  /// What is in the subtree that a frame's walks look for, packed: see [`Self::subtree`].
  subtree: Cell<u16>,
  local_dirty: Cell<bool>,
  descendant_dirty: Cell<bool>,
  /// The tree this node's served cache entry was last prepared into, and what it was prepared from: boxed, as few
  /// nodes are served whole.
  prepared: Cell<Option<Box<PreparedServe>>>,
  /// The subtree as a transition engine last ticked it with nothing running in it: see
  /// [`crate::animation::TransitionEngine`]. Boxed, and held by each node of such a subtree.
  ticked: Cell<Option<Box<TickedClean>>>,
  /// Whether every descendant cache's front entry belongs to this cache's
  /// front entry, i.e. no older entry was served since the last store.
  /// Serving an older entry skips the descendants, so their front entries
  /// still describe the layout they were last visited in (another size of
  /// this node), and repairing a dirty descendant under them would lay it
  /// out for that other size.
  descendants_match_front: Cell<bool>,
}

#[derive(Clone, Copy, Default)]
pub(crate) struct LayoutSubtree {
  pub(crate) text_input: bool,
  pub(crate) select: bool,
  pub(crate) timeline: bool,
  pub(crate) scroll: bool,
  pub(crate) canvas: bool,
  pub(crate) resource_images: bool,
  pub(crate) resource_svgs: bool,
  pub(crate) loading_images: bool,
  /// It, or something under it, holds an element ref: what a frame tells the refs of where their elements are.
  pub(crate) refs: bool,
  /// It, or something under it, declares a layer over the tree (an overlay, a modal) or anchors a dropdown: what
  /// the overlay index records.
  pub(crate) layers: bool,
  /// It, or something under it, is a child its row or column may drop (`ShrinkLimit::Drop`, a drop marker).
  pub(crate) droppable: bool,
  /// It, or something under it, plays an animation: what the animation engine ticks.
  pub(crate) animations: bool,
  /// It, or something under it, is the root of a component's output: where a component built again on its own is
  /// looked for.
  pub(crate) slots: bool,
}

impl LayoutSubtree {
  fn flags(&self) -> [bool; 13] {
    [
      self.text_input,
      self.select,
      self.timeline,
      self.scroll,
      self.canvas,
      self.resource_images,
      self.resource_svgs,
      self.loading_images,
      self.refs,
      self.layers,
      self.droppable,
      self.animations,
      self.slots,
    ]
  }

  fn pack(&self) -> u16 {
    self
      .flags()
      .iter()
      .enumerate()
      .fold(0, |bits, (at, on)| bits | (u16::from(*on) << at))
  }

  fn unpack(bits: u16) -> Self {
    let on = |at: u16| bits & (1 << at) != 0;
    Self {
      text_input: on(0),
      select: on(1),
      timeline: on(2),
      scroll: on(3),
      canvas: on(4),
      resource_images: on(5),
      resource_svgs: on(6),
      loading_images: on(7),
      refs: on(8),
      layers: on(9),
      droppable: on(10),
      animations: on(11),
      slots: on(12),
    }
  }

  /// Whether a frame's index of the tree (its element refs, layers, inputs and open selects) has anything here.
  pub(crate) fn indexed(&self) -> bool {
    self.refs || self.layers || self.text_input || self.select
  }
}

struct ValidatedLayout {
  generation: u64,
  result: Weak<LayoutResult>,
}

struct CachedLayout {
  constraints: Constraints,
  result: Arc<LayoutResult>,
}

struct TwoLayouts {
  slots: [Option<CachedLayout>; 2],
  front: usize,
}

#[derive(Default)]
enum CachedLayouts {
  #[default]
  Empty,
  One(CachedLayout),
  /// Keeps its box when cleared: a node laid out under two constraints once
  /// tends to be again.
  Two(Box<TwoLayouts>),
}

impl CachedLayouts {
  fn front(&self) -> Option<&CachedLayout> {
    match self {
      Self::Empty => None,
      Self::One(cached) => Some(cached),
      Self::Two(two) => two.slots[two.front].as_ref(),
    }
  }

  fn front_index(&self) -> usize {
    match self {
      Self::Two(two) => two.front,
      _ => 0,
    }
  }

  /// `index` comes from [`Self::find`]; a single entry is the front one already.
  fn set_front(&mut self, index: usize) {
    if let Self::Two(two) = self {
      two.front = index;
    }
  }

  fn entries(&self) -> [Option<&CachedLayout>; 2] {
    match self {
      Self::Empty => [None, None],
      Self::One(cached) => [Some(cached), None],
      Self::Two(two) => [two.slots[0].as_ref(), two.slots[1].as_ref()],
    }
  }

  fn entry_mut(&mut self, index: usize) -> Option<&mut CachedLayout> {
    match self {
      Self::Empty => None,
      Self::One(cached) => Some(cached),
      Self::Two(two) => two.slots[index].as_mut(),
    }
  }

  fn find(&self, constraints: Constraints) -> Option<usize> {
    self
      .entries()
      .iter()
      .position(|slot| slot.is_some_and(|cached| cached.constraints == constraints))
  }

  fn clear(&mut self) {
    match self {
      Self::Two(two) => two.slots = [None, None],
      _ => *self = Self::Empty,
    }
  }

  fn store(&mut self, constraints: Constraints, result: Arc<LayoutResult>) {
    let index = self.find(constraints);
    let entry = CachedLayout { constraints, result };
    match self {
      Self::Empty => *self = Self::One(entry),
      Self::One(cached) if index.is_some() => *cached = entry,
      Self::One(_) => {
        let Self::One(first) = std::mem::take(self) else {
          unreachable!("matched just above");
        };
        *self = Self::Two(Box::new(TwoLayouts {
          slots: [Some(first), Some(entry)],
          front: 1,
        }));
      }
      Self::Two(two) => {
        let index = index.unwrap_or(1 - two.front);
        two.slots[index] = Some(entry);
        two.front = index;
      }
    }
  }
}

impl LayoutCache {
  pub fn new() -> Self {
    Self {
      inner: RefCell::new(CachedLayouts::Empty),
      validated: Cell::new(None),
      watch: OnceCell::new(),
      tracking_generation: Cell::new(0),
      inspected_generation: Cell::new(0),
      guards_generation: Cell::new(0),
      override_clear_generation: Cell::new(0),
      subtree: Cell::new(0),
      local_dirty: Cell::new(false),
      descendant_dirty: Cell::new(false),
      descendants_match_front: Cell::new(true),
      prepared: Cell::new(None),
      ticked: Cell::new(None),
    }
  }

  /// What is in the subtree that a frame's walks look for, as its tracking last found it.
  pub(crate) fn subtree(&self) -> LayoutSubtree {
    LayoutSubtree::unpack(self.subtree.get())
  }

  pub(crate) fn set_subtree(&self, subtree: LayoutSubtree) {
    self.subtree.set(subtree.pack());
  }

  /// What a transition engine left of its last tick of this subtree, taken out.
  pub(crate) fn take_ticked(&self) -> Option<Box<TickedClean>> {
    self.ticked.take()
  }

  pub(crate) fn set_ticked(&self, ticked: Option<Box<TickedClean>>) {
    self.ticked.set(ticked);
  }

  /// Whether a transition engine ticked this subtree at its generation as it is, with nothing running in it.
  pub(crate) fn ticked_clean(&self) -> bool {
    let ticked = self.ticked.take();
    let clean = ticked.as_ref().is_some_and(|ticked| ticked.is_current(self.watch()));
    self.ticked.set(ticked);
    clean
  }

  /// What this node's served entry was last prepared into, taken out.
  pub(crate) fn take_prepared(&self) -> Option<Box<PreparedServe>> {
    self.prepared.take()
  }

  pub(crate) fn set_prepared(&self, prepared: Option<Box<PreparedServe>>) {
    self.prepared.set(prepared);
  }

  /// Whether `entry` is the one this node was last prepared from, or into, and no text's layout was written since
  /// (`text_writes` is [`crate::node::node_kind::text_state_writes`] now): what is in it holds what it was
  /// prepared with.
  pub(crate) fn prepared_from(&self, entry: &Arc<LayoutResult>, text_writes: u64) -> bool {
    let prepared = self.prepared.take();
    let held = prepared.as_ref().is_some_and(|prepared| {
      prepared.text_writes == text_writes
        && (prepared.served == Arc::as_ptr(entry) as usize || Arc::ptr_eq(&prepared.result, entry))
    });
    self.prepared.set(prepared);
    held
  }

  /// Notes `result` as prepared as it is, with `text_writes` written: served again with nothing written since, it is
  /// not walked again. Only a tree with texts or scroll containers to walk is noted.
  pub(crate) fn prepared_now(&self, result: &Arc<LayoutResult>, text_writes: u64) {
    if !(result.holds.scroll || result.holds.text) {
      self.prepared.set(None);
      return;
    }
    self.prepared.set(Some(Box::new(PreparedServe {
      served: Arc::as_ptr(result) as usize,
      text_writes,
      result: result.clone(),
    })));
  }

  /// The node's watch, made here the first time anything reads or binds it.
  #[inline]
  pub(crate) fn watch(&self) -> &Arc<LayoutWatch> {
    match self.watch.get() {
      Some(watch) => watch,
      None => self.make_watch(),
    }
  }

  // Out of line: the layout walks recurse through `watch`, and the making
  // inlined into them grew every level's frame.
  #[cold]
  #[inline(never)]
  fn make_watch(&self) -> &Arc<LayoutWatch> {
    self.watch.get_or_init(LayoutWatch::new)
  }

  #[cfg(test)]
  pub(crate) fn has_watch(&self) -> bool {
    self.watch.get().is_some()
  }

  /// `LayoutWatch::mark` on the watch, if it was made: see `watch`.
  pub(crate) fn mark_watch(&self) {
    if let Some(watch) = self.watch.get() {
      watch.mark();
    }
  }

  /// Takes over the watch of `old`, the node a rebuilt node carries its
  /// state over from, when this node has made none: a rebuilt tree's first
  /// layout made one per node. The caller marks it right after, so its
  /// generation is as new as a new watch's, and it starts without a parent
  /// like one. What still notifies it for `old` (a shared state, a signal)
  /// at most lays this node out once more; `old` is dropped right after
  /// (see `preserve_from`).
  pub(crate) fn adopt_watch_from(&self, old: &Self) {
    if self.watch.get().is_none()
      && let Some(watch) = old.watch.get()
    {
      watch.detach_parent();
      let _ = self.watch.set(watch.clone());
    }
  }

  /// Serves the entry laid out under `constraints` and makes it the front
  /// entry, so the constraints of the layout last served stay first.
  #[cfg(test)]
  pub fn get(&self, constraints: Constraints) -> Option<LayoutResult> {
    self.get_shared(constraints).map(|result| result.as_ref().clone())
  }

  pub(crate) fn get_shared(&self, constraints: Constraints) -> Option<Arc<LayoutResult>> {
    if self.is_dirty() {
      return None;
    }
    let mut entries = self.inner.borrow_mut();
    let index = entries.find(constraints)?;
    if index != entries.front_index() {
      entries.set_front(index);
      self.descendants_match_front.set(false);
    }
    Some(entries.front()?.result.clone())
  }

  pub(crate) fn matches_validated(&self, result: &Arc<LayoutResult>) -> bool {
    let validated = self.validated.take();
    let matches = validated.as_ref().is_some_and(|validated| {
      validated.generation == self.watch().generation() && std::ptr::eq(validated.result.as_ptr(), Arc::as_ptr(result))
    });
    self.validated.set(validated);
    matches
  }

  pub(crate) fn remember_validation(&self, result: &Arc<LayoutResult>) {
    self.validated.set(Some(ValidatedLayout {
      generation: self.watch().generation(),
      result: Arc::downgrade(result),
    }));
  }

  pub(crate) fn record_validation(&self, constraints: Constraints, generation: u64) {
    let mut entries = self.inner.borrow_mut();
    if let Some(index) = entries.find(constraints) {
      let result = &mut entries.entry_mut(index).unwrap().result;
      if result.generation != generation {
        Arc::make_mut(result).generation = generation;
      }
    }
  }

  pub(crate) fn contains(&self, constraints: Constraints) -> bool {
    if self.is_dirty() {
      return false;
    }
    self.inner.borrow().find(constraints).is_some()
  }

  /// Records that the parent reused `result`, this node's layout under
  /// `constraints` from earlier in the parent's layout, instead of laying
  /// the node out again (a repaired child's override). Like a hit, it makes
  /// those constraints the front ones: the parent may have laid the node out
  /// under other constraints in between, and its next repair must not use
  /// them. The entry is put back if those layouts pushed it out.
  pub(crate) fn record_reuse(&self, constraints: Constraints, result: &Arc<LayoutResult>) {
    let mut entries = self.inner.borrow_mut();
    match entries.find(constraints) {
      Some(index) if index == entries.front_index() => return,
      Some(index) => entries.set_front(index),
      None => entries.store(constraints, result.clone()),
    }
    self.descendants_match_front.set(false);
  }

  /// The cached result a dirty node may patch its dirty children into:
  /// the front entry, when it was laid out under `constraints` and its
  /// descendants were not laid out for another entry since. The patch lays
  /// each dirty child out again under that child's front constraints, which
  /// are only the ones this result gave it under those two conditions.
  pub(crate) fn get_repairable(&self, constraints: Constraints) -> Option<Arc<LayoutResult>> {
    if !self.descendants_match_front.get() {
      return None;
    }
    let entries = self.inner.borrow();
    let front = entries.front()?;
    (front.constraints == constraints).then(|| front.result.clone())
  }

  pub(crate) fn constraints(&self) -> Option<Constraints> {
    self.inner.borrow().front().map(|cached| cached.constraints)
  }

  pub(crate) fn has_cached_result(&self) -> bool {
    self.inner.borrow().front().is_some()
  }

  /// Constraints and size of the most recently stored result, if any.
  pub(crate) fn cached_entry(&self) -> Option<(Constraints, crate::layout::Size)> {
    self
      .inner
      .borrow()
      .front()
      .map(|cached| (cached.constraints, cached.result.size))
  }

  /// Takes over the entries of `old`, a cache of the tree being replaced:
  /// every caller drops that node right after reconciling (`Tree::set_root`,
  /// `Tree::rebuild`, the component slots, the live slot replacement, the
  /// overlays), and each old node is preserved from at most once, so moving
  /// the entries saves cloning them for every node of a rebuilt tree. `old`
  /// serves nothing afterwards; only its flags stay as they were.
  pub(crate) fn preserve_from(&self, old: &Self) {
    self.mark_watch();
    self.override_clear_generation.set(old.override_clear_generation.get());
    *self.inner.borrow_mut() = old.inner.take();
    // The descendants take over the old descendants' caches the same way, so
    // whether they match the front entry carries over with the entries.
    self.descendants_match_front.set(old.descendants_match_front.get());
    // Carry the old cache's unresolved dirtiness instead of clearing it: the
    // old tree may hold marks no layout pass has consumed yet (re-render
    // chains between paints). Dropping them here laundered staleness — a
    // duplicate re-render inherited the stale results with clean flags and
    // the engine served them wholesale (stale spacer heights / stale text
    // measurements on screen).
    self.local_dirty.set(self.local_dirty.get() || old.local_dirty.get());
    self
      .descendant_dirty
      .set(self.descendant_dirty.get() || old.descendant_dirty.get());
  }

  #[cfg(test)]
  pub fn store(&self, constraints: Constraints, result: LayoutResult) {
    self.store_shared(constraints, Arc::new(result));
  }

  pub(crate) fn store_shared(&self, constraints: Constraints, result: Arc<LayoutResult>) {
    let mut borrow = self.inner.borrow_mut();
    if self.is_dirty() {
      // The dirty flags are cache-wide, but a store only replaces the entry
      // for the constraints just laid out. Any other cached entry predates
      // the invalidation and is equally stale — clearing the flags below
      // while keeping it would launder it into a servable result (observed
      // in production: a two-entry cache under oscillating constraints — a
      // scrollbar gutter toggling a column's width — served a pre-change
      // sibling layout with clean flags, freezing a text row at its old
      // child offsets).
      borrow.clear();
    }
    borrow.store(constraints, result);
    self.descendants_match_front.set(true);
    self.clear_dirty();
  }

  pub fn invalidate(&self) {
    self.mark_watch();
    self.validated.take();
    *self.inner.borrow_mut() = CachedLayouts::Empty;
    self.descendants_match_front.set(true);
    self.clear_dirty();
  }

  /// The node was placed by its parent's layout and holds no result of its
  /// own (an inline link, placed by its paragraph): the marks that asked for
  /// its layout are consumed by the parent's. A mark left behind would keep
  /// the layout dirty for every pass, since no store of its own clears it.
  pub(crate) fn mark_placed_by_parent(&self) {
    self.clear_dirty();
  }

  pub(crate) fn mark_local_dirty(&self) {
    self.mark_watch();
    self.local_dirty.set(true);
  }

  pub(crate) fn mark_descendant_dirty(&self) {
    if let Some(watch) = self.watch.get() {
      watch.mark_descendant();
    }
    self.descendant_dirty.set(true);
  }

  pub(crate) fn needs_dirty_scan(&self) -> bool {
    self.inspected_generation.get() != self.watch().generation()
  }

  pub(crate) fn record_dirty_scan(&self, generation: u64, local: bool, descendant: bool) {
    self.local_dirty.set(self.local_dirty.get() || local);
    self.descendant_dirty.set(self.descendant_dirty.get() || descendant);
    // A shared handle can change while the walk consumes its marks. Only
    // acknowledge the generation the walk started with, so a later write
    // still asks for another inspection.
    self.inspected_generation.set(generation);
  }

  pub(crate) fn take_override_cleared(&self, generation: u64) -> bool {
    self.override_clear_generation.replace(generation) != generation
  }

  pub(crate) fn is_local_dirty(&self) -> bool {
    self.local_dirty.get()
  }

  pub(crate) fn is_descendant_dirty(&self) -> bool {
    self.descendant_dirty.get()
  }

  pub(crate) fn is_dirty(&self) -> bool {
    self.is_local_dirty() || self.is_descendant_dirty()
  }

  fn clear_dirty(&self) {
    self.local_dirty.set(false);
    self.descendant_dirty.set(false);
  }

  pub(crate) fn estimated_memory_bytes(&self) -> usize {
    let borrow = self.inner.borrow();
    let cached_bytes = borrow
      .entries()
      .into_iter()
      .flatten()
      .map(|cached| cached.result.estimated_memory_bytes() + std::mem::size_of::<[usize; 2]>())
      .sum::<usize>();
    let slots_bytes = if matches!(*borrow, CachedLayouts::Two(_)) {
      std::mem::size_of::<TwoLayouts>()
    } else {
      0
    };
    std::mem::size_of::<Self>()
      + std::mem::size_of::<crate::core::layout_dirty::LayoutWatch>()
      + slots_bytes
      + cached_bytes
  }
}

/// The changes of every theme, so far.
pub(crate) fn world_changes() -> u64 {
  crate::app::theme::theme_mutations()
}

/// A subtree a transition engine ticked with no transition running in it and no animation playing: its generation
/// then, the engine's epoch, and the nodes in it that have transitions, which the engine still counts as seen while
/// it does not tick them again.
pub(crate) struct TickedClean {
  pub(crate) generation: u64,
  pub(crate) epoch: u64,
  /// The subtree's revision of its state styles when it was ticked (see
  /// [`crate::core::layout_dirty::LayoutWatch::mark_tick`]): a state of interaction changes what a node heads to
  /// without a layout.
  pub(crate) ticks: u64,
  /// The changes of themes so far when it was ticked: a theme changes what a node heads to without a layout.
  pub(crate) world: u64,
  /// The nodes under it that have transitions; `None` for none.
  pub(crate) ids: Option<Arc<TickedIds>>,
}

impl TickedClean {
  /// Whether the subtree is as it was ticked: no layout, no state of interaction and no theme changed in it since.
  pub(crate) fn is_current(&self, watch: &crate::core::layout_dirty::LayoutWatch) -> bool {
    self.generation == watch.generation() && self.ticks == watch.ticks() && self.world == world_changes()
  }
}

/// The nodes of a clean subtree that have transitions: its own, and its children's as they each left them, shared
/// and not copied, so that every node of the subtree keeps its own and a parent's costs only its children's count.
pub(crate) struct TickedIds {
  pub(crate) own: Option<crate::core::NodeId>,
  pub(crate) children: Vec<Arc<TickedIds>>,
}

impl TickedIds {
  /// Calls `each` with every node in it.
  pub(crate) fn each(&self, each: &mut impl FnMut(crate::core::NodeId)) {
    if let Some(own) = self.own {
      each(own);
    }
    for child in &self.children {
      child.each(each);
    }
  }
}

/// A cached entry served and prepared: its scroll containers synced and its texts' layouts written back. Served
/// again with nothing moved since, it is the same tree.
pub(crate) struct PreparedServe {
  /// The cached entry it was prepared from, by address.
  pub(crate) served: usize,
  /// [`crate::node::node_kind::text_state_writes`] once it was prepared.
  pub(crate) text_writes: u64,
  pub(crate) result: Arc<LayoutResult>,
}

impl Default for LayoutCache {
  fn default() -> Self {
    Self::new()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::layout::Size;

  #[test]
  fn dirty_scan_does_not_consume_a_later_notification() {
    let cache = LayoutCache::new();
    let generation = cache.watch().generation();
    cache.watch().mark();

    cache.record_dirty_scan(generation, false, false);

    assert!(cache.needs_dirty_scan());
  }

  /// Marks before anything reads the watch make none, and the watch made
  /// later is newer than all of them, as a marked one would be.
  #[test]
  fn a_watch_made_after_marks_is_newer_than_them() {
    let cache = LayoutCache::new();
    cache.invalidate();
    cache.mark_local_dirty();
    cache.mark_descendant_dirty();
    assert!(!cache.has_watch());
    let after_marks = LayoutWatch::new().generation();

    assert!(cache.watch().generation() > after_marks);
    assert!(cache.needs_dirty_scan());
    assert!(cache.is_local_dirty() && cache.is_descendant_dirty());
  }

  /// A watch is taken over only by a cache without one, and leaves its parent.
  #[test]
  fn adopting_a_watch_keeps_one_already_made() {
    let parent = LayoutWatch::new();
    let old = LayoutCache::new();
    assert!(old.watch().set_parent(&parent));

    let made = LayoutCache::new();
    let own = made.watch().clone();
    made.adopt_watch_from(&old);
    assert!(Arc::ptr_eq(made.watch(), &own));

    let new = LayoutCache::new();
    new.adopt_watch_from(&old);
    assert!(Arc::ptr_eq(new.watch(), old.watch()));
    let before = parent.generation();
    new.mark_watch();
    assert_eq!(parent.generation(), before, "the old parent hears no more");
  }

  fn constraints(max_width: f32) -> Constraints {
    Constraints {
      min_width: 0.0,
      min_height: 0.0,
      max_width,
      max_height: f32::MAX,
    }
  }

  fn result(width: f32) -> LayoutResult {
    LayoutResult {
      size: Size::new(width, 10.0),
      children: vec![],
      text_layout: None,
      dropped: false,
      holds: SubtreeHolds::UNKNOWN,
      generation: 0,
      sticky_shifts: None,
      reach: crate::layout::layout_result::Reach::UNKNOWN,
    }
  }

  #[test]
  fn a_validation_holds_for_its_result_until_the_generation_moves() {
    let cache = LayoutCache::new();
    let validated = Arc::new(result(40.0));
    let other = Arc::new(result(40.0));
    assert!(!cache.matches_validated(&validated), "nothing validated yet");

    cache.remember_validation(&validated);
    assert!(cache.matches_validated(&validated));
    assert!(cache.matches_validated(&validated), "asking keeps the record");
    assert!(!cache.matches_validated(&other), "another snapshot was not validated");

    cache.watch().mark();
    assert!(!cache.matches_validated(&validated), "a later change voids it");

    cache.remember_validation(&validated);
    assert!(cache.matches_validated(&validated));
    cache.remember_validation(&other);
    assert!(!cache.matches_validated(&validated), "the record holds one snapshot");
    assert!(cache.matches_validated(&other));

    cache.invalidate();
    assert!(!cache.matches_validated(&other));
  }

  /// A dirty cache must not keep sibling entries across a store: they were
  /// computed before the invalidation, and clearing the cache-wide dirty
  /// flags while keeping them would serve them as fresh once the caller's
  /// constraints oscillate back (the studio skills-viewer bug: a scrollbar
  /// gutter toggled a column's width per pass, and a text row whose content
  /// grew kept serving its pre-change layout from the second cache slot).
  #[test]
  fn store_on_a_dirty_cache_drops_stale_sibling_entries() {
    let cache = LayoutCache::new();
    cache.store(constraints(100.0), result(40.0));
    cache.store(constraints(90.0), result(38.0));
    assert!(cache.get(constraints(100.0)).is_some());
    assert!(cache.get(constraints(90.0)).is_some());

    // Content changed: both entries are stale. Repair relayouts under one
    // constraint set only.
    cache.mark_descendant_dirty();
    cache.store(constraints(90.0), result(45.0));

    assert_eq!(
      cache.get(constraints(90.0)).map(|cached| cached.size.width),
      Some(45.0),
      "the freshly stored entry is served"
    );
    assert!(
      cache.get(constraints(100.0)).is_none(),
      "the pre-invalidation sibling entry must not be served as fresh"
    );
  }

  /// A clean cache keeps memoizing both constraint sets (the two-slot memo
  /// exists for constraint oscillation with unchanged content).
  #[test]
  fn clean_stores_keep_both_entries() {
    let cache = LayoutCache::new();
    cache.store(constraints(100.0), result(40.0));
    cache.store(constraints(90.0), result(38.0));
    assert_eq!(
      cache.get(constraints(100.0)).map(|cached| cached.size.width),
      Some(40.0)
    );
    assert_eq!(cache.get(constraints(90.0)).map(|cached| cached.size.width), Some(38.0));
  }

  /// Serving the older entry makes it the front one: the parent's next
  /// repair asks for the constraints this node was last laid out under (the
  /// window resized back to an earlier size served the other slot, and a
  /// modal's content was then repaired at the size before).
  #[test]
  fn serving_an_entry_makes_its_constraints_the_front_ones() {
    let cache = LayoutCache::new();
    cache.store(constraints(1440.0), result(1440.0));
    cache.store(constraints(960.0), result(960.0));

    assert!(cache.get(constraints(1440.0)).is_some());

    assert_eq!(cache.constraints().map(|front| front.max_width), Some(1440.0));
    assert_eq!(cache.cached_entry().map(|(_, size)| size.width), Some(1440.0));
  }

  /// After the older entry was served, the descendants' front entries
  /// belong to the other layout, so the cache refuses a repair until the
  /// node is laid out (stored) again.
  #[test]
  fn a_repair_needs_the_front_entry_its_descendants_were_laid_out_for() {
    let cache = LayoutCache::new();
    cache.store(constraints(1440.0), result(1440.0));
    cache.store(constraints(960.0), result(960.0));
    assert!(cache.get_repairable(constraints(960.0)).is_some());
    assert!(
      cache.get_repairable(constraints(1440.0)).is_none(),
      "an entry behind the front one is not repairable"
    );

    assert!(cache.get(constraints(1440.0)).is_some());
    assert!(
      cache.get_repairable(constraints(1440.0)).is_none(),
      "a served older entry skipped its descendants"
    );
    assert!(
      cache.get(constraints(1440.0)).is_some(),
      "the served entry is still a clean hit"
    );

    cache.store(constraints(1440.0), result(1440.0));
    assert!(cache.get_repairable(constraints(1440.0)).is_some());
  }

  #[test]
  fn preserving_a_cache_keeps_whether_its_descendants_match_the_front_entry() {
    let old = LayoutCache::new();
    old.store(constraints(1440.0), result(1440.0));
    old.store(constraints(960.0), result(960.0));
    assert!(old.get(constraints(1440.0)).is_some());

    let new = LayoutCache::new();
    new.preserve_from(&old);

    assert!(new.get_repairable(constraints(1440.0)).is_none());
  }

  /// A rebuilt tree takes its layouts over from the tree it replaces: the
  /// entries move, in their order, and the old cache has none left to serve.
  #[test]
  fn preserving_a_cache_takes_the_entries_instead_of_cloning_them() {
    let old = LayoutCache::new();
    old.store(constraints(1440.0), result(1440.0));
    old.store(constraints(960.0), result(960.0));
    let older = old.get_shared(constraints(1440.0)).unwrap();
    let front = old.get_shared(constraints(960.0)).unwrap();

    let new = LayoutCache::new();
    new.preserve_from(&old);

    assert!(!old.has_cached_result(), "the old cache keeps no entry");
    assert!(old.get_shared(constraints(960.0)).is_none());
    assert_eq!(
      Arc::strong_count(&front),
      2,
      "only the new cache holds the result besides this test"
    );
    assert_eq!(new.constraints().map(|front| front.max_width), Some(960.0));
    assert!(Arc::ptr_eq(&new.get_shared(constraints(960.0)).unwrap(), &front));
    assert!(Arc::ptr_eq(&new.get_shared(constraints(1440.0)).unwrap(), &older));
  }

  /// Taking the entries must not launder what the old cache had pending.
  #[test]
  fn preserving_a_cache_carries_its_dirty_flags_with_the_entries() {
    let old = LayoutCache::new();
    old.store(constraints(960.0), result(960.0));
    old.mark_local_dirty();
    old.mark_descendant_dirty();

    let new = LayoutCache::new();
    new.preserve_from(&old);

    assert!(new.is_local_dirty());
    assert!(new.is_descendant_dirty());
    assert!(new.has_cached_result());
    assert!(
      new.get_shared(constraints(960.0)).is_none(),
      "a dirty cache serves nothing"
    );
  }

  /// A reused override becomes the front entry, and comes back if the
  /// parent's layouts in between pushed it out of the cache.
  #[test]
  fn a_reused_result_becomes_the_front_entry() {
    let cache = LayoutCache::new();
    cache.store(constraints(292.0), result(292.0));
    cache.store(constraints(300.0), result(300.0));
    cache.record_reuse(constraints(292.0), &result(292.0).into());
    assert_eq!(cache.constraints().map(|front| front.max_width), Some(292.0));
    assert!(cache.get_repairable(constraints(292.0)).is_none());

    cache.store(constraints(300.0), result(300.0));
    cache.store(constraints(310.0), result(310.0));
    cache.record_reuse(constraints(292.0), &result(292.0).into());
    assert_eq!(
      cache.cached_entry().map(|(front, size)| (front.max_width, size.width)),
      Some((292.0, 292.0))
    );
    assert!(cache.get(constraints(310.0)).is_some(), "the newer entry stays");
  }

  /// A first layout stores one entry per node: it must stay inline, and only
  /// a second set of constraints may pay for the box of two slots.
  #[test]
  fn only_a_second_set_of_constraints_boxes_the_entries() {
    let cache = LayoutCache::new();
    assert!(matches!(*cache.inner.borrow(), CachedLayouts::Empty));

    cache.store(constraints(100.0), result(40.0));
    assert!(matches!(*cache.inner.borrow(), CachedLayouts::One(_)));
    cache.store(constraints(100.0), result(41.0));
    assert!(
      matches!(*cache.inner.borrow(), CachedLayouts::One(_)),
      "the same constraints replace the entry"
    );
    assert_eq!(
      cache.get(constraints(100.0)).map(|cached| cached.size.width),
      Some(41.0)
    );
    cache.record_reuse(constraints(100.0), &result(41.0).into());
    assert!(
      matches!(*cache.inner.borrow(), CachedLayouts::One(_)),
      "the only entry is the front one already"
    );

    cache.store(constraints(90.0), result(38.0));
    assert!(matches!(*cache.inner.borrow(), CachedLayouts::Two(_)));
    assert_eq!(
      cache.get(constraints(100.0)).map(|cached| cached.size.width),
      Some(41.0)
    );
    assert_eq!(cache.get(constraints(90.0)).map(|cached| cached.size.width), Some(38.0));

    cache.invalidate();
    assert!(matches!(*cache.inner.borrow(), CachedLayouts::Empty));
  }

  /// An entry stored inline is pushed out like one in a slot: a new store
  /// replaces the entry behind the front one, whichever came first.
  #[test]
  fn a_third_set_of_constraints_replaces_the_entry_behind_the_front_one() {
    let cache = LayoutCache::new();
    cache.store(constraints(100.0), result(100.0));
    cache.store(constraints(90.0), result(90.0));
    cache.store(constraints(80.0), result(80.0));
    assert!(
      cache.get(constraints(100.0)).is_none(),
      "the inline entry was behind the front one"
    );
    assert!(cache.get(constraints(90.0)).is_some());

    let cache = LayoutCache::new();
    cache.store(constraints(100.0), result(100.0));
    cache.store(constraints(90.0), result(90.0));
    assert!(cache.get(constraints(100.0)).is_some());
    cache.store(constraints(80.0), result(80.0));
    assert!(
      cache.get(constraints(90.0)).is_none(),
      "the served inline entry was the front one"
    );
    assert!(cache.get(constraints(100.0)).is_some());
  }

  /// A dirty store drops the other entries whether the cache holds one inline
  /// or two boxed, and a preserved cache keeps the inline entry it took over.
  #[test]
  fn an_inline_entry_is_cleared_and_preserved_like_a_boxed_one() {
    let cache = LayoutCache::new();
    cache.store(constraints(100.0), result(100.0));
    cache.mark_local_dirty();
    assert!(cache.get(constraints(100.0)).is_none(), "a dirty cache serves nothing");
    cache.store(constraints(90.0), result(90.0));
    assert!(
      matches!(*cache.inner.borrow(), CachedLayouts::One(_)),
      "the stale entry is gone"
    );
    assert!(cache.get(constraints(100.0)).is_none());
    assert!(cache.get_repairable(constraints(90.0)).is_some());

    let new = LayoutCache::new();
    new.preserve_from(&cache);
    assert!(!cache.has_cached_result());
    assert_eq!(
      new.cached_entry().map(|(front, size)| (front.max_width, size.width)),
      Some((90.0, 90.0))
    );
  }
}

#[cfg(test)]
mod subtree_tests {
  use super::*;

  #[test]
  fn every_flag_of_a_subtree_is_kept_as_it_was_set() {
    let cache = LayoutCache::default();
    for at in 0..13 {
      let mut flags = [false; 13];
      flags[at] = true;
      let subtree = LayoutSubtree::unpack(1 << at);
      assert_eq!(subtree.flags(), flags, "flag {at}");
      cache.set_subtree(subtree);
      assert_eq!(cache.subtree().flags(), flags, "flag {at} kept");
    }
    cache.set_subtree(LayoutSubtree::unpack(0x1fff));
    assert_eq!(cache.subtree().flags(), [true; 13]);
  }
}