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
use crate::{
AnyElement, App, Bounds, Element, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
Pixels, Window,
};
use std::rc::Rc;
/// Builds a `Deferred` element, which delays the layout and paint of its child.
pub fn deferred(child: impl IntoElement) -> Deferred {
Deferred {
child: Some(child.into_any_element()),
priority: 0,
clip_to_ancestors: false,
stack_key: None,
}
}
/// An element which delays the painting of its child until after all of
/// its ancestors, while keeping its layout as part of the current element tree.
pub struct Deferred {
child: Option<AnyElement>,
priority: usize,
clip_to_ancestors: bool,
stack_key: Option<Rc<[u128]>>,
}
impl Deferred {
/// Sets the `priority` value of the `deferred` element, which
/// determines the drawing order relative to other deferred elements,
/// with higher values being drawn on top.
pub fn with_priority(mut self, priority: usize) -> Self {
self.priority = priority;
self
}
/// Keep the CONTENT MASK in force where the element was deferred from.
///
/// A deferred draw is replayed at the top of the frame, so by default it
/// escapes every ancestor's `overflow` clip along with their paint order —
/// which is what a popover or a context menu wants. CSS says something
/// narrower: a positioned element with a `z-index` escapes its siblings'
/// PAINT ORDER but is still clipped by the overflow of the ancestors it is
/// laid out inside. This opts into that reading.
///
/// (Without it, a `z-index`ed page section inside a scrolling viewport
/// paints its overflow outside the viewport entirely — over whatever the
/// host draws below it.)
pub fn clip_to_ancestors(mut self, clip: bool) -> Self {
self.clip_to_ancestors = clip;
self
}
/// vue-native fork: where this draw sorts among the deferred draws of the
/// same `priority`, compared lexicographically, a key that is a prefix of
/// another sorting first. Draws without a key sort before every keyed one.
///
/// Unlike `priority`, which is one number, a key can say where a draw sits
/// inside the draws it is nested in: an embedder whose paint order is a
/// tree of layers (CSS stacking contexts) gives each draw the path of its
/// layers, and the whole of an earlier layer then paints before a later
/// one however deep its own draws are nested. The order is the PAINT order
/// and the hit-test order alike (`Frame::vn_hit_order`).
pub fn with_stack_key(mut self, key: Rc<[u128]>) -> Self {
self.stack_key = Some(key);
self
}
}
impl Element for Deferred {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<crate::ElementId> {
None
}
fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
let layout_id = self.child.as_mut().unwrap().request_layout(window, cx);
(layout_id, ())
}
fn prepaint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
_bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
window: &mut Window,
_cx: &mut App,
) {
let child = self.child.take().unwrap();
let element_offset = window.element_offset();
let mask = self.clip_to_ancestors.then(|| window.content_mask());
window.defer_draw_with_stack_key(
child,
element_offset,
self.priority,
mask,
self.stack_key.take(),
)
}
fn paint(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
_bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
_prepaint: &mut Self::PrepaintState,
_window: &mut Window,
_cx: &mut App,
) {
}
}
impl Deferred {
/// Sets a priority for the element. A higher priority conceptually means painting the element
/// on top of deferred draws with a lower priority (i.e. closer to the viewer).
pub fn priority(mut self, priority: usize) -> Self {
self.priority = priority;
self
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use crate::{
Context, Entity, StyleRefinement, TestAppContext, Window, anchored, deferred, div, point,
prelude::*, px, size,
};
struct SubscriptionLeaf {
value: usize,
output: Rc<Cell<usize>>,
}
struct SubscriptionPanel {
leaf: Entity<SubscriptionLeaf>,
deferred_child: bool,
renders: Rc<Cell<usize>>,
}
impl Render for SubscriptionPanel {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let leaf = self.leaf.clone();
let child = crate::canvas(
|_, _, _| {},
move |_, _, _, cx| {
let leaf = leaf.read(cx);
leaf.output.set(leaf.value);
},
)
.size(px(50.));
if self.deferred_child {
deferred(child).into_any_element()
} else {
child.into_any_element()
}
}
}
struct SubscriptionRoot {
panel: Entity<SubscriptionPanel>,
deferred_panel: bool,
renders: Rc<Cell<usize>>,
}
impl Render for SubscriptionRoot {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let panel = self
.panel
.clone()
.cached(StyleRefinement::default().size(px(100.)));
if self.deferred_panel {
deferred(panel).into_any_element()
} else {
panel.into_any_element()
}
}
}
#[gpui::test]
fn test_cached_reuse_keeps_entity_subscriptions(cx: &mut TestAppContext) {
for deferred_child in [true, false] {
for deferred_panel in [false, true] {
let output = Rc::new(Cell::new(0));
let renders = Rc::new(Cell::new(0));
let root_renders = Rc::new(Cell::new(0));
let leaf = cx.new(|_| SubscriptionLeaf {
value: 1,
output: output.clone(),
});
let panel = cx.new(|_| SubscriptionPanel {
leaf: leaf.clone(),
deferred_child,
renders: renders.clone(),
});
let window = cx.open_window(size(px(800.), px(600.)), |_, _| SubscriptionRoot {
panel,
deferred_panel,
renders: root_renders.clone(),
});
cx.run_until_parked();
assert_eq!(output.get(), 1);
let initial_renders = renders.get();
for _ in 0..2 {
window
.update(cx, |_, _, cx| cx.notify())
.expect("notify root");
cx.run_until_parked();
assert_eq!(
renders.get(),
initial_renders,
"panel should reuse its cache"
);
}
let renders_before_notify = root_renders.get();
leaf.update(cx, |leaf, cx| {
leaf.value = 2;
cx.notify();
});
cx.run_until_parked();
let context =
format!("deferred child {deferred_child}, deferred panel {deferred_panel}");
assert!(
root_renders.get() > renders_before_notify,
"leaf notification should redraw: {context}"
);
// A plain entity read has no dispatch-tree path to invalidate the
// cached panel, so refresh to run the paint callback again.
window
.update(cx, |_, window, _| window.refresh())
.expect("refresh canvas");
cx.run_until_parked();
assert_eq!(output.get(), 2, "{context}");
}
}
}
/// A stand-in for a dock panel hosting a popover (deferred draw) whose
/// content opens another popover (a deferred draw created while
/// prepainting the first one's content).
struct PanelView;
impl Render for PanelView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().key_context("Panel").size_full().child(
deferred(
anchored().position(point(px(10.), px(10.))).child(
div().key_context("Popover").w(px(200.)).h(px(200.)).child(
deferred(
anchored().position(point(px(30.), px(30.))).child(
div()
.key_context("NestedMenu")
.debug_selector(|| "NESTED_MENU".into())
.w(px(50.))
.h(px(50.)),
),
)
.with_priority(2),
),
),
)
.with_priority(1),
)
}
}
struct RootView {
panel: Entity<PanelView>,
}
impl Render for RootView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().key_context("Root").size_full().child(
self.panel
.clone()
.cached(StyleRefinement::default().size_full()),
)
}
}
/// Regression test for a crash with nested deferred draws (e.g. a popover
/// menu inside a popover hosted by a cached dock panel). Prepaint indices
/// recorded during the deferred draw rounds must index the same
/// `deferred_draws` vector that `reuse_prepaint` slices on the next frame;
/// previously they were measured against a transient per-round vector, so
/// reusing the panel's subtree grafted the wrong deferred draws and
/// panicked in the dispatch tree.
#[gpui::test]
fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
let panel = cx.new(|_| PanelView);
RootView { panel }
});
cx.run_until_parked();
let menu_bounds = window
.update(cx, |_, window, _| {
window
.rendered_frame
.debug_bounds
.get("NESTED_MENU")
.copied()
})
.unwrap()
.expect("NESTED_MENU debug bounds not found");
assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
// Re-render only the root view; the panel is cached, so its subtree -
// including both deferred draw records - is reused from the previous
// frame.
window.update(cx, |_, _, cx| cx.notify()).unwrap();
cx.run_until_parked();
// Reuse the subtree a second time, exercising ranges that were
// themselves recorded during a reused frame.
window.update(cx, |_, _, cx| cx.notify()).unwrap();
cx.run_until_parked();
// Re-render the panel itself again to prove the popovers still draw.
window
.update(cx, |root, _, cx| {
root.panel.update(cx, |_, cx| cx.notify());
})
.unwrap();
cx.run_until_parked();
window
.update(cx, |_, window, _| {
assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
assert!(
window
.rendered_frame
.debug_bounds
.contains_key("NESTED_MENU")
);
})
.unwrap();
}
}
/// vue-native fork: draws keyed with `with_stack_key` paint, and hit-test, in
/// key order, however deep each one is nested; and a draw keeps the opacity
/// in force where it was deferred from.
#[cfg(test)]
mod vn_stack_key_tests {
use crate::{
Context, HitboxBehavior, HitboxId, TestAppContext, Window, canvas, deferred, div, point,
prelude::*, px, size,
};
use std::{cell::RefCell, rc::Rc};
type Log = Rc<RefCell<Vec<(&'static str, HitboxId, f32)>>>;
fn key(slots: &[u128]) -> Rc<[u128]> {
slots.into()
}
/// A 100px square at the window's origin with a hitbox, logging its paint.
fn probe(name: &'static str, log: &Log) -> impl IntoElement {
let log = log.clone();
canvas(
|bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
move |_, hitbox, window, _| {
log.borrow_mut().push((name, hitbox.id, window.element_opacity))
},
)
.absolute()
.top_0()
.left_0()
.size(px(100.))
}
/// Two overlays of the same z, the EARLIER one with a layer inside it
/// that is deferred one round deeper: an embedder's popover with a
/// `z-index: 2` layer, and the menu it opens. CSS paints the popover
/// whole, layer included, before the menu.
struct TwoOverlays {
log: Log,
}
impl Render for TwoOverlays {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let log = &self.log;
div()
.size_full()
.child(
deferred(
div()
.absolute()
.top_0()
.left_0()
.size(px(100.))
.child(probe("popover", log))
.child(deferred(probe("layer", log)).with_stack_key(key(&[50, 2]))),
)
.with_stack_key(key(&[50])),
)
.child(deferred(probe("menu", log)).with_stack_key(key(&[51])))
}
}
/// The last frame's paints, in order.
fn last_frame(log: &Log, n: usize) -> Vec<(&'static str, HitboxId, f32)> {
let log = log.borrow();
assert!(log.len() >= n, "painted: {:?}", log.iter().map(|e| e.0).collect::<Vec<_>>());
log[log.len() - n..].to_vec()
}
#[gpui::test]
fn a_nested_draw_paints_and_hit_tests_inside_its_overlay(cx: &mut TestAppContext) {
let log: Log = Default::default();
let view_log = log.clone();
let window = cx.open_window(size(px(200.), px(200.)), move |_, _| TwoOverlays {
log: view_log,
});
cx.run_until_parked();
let frame = last_frame(&log, 3);
let names: Vec<_> = frame.iter().map(|e| e.0).collect();
// Rounds alone painted ["popover", "menu", "layer"].
assert_eq!(names, ["popover", "layer", "menu"]);
let id = |name| frame.iter().find(|e| e.0 == name).unwrap().1;
window
.update(cx, |_, window, _| {
let hit = window.rendered_frame.hit_test(point(px(50.), px(50.)), window.scale_factor());
assert_eq!(
hit.ids.to_vec(),
vec![id("menu"), id("layer"), id("popover")],
"topmost painted first"
);
})
.unwrap();
}
struct Faded {
log: Log,
}
impl Render for Faded {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.opacity(0.5)
.child(deferred(probe("inside", &self.log)).with_stack_key(key(&[1])))
}
}
#[gpui::test]
fn a_deferred_draw_keeps_its_ancestors_opacity(cx: &mut TestAppContext) {
let log: Log = Default::default();
let view_log = log.clone();
let _window = cx.open_window(size(px(200.), px(200.)), move |_, _| Faded { log: view_log });
cx.run_until_parked();
assert_eq!(last_frame(&log, 1)[0].2, 0.5);
}
}
/// vue-native fork: a deferred element paints under the text style its
/// ancestors set, as it is prepainted under it.
#[cfg(test)]
mod vn_deferred_text_style_tests {
use crate::{
Context, Hsla, TestAppContext, Window, canvas, deferred, div, prelude::*, px, red, size,
};
use std::{cell::RefCell, rc::Rc};
struct Tinted {
seen: Rc<RefCell<Vec<Hsla>>>,
}
impl Render for Tinted {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let seen = self.seen.clone();
div().size_full().text_color(red()).child(
deferred(
canvas(
|_, _, _| (),
move |_, _, window, _| seen.borrow_mut().push(window.text_style().color),
)
.size(px(10.)),
)
.with_priority(1),
)
}
}
#[gpui::test]
fn a_deferred_paint_reads_the_inherited_text_style(cx: &mut TestAppContext) {
let seen = Rc::new(RefCell::new(Vec::new()));
let view_seen = seen.clone();
let _window = cx.open_window(size(px(200.), px(200.)), move |_, _| Tinted { seen: view_seen });
cx.run_until_parked();
let seen = seen.borrow();
assert!(!seen.is_empty(), "the deferred canvas painted");
assert!(seen.iter().all(|c| *c == red()), "painted under the ancestor's colour: {seen:?}");
}
}