1use crate::{
3 AnyElement, App, Bounds, Element, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
4 Pixels, Window,
5};
6
7pub fn deferred(child: impl IntoElement) -> Deferred {
9 Deferred {
10 child: Some(child.into_any_element()),
11 priority: 0,
12 }
13}
14
15pub struct Deferred {
18 child: Option<AnyElement>,
19 priority: usize,
20}
21
22impl Deferred {
23 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 Deferred {
83 pub fn priority(mut self, priority: usize) -> Self {
86 self.priority = priority;
87 self
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use std::{cell::Cell, rc::Rc};
94
95 use crate::{
96 AvailableSpace, Bounds, ContentMask, Context, Entity, Modifiers, MouseButton,
97 StyleRefinement, TestAppContext, Window, anchored, canvas, deferred, div, point,
98 prelude::*, px, size,
99 };
100
101 struct SubscriptionLeaf {
102 value: usize,
103 output: Rc<Cell<usize>>,
104 }
105
106 struct SubscriptionPanel {
107 leaf: Entity<SubscriptionLeaf>,
108 deferred_child: bool,
109 renders: Rc<Cell<usize>>,
110 }
111
112 impl Render for SubscriptionPanel {
113 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
114 self.renders.set(self.renders.get() + 1);
115 let leaf = self.leaf.clone();
116 let child = crate::canvas(
117 |_, _, _| {},
118 move |_, _, _, cx| {
119 let leaf = leaf.read(cx);
120 leaf.output.set(leaf.value);
121 },
122 )
123 .size(px(50.));
124 if self.deferred_child {
125 deferred(child).into_any_element()
126 } else {
127 child.into_any_element()
128 }
129 }
130 }
131
132 struct SubscriptionRoot {
133 panel: Entity<SubscriptionPanel>,
134 deferred_panel: bool,
135 renders: Rc<Cell<usize>>,
136 }
137
138 impl Render for SubscriptionRoot {
139 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
140 self.renders.set(self.renders.get() + 1);
141 let panel = self
142 .panel
143 .clone()
144 .cached(StyleRefinement::default().size(px(100.)));
145 if self.deferred_panel {
146 deferred(panel).into_any_element()
147 } else {
148 panel.into_any_element()
149 }
150 }
151 }
152
153 #[gpui::test]
154 fn test_cached_reuse_keeps_entity_subscriptions(cx: &mut TestAppContext) {
155 for deferred_child in [true, false] {
156 for deferred_panel in [false, true] {
157 let output = Rc::new(Cell::new(0));
158 let renders = Rc::new(Cell::new(0));
159 let root_renders = Rc::new(Cell::new(0));
160 let leaf = cx.new(|_| SubscriptionLeaf {
161 value: 1,
162 output: output.clone(),
163 });
164 let panel = cx.new(|_| SubscriptionPanel {
165 leaf: leaf.clone(),
166 deferred_child,
167 renders: renders.clone(),
168 });
169 let window = cx.open_window(size(px(800.), px(600.)), |_, _| SubscriptionRoot {
170 panel,
171 deferred_panel,
172 renders: root_renders.clone(),
173 });
174 cx.run_until_parked();
175 assert_eq!(output.get(), 1);
176 let initial_renders = renders.get();
177 for _ in 0..2 {
178 window
179 .update(cx, |_, _, cx| cx.notify())
180 .expect("notify root");
181 cx.run_until_parked();
182 assert_eq!(
183 renders.get(),
184 initial_renders,
185 "panel should reuse its cache"
186 );
187 }
188
189 let renders_before_notify = root_renders.get();
190 leaf.update(cx, |leaf, cx| {
191 leaf.value = 2;
192 cx.notify();
193 });
194 cx.run_until_parked();
195 let context =
196 format!("deferred child {deferred_child}, deferred panel {deferred_panel}");
197 let fast_redrew_panel = renders.get() > initial_renders;
199 assert!(
200 root_renders.get() > renders_before_notify || fast_redrew_panel,
201 "leaf notification should redraw: {context}"
202 );
203 window
206 .update(cx, |_, window, _| window.refresh())
207 .expect("refresh canvas");
208 cx.run_until_parked();
209 assert_eq!(output.get(), 2, "{context}");
210 }
211 }
212 }
213
214 struct PanelView;
218
219 impl Render for PanelView {
220 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
221 div().key_context("Panel").size_full().child(
222 deferred(
223 anchored().position(point(px(10.), px(10.))).child(
224 div().key_context("Popover").w(px(200.)).h(px(200.)).child(
225 deferred(
226 anchored().position(point(px(30.), px(30.))).child(
227 div()
228 .key_context("NestedMenu")
229 .debug_selector(|| "NESTED_MENU".into())
230 .w(px(50.))
231 .h(px(50.)),
232 ),
233 )
234 .with_priority(2),
235 ),
236 ),
237 )
238 .with_priority(1),
239 )
240 }
241 }
242
243 struct RootView {
244 panel: Entity<PanelView>,
245 }
246
247 impl Render for RootView {
248 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
249 div().key_context("Root").size_full().child(
250 self.panel
251 .clone()
252 .cached(StyleRefinement::default().size_full()),
253 )
254 }
255 }
256
257 #[gpui::test]
265 fn test_nested_deferred_draws_with_reused_views(cx: &mut TestAppContext) {
266 let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
267 let panel = cx.new(|_| PanelView);
268 RootView { panel }
269 });
270 cx.run_until_parked();
271
272 let menu_bounds = window
273 .update(cx, |_, window, _| {
274 window
275 .rendered_frame
276 .debug_bounds
277 .get("NESTED_MENU")
278 .copied()
279 })
280 .unwrap()
281 .expect("NESTED_MENU debug bounds not found");
282 assert_eq!(menu_bounds.size, size(px(50.), px(50.)));
283
284 window.update(cx, |_, _, cx| cx.notify()).unwrap();
288 cx.run_until_parked();
289
290 window.update(cx, |_, _, cx| cx.notify()).unwrap();
293 cx.run_until_parked();
294
295 window
297 .update(cx, |root, _, cx| {
298 root.panel.update(cx, |_, cx| cx.notify());
299 })
300 .unwrap();
301 cx.run_until_parked();
302
303 window
304 .update(cx, |_, window, _| {
305 assert_eq!(window.rendered_frame.deferred_draws.len(), 2);
306 assert!(
307 window
308 .rendered_frame
309 .debug_bounds
310 .contains_key("NESTED_MENU")
311 );
312 })
313 .unwrap();
314 }
315
316 struct MaskedOverlayView(Rc<Cell<usize>>);
317
318 impl Render for MaskedOverlayView {
319 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
320 let clicks = self.0.clone();
321 let on_click = move |_: &_, _: &mut _, _: &mut _| clicks.set(clicks.get() + 1);
322 let overlay = |bounds: Bounds<_>, window: &mut Window, cx: &mut _| {
323 let mut overlay = div().size(px(200.)).occlude().into_any_element();
324 overlay.layout_as_root(AvailableSpace::min_size(), window, cx);
325 let mask = ContentMask {
326 bounds: Bounds::new(bounds.origin, size(px(100.), px(200.))),
327 };
328 window.defer_draw(overlay, bounds.origin, 1, Some(mask));
329 };
330 div()
331 .size_full()
332 .child(
333 div()
334 .absolute()
335 .size(px(200.))
336 .on_mouse_down(MouseButton::Left, on_click),
337 )
338 .child(canvas(overlay, |_, _, _, _| {}).size_full())
339 }
340 }
341
342 #[gpui::test]
343 fn test_deferred_content_mask_clips_hitboxes(cx: &mut TestAppContext) {
344 let clicks = Rc::new(Cell::new(0));
345 let (_, cx) = cx.add_window_view({
346 let clicks = clicks.clone();
347 |_, _| MaskedOverlayView(clicks)
348 });
349 cx.run_until_parked();
350
351 cx.simulate_click(point(px(50.), px(50.)), Modifiers::none());
352 assert_eq!(clicks.get(), 0, "the visible overlay should block clicks");
353
354 cx.simulate_click(point(px(150.), px(50.)), Modifiers::none());
355 assert_eq!(clicks.get(), 1, "the clipped area should not block clicks");
356 }
357}