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