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