Skip to main content

gpui/
view.rs

1use crate::{
2    AnyElement, AnyEntity, AnyWeakEntity, App, AvailableSpace, Bounds, ContentMask, Context,
3    Element, ElementId, Entity, EntityId, GlobalElementId, InspectorElementId, IntoElement,
4    LayoutId, PaintIndex, Pixels, PrepaintStateIndex, Render, RenderOnce, Size, Style,
5    StyleRefinement, TextStyle, WeakEntity,
6};
7use crate::{Empty, Window};
8use anyhow::Result;
9use collections::FxHashSet;
10use refineable::Refineable;
11use std::mem;
12use std::{
13    any::{TypeId, type_name},
14    fmt,
15    ops::Range,
16};
17
18/// A dynamically-typed view handle that can be downcast to a specific `Entity<V>`.
19///
20/// This is the type-erased counterpart to [`ViewElement`]: it holds an entity plus
21/// a function pointer to its render, and is itself a [`View`], so embedding it as an
22/// element goes through the same [`ViewElement`] machinery as any other view.
23#[derive(Clone, Debug)]
24pub struct AnyView {
25    entity: AnyEntity,
26    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
27    view_type_name: &'static str,
28}
29
30impl<V: Render> From<Entity<V>> for AnyView {
31    fn from(value: Entity<V>) -> Self {
32        AnyView {
33            entity: value.into_any(),
34            render: any_view::render::<V>,
35            view_type_name: type_name::<V>(),
36        }
37    }
38}
39
40impl AnyView {
41    /// Embed this view as a cached [`ViewElement`] laid out at `style`.
42    ///
43    /// The rendered subtree is recycled from the previous frame unless
44    /// [Context::notify] was called on the backing entity since it was rendered
45    /// (or [Window::refresh] is called, which ignores caching).
46    pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
47        self.into_element().cached(style)
48    }
49
50    /// Convert this to a weak handle.
51    pub fn downgrade(&self) -> AnyWeakView {
52        AnyWeakView {
53            entity: self.entity.downgrade(),
54            render: self.render,
55            view_type_name: self.view_type_name,
56        }
57    }
58
59    /// Convert this to a [Entity] of a specific type.
60    /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
61    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
62        match self.entity.downcast() {
63            Ok(entity) => Ok(entity),
64            Err(entity) => Err(Self {
65                entity,
66                render: self.render,
67                view_type_name: self.view_type_name,
68            }),
69        }
70    }
71
72    /// Gets the [TypeId] of the underlying view.
73    pub fn entity_type(&self) -> TypeId {
74        self.entity.entity_type
75    }
76
77    /// The [`EntityId`] of this view.
78    pub fn entity_id(&self) -> EntityId {
79        self.entity.entity_id()
80    }
81}
82
83impl PartialEq for AnyView {
84    fn eq(&self, other: &Self) -> bool {
85        self.entity == other.entity
86    }
87}
88
89impl Eq for AnyView {}
90
91/// `AnyView` is the type-erased [`View`]: its `render` is a function pointer rather
92/// than a concrete type, but it participates in the reactive graph exactly like any
93/// other view via [`ViewElement`].
94impl View for AnyView {
95    fn entity_id(&self) -> Option<EntityId> {
96        Some(self.entity.entity_id())
97    }
98
99    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
100        (self.render)(&self, window, cx)
101    }
102}
103
104impl<V: 'static + Render> IntoElement for Entity<V> {
105    type Element = ViewElement<Entity<V>>;
106
107    fn into_element(self) -> Self::Element {
108        ViewElement::with_type_name(self, type_name::<V>())
109    }
110
111    #[inline(never)]
112    fn into_any_element(self) -> AnyElement {
113        self.into_element().into_any()
114    }
115}
116
117impl IntoElement for AnyView {
118    type Element = ViewElement<AnyView>;
119
120    fn into_element(self) -> Self::Element {
121        let view_type_name = self.view_type_name;
122        ViewElement::with_type_name(self, view_type_name)
123    }
124}
125
126/// A weak, dynamically-typed view handle.
127pub struct AnyWeakView {
128    entity: AnyWeakEntity,
129    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
130    view_type_name: &'static str,
131}
132
133impl AnyWeakView {
134    /// Upgrade to a strong `AnyView` handle, if the view is still alive.
135    pub fn upgrade(&self) -> Option<AnyView> {
136        let entity = self.entity.upgrade()?;
137        Some(AnyView {
138            entity,
139            render: self.render,
140            view_type_name: self.view_type_name,
141        })
142    }
143}
144
145impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
146    fn from(view: WeakEntity<V>) -> Self {
147        AnyWeakView {
148            entity: view.into(),
149            render: any_view::render::<V>,
150            view_type_name: type_name::<V>(),
151        }
152    }
153}
154
155impl PartialEq for AnyWeakView {
156    fn eq(&self, other: &Self) -> bool {
157        self.entity == other.entity
158    }
159}
160
161impl std::fmt::Debug for AnyWeakView {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.debug_struct("AnyWeakView")
164            .field("entity_id", &self.entity.entity_id)
165            .finish_non_exhaustive()
166    }
167}
168
169mod any_view {
170    use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
171
172    pub(crate) fn render<V: 'static + Render>(
173        view: &AnyView,
174        window: &mut Window,
175        cx: &mut App,
176    ) -> AnyElement {
177        let view = view.clone().downcast::<V>().unwrap();
178        // Record the view's Render type name so the accessibility debug dump can
179        // attribute nodes to the view that produced them.
180        #[cfg(debug_assertions)]
181        window
182            .a11y
183            .view_type_names
184            .insert(view.entity_id(), std::any::type_name::<V>());
185        view.update(cx, |view, cx| view.render(window, cx).into_any_element())
186    }
187}
188
189/// A renderable that participates in GPUI's reactive graph — the unifying model
190/// behind [`Render`] and [`RenderOnce`].
191///
192/// When `entity_id()` returns `Some`, that id becomes the view's identity: it gets
193/// a unique element-id space (so internal `use_state` / `.id(..)` never collide
194/// across siblings) and `cx.notify()` on that entity re-renders only this view's
195/// subtree. `None` behaves like a stateless component.
196///
197/// You rarely implement `View` directly. `Entity<T: Render>` and any `T: RenderOnce`
198/// get a blanket impl below; implement it by hand only when a component needs both
199/// parent-supplied props *and* a backing entity for identity.
200pub trait View: 'static + Sized {
201    /// This view's identity, if it has one. A view typically holds the backing
202    /// entity as a field and returns its [`EntityId`] here.
203    ///
204    /// The id becomes this view's [`ElementId`], so two views keyed on the same
205    /// entity must not be rendered at the same position in the element tree
206    /// (e.g. as siblings under the same parent): their internal element state
207    /// (`use_state`, scroll offsets, etc.) would silently collide. Nesting is
208    /// fine — the id is scoped by the parent path.
209    fn entity_id(&self) -> Option<EntityId>;
210
211    /// Render this view into an element tree, consuming `self`.
212    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
213}
214
215/// A stateless component (`RenderOnce`) is a `View` with no identity.
216impl<T: RenderOnce> View for T {
217    fn entity_id(&self) -> Option<EntityId> {
218        None
219    }
220
221    #[inline]
222    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
223        RenderOnce::render(self, window, cx)
224    }
225}
226
227/// An entity that renders itself (`Render`) is a `View` keyed on its own id.
228impl<T: Render> View for Entity<T> {
229    fn entity_id(&self) -> Option<EntityId> {
230        Some(Entity::entity_id(self))
231    }
232
233    #[inline]
234    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
235        self.update(cx, |this, cx| {
236            Render::render(this, window, cx).into_any_element()
237        })
238    }
239}
240
241impl<T: Render> Entity<T> {
242    /// Embed this entity as a cached [`ViewElement`] laid out at `style`.
243    ///
244    /// The rendered subtree is reused until the entity is notified (or the
245    /// cached bounds / text style change). Caching requires a definite size:
246    /// a cached view is laid out from `style` and is *not* measured from its
247    /// contents. Use [`ViewElement::new`] (or `.child(entity)`) for the
248    /// uncached case.
249    #[track_caller]
250    pub fn cached(self, style: StyleRefinement) -> ViewElement<Entity<T>> {
251        ViewElement::with_type_name(self, type_name::<T>()).cached(style)
252    }
253}
254
255/// The element type for [`View`] implementations. Wraps a `View` and hooks it
256/// into layout, prepaint, and paint. Constructed via [`ViewElement::new`].
257#[doc(hidden)]
258pub struct ViewElement<V: View> {
259    view: Option<V>,
260    entity_id: Option<EntityId>,
261    cached_style: Option<StyleRefinement>,
262    #[cfg(feature = "profiler")]
263    view_type_name: &'static str,
264    #[cfg(debug_assertions)]
265    source: &'static core::panic::Location<'static>,
266}
267
268impl<V: View> ViewElement<V> {
269    /// Wrap a [`View`] as an element.
270    #[track_caller]
271    pub fn new(view: V) -> Self {
272        Self::with_type_name(view, type_name::<V>())
273    }
274
275    /// Wraps a view whose draw time profiling attributes to `view_type_name`,
276    /// such as an entity's type rather than [`Entity`]'s.
277    #[track_caller]
278    #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
279    pub(crate) fn with_type_name(view: V, view_type_name: &'static str) -> Self {
280        let entity_id = view.entity_id();
281        ViewElement {
282            entity_id,
283            cached_style: None,
284            #[cfg(feature = "profiler")]
285            view_type_name,
286            view: Some(view),
287            #[cfg(debug_assertions)]
288            source: core::panic::Location::caller(),
289        }
290    }
291
292    /// Enable caching of this view's rendered subtree, laid out at `style`.
293    /// The composer supplies the layout style because caching skips rendering
294    /// the contents to measure them.
295    ///
296    /// Crate-private on purpose: caching is only sound for entity-backed views,
297    /// where [`Context::notify`] is the contract that busts the cache. A stateless
298    /// view has no such contract, so a frozen subtree could never be invalidated.
299    /// Reach this through [`Entity::cached`] or [`AnyView::cached`], which are
300    /// entity-backed by construction.
301    pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
302        self.cached_style = Some(style);
303        self
304    }
305}
306
307impl<V: View> IntoElement for ViewElement<V> {
308    type Element = Self;
309
310    fn into_element(self) -> Self::Element {
311        self
312    }
313}
314
315struct ViewElementState {
316    prepaint_range: Range<PrepaintStateIndex>,
317    paint_range: Range<PaintIndex>,
318    cache_key: ViewElementCacheKey,
319    accessed_entities: FxHashSet<EntityId>,
320}
321
322struct ViewElementCacheKey {
323    bounds: Bounds<Pixels>,
324    content_mask: ContentMask<Pixels>,
325    text_style: TextStyle,
326}
327
328impl<V: View> Element for ViewElement<V> {
329    type RequestLayoutState = Option<AnyElement>;
330    type PrepaintState = Option<AnyElement>;
331
332    fn id(&self) -> Option<ElementId> {
333        self.entity_id.map(ElementId::View)
334    }
335
336    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
337        #[cfg(debug_assertions)]
338        return Some(self.source);
339
340        #[cfg(not(debug_assertions))]
341        return None;
342    }
343
344    fn request_layout(
345        &mut self,
346        _id: Option<&GlobalElementId>,
347        _inspector_id: Option<&InspectorElementId>,
348        window: &mut Window,
349        cx: &mut App,
350    ) -> (LayoutId, Self::RequestLayoutState) {
351        if let Some(entity_id) = self.entity_id {
352            // Stateful path: create a reactive boundary.
353            #[cfg(feature = "profiler")]
354            let start = window.window_profiler.begin_view();
355            let view = &mut self.view;
356            let layout = request_layout_view(
357                entity_id,
358                self.cached_style.as_ref(),
359                window,
360                cx,
361                &mut |window, cx| view.take().unwrap().render(window, cx).into_any_element(),
362            );
363            #[cfg(feature = "profiler")]
364            window.window_profiler.end_view(
365                start,
366                self.view_type_name,
367                crate::profiler::ViewPhase::RequestLayout,
368            );
369            layout
370        } else {
371            // Stateless path: isolate subtree via type name (no entity identity).
372            request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
373                self.view
374                    .take()
375                    .unwrap()
376                    .render(window, cx)
377                    .into_any_element()
378            })
379        }
380    }
381
382    fn prepaint(
383        &mut self,
384        global_id: Option<&GlobalElementId>,
385        _inspector_id: Option<&InspectorElementId>,
386        bounds: Bounds<Pixels>,
387        element: &mut Self::RequestLayoutState,
388        window: &mut Window,
389        cx: &mut App,
390    ) -> Option<AnyElement> {
391        if let Some(entity_id) = self.entity_id {
392            // Stateful path.
393            #[cfg(feature = "profiler")]
394            let start = window.window_profiler.begin_view();
395            let prepainted = prepaint_view(
396                entity_id,
397                global_id,
398                bounds,
399                element,
400                window,
401                cx,
402                &mut |window, cx| {
403                    self.view
404                        .take()
405                        .unwrap()
406                        .render(window, cx)
407                        .into_any_element()
408                },
409            );
410            #[cfg(feature = "profiler")]
411            window.window_profiler.end_view(
412                start,
413                self.view_type_name,
414                crate::profiler::ViewPhase::Prepaint,
415            );
416            prepainted
417        } else {
418            // Stateless path: just prepaint the element.
419            prepaint_component(type_name::<V>(), element, window, cx)
420        }
421    }
422
423    fn paint(
424        &mut self,
425        global_id: Option<&GlobalElementId>,
426        _inspector_id: Option<&InspectorElementId>,
427        _bounds: Bounds<Pixels>,
428        _request_layout: &mut Self::RequestLayoutState,
429        element: &mut Self::PrepaintState,
430        window: &mut Window,
431        cx: &mut App,
432    ) {
433        if let Some(entity_id) = self.entity_id {
434            // Stateful path.
435            #[cfg(feature = "profiler")]
436            let start = window.window_profiler.begin_view();
437            paint_view(
438                entity_id,
439                self.cached_style.is_some(),
440                global_id,
441                element,
442                window,
443                cx,
444            );
445            #[cfg(feature = "profiler")]
446            window.window_profiler.end_view(
447                start,
448                self.view_type_name,
449                crate::profiler::ViewPhase::Paint,
450            );
451        } else {
452            // Stateless path: just paint the element.
453            paint_component(std::any::type_name::<V>(), element, window, cx);
454        }
455    }
456}
457
458/// A view that renders nothing
459pub struct EmptyView;
460
461impl Render for EmptyView {
462    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
463        Empty
464    }
465}
466
467#[inline(never)]
468fn request_layout_view(
469    entity_id: EntityId,
470    cached_style: Option<&StyleRefinement>,
471    window: &mut Window,
472    cx: &mut App,
473    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
474) -> (LayoutId, Option<AnyElement>) {
475    window.with_rendered_view(entity_id, |window| {
476        let caching_disabled = window.is_inspector_picking(cx);
477        match cached_style {
478            Some(style) if !caching_disabled => {
479                let mut root_style = Style::default();
480                root_style.refine(style);
481                let layout_id = window.request_layout(root_style, None, cx);
482                (layout_id, None)
483            }
484            _ => {
485                let mut element = render(window, cx);
486                let layout_id = element.request_layout(window, cx);
487                (layout_id, Some(element))
488            }
489        }
490    })
491}
492
493#[inline(never)]
494fn request_layout_component(
495    name: &'static str,
496    window: &mut Window,
497    cx: &mut App,
498    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
499) -> (LayoutId, Option<AnyElement>) {
500    window.with_id(ElementId::from(name), |window| {
501        let mut element = render(window, cx);
502        let layout_id = element.request_layout(window, cx);
503        (layout_id, Some(element))
504    })
505}
506
507#[inline(never)]
508fn prepaint_view(
509    entity_id: EntityId,
510    global_id: Option<&GlobalElementId>,
511    bounds: Bounds<Pixels>,
512    element: &mut Option<AnyElement>,
513    window: &mut Window,
514    cx: &mut App,
515    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
516) -> Option<AnyElement> {
517    window.set_view_id(entity_id);
518    window.with_rendered_view(entity_id, |window| {
519        if let Some(mut element) = element.take() {
520            element.prepaint(window, cx);
521            return Some(element);
522        }
523
524        window.with_element_state::<ViewElementState, _>(
525            global_id.unwrap(),
526            |element_state, window| {
527                let content_mask = window.content_mask();
528                let text_style = window.text_style();
529
530                if let Some(mut element_state) = element_state
531                    && element_state.cache_key.bounds == bounds
532                    && element_state.cache_key.content_mask == content_mask
533                    && element_state.cache_key.text_style == text_style
534                    && !window.dirty_views.contains(&entity_id)
535                    && !window.refreshing
536                {
537                    let prepaint_start = window.prepaint_index();
538                    window.reuse_prepaint(element_state.prepaint_range.clone());
539                    cx.entities
540                        .extend_accessed(&element_state.accessed_entities);
541                    let prepaint_end = window.prepaint_index();
542                    element_state.prepaint_range = prepaint_start..prepaint_end;
543
544                    return (None, element_state);
545                }
546
547                let refreshing = mem::replace(&mut window.refreshing, true);
548                let prepaint_start = window.prepaint_index();
549                let (element, accessed_entities) = cx.detect_accessed_entities(|cx| {
550                    let mut element = render(window, cx);
551                    element.layout_as_root(Size::<AvailableSpace>::from(bounds.size), window, cx);
552                    element.prepaint_at(bounds.origin, window, cx);
553                    element
554                });
555
556                let prepaint_end = window.prepaint_index();
557                window.refreshing = refreshing;
558
559                (
560                    Some(element),
561                    ViewElementState {
562                        accessed_entities,
563                        prepaint_range: prepaint_start..prepaint_end,
564                        paint_range: PaintIndex::default()..PaintIndex::default(),
565                        cache_key: ViewElementCacheKey {
566                            bounds,
567                            content_mask,
568                            text_style,
569                        },
570                    },
571                )
572            },
573        )
574    })
575}
576
577#[inline(never)]
578fn prepaint_component(
579    name: &'static str,
580    element: &mut Option<AnyElement>,
581    window: &mut Window,
582    cx: &mut App,
583) -> Option<AnyElement> {
584    window.with_id(ElementId::from(name), |window| {
585        element.as_mut().unwrap().prepaint(window, cx);
586    });
587    Some(element.take().unwrap())
588}
589
590#[inline(never)]
591fn paint_view(
592    entity_id: EntityId,
593    cached: bool,
594    global_id: Option<&GlobalElementId>,
595    element: &mut Option<AnyElement>,
596    window: &mut Window,
597    cx: &mut App,
598) {
599    window.with_rendered_view(entity_id, |window| {
600        let caching_disabled = window.is_inspector_picking(cx);
601        if cached && !caching_disabled {
602            window.with_element_state::<ViewElementState, _>(
603                global_id.unwrap(),
604                |element_state, window| {
605                    let mut element_state = element_state.unwrap();
606
607                    let paint_start = window.paint_index();
608
609                    if let Some(element) = element {
610                        let refreshing = mem::replace(&mut window.refreshing, true);
611                        element.paint(window, cx);
612                        window.refreshing = refreshing;
613                    } else {
614                        window.reuse_paint(element_state.paint_range.clone());
615                    }
616
617                    let paint_end = window.paint_index();
618                    element_state.paint_range = paint_start..paint_end;
619
620                    ((), element_state)
621                },
622            )
623        } else {
624            element.as_mut().unwrap().paint(window, cx);
625        }
626    });
627}
628
629#[inline(never)]
630fn paint_component(
631    name: &'static str,
632    element: &mut Option<AnyElement>,
633    window: &mut Window,
634    cx: &mut App,
635) {
636    window.with_id(ElementId::Name(name.into()), |window| {
637        element.as_mut().unwrap().paint(window, cx);
638    });
639}