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 IntoElement for Deferred {
82    type Element = Self;
83
84    fn into_element(self) -> Self::Element {
85        self
86    }
87}
88
89impl Deferred {
90    /// Sets a priority for the element. A higher priority conceptually means painting the element
91    /// on top of deferred draws with a lower priority (i.e. closer to the viewer).
92    pub fn priority(mut self, priority: usize) -> Self {
93        self.priority = priority;
94        self
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use crate::{
101        Context, Entity, StyleRefinement, TestAppContext, Window, anchored, deferred, div, point,
102        prelude::*, px, size,
103    };
104
105    /// A stand-in for a dock panel hosting a popover (deferred draw) whose
106    /// content opens another popover (a deferred draw created while
107    /// prepainting the first one's content).
108    struct PanelView;
109
110    impl Render for PanelView {
111        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
112            div()
113                .debug_selector(|| "PANEL".into())
114                .key_context("Panel")
115                .size_full()
116                .child(
117                    deferred(
118                        anchored().position(point(px(10.), px(10.))).child(
119                            div().key_context("Popover").w(px(200.)).h(px(200.)).child(
120                                deferred(
121                                    anchored().position(point(px(30.), px(30.))).child(
122                                        div()
123                                            .key_context("NestedMenu")
124                                            .debug_selector(|| "NESTED_MENU".into())
125                                            .w(px(50.))
126                                            .h(px(50.)),
127                                    ),
128                                )
129                                .with_priority(2),
130                            ),
131                        ),
132                    )
133                    .with_priority(1),
134                )
135        }
136    }
137
138    struct RootView {
139        panel: Entity<PanelView>,
140    }
141
142    impl Render for RootView {
143        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
144            div().key_context("Root").size_full().child(
145                self.panel
146                    .clone()
147                    .cached(StyleRefinement::default().size_full()),
148            )
149        }
150    }
151
152    /// Regression test for a crash with nested deferred draws (e.g. a popover
153    /// menu inside a popover hosted by a cached dock panel). Prepaint indices
154    /// recorded during the deferred draw rounds must index the same
155    /// `deferred_draws` vector that `reuse_prepaint` slices on the next frame;
156    /// previously they were measured against a transient per-round vector, so
157    /// reusing the panel's subtree grafted the wrong deferred draws and
158    /// panicked in the dispatch tree.
159    #[gpui::test]
160    fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
161        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
162            let panel = cx.new(|_| PanelView);
163            RootView { panel }
164        });
165        cx.run_until_parked();
166
167        let menu_bounds = window
168            .update(cx, |_, window, _| {
169                window
170                    .rendered_frame
171                    .debug_bounds
172                    .get("NESTED_MENU")
173                    .copied()
174            })
175            .unwrap()
176            .expect("NESTED_MENU debug bounds not found");
177        assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
178        let panel_bounds = window
179            .update(
180                cx,
181                |_, window, _| window.rendered_frame.debug_bounds["PANEL"],
182            )
183            .unwrap();
184
185        // Re-render only the root view; the panel is cached, so its subtree -
186        // including both deferred draw records - is reused from the previous
187        // frame.
188        window.update(cx, |_, _, cx| cx.notify()).unwrap();
189        cx.run_until_parked();
190        window
191            .update(cx, |_, window, _| {
192                assert_eq!(
193                    window.rendered_frame.debug_bounds.get("NESTED_MENU"),
194                    Some(&menu_bounds)
195                );
196                assert_eq!(
197                    window.rendered_frame.debug_bounds.get("PANEL"),
198                    Some(&panel_bounds)
199                );
200            })
201            .unwrap();
202
203        // Reuse the subtree a second time, exercising ranges that were
204        // themselves recorded during a reused frame.
205        window.update(cx, |_, _, cx| cx.notify()).unwrap();
206        cx.run_until_parked();
207        window
208            .update(cx, |_, window, _| {
209                assert_eq!(
210                    window.rendered_frame.debug_bounds.get("NESTED_MENU"),
211                    Some(&menu_bounds)
212                );
213                assert_eq!(
214                    window.rendered_frame.debug_bounds.get("PANEL"),
215                    Some(&panel_bounds)
216                );
217            })
218            .unwrap();
219
220        // Re-render the panel itself again to prove the popovers still draw.
221        window
222            .update(cx, |root, _, cx| {
223                root.panel.update(cx, |_, cx| cx.notify());
224            })
225            .unwrap();
226        cx.run_until_parked();
227
228        window
229            .update(cx, |_, window, _| {
230                assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
231                assert!(
232                    window
233                        .rendered_frame
234                        .debug_bounds
235                        .contains_key("NESTED_MENU")
236                );
237            })
238            .unwrap();
239    }
240}