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    glyph_brush: Option<crate::window::GlyphBrushCacheKey>,
327    layer_captured: bool,
328    layer_clip: Option<Bounds<Pixels>>,
329}
330
331impl<V: View> Element for ViewElement<V> {
332    type RequestLayoutState = Option<AnyElement>;
333    type PrepaintState = Option<AnyElement>;
334
335    fn id(&self) -> Option<ElementId> {
336        self.entity_id.map(ElementId::View)
337    }
338
339    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
340        #[cfg(debug_assertions)]
341        return Some(self.source);
342
343        #[cfg(not(debug_assertions))]
344        return None;
345    }
346
347    fn request_layout(
348        &mut self,
349        _id: Option<&GlobalElementId>,
350        _inspector_id: Option<&InspectorElementId>,
351        window: &mut Window,
352        cx: &mut App,
353    ) -> (LayoutId, Self::RequestLayoutState) {
354        if let Some(entity_id) = self.entity_id {
355            // Stateful path: create a reactive boundary.
356            #[cfg(feature = "profiler")]
357            let start = window.window_profiler.begin_view();
358            let view = &mut self.view;
359            let layout = request_layout_view(
360                entity_id,
361                self.cached_style.as_ref(),
362                window,
363                cx,
364                &mut |window, cx| view.take().unwrap().render(window, cx).into_any_element(),
365            );
366            #[cfg(feature = "profiler")]
367            window.window_profiler.end_view(
368                start,
369                self.view_type_name,
370                crate::profiler::ViewPhase::RequestLayout,
371            );
372            layout
373        } else {
374            // Stateless path: isolate subtree via type name (no entity identity).
375            request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
376                self.view
377                    .take()
378                    .unwrap()
379                    .render(window, cx)
380                    .into_any_element()
381            })
382        }
383    }
384
385    fn prepaint(
386        &mut self,
387        global_id: Option<&GlobalElementId>,
388        _inspector_id: Option<&InspectorElementId>,
389        bounds: Bounds<Pixels>,
390        element: &mut Self::RequestLayoutState,
391        window: &mut Window,
392        cx: &mut App,
393    ) -> Option<AnyElement> {
394        if let Some(entity_id) = self.entity_id {
395            // Stateful path.
396            #[cfg(feature = "profiler")]
397            let start = window.window_profiler.begin_view();
398            let prepainted = prepaint_view(
399                entity_id,
400                global_id,
401                bounds,
402                element,
403                window,
404                cx,
405                &mut |window, cx| {
406                    self.view
407                        .take()
408                        .unwrap()
409                        .render(window, cx)
410                        .into_any_element()
411                },
412            );
413            #[cfg(feature = "profiler")]
414            window.window_profiler.end_view(
415                start,
416                self.view_type_name,
417                crate::profiler::ViewPhase::Prepaint,
418            );
419            prepainted
420        } else {
421            // Stateless path: just prepaint the element.
422            prepaint_component(type_name::<V>(), element, window, cx)
423        }
424    }
425
426    fn paint(
427        &mut self,
428        global_id: Option<&GlobalElementId>,
429        _inspector_id: Option<&InspectorElementId>,
430        _bounds: Bounds<Pixels>,
431        _request_layout: &mut Self::RequestLayoutState,
432        element: &mut Self::PrepaintState,
433        window: &mut Window,
434        cx: &mut App,
435    ) {
436        if let Some(entity_id) = self.entity_id {
437            // Stateful path.
438            #[cfg(feature = "profiler")]
439            let start = window.window_profiler.begin_view();
440            paint_view(
441                entity_id,
442                self.cached_style.is_some(),
443                global_id,
444                element,
445                window,
446                cx,
447            );
448            #[cfg(feature = "profiler")]
449            window.window_profiler.end_view(
450                start,
451                self.view_type_name,
452                crate::profiler::ViewPhase::Paint,
453            );
454        } else {
455            // Stateless path: just paint the element.
456            paint_component(std::any::type_name::<V>(), element, window, cx);
457        }
458    }
459}
460
461/// A view that renders nothing
462pub struct EmptyView;
463
464impl Render for EmptyView {
465    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
466        Empty
467    }
468}
469
470#[inline(never)]
471fn request_layout_view(
472    entity_id: EntityId,
473    cached_style: Option<&StyleRefinement>,
474    window: &mut Window,
475    cx: &mut App,
476    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
477) -> (LayoutId, Option<AnyElement>) {
478    window.with_rendered_view(entity_id, |window| {
479        let caching_disabled = window.is_inspector_picking(cx);
480        match cached_style {
481            Some(style) if !caching_disabled => {
482                let mut root_style = Style::default();
483                root_style.refine(style);
484                let layout_id = window.request_layout(root_style, None, cx);
485                (layout_id, None)
486            }
487            _ => {
488                let mut element = render(window, cx);
489                let layout_id = element.request_layout(window, cx);
490                (layout_id, Some(element))
491            }
492        }
493    })
494}
495
496#[inline(never)]
497fn request_layout_component(
498    name: &'static str,
499    window: &mut Window,
500    cx: &mut App,
501    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
502) -> (LayoutId, Option<AnyElement>) {
503    window.with_id(ElementId::from(name), |window| {
504        let mut element = render(window, cx);
505        let layout_id = element.request_layout(window, cx);
506        (layout_id, Some(element))
507    })
508}
509
510#[inline(never)]
511fn prepaint_view(
512    entity_id: EntityId,
513    global_id: Option<&GlobalElementId>,
514    bounds: Bounds<Pixels>,
515    element: &mut Option<AnyElement>,
516    window: &mut Window,
517    cx: &mut App,
518    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
519) -> Option<AnyElement> {
520    window.set_view_id(entity_id);
521    window.with_rendered_view(entity_id, |window| {
522        if let Some(mut element) = element.take() {
523            element.prepaint(window, cx);
524            return Some(element);
525        }
526
527        window.with_element_state::<ViewElementState, _>(
528            global_id.unwrap(),
529            |element_state, window| {
530                let content_mask = window.content_mask();
531                let text_style = window.text_style();
532                let glyph_brush = window.glyph_brush_cache_key();
533                let layer_captured = window.is_layer_captured();
534                let layer_clip = window.layer_capture_visible_bounds();
535
536                if let Some(mut element_state) = element_state
537                    && element_state.cache_key.bounds == bounds
538                    && element_state.cache_key.content_mask == content_mask
539                    && element_state.cache_key.text_style == text_style
540                    && element_state.cache_key.glyph_brush == glyph_brush
541                    && element_state.cache_key.layer_captured == layer_captured
542                    && element_state.cache_key.layer_clip == layer_clip
543                    && !window.dirty_views.contains(&entity_id)
544                    && !window.refreshing
545                {
546                    let prepaint_start = window.prepaint_index();
547                    window.reuse_prepaint(element_state.prepaint_range.clone());
548                    cx.entities
549                        .extend_accessed(&element_state.accessed_entities);
550                    let prepaint_end = window.prepaint_index();
551                    element_state.prepaint_range = prepaint_start..prepaint_end;
552
553                    return (None, element_state);
554                }
555
556                let refreshing = mem::replace(&mut window.refreshing, true);
557                let prepaint_start = window.prepaint_index();
558                let (element, accessed_entities) = cx.detect_accessed_entities(|cx| {
559                    let mut element = render(window, cx);
560                    element.layout_as_root(Size::<AvailableSpace>::from(bounds.size), window, cx);
561                    element.prepaint_at(bounds.origin, window, cx);
562                    element
563                });
564
565                let prepaint_end = window.prepaint_index();
566                window.refreshing = refreshing;
567
568                (
569                    Some(element),
570                    ViewElementState {
571                        accessed_entities,
572                        prepaint_range: prepaint_start..prepaint_end,
573                        paint_range: PaintIndex::default()..PaintIndex::default(),
574                        cache_key: ViewElementCacheKey {
575                            bounds,
576                            content_mask,
577                            text_style,
578                            glyph_brush,
579                            layer_captured,
580                            layer_clip,
581                        },
582                    },
583                )
584            },
585        )
586    })
587}
588
589#[inline(never)]
590fn prepaint_component(
591    name: &'static str,
592    element: &mut Option<AnyElement>,
593    window: &mut Window,
594    cx: &mut App,
595) -> Option<AnyElement> {
596    window.with_id(ElementId::from(name), |window| {
597        element.as_mut().unwrap().prepaint(window, cx);
598    });
599    Some(element.take().unwrap())
600}
601
602#[inline(never)]
603fn paint_view(
604    entity_id: EntityId,
605    cached: bool,
606    global_id: Option<&GlobalElementId>,
607    element: &mut Option<AnyElement>,
608    window: &mut Window,
609    cx: &mut App,
610) {
611    window.with_rendered_view(entity_id, |window| {
612        let caching_disabled = window.is_inspector_picking(cx);
613        if cached && !caching_disabled {
614            window.with_element_state::<ViewElementState, _>(
615                global_id.unwrap(),
616                |element_state, window| {
617                    let mut element_state = element_state.unwrap();
618
619                    let paint_start = window.paint_index();
620
621                    if let Some(element) = element {
622                        let refreshing = mem::replace(&mut window.refreshing, true);
623                        element.paint(window, cx);
624                        window.refreshing = refreshing;
625                    } else {
626                        window.reuse_paint(element_state.paint_range.clone());
627                    }
628
629                    let paint_end = window.paint_index();
630                    element_state.paint_range = paint_start..paint_end;
631
632                    ((), element_state)
633                },
634            )
635        } else {
636            element.as_mut().unwrap().paint(window, cx);
637        }
638    });
639}
640
641#[inline(never)]
642fn paint_component(
643    name: &'static str,
644    element: &mut Option<AnyElement>,
645    window: &mut Window,
646    cx: &mut App,
647) {
648    window.with_id(ElementId::Name(name.into()), |window| {
649        element.as_mut().unwrap().paint(window, cx);
650    });
651}