Skip to main content

gpui/elements/
deferred.rs

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