Skip to main content

gpui/elements/
deferred.rs

1use crate::{
2    AnyElement, App, Bounds, Element, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
3    Pixels, Window,
4};
5use std::rc::Rc;
6
7/// Builds a `Deferred` element, which delays the layout and paint of its child.
8pub fn deferred(child: impl IntoElement) -> Deferred {
9    Deferred {
10        child: Some(child.into_any_element()),
11        priority: 0,
12        clip_to_ancestors: false,
13        stack_key: None,
14    }
15}
16
17/// An element which delays the painting of its child until after all of
18/// its ancestors, while keeping its layout as part of the current element tree.
19pub struct Deferred {
20    child: Option<AnyElement>,
21    priority: usize,
22    clip_to_ancestors: bool,
23    stack_key: Option<Rc<[u128]>>,
24}
25
26impl Deferred {
27    /// Sets the `priority` value of the `deferred` element, which
28    /// determines the drawing order relative to other deferred elements,
29    /// with higher values being drawn on top.
30    pub fn with_priority(mut self, priority: usize) -> Self {
31        self.priority = priority;
32        self
33    }
34
35    /// Keep the CONTENT MASK in force where the element was deferred from.
36    ///
37    /// A deferred draw is replayed at the top of the frame, so by default it
38    /// escapes every ancestor's `overflow` clip along with their paint order —
39    /// which is what a popover or a context menu wants. CSS says something
40    /// narrower: a positioned element with a `z-index` escapes its siblings'
41    /// PAINT ORDER but is still clipped by the overflow of the ancestors it is
42    /// laid out inside. This opts into that reading.
43    ///
44    /// (Without it, a `z-index`ed page section inside a scrolling viewport
45    /// paints its overflow outside the viewport entirely — over whatever the
46    /// host draws below it.)
47    pub fn clip_to_ancestors(mut self, clip: bool) -> Self {
48        self.clip_to_ancestors = clip;
49        self
50    }
51
52    /// vue-native fork: where this draw sorts among the deferred draws of the
53    /// same `priority`, compared lexicographically, a key that is a prefix of
54    /// another sorting first. Draws without a key sort before every keyed one.
55    ///
56    /// Unlike `priority`, which is one number, a key can say where a draw sits
57    /// inside the draws it is nested in: an embedder whose paint order is a
58    /// tree of layers (CSS stacking contexts) gives each draw the path of its
59    /// layers, and the whole of an earlier layer then paints before a later
60    /// one however deep its own draws are nested. The order is the PAINT order
61    /// and the hit-test order alike (`Frame::vn_hit_order`).
62    pub fn with_stack_key(mut self, key: Rc<[u128]>) -> Self {
63        self.stack_key = Some(key);
64        self
65    }
66}
67
68impl Element for Deferred {
69    type RequestLayoutState = ();
70    type PrepaintState = ();
71
72    fn id(&self) -> Option<crate::ElementId> {
73        None
74    }
75
76    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
77        None
78    }
79
80    fn request_layout(
81        &mut self,
82        _id: Option<&GlobalElementId>,
83        _inspector_id: Option<&InspectorElementId>,
84        window: &mut Window,
85        cx: &mut App,
86    ) -> (LayoutId, ()) {
87        let layout_id = self.child.as_mut().unwrap().request_layout(window, cx);
88        (layout_id, ())
89    }
90
91    fn prepaint(
92        &mut self,
93        _id: Option<&GlobalElementId>,
94        _inspector_id: Option<&InspectorElementId>,
95        _bounds: Bounds<Pixels>,
96        _request_layout: &mut Self::RequestLayoutState,
97        window: &mut Window,
98        _cx: &mut App,
99    ) {
100        let child = self.child.take().unwrap();
101        let element_offset = window.element_offset();
102        let mask = self.clip_to_ancestors.then(|| window.content_mask());
103        window.defer_draw_with_stack_key(
104            child,
105            element_offset,
106            self.priority,
107            mask,
108            self.stack_key.take(),
109        )
110    }
111
112    fn paint(
113        &mut self,
114        _id: Option<&GlobalElementId>,
115        _inspector_id: Option<&InspectorElementId>,
116        _bounds: Bounds<Pixels>,
117        _request_layout: &mut Self::RequestLayoutState,
118        _prepaint: &mut Self::PrepaintState,
119        _window: &mut Window,
120        _cx: &mut App,
121    ) {
122    }
123}
124
125impl Deferred {
126    /// Sets a priority for the element. A higher priority conceptually means painting the element
127    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
128    pub fn priority(mut self, priority: usize) -> Self {
129        self.priority = priority;
130        self
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use std::{cell::Cell, rc::Rc};
137
138    use crate::{
139        Context, Entity, StyleRefinement, TestAppContext, Window, anchored, deferred, div, point,
140        prelude::*, px, size,
141    };
142
143    struct SubscriptionLeaf {
144        value: usize,
145        output: Rc<Cell<usize>>,
146    }
147
148    struct SubscriptionPanel {
149        leaf: Entity<SubscriptionLeaf>,
150        deferred_child: bool,
151        renders: Rc<Cell<usize>>,
152    }
153
154    impl Render for SubscriptionPanel {
155        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
156            self.renders.set(self.renders.get() + 1);
157            let leaf = self.leaf.clone();
158            let child = crate::canvas(
159                |_, _, _| {},
160                move |_, _, _, cx| {
161                    let leaf = leaf.read(cx);
162                    leaf.output.set(leaf.value);
163                },
164            )
165            .size(px(50.));
166            if self.deferred_child {
167                deferred(child).into_any_element()
168            } else {
169                child.into_any_element()
170            }
171        }
172    }
173
174    struct SubscriptionRoot {
175        panel: Entity<SubscriptionPanel>,
176        deferred_panel: bool,
177        renders: Rc<Cell<usize>>,
178    }
179
180    impl Render for SubscriptionRoot {
181        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
182            self.renders.set(self.renders.get() + 1);
183            let panel = self
184                .panel
185                .clone()
186                .cached(StyleRefinement::default().size(px(100.)));
187            if self.deferred_panel {
188                deferred(panel).into_any_element()
189            } else {
190                panel.into_any_element()
191            }
192        }
193    }
194
195    #[gpui::test]
196    fn test_cached_reuse_keeps_entity_subscriptions(cx: &mut TestAppContext) {
197        for deferred_child in [true, false] {
198            for deferred_panel in [false, true] {
199                let output = Rc::new(Cell::new(0));
200                let renders = Rc::new(Cell::new(0));
201                let root_renders = Rc::new(Cell::new(0));
202                let leaf = cx.new(|_| SubscriptionLeaf {
203                    value: 1,
204                    output: output.clone(),
205                });
206                let panel = cx.new(|_| SubscriptionPanel {
207                    leaf: leaf.clone(),
208                    deferred_child,
209                    renders: renders.clone(),
210                });
211                let window = cx.open_window(size(px(800.), px(600.)), |_, _| SubscriptionRoot {
212                    panel,
213                    deferred_panel,
214                    renders: root_renders.clone(),
215                });
216                cx.run_until_parked();
217                assert_eq!(output.get(), 1);
218                let initial_renders = renders.get();
219                for _ in 0..2 {
220                    window
221                        .update(cx, |_, _, cx| cx.notify())
222                        .expect("notify root");
223                    cx.run_until_parked();
224                    assert_eq!(
225                        renders.get(),
226                        initial_renders,
227                        "panel should reuse its cache"
228                    );
229                }
230
231                let renders_before_notify = root_renders.get();
232                leaf.update(cx, |leaf, cx| {
233                    leaf.value = 2;
234                    cx.notify();
235                });
236                cx.run_until_parked();
237                let context =
238                    format!("deferred child {deferred_child}, deferred panel {deferred_panel}");
239                assert!(
240                    root_renders.get() > renders_before_notify,
241                    "leaf notification should redraw: {context}"
242                );
243                // A plain entity read has no dispatch-tree path to invalidate the
244                // cached panel, so refresh to run the paint callback again.
245                window
246                    .update(cx, |_, window, _| window.refresh())
247                    .expect("refresh canvas");
248                cx.run_until_parked();
249                assert_eq!(output.get(), 2, "{context}");
250            }
251        }
252    }
253
254    /// A stand-in for a dock panel hosting a popover (deferred draw) whose
255    /// content opens another popover (a deferred draw created while
256    /// prepainting the first one's content).
257    struct PanelView;
258
259    impl Render for PanelView {
260        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
261            div().key_context("Panel").size_full().child(
262                deferred(
263                    anchored().position(point(px(10.), px(10.))).child(
264                        div().key_context("Popover").w(px(200.)).h(px(200.)).child(
265                            deferred(
266                                anchored().position(point(px(30.), px(30.))).child(
267                                    div()
268                                        .key_context("NestedMenu")
269                                        .debug_selector(|| "NESTED_MENU".into())
270                                        .w(px(50.))
271                                        .h(px(50.)),
272                                ),
273                            )
274                            .with_priority(2),
275                        ),
276                    ),
277                )
278                .with_priority(1),
279            )
280        }
281    }
282
283    struct RootView {
284        panel: Entity<PanelView>,
285    }
286
287    impl Render for RootView {
288        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
289            div().key_context("Root").size_full().child(
290                self.panel
291                    .clone()
292                    .cached(StyleRefinement::default().size_full()),
293            )
294        }
295    }
296
297    /// Regression test for a crash with nested deferred draws (e.g. a popover
298    /// menu inside a popover hosted by a cached dock panel). Prepaint indices
299    /// recorded during the deferred draw rounds must index the same
300    /// `deferred_draws` vector that `reuse_prepaint` slices on the next frame;
301    /// previously they were measured against a transient per-round vector, so
302    /// reusing the panel's subtree grafted the wrong deferred draws and
303    /// panicked in the dispatch tree.
304    #[gpui::test]
305    fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
306        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
307            let panel = cx.new(|_| PanelView);
308            RootView { panel }
309        });
310        cx.run_until_parked();
311
312        let menu_bounds = window
313            .update(cx, |_, window, _| {
314                window
315                    .rendered_frame
316                    .debug_bounds
317                    .get("NESTED_MENU")
318                    .copied()
319            })
320            .unwrap()
321            .expect("NESTED_MENU debug bounds not found");
322        assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
323
324        // Re-render only the root view; the panel is cached, so its subtree -
325        // including both deferred draw records - is reused from the previous
326        // frame.
327        window.update(cx, |_, _, cx| cx.notify()).unwrap();
328        cx.run_until_parked();
329
330        // Reuse the subtree a second time, exercising ranges that were
331        // themselves recorded during a reused frame.
332        window.update(cx, |_, _, cx| cx.notify()).unwrap();
333        cx.run_until_parked();
334
335        // Re-render the panel itself again to prove the popovers still draw.
336        window
337            .update(cx, |root, _, cx| {
338                root.panel.update(cx, |_, cx| cx.notify());
339            })
340            .unwrap();
341        cx.run_until_parked();
342
343        window
344            .update(cx, |_, window, _| {
345                assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
346                assert!(
347                    window
348                        .rendered_frame
349                        .debug_bounds
350                        .contains_key("NESTED_MENU")
351                );
352            })
353            .unwrap();
354    }
355}
356
357/// vue-native fork: draws keyed with `with_stack_key` paint, and hit-test, in
358/// key order, however deep each one is nested; and a draw keeps the opacity
359/// in force where it was deferred from.
360#[cfg(test)]
361mod vn_stack_key_tests {
362    use crate::{
363        Context, HitboxBehavior, HitboxId, TestAppContext, Window, canvas, deferred, div, point,
364        prelude::*, px, size,
365    };
366    use std::{cell::RefCell, rc::Rc};
367
368    type Log = Rc<RefCell<Vec<(&'static str, HitboxId, f32)>>>;
369
370    fn key(slots: &[u128]) -> Rc<[u128]> {
371        slots.into()
372    }
373
374    /// A 100px square at the window's origin with a hitbox, logging its paint.
375    fn probe(name: &'static str, log: &Log) -> impl IntoElement {
376        let log = log.clone();
377        canvas(
378            |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
379            move |_, hitbox, window, _| {
380                log.borrow_mut().push((name, hitbox.id, window.element_opacity))
381            },
382        )
383        .absolute()
384        .top_0()
385        .left_0()
386        .size(px(100.))
387    }
388
389    /// Two overlays of the same z, the EARLIER one with a layer inside it
390    /// that is deferred one round deeper: an embedder's popover with a
391    /// `z-index: 2` layer, and the menu it opens. CSS paints the popover
392    /// whole, layer included, before the menu.
393    struct TwoOverlays {
394        log: Log,
395    }
396
397    impl Render for TwoOverlays {
398        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
399            let log = &self.log;
400            div()
401                .size_full()
402                .child(
403                    deferred(
404                        div()
405                            .absolute()
406                            .top_0()
407                            .left_0()
408                            .size(px(100.))
409                            .child(probe("popover", log))
410                            .child(deferred(probe("layer", log)).with_stack_key(key(&[50, 2]))),
411                    )
412                    .with_stack_key(key(&[50])),
413                )
414                .child(deferred(probe("menu", log)).with_stack_key(key(&[51])))
415        }
416    }
417
418    /// The last frame's paints, in order.
419    fn last_frame(log: &Log, n: usize) -> Vec<(&'static str, HitboxId, f32)> {
420        let log = log.borrow();
421        assert!(log.len() >= n, "painted: {:?}", log.iter().map(|e| e.0).collect::<Vec<_>>());
422        log[log.len() - n..].to_vec()
423    }
424
425    #[gpui::test]
426    fn a_nested_draw_paints_and_hit_tests_inside_its_overlay(cx: &mut TestAppContext) {
427        let log: Log = Default::default();
428        let view_log = log.clone();
429        let window = cx.open_window(size(px(200.), px(200.)), move |_, _| TwoOverlays {
430            log: view_log,
431        });
432        cx.run_until_parked();
433        let frame = last_frame(&log, 3);
434        let names: Vec<_> = frame.iter().map(|e| e.0).collect();
435        // Rounds alone painted ["popover", "menu", "layer"].
436        assert_eq!(names, ["popover", "layer", "menu"]);
437        let id = |name| frame.iter().find(|e| e.0 == name).unwrap().1;
438        window
439            .update(cx, |_, window, _| {
440                let hit = window.rendered_frame.hit_test(point(px(50.), px(50.)), window.scale_factor());
441                assert_eq!(
442                    hit.ids.to_vec(),
443                    vec![id("menu"), id("layer"), id("popover")],
444                    "topmost painted first"
445                );
446            })
447            .unwrap();
448    }
449
450    struct Faded {
451        log: Log,
452    }
453
454    impl Render for Faded {
455        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
456            div()
457                .size_full()
458                .opacity(0.5)
459                .child(deferred(probe("inside", &self.log)).with_stack_key(key(&[1])))
460        }
461    }
462
463    #[gpui::test]
464    fn a_deferred_draw_keeps_its_ancestors_opacity(cx: &mut TestAppContext) {
465        let log: Log = Default::default();
466        let view_log = log.clone();
467        let _window = cx.open_window(size(px(200.), px(200.)), move |_, _| Faded { log: view_log });
468        cx.run_until_parked();
469        assert_eq!(last_frame(&log, 1)[0].2, 0.5);
470    }
471}
472
473/// vue-native fork: a deferred element paints under the text style its
474/// ancestors set, as it is prepainted under it.
475#[cfg(test)]
476mod vn_deferred_text_style_tests {
477    use crate::{
478        Context, Hsla, TestAppContext, Window, canvas, deferred, div, prelude::*, px, red, size,
479    };
480    use std::{cell::RefCell, rc::Rc};
481
482    struct Tinted {
483        seen: Rc<RefCell<Vec<Hsla>>>,
484    }
485
486    impl Render for Tinted {
487        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
488            let seen = self.seen.clone();
489            div().size_full().text_color(red()).child(
490                deferred(
491                    canvas(
492                        |_, _, _| (),
493                        move |_, _, window, _| seen.borrow_mut().push(window.text_style().color),
494                    )
495                    .size(px(10.)),
496                )
497                .with_priority(1),
498            )
499        }
500    }
501
502    #[gpui::test]
503    fn a_deferred_paint_reads_the_inherited_text_style(cx: &mut TestAppContext) {
504        let seen = Rc::new(RefCell::new(Vec::new()));
505        let view_seen = seen.clone();
506        let _window = cx.open_window(size(px(200.), px(200.)), move |_, _| Tinted { seen: view_seen });
507        cx.run_until_parked();
508        let seen = seen.borrow();
509        assert!(!seen.is_empty(), "the deferred canvas painted");
510        assert!(seen.iter().all(|c| *c == red()), "painted under the ancestor's colour: {seen:?}");
511    }
512}