Skip to main content

gpui/
view.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{
3    AnyElement, AnyEntity, AnyWeakEntity, App, Bounds, Context, Element, ElementId, Entity,
4    EntityId, GlobalElementId, InspectorElementId, IntoElement, LayoutId, Pixels, Render,
5    RenderOnce, StyleRefinement, WeakEntity,
6};
7use crate::{Empty, Window};
8use anyhow::Result;
9use std::{
10    any::{TypeId, type_name},
11    fmt,
12};
13
14/// A dynamically-typed view handle that can be downcast to a specific `Entity<V>`.
15///
16/// This is the type-erased counterpart to [`ViewElement`]: it holds an entity plus
17/// a function pointer to its render, and is itself a [`View`], so embedding it as an
18/// element goes through the same [`ViewElement`] machinery as any other view.
19#[derive(Clone, Debug)]
20pub struct AnyView {
21    entity: AnyEntity,
22    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
23    pub(crate) view_type_name: &'static str,
24}
25
26impl<V: Render> From<Entity<V>> for AnyView {
27    fn from(value: Entity<V>) -> Self {
28        AnyView {
29            entity: value.into_any(),
30            render: any_view::render::<V>,
31            view_type_name: type_name::<V>(),
32        }
33    }
34}
35
36impl AnyView {
37    /// Embed this view as a cached [`ViewElement`] laid out at `style`.
38    ///
39    /// The rendered subtree is recycled from the previous frame unless
40    /// [Context::notify] was called on the backing entity since it was rendered
41    /// (or [Window::refresh] is called, which ignores caching).
42    pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
43        self.into_element().cached(style)
44    }
45
46    /// Convert this to a weak handle.
47    pub fn downgrade(&self) -> AnyWeakView {
48        AnyWeakView {
49            entity: self.entity.downgrade(),
50            render: self.render,
51            view_type_name: self.view_type_name,
52        }
53    }
54
55    /// Convert this to a [Entity] of a specific type.
56    /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
57    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
58        match self.entity.downcast() {
59            Ok(entity) => Ok(entity),
60            Err(entity) => Err(Self {
61                entity,
62                render: self.render,
63                view_type_name: self.view_type_name,
64            }),
65        }
66    }
67
68    /// Gets the [TypeId] of the underlying view.
69    pub fn entity_type(&self) -> TypeId {
70        self.entity.entity_type
71    }
72
73    /// The [`EntityId`] of this view.
74    pub fn entity_id(&self) -> EntityId {
75        self.entity.entity_id()
76    }
77}
78
79impl PartialEq for AnyView {
80    fn eq(&self, other: &Self) -> bool {
81        self.entity == other.entity
82    }
83}
84
85impl Eq for AnyView {}
86
87/// `AnyView` is the type-erased [`View`]: its `render` is a function pointer rather
88/// than a concrete type, but it participates in the reactive graph exactly like any
89/// other view via [`ViewElement`].
90impl View for AnyView {
91    fn entity_id(&self) -> Option<EntityId> {
92        Some(self.entity.entity_id())
93    }
94
95    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
96        (self.render)(&self, window, cx)
97    }
98}
99
100impl<V: 'static + Render> IntoElement for Entity<V> {
101    type Element = ViewElement<Entity<V>>;
102
103    fn into_element(self) -> Self::Element {
104        crate::fast::splice::rebuildable(self.clone(), self.into())
105    }
106
107    #[inline(never)]
108    fn into_any_element(self) -> AnyElement {
109        self.into_element().into_any()
110    }
111}
112
113impl IntoElement for AnyView {
114    type Element = ViewElement<AnyView>;
115
116    fn into_element(self) -> Self::Element {
117        crate::fast::splice::rebuildable(self.clone(), self)
118    }
119}
120
121/// A weak, dynamically-typed view handle.
122pub struct AnyWeakView {
123    entity: AnyWeakEntity,
124    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
125    view_type_name: &'static str,
126}
127
128impl AnyWeakView {
129    /// Upgrade to a strong `AnyView` handle, if the view is still alive.
130    pub fn upgrade(&self) -> Option<AnyView> {
131        let entity = self.entity.upgrade()?;
132        Some(AnyView {
133            entity,
134            render: self.render,
135            view_type_name: self.view_type_name,
136        })
137    }
138}
139
140impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
141    fn from(view: WeakEntity<V>) -> Self {
142        AnyWeakView {
143            entity: view.into(),
144            render: any_view::render::<V>,
145            view_type_name: type_name::<V>(),
146        }
147    }
148}
149
150impl PartialEq for AnyWeakView {
151    fn eq(&self, other: &Self) -> bool {
152        self.entity == other.entity
153    }
154}
155
156impl std::fmt::Debug for AnyWeakView {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.debug_struct("AnyWeakView")
159            .field("entity_id", &self.entity.entity_id)
160            .finish_non_exhaustive()
161    }
162}
163
164mod any_view {
165    use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
166
167    pub(crate) fn render<V: 'static + Render>(
168        view: &AnyView,
169        window: &mut Window,
170        cx: &mut App,
171    ) -> AnyElement {
172        let view = view.clone().downcast::<V>().unwrap();
173        // Record the view's Render type name so the accessibility debug dump can
174        // attribute nodes to the view that produced them.
175        #[cfg(debug_assertions)]
176        window
177            .a11y
178            .view_type_names
179            .insert(view.entity_id(), std::any::type_name::<V>());
180        crate::fast::dependencies::render_next(&mut cx.entities, view.entity_id());
181        view.update(cx, |view, cx| view.render(window, cx).into_any_element())
182    }
183}
184
185/// A renderable that participates in GPUI's reactive graph — the unifying model
186/// behind [`Render`] and [`RenderOnce`].
187///
188/// When `entity_id()` returns `Some`, that id becomes the view's identity: it gets
189/// a unique element-id space (so internal `use_state` / `.id(..)` never collide
190/// across siblings) and `cx.notify()` on that entity re-renders only this view's
191/// subtree. `None` behaves like a stateless component.
192///
193/// You rarely implement `View` directly. `Entity<T: Render>` and any `T: RenderOnce`
194/// get a blanket impl below; implement it by hand only when a component needs both
195/// parent-supplied props *and* a backing entity for identity.
196pub trait View: 'static + Sized {
197    /// This view's identity, if it has one. A view typically holds the backing
198    /// entity as a field and returns its [`EntityId`] here.
199    ///
200    /// The id becomes this view's [`ElementId`], so two views keyed on the same
201    /// entity must not be rendered at the same position in the element tree
202    /// (e.g. as siblings under the same parent): their internal element state
203    /// (`use_state`, scroll offsets, etc.) would silently collide. Nesting is
204    /// fine — the id is scoped by the parent path.
205    fn entity_id(&self) -> Option<EntityId>;
206
207    /// Render this view into an element tree, consuming `self`.
208    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
209}
210
211/// A stateless component (`RenderOnce`) is a `View` with no identity.
212impl<T: RenderOnce> View for T {
213    fn entity_id(&self) -> Option<EntityId> {
214        None
215    }
216
217    #[inline]
218    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
219        RenderOnce::render(self, window, cx)
220    }
221}
222
223/// An entity that renders itself (`Render`) is a `View` keyed on its own id.
224impl<T: Render> View for Entity<T> {
225    fn entity_id(&self) -> Option<EntityId> {
226        Some(Entity::entity_id(self))
227    }
228
229    #[inline]
230    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
231        crate::fast::dependencies::render_next(&mut cx.entities, self.entity_id());
232        self.update(cx, |this, cx| {
233            Render::render(this, window, cx).into_any_element()
234        })
235    }
236}
237
238impl<T: Render> Entity<T> {
239    /// Embed this entity as a cached [`ViewElement`] laid out at `style`.
240    ///
241    /// The rendered subtree is reused until the entity is notified (or the
242    /// cached bounds / text style change). Caching requires a definite size:
243    /// a cached view is laid out from `style` and is *not* measured from its
244    /// contents. Use [`ViewElement::new`] (or `.child(entity)`) for the
245    /// uncached case.
246    #[track_caller]
247    pub fn cached(self, style: StyleRefinement) -> ViewElement<Entity<T>> {
248        crate::fast::splice::cached(self.clone(), self.into(), style)
249    }
250}
251
252/// The element type for [`View`] implementations. Wraps a `View` and hooks it
253/// into layout, prepaint, and paint. Constructed via [`ViewElement::new`].
254#[doc(hidden)]
255pub struct ViewElement<V: View> {
256    pub(crate) view: Option<V>,
257    pub(crate) entity_id: Option<EntityId>,
258    pub(crate) cached_style: Option<StyleRefinement>,
259    pub(crate) rebuild: crate::fast::splice::RebuildHandle,
260    #[cfg(feature = "profiler")]
261    pub(crate) view_type_name: &'static str,
262    #[cfg(debug_assertions)]
263    source: &'static core::panic::Location<'static>,
264}
265
266impl<V: View> ViewElement<V> {
267    /// Wrap a [`View`] as an element.
268    #[track_caller]
269    pub fn new(view: V) -> Self {
270        Self::with_type_name(view, type_name::<V>())
271    }
272
273    /// Wraps a view whose draw time profiling attributes to `view_type_name`,
274    /// such as an entity's type rather than [`Entity`]'s.
275    #[track_caller]
276    #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
277    pub(crate) fn with_type_name(view: V, view_type_name: &'static str) -> Self {
278        let entity_id = view.entity_id();
279        ViewElement {
280            entity_id,
281            cached_style: None,
282            rebuild: crate::fast::splice::RebuildHandle::default(),
283            #[cfg(feature = "profiler")]
284            view_type_name,
285            view: Some(view),
286            #[cfg(debug_assertions)]
287            source: core::panic::Location::caller(),
288        }
289    }
290
291    /// Enable caching of this view's rendered subtree, laid out at `style`.
292    /// The composer supplies the layout style because caching skips rendering
293    /// the contents to measure them.
294    ///
295    /// Crate-private on purpose: caching is only sound for entity-backed views,
296    /// where [`Context::notify`] is the contract that busts the cache. A stateless
297    /// view has no such contract, so a frozen subtree could never be invalidated.
298    /// Reach this through [`Entity::cached`] or [`AnyView::cached`], which are
299    /// entity-backed by construction.
300    pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
301        self.cached_style = Some(style);
302        self
303    }
304}
305
306impl<V: View> IntoElement for ViewElement<V> {
307    type Element = Self;
308
309    fn into_element(self) -> Self::Element {
310        self
311    }
312}
313
314impl<V: View> Element for ViewElement<V> {
315    type RequestLayoutState = crate::fast::retained::ViewLayoutState;
316    type PrepaintState = crate::fast::retained::ViewPrepaintState;
317
318    fn id(&self) -> Option<ElementId> {
319        self.entity_id.map(ElementId::View)
320    }
321
322    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
323        #[cfg(debug_assertions)]
324        return Some(self.source);
325
326        #[cfg(not(debug_assertions))]
327        return None;
328    }
329
330    fn request_layout(
331        &mut self,
332        _id: Option<&GlobalElementId>,
333        _inspector_id: Option<&InspectorElementId>,
334        window: &mut Window,
335        cx: &mut App,
336    ) -> (LayoutId, Self::RequestLayoutState) {
337        crate::fast::retained::request_view_layout(self, _id, window, cx)
338    }
339
340    fn prepaint(
341        &mut self,
342        global_id: Option<&GlobalElementId>,
343        _inspector_id: Option<&InspectorElementId>,
344        bounds: Bounds<Pixels>,
345        element: &mut Self::RequestLayoutState,
346        window: &mut Window,
347        cx: &mut App,
348    ) -> Self::PrepaintState {
349        crate::fast::retained::prepaint_view(self, global_id, bounds, element, window, cx)
350    }
351
352    fn paint(
353        &mut self,
354        global_id: Option<&GlobalElementId>,
355        _inspector_id: Option<&InspectorElementId>,
356        _bounds: Bounds<Pixels>,
357        _request_layout: &mut Self::RequestLayoutState,
358        element: &mut Self::PrepaintState,
359        window: &mut Window,
360        cx: &mut App,
361    ) {
362        crate::fast::retained::paint_view(self, global_id, element, window, cx)
363    }
364}
365
366/// A view that renders nothing
367pub struct EmptyView;
368
369impl Render for EmptyView {
370    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
371        Empty
372    }
373}