Skip to main content

gpui/elements/
deferred.rs

1use crate::{
2    AnyElement, App, Bounds, Element, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
3    Pixels, Window,
4};
5
6/// Builds a `Deferred` element, which delays the layout and paint of its child.
7pub fn deferred(child: impl IntoElement) -> Deferred {
8    Deferred {
9        child: Some(child.into_any_element()),
10        priority: 0,
11    }
12}
13
14/// An element which delays the painting of its child until after all of
15/// its ancestors, while keeping its layout as part of the current element tree.
16pub struct Deferred {
17    child: Option<AnyElement>,
18    priority: usize,
19}
20
21impl Deferred {
22    /// Sets the `priority` value of the `deferred` element, which
23    /// determines the drawing order relative to other deferred elements,
24    /// with higher values being drawn on top.
25    pub fn with_priority(mut self, priority: usize) -> Self {
26        self.priority = priority;
27        self
28    }
29}
30
31impl Element for Deferred {
32    type RequestLayoutState = ();
33    type PrepaintState = ();
34
35    fn id(&self) -> Option<crate::ElementId> {
36        None
37    }
38
39    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
40        None
41    }
42
43    fn request_layout(
44        &mut self,
45        _id: Option<&GlobalElementId>,
46        _inspector_id: Option<&InspectorElementId>,
47        window: &mut Window,
48        cx: &mut App,
49    ) -> (LayoutId, ()) {
50        let layout_id = self.child.as_mut().unwrap().request_layout(window, cx);
51        (layout_id, ())
52    }
53
54    fn prepaint(
55        &mut self,
56        _id: Option<&GlobalElementId>,
57        _inspector_id: Option<&InspectorElementId>,
58        _bounds: Bounds<Pixels>,
59        _request_layout: &mut Self::RequestLayoutState,
60        window: &mut Window,
61        _cx: &mut App,
62    ) {
63        let child = self.child.take().unwrap();
64        let element_offset = window.element_offset();
65        window.defer_draw(child, element_offset, self.priority, None)
66    }
67
68    fn paint(
69        &mut self,
70        _id: Option<&GlobalElementId>,
71        _inspector_id: Option<&InspectorElementId>,
72        _bounds: Bounds<Pixels>,
73        _request_layout: &mut Self::RequestLayoutState,
74        _prepaint: &mut Self::PrepaintState,
75        _window: &mut Window,
76        _cx: &mut App,
77    ) {
78    }
79}
80
81impl Deferred {
82    /// Sets a priority for the element. A higher priority conceptually means painting the element
83    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
84    pub fn priority(mut self, priority: usize) -> Self {
85        self.priority = priority;
86        self
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use std::{cell::Cell, rc::Rc};
93
94    use crate::{
95        AvailableSpace, Bounds, ContentMask, Context, Entity, Modifiers, MouseButton,
96        StyleRefinement, TestAppContext, Window, anchored, canvas, deferred, div, point,
97        prelude::*, px, size,
98    };
99
100    struct SubscriptionLeaf {
101        value: usize,
102        output: Rc<Cell<usize>>,
103    }
104
105    struct SubscriptionPanel {
106        leaf: Entity<SubscriptionLeaf>,
107        deferred_child: bool,
108        renders: Rc<Cell<usize>>,
109    }
110
111    impl Render for SubscriptionPanel {
112        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
113            self.renders.set(self.renders.get() + 1);
114            let leaf = self.leaf.clone();
115            let child = crate::canvas(
116                |_, _, _| {},
117                move |_, _, _, cx| {
118                    let leaf = leaf.read(cx);
119                    leaf.output.set(leaf.value);
120                },
121            )
122            .size(px(50.));
123            if self.deferred_child {
124                deferred(child).into_any_element()
125            } else {
126                child.into_any_element()
127            }
128        }
129    }
130
131    struct SubscriptionRoot {
132        panel: Entity<SubscriptionPanel>,
133        deferred_panel: bool,
134        renders: Rc<Cell<usize>>,
135    }
136
137    impl Render for SubscriptionRoot {
138        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
139            self.renders.set(self.renders.get() + 1);
140            let panel = self
141                .panel
142                .clone()
143                .cached(StyleRefinement::default().size(px(100.)));
144            if self.deferred_panel {
145                deferred(panel).into_any_element()
146            } else {
147                panel.into_any_element()
148            }
149        }
150    }
151
152    #[gpui::test]
153    fn test_cached_reuse_keeps_entity_subscriptions(cx: &mut TestAppContext) {
154        for deferred_child in [true, false] {
155            for deferred_panel in [false, true] {
156                let output = Rc::new(Cell::new(0));
157                let renders = Rc::new(Cell::new(0));
158                let root_renders = Rc::new(Cell::new(0));
159                let leaf = cx.new(|_| SubscriptionLeaf {
160                    value: 1,
161                    output: output.clone(),
162                });
163                let panel = cx.new(|_| SubscriptionPanel {
164                    leaf: leaf.clone(),
165                    deferred_child,
166                    renders: renders.clone(),
167                });
168                let window = cx.open_window(size(px(800.), px(600.)), |_, _| SubscriptionRoot {
169                    panel,
170                    deferred_panel,
171                    renders: root_renders.clone(),
172                });
173                cx.run_until_parked();
174                assert_eq!(output.get(), 1);
175                let initial_renders = renders.get();
176                for _ in 0..2 {
177                    window
178                        .update(cx, |_, _, cx| cx.notify())
179                        .expect("notify root");
180                    cx.run_until_parked();
181                    assert_eq!(
182                        renders.get(),
183                        initial_renders,
184                        "panel should reuse its cache"
185                    );
186                }
187
188                let renders_before_notify = root_renders.get();
189                leaf.update(cx, |leaf, cx| {
190                    leaf.value = 2;
191                    cx.notify();
192                });
193                cx.run_until_parked();
194                let context =
195                    format!("deferred child {deferred_child}, deferred panel {deferred_panel}");
196                assert!(
197                    root_renders.get() > renders_before_notify,
198                    "leaf notification should redraw: {context}"
199                );
200                // A plain entity read has no dispatch-tree path to invalidate the
201                // cached panel, so refresh to run the paint callback again.
202                window
203                    .update(cx, |_, window, _| window.refresh())
204                    .expect("refresh canvas");
205                cx.run_until_parked();
206                assert_eq!(output.get(), 2, "{context}");
207            }
208        }
209    }
210
211    /// A stand-in for a dock panel hosting a popover (deferred draw) whose
212    /// content opens another popover (a deferred draw created while
213    /// prepainting the first one's content).
214    struct PanelView;
215
216    impl Render for PanelView {
217        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
218            div().key_context("Panel").size_full().child(
219                deferred(
220                    anchored().position(point(px(10.), px(10.))).child(
221                        div().key_context("Popover").w(px(200.)).h(px(200.)).child(
222                            deferred(
223                                anchored().position(point(px(30.), px(30.))).child(
224                                    div()
225                                        .key_context("NestedMenu")
226                                        .debug_selector(|| "NESTED_MENU".into())
227                                        .w(px(50.))
228                                        .h(px(50.)),
229                                ),
230                            )
231                            .with_priority(2),
232                        ),
233                    ),
234                )
235                .with_priority(1),
236            )
237        }
238    }
239
240    struct RootView {
241        panel: Entity<PanelView>,
242    }
243
244    impl Render for RootView {
245        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
246            div().key_context("Root").size_full().child(
247                self.panel
248                    .clone()
249                    .cached(StyleRefinement::default().size_full()),
250            )
251        }
252    }
253
254    /// Regression test for a crash with nested deferred draws (e.g. a popover
255    /// menu inside a popover hosted by a cached dock panel). Prepaint indices
256    /// recorded during the deferred draw rounds must index the same
257    /// `deferred_draws` vector that `reuse_prepaint` slices on the next frame;
258    /// previously they were measured against a transient per-round vector, so
259    /// reusing the panel's subtree grafted the wrong deferred draws and
260    /// panicked in the dispatch tree.
261    #[gpui::test]
262    fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
263        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
264            let panel = cx.new(|_| PanelView);
265            RootView { panel }
266        });
267        cx.run_until_parked();
268
269        let menu_bounds = window
270            .update(cx, |_, window, _| {
271                window
272                    .rendered_frame
273                    .debug_bounds
274                    .get("NESTED_MENU")
275                    .copied()
276            })
277            .unwrap()
278            .expect("NESTED_MENU debug bounds not found");
279        assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
280
281        // Re-render only the root view; the panel is cached, so its subtree -
282        // including both deferred draw records - is reused from the previous
283        // frame.
284        window.update(cx, |_, _, cx| cx.notify()).unwrap();
285        cx.run_until_parked();
286
287        // Reuse the subtree a second time, exercising ranges that were
288        // themselves recorded during a reused frame.
289        window.update(cx, |_, _, cx| cx.notify()).unwrap();
290        cx.run_until_parked();
291
292        // Re-render the panel itself again to prove the popovers still draw.
293        window
294            .update(cx, |root, _, cx| {
295                root.panel.update(cx, |_, cx| cx.notify());
296            })
297            .unwrap();
298        cx.run_until_parked();
299
300        window
301            .update(cx, |_, window, _| {
302                assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
303                assert!(
304                    window
305                        .rendered_frame
306                        .debug_bounds
307                        .contains_key("NESTED_MENU")
308                );
309            })
310            .unwrap();
311    }
312
313    struct MaskedOverlayView(Rc<Cell<usize>>);
314
315    impl Render for MaskedOverlayView {
316        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
317            let clicks = self.0.clone();
318            let on_click = move |_: &_, _: &mut _, _: &mut _| clicks.set(clicks.get() + 1);
319            let overlay = |bounds: Bounds<_>, window: &mut Window, cx: &mut _| {
320                let mut overlay = div().size(px(200.)).occlude().into_any_element();
321                overlay.layout_as_root(AvailableSpace::min_size(), window, cx);
322                let mask = ContentMask {
323                    bounds: Bounds::new(bounds.origin, size(px(100.), px(200.))),
324                };
325                window.defer_draw(overlay, bounds.origin, 1, Some(mask));
326            };
327            div()
328                .size_full()
329                .child(
330                    div()
331                        .absolute()
332                        .size(px(200.))
333                        .on_mouse_down(MouseButton::Left, on_click),
334                )
335                .child(canvas(overlay, |_, _, _, _| {}).size_full())
336        }
337    }
338
339    #[gpui::test]
340    fn test_deferred_content_mask_clips_hitboxes(cx: &mut TestAppContext) {
341        let clicks = Rc::new(Cell::new(0));
342        let (_, cx) = cx.add_window_view({
343            let clicks = clicks.clone();
344            |_, _| MaskedOverlayView(clicks)
345        });
346        cx.run_until_parked();
347
348        cx.simulate_click(point(px(50.), px(50.)), Modifiers::none());
349        assert_eq!(clicks.get(), 0, "the visible overlay should block clicks");
350
351        cx.simulate_click(point(px(150.), px(50.)), Modifiers::none());
352        assert_eq!(clicks.get(), 1, "the clipped area should not block clicks");
353    }
354}