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        Context, Entity, StyleRefinement, TestAppContext, Window, anchored, deferred, div, point,
96        prelude::*, px, size,
97    };
98
99    struct SubscriptionLeaf {
100        value: usize,
101        output: Rc<Cell<usize>>,
102    }
103
104    struct SubscriptionPanel {
105        leaf: Entity<SubscriptionLeaf>,
106        deferred_child: bool,
107        renders: Rc<Cell<usize>>,
108    }
109
110    impl Render for SubscriptionPanel {
111        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
112            self.renders.set(self.renders.get() + 1);
113            let leaf = self.leaf.clone();
114            let child = crate::canvas(
115                |_, _, _| {},
116                move |_, _, _, cx| {
117                    let leaf = leaf.read(cx);
118                    leaf.output.set(leaf.value);
119                },
120            )
121            .size(px(50.));
122            if self.deferred_child {
123                deferred(child).into_any_element()
124            } else {
125                child.into_any_element()
126            }
127        }
128    }
129
130    struct SubscriptionRoot {
131        panel: Entity<SubscriptionPanel>,
132        deferred_panel: bool,
133        renders: Rc<Cell<usize>>,
134    }
135
136    impl Render for SubscriptionRoot {
137        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
138            self.renders.set(self.renders.get() + 1);
139            let panel = self
140                .panel
141                .clone()
142                .cached(StyleRefinement::default().size(px(100.)));
143            if self.deferred_panel {
144                deferred(panel).into_any_element()
145            } else {
146                panel.into_any_element()
147            }
148        }
149    }
150
151    #[gpui::test]
152    fn test_cached_reuse_keeps_entity_subscriptions(cx: &mut TestAppContext) {
153        for deferred_child in [true, false] {
154            for deferred_panel in [false, true] {
155                let output = Rc::new(Cell::new(0));
156                let renders = Rc::new(Cell::new(0));
157                let root_renders = Rc::new(Cell::new(0));
158                let leaf = cx.new(|_| SubscriptionLeaf {
159                    value: 1,
160                    output: output.clone(),
161                });
162                let panel = cx.new(|_| SubscriptionPanel {
163                    leaf: leaf.clone(),
164                    deferred_child,
165                    renders: renders.clone(),
166                });
167                let window = cx.open_window(size(px(800.), px(600.)), |_, _| SubscriptionRoot {
168                    panel,
169                    deferred_panel,
170                    renders: root_renders.clone(),
171                });
172                cx.run_until_parked();
173                assert_eq!(output.get(), 1);
174                let initial_renders = renders.get();
175                for _ in 0..2 {
176                    window
177                        .update(cx, |_, _, cx| cx.notify())
178                        .expect("notify root");
179                    cx.run_until_parked();
180                    assert_eq!(
181                        renders.get(),
182                        initial_renders,
183                        "panel should reuse its cache"
184                    );
185                }
186
187                let renders_before_notify = root_renders.get();
188                leaf.update(cx, |leaf, cx| {
189                    leaf.value = 2;
190                    cx.notify();
191                });
192                cx.run_until_parked();
193                let context =
194                    format!("deferred child {deferred_child}, deferred panel {deferred_panel}");
195                assert!(
196                    root_renders.get() > renders_before_notify,
197                    "leaf notification should redraw: {context}"
198                );
199                // A plain entity read has no dispatch-tree path to invalidate the
200                // cached panel, so refresh to run the paint callback again.
201                window
202                    .update(cx, |_, window, _| window.refresh())
203                    .expect("refresh canvas");
204                cx.run_until_parked();
205                assert_eq!(output.get(), 2, "{context}");
206            }
207        }
208    }
209
210    /// A stand-in for a dock panel hosting a popover (deferred draw) whose
211    /// content opens another popover (a deferred draw created while
212    /// prepainting the first one's content).
213    struct PanelView;
214
215    impl Render for PanelView {
216        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
217            div().key_context("Panel").size_full().child(
218                deferred(
219                    anchored().position(point(px(10.), px(10.))).child(
220                        div().key_context("Popover").w(px(200.)).h(px(200.)).child(
221                            deferred(
222                                anchored().position(point(px(30.), px(30.))).child(
223                                    div()
224                                        .key_context("NestedMenu")
225                                        .debug_selector(|| "NESTED_MENU".into())
226                                        .w(px(50.))
227                                        .h(px(50.)),
228                                ),
229                            )
230                            .with_priority(2),
231                        ),
232                    ),
233                )
234                .with_priority(1),
235            )
236        }
237    }
238
239    struct RootView {
240        panel: Entity<PanelView>,
241    }
242
243    impl Render for RootView {
244        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
245            div().key_context("Root").size_full().child(
246                self.panel
247                    .clone()
248                    .cached(StyleRefinement::default().size_full()),
249            )
250        }
251    }
252
253    /// Regression test for a crash with nested deferred draws (e.g. a popover
254    /// menu inside a popover hosted by a cached dock panel). Prepaint indices
255    /// recorded during the deferred draw rounds must index the same
256    /// `deferred_draws` vector that `reuse_prepaint` slices on the next frame;
257    /// previously they were measured against a transient per-round vector, so
258    /// reusing the panel's subtree grafted the wrong deferred draws and
259    /// panicked in the dispatch tree.
260    #[gpui::test]
261    fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
262        let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
263            let panel = cx.new(|_| PanelView);
264            RootView { panel }
265        });
266        cx.run_until_parked();
267
268        let menu_bounds = window
269            .update(cx, |_, window, _| {
270                window
271                    .rendered_frame
272                    .debug_bounds
273                    .get("NESTED_MENU")
274                    .copied()
275            })
276            .unwrap()
277            .expect("NESTED_MENU debug bounds not found");
278        assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
279
280        // Re-render only the root view; the panel is cached, so its subtree -
281        // including both deferred draw records - is reused from the previous
282        // frame.
283        window.update(cx, |_, _, cx| cx.notify()).unwrap();
284        cx.run_until_parked();
285
286        // Reuse the subtree a second time, exercising ranges that were
287        // themselves recorded during a reused frame.
288        window.update(cx, |_, _, cx| cx.notify()).unwrap();
289        cx.run_until_parked();
290
291        // Re-render the panel itself again to prove the popovers still draw.
292        window
293            .update(cx, |root, _, cx| {
294                root.panel.update(cx, |_, cx| cx.notify());
295            })
296            .unwrap();
297        cx.run_until_parked();
298
299        window
300            .update(cx, |_, window, _| {
301                assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
302                assert!(
303                    window
304                        .rendered_frame
305                        .debug_bounds
306                        .contains_key("NESTED_MENU")
307                );
308            })
309            .unwrap();
310    }
311}