Skip to main content

wgpui/
view.rs

1use crate::{
2    AnyElement, AnyEntity, AnyWeakEntity, App, Bounds, ContentMask, Context, Element, ElementId,
3    Entity, EntityId, GlobalElementId, InspectorElementId, IntoElement, LayoutId, PaintIndex,
4    Pixels, PrepaintStateIndex, Render, Style, StyleRefinement, TextStyle, WeakEntity,
5};
6use crate::{Empty, Window};
7use anyhow::Result;
8use collections::FxHashSet;
9use refineable::Refineable;
10use std::mem;
11use std::rc::Rc;
12use std::{any::TypeId, fmt, ops::Range};
13
14struct AnyViewState {
15    prepaint_range: Range<PrepaintStateIndex>,
16    paint_range: Range<PaintIndex>,
17    cache_key: ViewCacheKey,
18    accessed_entities: FxHashSet<EntityId>,
19}
20
21#[derive(Default)]
22struct ViewCacheKey {
23    bounds: Bounds<Pixels>,
24    content_mask: ContentMask<Pixels>,
25    text_style: TextStyle,
26}
27
28impl<V: Render> Element for Entity<V> {
29    type RequestLayoutState = AnyElement;
30    type PrepaintState = ();
31
32    fn id(&self) -> Option<ElementId> {
33        Some(ElementId::View(self.entity_id()))
34    }
35
36    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
37        None
38    }
39
40    fn request_layout(
41        &mut self,
42        _id: Option<&GlobalElementId>,
43        _inspector_id: Option<&InspectorElementId>,
44        window: &mut Window,
45        cx: &mut App,
46    ) -> (LayoutId, Self::RequestLayoutState) {
47        #[cfg(feature = "profiler")]
48        let profile_start = window.window_profiler.begin_view();
49        let profile_result = {
50            let mut element =
51                self.update(cx, |view, cx| view.render(window, cx).into_any_element());
52            let layout_id = window.with_rendered_view(self.entity_id(), |window| {
53                element.request_layout(window, cx)
54            });
55            (layout_id, element)
56        };
57        #[cfg(feature = "profiler")]
58        window.window_profiler.end_view(
59            profile_start,
60            std::any::type_name::<V>(),
61            crate::profiler::ViewPhase::RequestLayout,
62        );
63        profile_result
64    }
65
66    fn prepaint(
67        &mut self,
68        _id: Option<&GlobalElementId>,
69        _inspector_id: Option<&InspectorElementId>,
70        _: Bounds<Pixels>,
71        element: &mut Self::RequestLayoutState,
72        window: &mut Window,
73        cx: &mut App,
74    ) {
75        #[cfg(feature = "profiler")]
76        let profile_start = window.window_profiler.begin_view();
77        window.set_view_id(self.entity_id());
78        window.with_rendered_view(self.entity_id(), |window| element.prepaint(window, cx));
79        #[cfg(feature = "profiler")]
80        window.window_profiler.end_view(
81            profile_start,
82            std::any::type_name::<V>(),
83            crate::profiler::ViewPhase::Prepaint,
84        );
85    }
86
87    fn paint(
88        &mut self,
89        _id: Option<&GlobalElementId>,
90        _inspector_id: Option<&InspectorElementId>,
91        _: Bounds<Pixels>,
92        element: &mut Self::RequestLayoutState,
93        _: &mut Self::PrepaintState,
94        window: &mut Window,
95        cx: &mut App,
96    ) {
97        #[cfg(feature = "profiler")]
98        let profile_start = window.window_profiler.begin_view();
99        window.with_rendered_view(self.entity_id(), |window| element.paint(window, cx));
100        #[cfg(feature = "profiler")]
101        window.window_profiler.end_view(
102            profile_start,
103            std::any::type_name::<V>(),
104            crate::profiler::ViewPhase::Paint,
105        );
106    }
107}
108
109/// A dynamically-typed handle to a view, which can be downcast to a [Entity] for a specific type.
110#[derive(Clone, Debug)]
111pub struct AnyView {
112    entity: AnyEntity,
113    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
114    view_type_name: &'static str,
115    cached_style: Option<Rc<StyleRefinement>>,
116}
117
118impl<V: Render> Entity<V> {
119    /// Cache this view until it is notified or its window is refreshed.
120    pub fn cached(self, style: StyleRefinement) -> AnyView {
121        AnyView::from(self).cached(style)
122    }
123}
124
125impl<V: Render> From<Entity<V>> for AnyView {
126    fn from(value: Entity<V>) -> Self {
127        AnyView {
128            entity: value.into_any(),
129            render: any_view::render::<V>,
130            view_type_name: std::any::type_name::<V>(),
131            cached_style: None,
132        }
133    }
134}
135
136impl AnyView {
137    /// Indicate that this view should be cached when using it as an element.
138    /// When using this method, the view's previous layout and paint will be recycled from the previous frame if [Context::notify] has not been called since it was rendered.
139    /// The one exception is when [Window::refresh] is called, in which case caching is ignored.
140    pub fn cached(mut self, style: StyleRefinement) -> Self {
141        self.cached_style = Some(style.into());
142        self
143    }
144
145    /// Convert this to a weak handle.
146    pub fn downgrade(&self) -> AnyWeakView {
147        AnyWeakView {
148            entity: self.entity.downgrade(),
149            render: self.render,
150            view_type_name: self.view_type_name,
151        }
152    }
153
154    /// Convert this to a [Entity] of a specific type.
155    /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
156    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
157        match self.entity.downcast() {
158            Ok(entity) => Ok(entity),
159            Err(entity) => Err(Self {
160                entity,
161                render: self.render,
162                view_type_name: self.view_type_name,
163                cached_style: self.cached_style,
164            }),
165        }
166    }
167
168    /// Gets the [TypeId] of the underlying view.
169    pub fn entity_type(&self) -> TypeId {
170        self.entity.entity_type
171    }
172
173    /// Gets the entity id of this handle.
174    pub fn entity_id(&self) -> EntityId {
175        self.entity.entity_id()
176    }
177}
178
179impl PartialEq for AnyView {
180    fn eq(&self, other: &Self) -> bool {
181        self.entity == other.entity
182    }
183}
184
185impl Eq for AnyView {}
186
187impl Element for AnyView {
188    type RequestLayoutState = Option<AnyElement>;
189    type PrepaintState = Option<AnyElement>;
190
191    fn id(&self) -> Option<ElementId> {
192        Some(ElementId::View(self.entity_id()))
193    }
194
195    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
196        None
197    }
198
199    fn request_layout(
200        &mut self,
201        _id: Option<&GlobalElementId>,
202        _inspector_id: Option<&InspectorElementId>,
203        window: &mut Window,
204        cx: &mut App,
205    ) -> (LayoutId, Self::RequestLayoutState) {
206        #[cfg(feature = "profiler")]
207        let profile_start = window.window_profiler.begin_view();
208        let profile_result = {
209            window.with_rendered_view(self.entity_id(), |window| {
210                // Disable caching when inspecting so that mouse_hit_test has all hitboxes.
211                let caching_disabled = window.is_inspector_picking(cx) || window.is_a11y_active();
212                match self.cached_style.as_ref() {
213                    Some(style) if !caching_disabled => {
214                        let mut root_style = Style::default();
215                        root_style.refine(style);
216                        let layout_id = window.request_layout(root_style, None, cx);
217                        (layout_id, None)
218                    }
219                    _ => {
220                        let mut element = (self.render)(self, window, cx);
221                        let layout_id = element.request_layout(window, cx);
222                        (layout_id, Some(element))
223                    }
224                }
225            })
226        };
227        #[cfg(feature = "profiler")]
228        window.window_profiler.end_view(
229            profile_start,
230            self.view_type_name,
231            crate::profiler::ViewPhase::RequestLayout,
232        );
233        profile_result
234    }
235
236    fn prepaint(
237        &mut self,
238        global_id: Option<&GlobalElementId>,
239        _inspector_id: Option<&InspectorElementId>,
240        bounds: Bounds<Pixels>,
241        element: &mut Self::RequestLayoutState,
242        window: &mut Window,
243        cx: &mut App,
244    ) -> Option<AnyElement> {
245        #[cfg(feature = "profiler")]
246        let profile_start = window.window_profiler.begin_view();
247        let profile_result = {
248            window.set_view_id(self.entity_id());
249            window.with_rendered_view(self.entity_id(), |window| {
250                if let Some(mut element) = element.take() {
251                    element.prepaint(window, cx);
252                    return Some(element);
253                }
254
255                window.with_element_state::<AnyViewState, _>(
256                    global_id.unwrap(),
257                    |element_state, window| {
258                        let content_mask = window.content_mask();
259                        let text_style = window.text_style();
260
261                        if let Some(mut element_state) = element_state
262                            && element_state.cache_key.bounds == bounds
263                            && element_state.cache_key.content_mask == content_mask
264                            && element_state.cache_key.text_style == text_style
265                            && !window.dirty_views.contains(&self.entity_id())
266                            && !window.refreshing
267                        {
268                            let prepaint_start = window.prepaint_index();
269                            window.reuse_prepaint(element_state.prepaint_range.clone());
270                            cx.entities
271                                .extend_accessed(&element_state.accessed_entities);
272                            let prepaint_end = window.prepaint_index();
273                            element_state.prepaint_range = prepaint_start..prepaint_end;
274
275                            return (None, element_state);
276                        }
277
278                        let refreshing = mem::replace(&mut window.refreshing, true);
279                        let prepaint_start = window.prepaint_index();
280                        let (mut element, accessed_entities) = cx.detect_accessed_entities(|cx| {
281                            let mut element = (self.render)(self, window, cx);
282                            element.layout_as_root(bounds.size.into(), window, cx);
283                            element.prepaint_at(bounds.origin, window, cx);
284                            element
285                        });
286
287                        let prepaint_end = window.prepaint_index();
288                        window.refreshing = refreshing;
289
290                        (
291                            Some(element),
292                            AnyViewState {
293                                accessed_entities,
294                                prepaint_range: prepaint_start..prepaint_end,
295                                paint_range: PaintIndex::default()..PaintIndex::default(),
296                                cache_key: ViewCacheKey {
297                                    bounds,
298                                    content_mask,
299                                    text_style,
300                                },
301                            },
302                        )
303                    },
304                )
305            })
306        };
307        #[cfg(feature = "profiler")]
308        window.window_profiler.end_view(
309            profile_start,
310            self.view_type_name,
311            crate::profiler::ViewPhase::Prepaint,
312        );
313        profile_result
314    }
315
316    fn paint(
317        &mut self,
318        global_id: Option<&GlobalElementId>,
319        _inspector_id: Option<&InspectorElementId>,
320        _bounds: Bounds<Pixels>,
321        _: &mut Self::RequestLayoutState,
322        element: &mut Self::PrepaintState,
323        window: &mut Window,
324        cx: &mut App,
325    ) {
326        #[cfg(feature = "profiler")]
327        let profile_start = window.window_profiler.begin_view();
328        window.with_rendered_view(self.entity_id(), |window| {
329            let caching_disabled = window.is_inspector_picking(cx) || window.is_a11y_active();
330            if self.cached_style.is_some() && !caching_disabled {
331                window.with_element_state::<AnyViewState, _>(
332                    global_id.unwrap(),
333                    |element_state, window| {
334                        let mut element_state = element_state.unwrap();
335
336                        let paint_start = window.paint_index();
337
338                        if let Some(element) = element {
339                            let refreshing = mem::replace(&mut window.refreshing, true);
340                            element.paint(window, cx);
341                            window.refreshing = refreshing;
342                        } else {
343                            window.reuse_paint(element_state.paint_range.clone());
344                        }
345
346                        let paint_end = window.paint_index();
347                        element_state.paint_range = paint_start..paint_end;
348
349                        ((), element_state)
350                    },
351                )
352            } else {
353                element.as_mut().unwrap().paint(window, cx);
354            }
355        });
356        #[cfg(feature = "profiler")]
357        window.window_profiler.end_view(
358            profile_start,
359            self.view_type_name,
360            crate::profiler::ViewPhase::Paint,
361        );
362    }
363}
364
365impl<V: 'static + Render> IntoElement for Entity<V> {
366    type Element = Entity<V>;
367
368    fn into_element(self) -> Self::Element {
369        self
370    }
371}
372
373impl IntoElement for AnyView {
374    type Element = Self;
375
376    fn into_element(self) -> Self::Element {
377        self
378    }
379}
380
381/// A weak, dynamically-typed view handle that does not prevent the view from being released.
382pub struct AnyWeakView {
383    entity: AnyWeakEntity,
384    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
385    view_type_name: &'static str,
386}
387
388impl AnyWeakView {
389    /// Convert to a strongly-typed handle if the referenced view has not yet been released.
390    pub fn upgrade(&self) -> Option<AnyView> {
391        let entity = self.entity.upgrade()?;
392        Some(AnyView {
393            entity,
394            render: self.render,
395            view_type_name: self.view_type_name,
396            cached_style: None,
397        })
398    }
399}
400
401impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
402    fn from(view: WeakEntity<V>) -> Self {
403        AnyWeakView {
404            entity: view.into(),
405            render: any_view::render::<V>,
406            view_type_name: std::any::type_name::<V>(),
407        }
408    }
409}
410
411impl PartialEq for AnyWeakView {
412    fn eq(&self, other: &Self) -> bool {
413        self.entity == other.entity
414    }
415}
416
417impl std::fmt::Debug for AnyWeakView {
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        f.debug_struct("AnyWeakView")
420            .field("entity_id", &self.entity.entity_id)
421            .finish_non_exhaustive()
422    }
423}
424
425mod any_view {
426    use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
427
428    pub(crate) fn render<V: 'static + Render>(
429        view: &AnyView,
430        window: &mut Window,
431        cx: &mut App,
432    ) -> AnyElement {
433        let view = view.clone().downcast::<V>().unwrap();
434        view.update(cx, |view, cx| view.render(window, cx).into_any_element())
435    }
436}
437
438/// A view that renders nothing
439pub struct EmptyView;
440
441impl Render for EmptyView {
442    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
443        Empty
444    }
445}
446
447#[cfg(test)]
448mod cached_debug_bounds_tests {
449    use super::*;
450    use crate::{
451        AppContext as _, InteractiveElement, ParentElement, Styled, TestAppContext, div, px,
452    };
453    use std::cell::Cell;
454
455    struct CachedChild {
456        selector: &'static str,
457        renders: Rc<Cell<usize>>,
458    }
459
460    impl Render for CachedChild {
461        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
462            self.renders.set(self.renders.get() + 1);
463            let selector = self.selector;
464            div().size_full().debug_selector(move || selector.into())
465        }
466    }
467
468    struct CachedRoot {
469        first: Entity<CachedChild>,
470        second: Entity<CachedChild>,
471        show_second: bool,
472    }
473
474    impl Render for CachedRoot {
475        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
476            let mut content = div().size_full().flex().flex_col().child(
477                self.first
478                    .clone()
479                    .cached(StyleRefinement::default().size(px(40.))),
480            );
481            if self.show_second {
482                content = content.child(
483                    self.second
484                        .clone()
485                        .cached(StyleRefinement::default().size(px(40.))),
486                );
487            }
488            content
489        }
490    }
491
492    #[wgpui::test]
493    fn cached_selectors_replay_only_while_their_subtree_is_present(cx: &mut TestAppContext) {
494        let first_renders = Rc::new(Cell::new(0));
495        let second_renders = Rc::new(Cell::new(0));
496        let (root, cx) = cx.add_window_view(|_, cx| CachedRoot {
497            first: cx.new(|_| CachedChild {
498                selector: "first-cached-child",
499                renders: first_renders.clone(),
500            }),
501            second: cx.new(|_| CachedChild {
502                selector: "second-cached-child",
503                renders: second_renders.clone(),
504            }),
505            show_second: true,
506        });
507        let first_bounds = cx
508            .debug_bounds("first-cached-child")
509            .expect("first painted selector");
510        let second_bounds = cx
511            .debug_bounds("second-cached-child")
512            .expect("second painted selector");
513        let rendered = (first_renders.get(), second_renders.get());
514        for _ in 0..3 {
515            cx.update(|window, cx| window.draw(cx).clear());
516            assert_eq!(cx.debug_bounds("first-cached-child"), Some(first_bounds));
517            assert_eq!(cx.debug_bounds("second-cached-child"), Some(second_bounds));
518            assert_eq!((first_renders.get(), second_renders.get()), rendered);
519        }
520
521        root.update(cx, |root, cx| {
522            root.show_second = false;
523            cx.notify();
524        });
525        cx.update(|window, cx| window.draw(cx).clear());
526        assert_eq!(cx.debug_bounds("first-cached-child"), Some(first_bounds));
527        assert_eq!(cx.debug_bounds("second-cached-child"), None);
528        assert_eq!((first_renders.get(), second_renders.get()), rendered);
529    }
530}