gpui-pre 0.3.15

Zed's GPU-accelerated UI framework (gpui-pre snapshot of zed@a36d485)
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
use crate::{
    AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, PathHash, Pixels,
    Point, Size, Style, Window, size,
    util::{
        ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
        round_to_device_pixel,
    },
};
use collections::{FxHashMap, FxHashSet};
use slotmap::{DefaultKey, KeyData, SecondaryMap};
use smallvec::SmallVec;
use std::{any::Any, fmt::Debug, ops::Range};
use taffy::{
    TaffyTree, TraversePartialTree as _,
    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
    prelude::{max_content, min_content},
    style::AvailableSpace as TaffyAvailableSpace,
    tree::NodeId,
};

#[cfg(feature = "stacker")]
type StackSafe<T> = stacksafe::StackSafe<T>;
#[cfg(not(feature = "stacker"))]
type StackSafe<T> = T;

type NodeContext = StackSafe<Box<dyn Measure>>;

/// Lets a node hold any [`KeyedMeasure`] in a single allocation.
trait Measure: Any {
    /// `final_layout` is false when Taffy is only probing the node's size.
    fn measure(
        &mut self,
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<AvailableSpace>,
        final_layout: bool,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels>;
}

/// Replaces `previous` in place when it already holds a `KeyedMeasure<K, F>`, returning
/// whether `reuse` said its cached sizes still apply. Returns `Err((key, measure))` when
/// the node held a measure of a different type and needs a fresh allocation.
///
/// Unlike the rest of a layout request, this reads the node's context, which with the
/// `stacker` feature may only be done from a stack-safe function.
#[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
fn replace_measure_in_place<K, F>(
    previous: &mut NodeContext,
    mut key: K,
    reuse: fn(&mut K, &mut K) -> bool,
    measure: F,
) -> Result<bool, (K, F)>
where
    K: 'static,
    F: FnMut(
            &K,
            Size<Option<Pixels>>,
            Size<AvailableSpace>,
            bool,
            &mut Window,
            &mut App,
        ) -> Size<Pixels>
        + 'static,
{
    let previous: &mut Box<dyn Measure> = previous;
    let Some(previous) = (&mut **previous as &mut dyn Any).downcast_mut::<KeyedMeasure<K, F>>()
    else {
        return Err((key, measure));
    };
    let reused = reuse(&mut key, &mut previous.key);
    previous.key = key;
    previous.measure = measure;
    Ok(reused)
}

fn box_measure<K, F>(key: K, measure: F) -> NodeContext
where
    K: 'static,
    F: FnMut(
            &K,
            Size<Option<Pixels>>,
            Size<AvailableSpace>,
            bool,
            &mut Window,
            &mut App,
        ) -> Size<Pixels>
        + 'static,
{
    let measure: Box<dyn Measure> = Box::new(KeyedMeasure { key, measure });
    #[cfg(feature = "stacker")]
    let measure = StackSafe::new(measure);
    measure
}

/// A measure function and the key describing what its measured size depends on.
struct KeyedMeasure<K, F> {
    key: K,
    measure: F,
}

impl<K, F> Measure for KeyedMeasure<K, F>
where
    K: 'static,
    F: FnMut(
            &K,
            Size<Option<Pixels>>,
            Size<AvailableSpace>,
            bool,
            &mut Window,
            &mut App,
        ) -> Size<Pixels>
        + 'static,
{
    fn measure(
        &mut self,
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<AvailableSpace>,
        final_layout: bool,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels> {
        (self.measure)(
            &self.key,
            known_dimensions,
            available_space,
            final_layout,
            window,
            cx,
        )
    }
}

pub struct TaffyLayoutEngine {
    taffy: TaffyTree,
    /// Kept outside of Taffy, whose context map hashes every access and marks a node dirty
    /// whenever its context is replaced.
    contexts: SecondaryMap<DefaultKey, NodeContext>,
    /// Keeps layout nodes alive from one frame to the next, so Taffy's layout cache can
    /// skip subtrees whose styles and children didn't change.
    cache: LayoutCache,
    absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
    /// Unrounded absolute border-box top-left per-node coordinate in device pixels.
    absolute_outer_origins: FxHashMap<LayoutId, Point<f32>>,
    computed_layouts: FxHashSet<LayoutId>,
    layout_bounds_scratch_space: Vec<LayoutId>,
}

/// Layout nodes requested by elements under one element ID path, in request order.
///
/// Elements without IDs are distinguished only by their order within the nearest ancestor
/// with one. Which node a request reuses only affects how much of Taffy's cache survives:
/// a reused node's style, children and measure function are always brought up to date.
#[derive(Default)]
struct LayoutScope {
    /// How many of `nodes` were requested this frame.
    requested: usize,
    nodes: SmallVec<[NodeId; 4]>,
}

struct CachedNode {
    /// What the node's Taffy style was converted from, compared before converting again.
    style: LayoutStyle,
    /// The last frame the node was requested in.
    frame: u64,
    /// Whether `stretch_auto_size_to_fill` changed the Taffy style since it was converted.
    stretched: bool,
}

#[derive(Default)]
struct LayoutCache {
    scopes: FxHashMap<PathHash, LayoutScope>,
    nodes: SecondaryMap<DefaultKey, CachedNode>,
    /// Nodes no element requested last frame, detached from the tree. A request that
    /// misses reuses one before allocating, and those still unused at the end of this
    /// frame are removed.
    free_nodes: Vec<NodeId>,
    frame: u64,
    /// Scale factor Taffy's cached device-pixel styles and measurements were computed at.
    scale_factor: Option<f32>,
}

fn node_key(id: NodeId) -> DefaultKey {
    KeyData::from_ffi(id.into()).into()
}

const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";

impl TaffyLayoutEngine {
    pub fn new() -> Self {
        let mut taffy = TaffyTree::new();
        taffy.disable_rounding();
        TaffyLayoutEngine {
            taffy,
            contexts: SecondaryMap::new(),
            cache: LayoutCache::default(),
            absolute_layout_bounds: FxHashMap::default(),
            absolute_outer_origins: FxHashMap::default(),
            computed_layouts: FxHashSet::default(),
            layout_bounds_scratch_space: Vec::new(),
        }
    }

    /// Drops every layout node kept from earlier frames, so the next frame builds its
    /// tree from scratch.
    pub(crate) fn clear_layout_cache(&mut self) {
        self.taffy.clear();
        self.contexts.clear();
        self.cache = LayoutCache::default();
        self.absolute_layout_bounds.clear();
        self.absolute_outer_origins.clear();
        self.computed_layouts.clear();
    }

    /// Clears the layout cache when the window's scale factor changes. Taffy stores styles
    /// and measured leaf sizes in device pixels, so none of the cached layouts apply at a
    /// different scale factor.
    pub(crate) fn clear_if_scale_factor_changed(&mut self, scale_factor: f32) {
        if self
            .cache
            .scale_factor
            .is_some_and(|previous| previous != scale_factor)
        {
            self.clear_layout_cache();
        }
        self.cache.scale_factor = Some(scale_factor);
    }

    #[cfg(test)]
    pub(crate) fn node_count(&self) -> usize {
        self.taffy.total_node_count()
    }

    /// Ends the frame: nodes that weren't requested during it are evicted.
    pub fn clear(&mut self) {
        self.cache
            .evict_unrequested(&mut self.taffy, &mut self.contexts);
        self.absolute_layout_bounds.clear();
        self.absolute_outer_origins.clear();
        self.computed_layouts.clear();
    }

    pub fn request_layout(
        &mut self,
        scope: PathHash,
        style: &Style,
        rem_size: Pixels,
        scale_factor: f32,
        children: &[LayoutId],
    ) -> LayoutId {
        let id = self.acquire_node(scope, style, rem_size, scale_factor, children);
        if self.contexts.remove(node_key(id)).is_some() {
            self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE);
        }
        id.into()
    }

    /// See [`Window::request_keyed_measure`].
    pub(crate) fn request_keyed_measure<K, F>(
        &mut self,
        scope: PathHash,
        style: &Style,
        rem_size: Pixels,
        scale_factor: f32,
        key: K,
        reuse: fn(&mut K, &mut K) -> bool,
        measure: F,
    ) -> LayoutId
    where
        K: 'static,
        F: FnMut(
                &K,
                Size<Option<Pixels>>,
                Size<AvailableSpace>,
                bool,
                &mut Window,
                &mut App,
            ) -> Size<Pixels>
            + 'static,
    {
        let id = self.acquire_node(scope, style, rem_size, scale_factor, &[]);
        let key_id = node_key(id);
        // A measure that measures the same as the node's previous one keeps the sizes
        // Taffy cached from it; any other must invalidate them. Updating a same-type
        // context in place avoids allocating and freeing a Box on steady-state frames.
        let reused = if let Some(previous) = self.contexts.get_mut(key_id) {
            match replace_measure_in_place(previous, key, reuse, measure) {
                Ok(reused) => reused,
                Err((key, measure)) => {
                    *previous = box_measure(key, measure);
                    false
                }
            }
        } else {
            self.contexts.insert(key_id, box_measure(key, measure));
            false
        };
        if !reused {
            self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE);
        }
        id.into()
    }

    fn acquire_node(
        &mut self,
        scope: PathHash,
        style: &Style,
        rem_size: Pixels,
        scale_factor: f32,
        children: &[LayoutId],
    ) -> NodeId {
        // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
        let children = LayoutId::to_taffy_slice(children);
        let taffy = &mut self.taffy;
        let cache = &mut self.cache;

        let frame = cache.frame;
        let scope = cache.scopes.entry(scope).or_default();
        let ordinal = scope.requested;
        scope.requested += 1;
        let id = if let Some(&id) = scope.nodes.get(ordinal) {
            let node = &mut cache.nodes[node_key(id)];
            debug_assert_ne!(
                node.frame, frame,
                "layout node requested twice in one frame"
            );
            if node.stretched || !node.style.matches(style, rem_size, scale_factor) {
                node.style = LayoutStyle::new(style, rem_size, scale_factor);
                node.stretched = false;
                let taffy_style = node.style.to_taffy();
                if taffy.style(id).expect(EXPECT_MESSAGE) != &taffy_style {
                    taffy.set_style(id, taffy_style).expect(EXPECT_MESSAGE);
                }
            }
            if !taffy.child_ids(id).eq(children.iter().copied()) {
                taffy.set_children(id, children).expect(EXPECT_MESSAGE);
            }
            id
        } else {
            let style = LayoutStyle::new(style, rem_size, scale_factor);
            let taffy_style = style.to_taffy();
            let id = if let Some(id) = cache.free_nodes.pop() {
                taffy.set_style(id, taffy_style).expect(EXPECT_MESSAGE);
                let node = &mut cache.nodes[node_key(id)];
                node.style = style;
                node.stretched = false;
                id
            } else {
                let id = taffy.new_leaf(taffy_style).expect(EXPECT_MESSAGE);
                let node = CachedNode {
                    style,
                    frame,
                    stretched: false,
                };
                cache.nodes.insert(node_key(id), node);
                id
            };
            if !children.is_empty() {
                // Unlike `new_with_children`, this detaches children from their previous parents.
                taffy.set_children(id, children).expect(EXPECT_MESSAGE);
            }
            scope.nodes.push(id);
            id
        };

        cache.nodes[node_key(id)].frame = frame;
        id
    }

    /// Treats any `auto` dimension of the given node's style as filling `size`.
    ///
    /// This is applied to window roots before layout so they behave like the
    /// root element on the web, which stretches to fill the initial containing
    /// block (the viewport) unless given an explicit size. Explicitly styled
    /// dimensions are preserved.
    pub fn stretch_auto_size_to_fill(
        &mut self,
        id: LayoutId,
        size: Size<Pixels>,
        scale_factor: f32,
    ) {
        let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
        let stretch_width = style.size.width.is_auto();
        let stretch_height = style.size.height.is_auto();
        if !stretch_width && !stretch_height {
            return;
        }
        // The next request for this node must restore its style, unless it is stretched
        // again; it may not be a root by then.
        if let Some(node) = self.cache.nodes.get_mut(node_key(id.0)) {
            node.stretched = true;
        }
        let mut style = style.clone();
        if stretch_width {
            style.size.width =
                taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
        }
        if stretch_height {
            style.size.height =
                taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
        }
        self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
    }

    // Used to understand performance
    #[allow(dead_code)]
    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
        let mut count = 0;

        for child in self.taffy.children(parent.0)? {
            // Count this child.
            count += 1;

            // Count all of this child's children.
            count += self.count_all_children(LayoutId(child))?
        }

        Ok(count)
    }

    // Used to understand performance
    #[allow(dead_code)]
    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
        println!(
            "{parent:?} at depth {depth} has {} children",
            self.taffy.child_count(parent.0)
        );

        let mut max_child_depth = 0;

        for child in self.taffy.children(parent.0)? {
            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
        }

        Ok(depth + 1 + max_child_depth)
    }

    // Used to understand performance
    #[allow(dead_code)]
    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
        let mut edges = Vec::new();

        for child in self.taffy.children(parent.0)? {
            edges.push((parent, LayoutId(child)));

            edges.extend(self.get_edges(LayoutId(child))?);
        }

        Ok(edges)
    }

    #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
    pub fn compute_layout(
        &mut self,
        id: LayoutId,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) {
        // Leaving this here until we have a better instrumentation approach.
        // println!("Laying out {} children", self.count_all_children(id)?);
        // println!("Max layout depth: {}", self.max_depth(0, id)?);

        // Output the edges (branches) of the tree in Mermaid format for visualization.
        // println!("Edges:");
        // for (a, b) in self.get_edges(id)? {
        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
        // }
        //

        // A node computed as a root may still be attached to a parent from an earlier
        // frame that no element requested in this one. Its layout must not be relative to
        // that parent.
        let cache = &self.cache;
        if let Some(parent) = self.taffy.parent(id.0)
            && cache
                .nodes
                .get(node_key(parent))
                .is_none_or(|node| node.frame != cache.frame)
        {
            self.taffy.remove_child(parent, id.0).expect(EXPECT_MESSAGE);
        }

        if !self.computed_layouts.insert(id) {
            let stack = &mut self.layout_bounds_scratch_space;
            stack.push(id);
            while let Some(id) = stack.pop() {
                self.absolute_layout_bounds.remove(&id);
                self.absolute_outer_origins.remove(&id);
                stack.extend(
                    self.taffy
                        .children(id.into())
                        .expect(EXPECT_MESSAGE)
                        .into_iter()
                        .map(LayoutId::from),
                );
            }
        }

        let scale_factor = window.scale_factor();

        let transform = |v: AvailableSpace| match v {
            AvailableSpace::Definite(pixels) => {
                AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
            }
            AvailableSpace::MinContent => AvailableSpace::MinContent,
            AvailableSpace::MaxContent => AvailableSpace::MaxContent,
        };
        let available_space = size(
            transform(available_space.width),
            transform(available_space.height),
        );

        let contexts = &mut self.contexts;
        self.taffy
            .compute_layout_with_measure(
                id.into(),
                available_space.into(),
                |input, id, _, style| {
                    let node_context = contexts.get_mut(node_key(id));
                    taffy::compute_leaf_layout(
                        input,
                        style,
                        |_, _| 0.0,
                        |known_dimensions, available_space| {
                            let Some(node_context) = node_context else {
                                return taffy::geometry::Size::default();
                            };

                            let known_dimensions = Size {
                                width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
                                height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
                            };

                            let available_space: Size<AvailableSpace> = available_space.into();
                            let untransform = |ev: AvailableSpace| match ev {
                                AvailableSpace::Definite(pixels) => {
                                    AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
                                }
                                AvailableSpace::MinContent => AvailableSpace::MinContent,
                                AvailableSpace::MaxContent => AvailableSpace::MaxContent,
                            };
                            let available_space = size(
                                untransform(available_space.width),
                                untransform(available_space.height),
                            );

                            let final_layout = input.run_mode == taffy::RunMode::PerformLayout;
                            let measured_size = node_context.measure(
                                known_dimensions,
                                available_space,
                                final_layout,
                                window,
                                cx,
                            );
                            snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
                        },
                    )
                },
            )
            .expect(EXPECT_MESSAGE);
    }

    // Pixel snapping
    //
    // Painting primitives at non-integer pixel coordinates produces blurry
    // output. Pixel snapping converts layout coordinates into integer
    // device-pixel coordinates so painted edges land exactly on physical
    // pixel boundaries.
    //
    // Non-integer coordinates can arise for several reasons, including:
    //   - flex distribution, percentages, centering, and text measurement
    //     can produce fractional element sizes and positions;
    //   - at fractional scale factors (for example 125% or 150%), integer
    //     logical-pixel values can map to non-integer device-pixel values.
    //
    // We pixel-snap by rounding in device-pixel space, after multiplying
    // by `scale_factor`, so that snapping targets physical pixels. Bounds
    // are divided by `scale_factor` before being returned to GPUI.
    //
    // Midpoints are rounded toward zero. This is a stylistic choice: a
    // 1-logical-pixel line at 150% scale should render as 1 dp rather than
    // 2 dp.
    //
    // Pixel snapping is done in two phases:
    //
    //  1. Pre-layout metric snapping. Before Taffy computes layout, all
    //     authored absolute lengths are rounded in `to_taffy`. This
    //     includes borders, padding, gaps, and explicit sizes.
    //     Custom-measured leaf nodes have their measured sizes rounded up
    //     to integer device-pixel lengths.
    //
    //  2. Post-layout edge snapping. After Taffy resolves the tree, layout
    //     relationships such as flex shares, grid tracks, percentages, and
    //     centering can produce new fractional edge positions. Boxes now
    //     have edges in absolute coordinates, and snapping must decide
    //     where those edges land on the device-pixel grid.
    //
    // Ideally, post-layout snapping would satisfy:
    //
    //  - Edge closure. Two raw layout edges at the same absolute position
    //    should snap to the same pixel column.
    //  - Translation stability. A component's internal geometry should not
    //    change when it moves to a new absolute position.
    //
    // These goals are in tension because rounding is not associative.
    // The simple local schemes make different tradeoffs:
    //
    //  - Absolute edge rounding gives each window coordinate one answer,
    //    so coincident edges always close globally. But a span's snapped
    //    length is `round(far) - round(near)`, which may change by 1 dp
    //    as its absolute origin moves.
    //
    //  - Parent-relative edge rounding rounds each child inside its
    //    parent's coordinate space. This guarantees translation stability,
    //    but a shared edge reached through different parents can
    //    accumulate different rounding, causing non-closure between
    //    cousins.
    //
    //  - Length rounding rounds each width, height, and thickness
    //    independently and then places boxes from those rounded lengths.
    //    Sizes stay stable under translation, but neighboring boxes derive
    //    their shared boundary from different sources, so closure is not
    //    guaranteed.
    //
    // We apply absolute edge rounding for each element's outer box in
    // post-layout rounding to preserve closure. Border and padding widths
    // are not touched by post-layout rounding; they keep their pre-layout
    // rounded value so that they remain stable under translation.
    //
    // This gives both closure and translation stability in the case that
    // all local metrics are integer device-pixel lengths. Pre-layout
    // rounding covers that in most cases. The exception is metrics
    // resolved by layout relationships, such as percentages. Outer box
    // edges will still close globally, and painted border widths are still
    // snapped independently, but the raw content-box origin can carry a
    // 1dp residual into descendants.

    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
            return layout;
        }

        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
        let layout_location = layout.location;
        let layout_size = layout.size;
        let parent = self.taffy.parent(id.0);

        let absolute_outer_origin = match parent {
            Some(parent_id) => {
                let parent_id = LayoutId::from(parent_id);
                self.layout_bounds(parent_id, scale_factor);
                let parent_origin = *self
                    .absolute_outer_origins
                    .get(&parent_id)
                    .expect("parent absolute outer origin should be cached");
                parent_origin + Point::from(layout_location)
            }
            None => Point::from(layout_location),
        };
        self.absolute_outer_origins
            .insert(id, absolute_outer_origin);

        let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
        let snapped_bounds = Bounds::from_corners(
            absolute_outer_origin.map(round_half_toward_zero),
            absolute_far.map(round_half_toward_zero),
        );

        let bounds = (snapped_bounds / scale_factor).map(Pixels);
        self.absolute_layout_bounds.insert(id, bounds);
        bounds
    }
}

impl LayoutCache {
    fn evict_unrequested(
        &mut self,
        taffy: &mut TaffyTree,
        contexts: &mut SecondaryMap<DefaultKey, NodeContext>,
    ) {
        for id in self.free_nodes.drain(..) {
            self.nodes.remove(node_key(id));
            taffy.remove(id).expect(EXPECT_MESSAGE);
        }

        let free_nodes = &mut self.free_nodes;
        self.scopes.retain(|_, scope| {
            let requested = std::mem::take(&mut scope.requested);
            free_nodes.extend(scope.nodes.drain(requested..));
            requested > 0
        });

        // Every node an element requested this frame had its children set to nodes also
        // requested this frame, so an unrequested node's parent is unrequested too (or it
        // has none). Clearing their children therefore detaches all of them without
        // touching the live tree. Measure functions can hold on to anything, so they're
        // dropped now rather than when the node is reused or removed.
        for &id in &self.free_nodes {
            contexts.remove(node_key(id));
            if taffy.child_count(id) > 0 {
                taffy.set_children(id, &[]).expect(EXPECT_MESSAGE);
            }
        }
        debug_assert!(self.free_nodes.iter().all(|&id| taffy.parent(id).is_none()));
        self.frame += 1;
    }
}

/// A unique identifier for a layout node, generated when requesting a layout from Taffy
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[repr(transparent)]
pub struct LayoutId(NodeId);

impl LayoutId {
    fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
    }
}

impl std::hash::Hash for LayoutId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        u64::from(self.0).hash(state);
    }
}

impl From<NodeId> for LayoutId {
    fn from(node_id: NodeId) -> Self {
        Self(node_id)
    }
}

impl From<LayoutId> for NodeId {
    fn from(layout_id: LayoutId) -> NodeId {
        layout_id.0
    }
}

fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
    size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
}

fn border_widths_to_taffy(
    widths: &Edges<AbsoluteLength>,
    rem_size: Pixels,
    scale_factor: f32,
) -> TaffyRect<taffy::style::LengthPercentage> {
    let snap = |w: &AbsoluteLength| {
        taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
            w.to_pixels(rem_size).0,
            scale_factor,
        ))
    };
    TaffyRect {
        top: snap(&widths.top),
        right: snap(&widths.right),
        bottom: snap(&widths.bottom),
        left: snap(&widths.left),
    }
}

trait ToTaffy<Output> {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
}

// Conversion reads the copied fields, not `Style`, so a field can't affect layout
// without also being compared to decide whether to convert again.
macro_rules! layout_style {
    ($($field:ident: $field_type:ty),* $(,)?) => {
        /// The fields of a [`Style`] that affect layout, and what their lengths are
        /// resolved against.
        #[derive(Clone, Debug)]
        struct LayoutStyle {
            rem_size: Pixels,
            scale_factor: f32,
            $($field: $field_type,)*
        }

        impl LayoutStyle {
            fn new(style: &Style, rem_size: Pixels, scale_factor: f32) -> Self {
                Self {
                    rem_size,
                    scale_factor,
                    $($field: Clone::clone(&style.$field),)*
                }
            }

            fn matches(&self, style: &Style, rem_size: Pixels, scale_factor: f32) -> bool {
                self.rem_size == rem_size
                    && self.scale_factor == scale_factor
                    $(&& self.$field == style.$field)*
            }
        }
    };
}

layout_style! {
    display: crate::Display,
    overflow: Point<crate::Overflow>,
    scrollbar_width: AbsoluteLength,
    position: crate::Position,
    inset: Edges<Length>,
    size: Size<Length>,
    min_size: Size<Length>,
    max_size: Size<Length>,
    aspect_ratio: Option<f32>,
    margin: Edges<Length>,
    padding: Edges<DefiniteLength>,
    border_widths: Edges<AbsoluteLength>,
    align_items: Option<crate::AlignItems>,
    align_self: Option<crate::AlignSelf>,
    align_content: Option<crate::AlignContent>,
    justify_content: Option<crate::JustifyContent>,
    gap: Size<DefiniteLength>,
    flex_direction: crate::FlexDirection,
    flex_wrap: crate::FlexWrap,
    flex_basis: Length,
    flex_grow: f32,
    flex_shrink: f32,
    grid_rows: Option<GridTemplate>,
    grid_cols: Option<GridTemplate>,
    grid_location: Option<crate::GridLocation>,
}

impl LayoutStyle {
    fn to_taffy(&self) -> taffy::style::Style {
        use taffy::style_helpers::{fr, length, minmax, repeat};

        let rem_size = self.rem_size;
        let scale_factor = self.scale_factor;

        fn to_grid_line(
            placement: &Range<crate::GridPlacement>,
        ) -> taffy::Line<taffy::GridPlacement> {
            taffy::Line {
                start: placement.start.into(),
                end: placement.end.into(),
            }
        }

        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
            unit: &Option<GridTemplate>,
        ) -> Vec<taffy::GridTemplateComponent<T>> {
            unit.map(|template| {
                match template.min_size {
                    // grid-template-*: repeat(<number>, minmax(0, 1fr));
                    crate::GridTemplateMinSize::Zero => {
                        vec![repeat(
                            template.repeat,
                            vec![minmax(length(0.0_f32), fr(1.0_f32))],
                        )]
                    }
                    // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
                    crate::GridTemplateMinSize::MinContent => {
                        vec![repeat(
                            template.repeat,
                            vec![minmax(min_content(), fr(1.0_f32))],
                        )]
                    }
                    // grid-template-*: repeat(<number>, minmax(0, max-content))
                    crate::GridTemplateMinSize::MaxContent => {
                        vec![repeat(
                            template.repeat,
                            vec![minmax(length(0.0_f32), max_content())],
                        )]
                    }
                }
            })
            .unwrap_or_default()
        }

        taffy::style::Style {
            display: self.display.into(),
            overflow: self.overflow.into(),
            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
            position: self.position.into(),
            inset: self.inset.to_taffy(rem_size, scale_factor),
            size: self.size.to_taffy(rem_size, scale_factor),
            min_size: self.min_size.to_taffy(rem_size, scale_factor),
            max_size: self.max_size.to_taffy(rem_size, scale_factor),
            aspect_ratio: self.aspect_ratio,
            margin: self.margin.to_taffy(rem_size, scale_factor),
            padding: self.padding.to_taffy(rem_size, scale_factor),
            border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
            align_items: self.align_items.map(Into::into).unwrap_or_default(),
            align_self: self.align_self.map(|x| x.into()),
            align_content: self.align_content.map(Into::into).unwrap_or_default(),
            justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
            gap: self.gap.to_taffy(rem_size, scale_factor),
            flex_direction: self.flex_direction.into(),
            flex_wrap: self.flex_wrap.into(),
            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
            flex_grow: self.flex_grow,
            flex_shrink: self.flex_shrink,
            grid_template_rows: to_grid_repeat(&self.grid_rows),
            grid_template_columns: to_grid_repeat(&self.grid_cols),
            grid_row: self
                .grid_location
                .as_ref()
                .map(|location| to_grid_line(&location.row))
                .unwrap_or_default(),
            grid_column: self
                .grid_location
                .as_ref()
                .map(|location| to_grid_line(&location.column))
                .unwrap_or_default(),
            ..Default::default()
        }
    }
}

impl ToTaffy<f32> for AbsoluteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
        round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
    }
}

impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
    fn to_taffy(
        &self,
        rem_size: Pixels,
        scale_factor: f32,
    ) -> taffy::prelude::LengthPercentageAuto {
        match self {
            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
        }
    }
}

impl ToTaffy<taffy::style::Dimension> for Length {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
        match self {
            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
            Length::Auto => taffy::prelude::Dimension::auto(),
        }
    }
}

impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
        match self {
            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
            DefiniteLength::Fraction(fraction) => {
                taffy::style::LengthPercentage::percent(*fraction)
            }
        }
    }
}

impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
        match self {
            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
            DefiniteLength::Fraction(fraction) => {
                taffy::style::LengthPercentageAuto::percent(*fraction)
            }
        }
    }
}

impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
        match self {
            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
        }
    }
}

impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
        taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
    }
}

impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
        taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
    }
}

impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
        taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
    }
}

impl<T, T2> From<TaffyPoint<T>> for Point<T2>
where
    T: Into<T2>,
    T2: Clone + Debug + Default + PartialEq,
{
    fn from(point: TaffyPoint<T>) -> Point<T2> {
        Point {
            x: point.x.into(),
            y: point.y.into(),
        }
    }
}

impl<T, T2> From<Point<T>> for TaffyPoint<T2>
where
    T: Into<T2> + Clone + Debug + Default + PartialEq,
{
    fn from(val: Point<T>) -> Self {
        TaffyPoint {
            x: val.x.into(),
            y: val.y.into(),
        }
    }
}

impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
where
    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
{
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
        TaffySize {
            width: self.width.to_taffy(rem_size, scale_factor),
            height: self.height.to_taffy(rem_size, scale_factor),
        }
    }
}

impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
where
    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
{
    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
        TaffyRect {
            top: self.top.to_taffy(rem_size, scale_factor),
            right: self.right.to_taffy(rem_size, scale_factor),
            bottom: self.bottom.to_taffy(rem_size, scale_factor),
            left: self.left.to_taffy(rem_size, scale_factor),
        }
    }
}

impl<T, U> From<TaffySize<T>> for Size<U>
where
    T: Into<U>,
    U: Clone + Debug + Default + PartialEq,
{
    fn from(taffy_size: TaffySize<T>) -> Self {
        Size {
            width: taffy_size.width.into(),
            height: taffy_size.height.into(),
        }
    }
}

impl<T, U> From<Size<T>> for TaffySize<U>
where
    T: Into<U> + Clone + Debug + Default + PartialEq,
{
    fn from(size: Size<T>) -> Self {
        TaffySize {
            width: size.width.into(),
            height: size.height.into(),
        }
    }
}

/// The space available for an element to be laid out in
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
pub enum AvailableSpace {
    /// The amount of space available is the specified number of pixels
    Definite(Pixels),
    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
    #[default]
    MinContent,
    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
    MaxContent,
}

impl AvailableSpace {
    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
    ///
    /// This function is useful when you want to create a `Size` with the minimum content constraints
    /// for both dimensions.
    ///
    /// # Examples
    ///
    /// ```
    /// use gpui::AvailableSpace;
    /// let min_content_size = AvailableSpace::min_size();
    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
    /// ```
    pub const fn min_size() -> Size<Self> {
        Size {
            width: Self::MinContent,
            height: Self::MinContent,
        }
    }
}

impl From<AvailableSpace> for TaffyAvailableSpace {
    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
        match space {
            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
        }
    }
}

impl From<TaffyAvailableSpace> for AvailableSpace {
    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
        match space {
            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
        }
    }
}

impl From<Pixels> for AvailableSpace {
    fn from(pixels: Pixels) -> Self {
        AvailableSpace::Definite(pixels)
    }
}

impl From<Size<Pixels>> for Size<AvailableSpace> {
    fn from(size: Size<Pixels>) -> Self {
        Size {
            width: AvailableSpace::Definite(size.width),
            height: AvailableSpace::Definite(size.height),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        AnyElement, AnyWindowHandle, AppContext as _, Context, Element, ElementId, GlobalElementId,
        InspectorElementId, InteractiveElement as _, IntoElement, ParentElement as _, Render,
        Styled as _, TestAppContext, div, px,
        randomized_element_tree::{RandomizedElementTree, RandomizedElementTreeConfig},
        rems,
    };
    use std::{cell::Cell, rc::Rc};

    type Frame = Box<dyn Fn(&mut Window) -> AnyElement>;

    struct FrameView {
        frame: Rc<Cell<usize>>,
        frames: Rc<Vec<Frame>>,
    }

    impl Render for FrameView {
        fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            (self.frames[self.frame.get()])(window)
        }
    }

    /// Draws each frame in a window that keeps its layout nodes and in one that rebuilds
    /// them, checking that every element with a debug selector has the same bounds in
    /// both.
    fn assert_frames_match_uncached(cx: &mut TestAppContext, frames: Vec<Frame>) {
        assert_frames_match_uncached_with(cx, frames, |_| {}, |_| ());
    }

    /// Like [`assert_frames_match_uncached`], running `before_cached` before and
    /// `after_cached` after each cached frame draw and returning the observations.
    fn assert_frames_match_uncached_with<T>(
        cx: &mut TestAppContext,
        frames: Vec<Frame>,
        mut before_cached: impl FnMut(&Window),
        mut after_cached: impl FnMut(&Window) -> T,
    ) -> Vec<T> {
        let frames = Rc::new(frames);
        let frame = Rc::new(Cell::new(0));
        let windows = [false, true].map(|rebuild| {
            let frames = frames.clone();
            let frame = frame.clone();
            let window = cx.open_window(size(px(800.), px(600.)), move |_, _| FrameView {
                frame,
                frames,
            });
            (AnyWindowHandle::from(window), rebuild)
        });
        let mut observations = Vec::new();
        for index in 0..frames.len() {
            frame.set(index);
            let [cached, uncached] = windows.map(|(window, rebuild)| {
                cx.update_window(window, |_, window, cx| {
                    if rebuild {
                        window.clear_layout_cache();
                    } else {
                        before_cached(window);
                    }
                    window.refresh();
                    window.draw(cx).clear(cx);
                    let observation = (!rebuild).then(|| after_cached(window));
                    let mut bounds = window
                        .rendered_frame
                        .debug_bounds
                        .iter()
                        .map(|(selector, bounds)| (selector.clone(), *bounds))
                        .collect::<Vec<_>>();
                    bounds.sort_by(|a, b| a.0.cmp(&b.0));
                    (bounds, observation)
                })
                .expect("window should remain open")
            });
            assert!(
                !uncached.0.is_empty(),
                "frame {index} has no debug selectors"
            );
            assert_eq!(cached.0, uncached.0, "frame {index}");
            observations.push(cached.1.expect("cached window observation"));
        }
        observations
    }

    fn frame(render: impl Fn(&mut Window) -> AnyElement + 'static) -> Frame {
        Box::new(render)
    }

    /// A leaf whose size comes from its measure function, which captures it and is keyed
    /// by it.
    struct MeasuredLeaf {
        size: Size<Pixels>,
        measurements: Option<Rc<Cell<usize>>>,
    }

    impl MeasuredLeaf {
        fn new(size: Size<Pixels>) -> Self {
            Self {
                size,
                measurements: None,
            }
        }

        fn with_counter(size: Size<Pixels>, measurements: Rc<Cell<usize>>) -> Self {
            Self {
                size,
                measurements: Some(measurements),
            }
        }
    }

    impl Element for MeasuredLeaf {
        type RequestLayoutState = ();
        type PrepaintState = ();

        fn id(&self) -> Option<ElementId> {
            None
        }

        fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
            None
        }

        fn request_layout(
            &mut self,
            _: Option<&GlobalElementId>,
            _: Option<&InspectorElementId>,
            window: &mut Window,
            _: &mut App,
        ) -> (LayoutId, ()) {
            let measured = self.size;
            let measurements = self.measurements.clone();
            let layout_id = window.request_keyed_measured_layout(
                Style::default(),
                measured,
                move |_, _, _, _| {
                    if let Some(measurements) = &measurements {
                        measurements.set(measurements.get() + 1);
                    }
                    measured
                },
            );
            (layout_id, ())
        }

        fn prepaint(
            &mut self,
            _: Option<&GlobalElementId>,
            _: Option<&InspectorElementId>,
            _: Bounds<Pixels>,
            _: &mut (),
            _: &mut Window,
            _: &mut App,
        ) {
        }

        fn paint(
            &mut self,
            _: Option<&GlobalElementId>,
            _: Option<&InspectorElementId>,
            _: Bounds<Pixels>,
            _: &mut (),
            _: &mut (),
            _: &mut Window,
            _: &mut App,
        ) {
        }
    }

    #[crate::test]
    fn stretched_root_style_is_restored_when_its_node_is_reused(cx: &mut TestAppContext) {
        // Elements without IDs are matched by request order, and children request first,
        // so the second frame's child reuses the first frame's root node.
        assert_frames_match_uncached(
            cx,
            vec![
                frame(|_| div().debug_selector(|| "root".into()).into_any_element()),
                frame(|_| {
                    div()
                        .size(px(100.))
                        .child(div().debug_selector(|| "child".into()))
                        .into_any_element()
                }),
            ],
        );
    }

    #[crate::test]
    fn root_is_detached_from_a_parent_no_longer_requested(cx: &mut TestAppContext) {
        // The second frame's root reuses the first frame's innermost node, whose parent
        // sat inside padding.
        assert_frames_match_uncached(
            cx,
            vec![
                frame(|_| {
                    div()
                        .p(px(10.))
                        .child(
                            div()
                                .p(px(7.))
                                .child(div().size(px(5.)).debug_selector(|| "leaf".into())),
                        )
                        .into_any_element()
                }),
                frame(|_| {
                    div()
                        .size(px(50.))
                        .debug_selector(|| "root".into())
                        .into_any_element()
                }),
            ],
        );
    }

    #[crate::test]
    fn hidden_element_is_laid_out_again_when_shown(cx: &mut TestAppContext) {
        let with_child_shown = |shown: bool| {
            frame(move |_| {
                let mut child = div().size(px(20.)).debug_selector(|| "child".into());
                if !shown {
                    child.style().display = Some(crate::Display::None);
                }
                div()
                    .flex()
                    .child(div().debug_selector(|| "wrapper".into()).child(child))
                    .into_any_element()
            })
        };
        assert_frames_match_uncached(
            cx,
            vec![
                with_child_shown(false),
                with_child_shown(false),
                with_child_shown(true),
                with_child_shown(false),
                with_child_shown(true),
            ],
        );
    }

    #[crate::test]
    fn measured_leaf_is_measured_again_only_when_its_key_changes(cx: &mut TestAppContext) {
        let counter = Rc::new(Cell::new(0));
        let measured = |width: f32, height: f32| {
            let counter = counter.clone();
            frame(move |_| {
                div()
                    .flex()
                    .child(div().debug_selector(|| "wrapper".into()).child(
                        MeasuredLeaf::with_counter(size(px(width), px(height)), counter.clone()),
                    ))
                    .into_any_element()
            })
        };
        let measurements = assert_frames_match_uncached_with(
            cx,
            vec![
                measured(10., 10.),
                measured(10., 10.),
                measured(30., 20.),
                measured(30., 20.),
                measured(5., 40.),
            ],
            |_| counter.set(0),
            |_| counter.get(),
        );
        // Opening the window draws the first frame, so drawing it again measures nothing.
        let measured = measurements
            .iter()
            .map(|count| *count > 0)
            .collect::<Vec<_>>();
        assert_eq!(
            measured,
            [false, false, true, false, true],
            "measurements per frame: {measurements:?}"
        );
    }

    #[crate::test]
    fn rem_size_changes_resolve_lengths_again(cx: &mut TestAppContext) {
        let with_rem_size = |rem_size: f32| {
            frame(move |window| {
                window.set_rem_size(px(rem_size));
                div()
                    .flex()
                    .child(
                        div()
                            .w(rems(2.5))
                            .h(rems(1.25))
                            .debug_selector(|| "sized".into()),
                    )
                    .into_any_element()
            })
        };
        assert_frames_match_uncached(
            cx,
            vec![with_rem_size(16.), with_rem_size(13.), with_rem_size(13.)],
        );
    }

    #[crate::test]
    fn element_ids_reused_by_different_elements(cx: &mut TestAppContext) {
        // One ID names a measured leaf, then nothing, then a container whose children
        // have no IDs, then a measured leaf again.
        let leaf = || {
            frame(|_| {
                div()
                    .flex()
                    .child(
                        div()
                            .id("reused")
                            .debug_selector(|| "reused".into())
                            .child(MeasuredLeaf::new(size(px(12.), px(9.)))),
                    )
                    .into_any_element()
            })
        };
        assert_frames_match_uncached(
            cx,
            vec![
                leaf(),
                frame(|_| {
                    div()
                        .flex()
                        .child(div().size(px(3.)).debug_selector(|| "other".into()))
                        .into_any_element()
                }),
                frame(|_| {
                    div()
                        .flex()
                        .child(
                            div()
                                .id("reused")
                                .flex_col()
                                .p(px(4.))
                                .debug_selector(|| "reused".into())
                                .child(div().size(px(20.)))
                                .child(div().size(px(8.)).debug_selector(|| "inner".into())),
                        )
                        .into_any_element()
                }),
                leaf(),
            ],
        );
    }

    #[crate::test]
    fn text_is_measured_again_only_when_it_changes(cx: &mut TestAppContext) {
        let text = |width: f32, text: &'static str, font_size: f32| {
            frame(move |_| {
                div()
                    .flex()
                    .child(
                        div()
                            .w(px(width))
                            .text_size(px(font_size))
                            .debug_selector(|| "wrapper".into())
                            .child(text),
                    )
                    .child(div().size(px(10.)).debug_selector(|| "sibling".into()))
                    .into_any_element()
            })
        };
        let short = "Some text";
        let same_length = "Same text";
        let long = "Some longer text that wraps in narrow parents";
        // Opening the window draws the first frame, so drawing it again measures nothing.
        let frames = [
            (text(200., short, 14.), false),
            (text(200., short, 14.), false),
            (text(200., same_length, 14.), true),
            (text(200., long, 14.), true),
            (text(200., long, 14.), false),
            (text(60., long, 14.), true),
            (text(60., long, 18.), true),
            (text(60., long, 18.), false),
            (text(200., long, 14.), true),
        ];
        let expected = frames
            .iter()
            .map(|(_, measured)| *measured)
            .collect::<Vec<_>>();
        let measurements = assert_frames_match_uncached_with(
            cx,
            frames.into_iter().map(|(frame, _)| frame).collect(),
            |_| {},
            |window| window.text_system().last_frame_wrapped_line_count(),
        );
        let measured = measurements
            .iter()
            .map(|count| *count > 0)
            .collect::<Vec<_>>();
        assert_eq!(
            measured, expected,
            "text measurements per frame: {measurements:?}"
        );
    }

    #[crate::test]
    fn measured_leaf_updates_when_scale_factor_changes(cx: &mut TestAppContext) {
        let at_scale = |scale_factor: f32| {
            frame(move |window| {
                window.set_scale_factor(scale_factor);
                div()
                    .flex()
                    .child(
                        div()
                            .debug_selector(|| "wrapper".into())
                            .child(MeasuredLeaf::new(size(px(100.), px(40.)))),
                    )
                    .into_any_element()
            })
        };
        assert_frames_match_uncached(cx, vec![at_scale(1.0), at_scale(2.0), at_scale(1.0)]);
    }

    #[crate::test]
    fn text_is_measured_again_when_fonts_are_added(cx: &mut TestAppContext) {
        let with_text = || {
            frame(|_| {
                div()
                    .flex()
                    .child(
                        div()
                            .w(px(200.))
                            .debug_selector(|| "wrapper".into())
                            .child("Some text"),
                    )
                    .into_any_element()
            })
        };
        let mut frame_index = 0;
        let measurements = assert_frames_match_uncached_with(
            cx,
            vec![with_text(), with_text(), with_text()],
            |window| {
                if frame_index == 1 {
                    window
                        .text_system()
                        .add_fonts(Vec::new())
                        .expect("noop text system accepts empty font list");
                }
                frame_index += 1;
            },
            |window| window.text_system().last_frame_wrapped_line_count(),
        );
        let measured = measurements
            .iter()
            .map(|count| *count > 0)
            .collect::<Vec<_>>();
        assert_eq!(
            measured,
            [false, true, false],
            "text measurements per frame: {measurements:?}"
        );
    }

    #[crate::test]
    fn evicted_nodes_do_not_accumulate_when_ids_change_every_frame(cx: &mut TestAppContext) {
        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
            RandomizedElementTree::new_with_config(RandomizedElementTreeConfig::new(3, 64), cx)
        });
        let root = window.root(cx).expect("window should have a root");
        let mut node_counts = Vec::new();
        for _ in 0..20 {
            root.update(cx, |tree, cx| tree.churn_element_ids(cx));
            let node_count = cx
                .update_window(window.into(), |_, window, cx| {
                    window.draw(cx).clear(cx);
                    window.layout_node_count()
                })
                .expect("window should remain open");
            node_counts.push(node_count);
        }
        // Each frame's evicted nodes are kept for the next frame to reuse, and every node
        // a frame doesn't reuse is removed, so the tree stays the size of one frame.
        assert!(
            node_counts.windows(2).all(|pair| pair[0] == pair[1]),
            "{node_counts:?}"
        );
    }

    #[test]
    fn border_widths_to_taffy_use_stroke_snapping() {
        let border_widths = Edges {
            top: Pixels(0.0).into(),
            right: Pixels(0.4).into(),
            bottom: Pixels(0.5).into(),
            left: Pixels(1.6).into(),
        };
        let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);

        assert_eq!(
            taffy_border.top,
            taffy::style::LengthPercentage::length(0.0)
        );
        assert_eq!(
            taffy_border.right,
            taffy::style::LengthPercentage::length(1.0)
        );
        assert_eq!(
            taffy_border.bottom,
            taffy::style::LengthPercentage::length(1.0)
        );
        assert_eq!(
            taffy_border.left,
            taffy::style::LengthPercentage::length(2.0)
        );
    }
}