skathi-gpui 0.5.1

gpui, Zed's GPU-accelerated UI framework, as Skathi renders with it
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
use super::*;
use crate::{
    AnyElement, Bounds, Context, Element, ElementId, InspectorElementId, IntoElement, Render,
    SharedString, StyledText, TestApp, TextLayout, div, prelude::*, px,
};
use std::cell::Cell;

fn scope(name: &'static str) -> GlobalElementId {
    GlobalElementId::new(&[ElementId::Name(name.into())])
}

fn fixed(width: f32, height: f32) -> taffy::style::Style {
    let mut style = taffy::style::Style::default();
    style.size.width = taffy::style::Dimension::length(width);
    style.size.height = taffy::style::Dimension::length(height);
    style
}

fn compute(engine: &mut TaffyLayoutEngine, id: LayoutId) -> f32 {
    engine
        .taffy
        .compute_layout(
            id.into(),
            taffy::geometry::Size {
                width: taffy::style::AvailableSpace::MaxContent,
                height: taffy::style::AvailableSpace::MaxContent,
            },
        )
        .unwrap();
    engine.taffy.layout(id.into()).unwrap().size.width
}

#[test]
fn transient_removal_dirties_auto_parent_before_child_equality_can_hide_it() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let child = request_layout(&mut engine, None, fixed(45., 20.), &[]);
    let root = request_layout(
        &mut engine,
        Some(scope("root")),
        Default::default(),
        &[child],
    );
    assert_eq!(compute(&mut engine, root), 45.);
    engine.clear();
    assert!(engine.taffy.dirty(root.into()).unwrap());
    let next_root = request_layout(&mut engine, Some(scope("root")), Default::default(), &[]);
    assert_eq!(next_root, root);
    assert_eq!(compute(&mut engine, next_root), 0.);
    let replacement = request_layout(&mut engine, None, fixed(10., 20.), &[]);
    assert_ne!(
        child, replacement,
        "removed Taffy IDs must retain their generation"
    );
}

/// A retained node whose parent was not requested this frame is a root now:
/// the parent is only freed when the frame ends, and until then it would
/// place the node at its own, last frame's, origin.
#[test]
fn a_child_that_became_a_root_forgets_the_parent_that_was_not_requested() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let spacer = request_layout(&mut engine, Some(scope("spacer")), fixed(40., 10.), &[]);
    let child = request_layout(&mut engine, Some(scope("child")), fixed(30., 10.), &[]);
    let parent = request_layout(&mut engine, Some(scope("parent")), Default::default(), &[child]);
    let root = request_layout(
        &mut engine,
        Some(scope("root")),
        Default::default(),
        &[spacer, parent],
    );
    assert_eq!(compute(&mut engine, root), 70.);
    assert_eq!(engine.layout_bounds(child, 1.).origin.x, px(40.));
    engine.clear();

    let child_again = request_layout(&mut engine, Some(scope("child")), fixed(30., 10.), &[]);
    assert_eq!(child_again, child);
    engine.detach_root(child_again);
    assert_eq!(compute(&mut engine, child_again), 30.);
    assert_eq!(engine.layout_bounds(child_again, 1.).origin.x, px(0.));
}

#[test]
fn reused_nodes_reconcile_full_style_child_order_and_reparenting() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let first = request_layout(&mut engine, Some(scope("first")), fixed(30., 10.), &[]);
    let second = request_layout(&mut engine, Some(scope("second")), fixed(50., 10.), &[]);
    let a = request_layout(
        &mut engine,
        Some(scope("a")),
        Default::default(),
        &[first, second],
    );
    let b = request_layout(&mut engine, Some(scope("b")), Default::default(), &[]);
    assert_eq!(compute(&mut engine, a), 80.);
    assert_eq!(compute(&mut engine, b), 0.);
    engine.clear();

    let first_again = request_layout(&mut engine, Some(scope("first")), fixed(35., 10.), &[]);
    let second_again = request_layout(&mut engine, Some(scope("second")), fixed(50., 10.), &[]);
    assert_eq!(first_again, first);
    assert_eq!(second_again, second);
    // Reparent before requesting a: set_children must detach from its real old parent.
    let b_again = request_layout(
        &mut engine,
        Some(scope("b")),
        Default::default(),
        &[first_again],
    );
    let a_again = request_layout(
        &mut engine,
        Some(scope("a")),
        Default::default(),
        &[second_again],
    );
    assert_eq!(b_again, b);
    assert_eq!(a_again, a);
    assert_eq!(compute(&mut engine, a_again), 50.);
    assert_eq!(compute(&mut engine, b_again), 35.);
    assert_eq!(engine.taffy.parent(first.into()), Some(b.into()));
    engine.clear();

    let first = request_layout(&mut engine, Some(scope("first")), fixed(35., 10.), &[]);
    let second = request_layout(&mut engine, Some(scope("second")), fixed(50., 10.), &[]);
    let a = request_layout(
        &mut engine,
        Some(scope("a")),
        Default::default(),
        &[second, first],
    );
    assert_eq!(compute(&mut engine, a), 85.);
    assert_eq!(engine.taffy.layout(first.into()).unwrap().location.x, 50.);
    engine.clear();
    assert_eq!(
        engine.taffy.total_node_count(),
        3,
        "unclaimed old parent must be collected"
    );
}

#[test]
fn former_auto_root_loses_viewport_stretch_when_attached_as_child() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let root = request_layout(
        &mut engine,
        Some(scope("former-root")),
        Default::default(),
        &[],
    );
    stretch(
        &mut engine,
        root,
        Size {
            width: px(300.),
            height: px(100.),
        },
        1.,
    );
    assert_eq!(compute(&mut engine, root), 300.);
    engine.clear();
    let child = request_layout(
        &mut engine,
        Some(scope("former-root")),
        Default::default(),
        &[],
    );
    let parent = request_layout(
        &mut engine,
        Some(scope("new-root")),
        Default::default(),
        &[child],
    );
    assert_eq!(compute(&mut engine, parent), 0.);
}

#[derive(Clone)]
struct Phase {
    text: &'static str,
    width: f32,
    font: f32,
    generation: u32,
    ellipsis: bool,
    rows_a: Vec<(u32, f32)>,
    rows_b: Vec<(u32, f32)>,
    scale: f32,
    rem: f32,
}

impl Default for Phase {
    fn default() -> Self {
        Self {
            text: "alpha beta gamma delta epsilon zeta eta theta",
            width: 100.,
            font: 14.,
            generation: 0,
            ellipsis: false,
            rows_a: vec![(1, 30.), (2, 50.)],
            rows_b: vec![],
            scale: 2.,
            rem: 16.,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
struct Snapshot {
    bounds: Vec<(u32, Bounds<Pixels>)>,
    text: String,
    wrapped: String,
    text_bounds: Bounds<Pixels>,
    measured: (u32, Size<Pixels>, Bounds<Pixels>),
}

struct Capture {
    id: u32,
    inner: AnyElement,
    bounds: Rc<RefCell<Vec<(u32, Bounds<Pixels>)>>>,
}

impl Element for Capture {
    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,
        cx: &mut App,
    ) -> (LayoutId, ()) {
        (self.inner.request_layout(window, cx), ())
    }
    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        self.bounds.borrow_mut().push((self.id, bounds));
        self.inner.prepaint(window, cx);
    }
    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut (),
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        self.inner.paint(window, cx);
    }
}

type MeasuredSnapshot = Rc<Cell<Option<(u32, Size<Pixels>, Bounds<Pixels>)>>>;

struct FreshMeasured {
    generation: u32,
    fresh: Rc<Cell<Option<(u32, Size<Pixels>)>>>,
    painted: MeasuredSnapshot,
}

impl Element for FreshMeasured {
    type RequestLayoutState = ();
    type PrepaintState = ();
    fn id(&self) -> Option<ElementId> {
        Some("fresh-measured".into())
    }
    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 fresh = self.fresh.clone();
        let generation = self.generation;
        let layout = window.request_measured_layout(Default::default(), move |_, _, _, _| {
            let size = Size {
                width: px(24.),
                height: px(12.),
            };
            fresh.set(Some((generation, size)));
            size
        });
        (layout, ())
    }
    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut (),
        _: &mut Window,
        _: &mut App,
    ) {
    }
    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut (),
        _: &mut (),
        _: &mut Window,
        _: &mut App,
    ) {
        let (generation, size) = self
            .fresh
            .get()
            .expect("the CURRENT element's measurement closure must run before paint");
        assert_eq!(generation, self.generation);
        self.painted.set(Some((generation, size, bounds)));
    }
}

struct Fixture {
    phase: Phase,
    layout: Option<TextLayout>,
    bounds: Rc<RefCell<Vec<(u32, Bounds<Pixels>)>>>,
    measured: MeasuredSnapshot,
}

impl Fixture {
    fn snapshot(&self) -> Snapshot {
        let layout = self.layout.as_ref().unwrap();
        let mut bounds = self.bounds.borrow().clone();
        bounds.sort_by_key(|(id, _)| *id);
        Snapshot {
            bounds,
            text: layout.text(),
            wrapped: layout.wrapped_text(),
            text_bounds: layout.bounds(),
            measured: self.measured.get().unwrap(),
        }
    }
}

impl Render for Fixture {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.bounds.borrow_mut().clear();
        self.measured.set(None);
        let text = StyledText::new(SharedString::from(self.phase.text));
        self.layout = Some(text.layout().clone());
        let capture = |id, inner| Capture {
            id,
            inner,
            bounds: self.bounds.clone(),
        };
        let row = |id, rows: &[(u32, f32)]| {
            capture(
                id,
                div()
                    .id(id as usize)
                    .flex()
                    .items_start()
                    .children(rows.iter().map(|(key, width)| {
                        capture(
                            *key,
                            div()
                                .id(*key as usize)
                                .w(px(*width))
                                .h(px(10.))
                                .into_any_element(),
                        )
                    }))
                    .into_any_element(),
            )
        };
        div()
            .id("fixture")
            .size_full()
            .flex()
            .flex_col()
            .items_start()
            .child(capture(
                100,
                div()
                    .id("text-box")
                    .w(px(self.phase.width))
                    .text_size(px(self.phase.font))
                    .when(self.phase.ellipsis, |element| element.truncate())
                    .child(text)
                    .into_any_element(),
            ))
            .child(row(200, &self.phase.rows_a))
            .child(row(300, &self.phase.rows_b))
            .child(FreshMeasured {
                generation: self.phase.generation,
                fresh: Rc::default(),
                painted: self.measured.clone(),
            })
    }
}

fn draw_phases(retained: bool, phases: &[Phase]) -> (Vec<Snapshot>, VnRetainedLayoutStats) {
    let mut app = TestApp::new();
    let mut window = app.open_window(|window, _| {
        if retained {
            window.vn_enable_retained_layout();
            window.vn_profile_retained_layout(true);
        }
        Fixture {
            phase: Phase::default(),
            layout: None,
            bounds: Rc::default(),
            measured: Rc::default(),
        }
    });
    window.draw();
    let mut snapshots = Vec::new();
    let mut last_scale = 2.;
    for phase in phases {
        if phase.scale != last_scale {
            window.simulate_scale_factor_change(phase.scale);
            last_scale = phase.scale;
        }
        window.update(|view, window, cx| {
            view.phase = phase.clone();
            window.set_rem_size(px(phase.rem));
            cx.notify();
        });
        window.draw();
        snapshots.push(window.read(|view, _| view.snapshot()));
    }
    let stats = window
        .update(|_, window, _| window.vn_take_retained_layout_stats())
        .unwrap_or_default();
    drop(window);
    app.update(|cx| cx.shutdown());
    (snapshots, stats)
}

#[test]
fn repeated_real_draws_refresh_measurements_and_match_text_wrap_geometry() {
    let base = Phase::default();
    let phases = vec![
        base.clone(),
        Phase {
            generation: 1,
            ..base.clone()
        },
        Phase {
            text: "equal width text can still be entirely new",
            generation: 2,
            ..base.clone()
        },
        Phase {
            width: 55.,
            generation: 3,
            ..base.clone()
        },
        Phase {
            width: 200.,
            font: 20.,
            generation: 4,
            ..base.clone()
        },
        Phase {
            width: 60.,
            ellipsis: true,
            generation: 5,
            ..base.clone()
        },
        Phase {
            width: 125.,
            scale: 1.25,
            rem: 19.,
            generation: 6,
            ..base.clone()
        },
    ];
    let (reference, _) = draw_phases(false, &phases);
    let (actual, stats) = draw_phases(true, &phases);
    assert_eq!(actual, reference);
    assert!(stats.nodes_reused > 0);
    assert!(
        stats.probe_replays > 0,
        "warm cached geometry must use current measurement state"
    );
    assert!(
        stats.probe_mismatches > 0,
        "changed text/constraints must invalidate stale cached measures"
    );
    assert_ne!(
        actual[0].wrapped, actual[3].wrapped,
        "the width phase must actually change wrapping"
    );
}

#[test]
fn real_draws_match_after_style_reorder_remove_and_parent_changes() {
    let base = Phase::default();
    let phases = vec![
        base.clone(),
        Phase {
            rows_a: vec![(2, 50.), (1, 35.)],
            generation: 1,
            ..base.clone()
        },
        Phase {
            rows_a: vec![(2, 50.)],
            rows_b: vec![(1, 35.)],
            generation: 2,
            ..base.clone()
        },
        Phase {
            rows_a: vec![],
            rows_b: vec![(1, 75.)],
            generation: 3,
            ..base.clone()
        },
        Phase {
            rows_a: vec![(3, 20.)],
            rows_b: vec![],
            generation: 4,
            ..base
        },
    ];
    let (reference, _) = draw_phases(false, &phases);
    let (actual, stats) = draw_phases(true, &phases);
    assert_eq!(actual, reference);
    assert!(stats.style_writes > 0);
    assert!(stats.child_writes > 0);
    assert!(stats.nodes_freed > 0);
}

#[test]
fn scope_buckets_keep_full_paths_and_independent_interleaved_slots() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let first_scope = GlobalElementId::new(&["first-parent".into(), "same-leaf".into()]);
    let second_scope = GlobalElementId::new(&["second-parent".into(), "same-leaf".into()]);
    let first = request_layout(&mut engine, Some(first_scope.clone()), fixed(10., 10.), &[]);
    let second = request_layout(
        &mut engine,
        Some(second_scope.clone()),
        fixed(20., 10.),
        &[],
    );
    let first_extra = request_layout(&mut engine, Some(first_scope.clone()), fixed(30., 10.), &[]);
    assert_ne!(first, second);
    assert_ne!(first, first_extra);
    assert_eq!(engine.retention.scopes.len(), 2);
    engine.clear();

    // Change the interleaving while retaining each scope's own request order.
    let second_again = request_layout(
        &mut engine,
        Some(second_scope.clone()),
        fixed(20., 10.),
        &[],
    );
    let first_again = request_layout(&mut engine, Some(first_scope.clone()), fixed(10., 10.), &[]);
    let first_extra_again =
        request_layout(&mut engine, Some(first_scope.clone()), fixed(30., 10.), &[]);
    assert_eq!(second_again, second);
    assert_eq!(first_again, first);
    assert_eq!(first_extra_again, first_extra);
    engine.clear();
    assert_eq!(engine.retention.retained_nodes, 3);
    assert_eq!(engine.taffy.total_node_count(), 3);
}

#[test]
fn scope_bucket_tail_and_identity_expiry_recycle_without_retaining_old_nodes() {
    let mut engine = TaffyLayoutEngine::new();
    engine.enable_retention();
    let first_scope = scope("first");
    let second_scope = scope("second");
    let first = request_layout(&mut engine, Some(first_scope.clone()), fixed(10., 10.), &[]);
    let dropped_tail = request_layout(&mut engine, Some(first_scope.clone()), fixed(30., 10.), &[]);
    for _ in 0..30 {
        request_layout(&mut engine, Some(first_scope.clone()), fixed(30., 10.), &[]);
    }
    let second = request_layout(
        &mut engine,
        Some(second_scope.clone()),
        fixed(20., 10.),
        &[],
    );
    let first_bucket = engine.retention.scopes[&first_scope];
    engine.clear();

    assert_eq!(
        request_layout(&mut engine, Some(first_scope.clone()), fixed(10., 10.), &[]),
        first
    );
    assert_eq!(
        request_layout(
            &mut engine,
            Some(second_scope.clone()),
            fixed(20., 10.),
            &[]
        ),
        second
    );
    engine.clear();
    assert_eq!(engine.retention.retained_nodes, 2);
    assert_eq!(
        engine.retention.buckets[first_bucket]
            .as_ref()
            .unwrap()
            .entries
            .len(),
        1
    );
    assert_eq!(engine.taffy.total_node_count(), 2);
    assert!(
        engine.retention.buckets[first_bucket]
            .as_ref()
            .unwrap()
            .entries
            .capacity()
            <= 4,
        "a surviving scope must release a large expired slot tail"
    );

    request_layout(
        &mut engine,
        Some(second_scope.clone()),
        fixed(20., 10.),
        &[],
    );
    engine.clear();
    assert!(!engine.retention.scopes.contains_key(&first_scope));
    assert_eq!(engine.retention.retained_nodes, 1);
    assert_eq!(engine.retention.free_buckets, [first_bucket]);

    let replacement_scope = scope("replacement");
    let replacement = request_layout(
        &mut engine,
        Some(replacement_scope.clone()),
        fixed(40., 10.),
        &[],
    );
    assert_ne!(replacement, first);
    assert_ne!(replacement, dropped_tail);
    assert_eq!(engine.retention.scopes[&replacement_scope], first_bucket);
    request_layout(&mut engine, Some(second_scope), fixed(20., 10.), &[]);
    engine.clear();
    assert_eq!(
        engine.retention.buckets.len(),
        2,
        "recycled scopes cannot grow the arena"
    );
    assert_eq!(engine.retention.retained_nodes, 2);
    assert_eq!(engine.taffy.total_node_count(), 2);
}