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    #[cfg(not(gpui_hot_reload))]
96    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
97        (self.render)(&self, window, cx)
98    }
99
100    // The stored function pointer was captured from the original binary, so it must be looked up
101    // in the jump table to reach the patched render.
102    #[cfg(gpui_hot_reload)]
103    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
104        subsecond::HotFn::current(self.render).call((&self, window, cx))
105    }
106}
107
108impl<V: 'static + Render> IntoElement for Entity<V> {
109    type Element = ViewElement<Entity<V>>;
110
111    fn into_element(self) -> Self::Element {
112        crate::fast::splice::rebuildable(self.clone(), self.into())
113    }
114
115    #[inline(never)]
116    fn into_any_element(self) -> AnyElement {
117        self.into_element().into_any()
118    }
119}
120
121impl IntoElement for AnyView {
122    type Element = ViewElement<AnyView>;
123
124    fn into_element(self) -> Self::Element {
125        crate::fast::splice::rebuildable(self.clone(), self)
126    }
127}
128
129/// A weak, dynamically-typed view handle.
130pub struct AnyWeakView {
131    entity: AnyWeakEntity,
132    render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
133    view_type_name: &'static str,
134}
135
136impl AnyWeakView {
137    /// Upgrade to a strong `AnyView` handle, if the view is still alive.
138    pub fn upgrade(&self) -> Option<AnyView> {
139        let entity = self.entity.upgrade()?;
140        Some(AnyView {
141            entity,
142            render: self.render,
143            view_type_name: self.view_type_name,
144        })
145    }
146}
147
148impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
149    fn from(view: WeakEntity<V>) -> Self {
150        AnyWeakView {
151            entity: view.into(),
152            render: any_view::render::<V>,
153            view_type_name: type_name::<V>(),
154        }
155    }
156}
157
158impl PartialEq for AnyWeakView {
159    fn eq(&self, other: &Self) -> bool {
160        self.entity == other.entity
161    }
162}
163
164impl std::fmt::Debug for AnyWeakView {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("AnyWeakView")
167            .field("entity_id", &self.entity.entity_id)
168            .finish_non_exhaustive()
169    }
170}
171
172mod any_view {
173    use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
174
175    pub(crate) fn render<V: 'static + Render>(
176        view: &AnyView,
177        window: &mut Window,
178        cx: &mut App,
179    ) -> AnyElement {
180        let view = view.clone().downcast::<V>().unwrap();
181        // Record the view's Render type name so the accessibility debug dump can
182        // attribute nodes to the view that produced them.
183        #[cfg(debug_assertions)]
184        window
185            .a11y
186            .view_type_names
187            .insert(view.entity_id(), std::any::type_name::<V>());
188        crate::fast::dependencies::render_next(&mut cx.entities, view.entity_id());
189        view.update(cx, |view, cx| view.render(window, cx).into_any_element())
190    }
191}
192
193/// A renderable that participates in GPUI's reactive graph — the unifying model
194/// behind [`Render`] and [`RenderOnce`].
195///
196/// When `entity_id()` returns `Some`, that id becomes the view's identity: it gets
197/// a unique element-id space (so internal `use_state` / `.id(..)` never collide
198/// across siblings) and `cx.notify()` on that entity re-renders only this view's
199/// subtree. `None` behaves like a stateless component.
200///
201/// You rarely implement `View` directly. `Entity<T: Render>` and any `T: RenderOnce`
202/// get a blanket impl below; implement it by hand only when a component needs both
203/// parent-supplied props *and* a backing entity for identity.
204pub trait View: 'static + Sized {
205    /// This view's identity, if it has one. A view typically holds the backing
206    /// entity as a field and returns its [`EntityId`] here.
207    ///
208    /// The id becomes this view's [`ElementId`], so two views keyed on the same
209    /// entity must not be rendered at the same position in the element tree
210    /// (e.g. as siblings under the same parent): their internal element state
211    /// (`use_state`, scroll offsets, etc.) would silently collide. Nesting is
212    /// fine — the id is scoped by the parent path.
213    fn entity_id(&self) -> Option<EntityId>;
214
215    /// Render this view into an element tree, consuming `self`.
216    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
217}
218
219/// A stateless component (`RenderOnce`) is a `View` with no identity.
220impl<T: RenderOnce> View for T {
221    fn entity_id(&self) -> Option<EntityId> {
222        None
223    }
224
225    #[inline]
226    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
227        RenderOnce::render(self, window, cx)
228    }
229}
230
231/// An entity that renders itself (`Render`) is a `View` keyed on its own id.
232impl<T: Render> View for Entity<T> {
233    fn entity_id(&self) -> Option<EntityId> {
234        Some(Entity::entity_id(self))
235    }
236
237    #[inline]
238    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
239        crate::fast::dependencies::render_next(&mut cx.entities, self.entity_id());
240        self.update(cx, |this, cx| {
241            Render::render(this, window, cx).into_any_element()
242        })
243    }
244}
245
246impl<T: Render> Entity<T> {
247    /// Embed this entity as a cached [`ViewElement`] laid out at `style`.
248    ///
249    /// The rendered subtree is reused until the entity is notified (or the
250    /// cached bounds / text style change). Caching requires a definite size:
251    /// a cached view is laid out from `style` and is *not* measured from its
252    /// contents. Use [`ViewElement::new`] (or `.child(entity)`) for the
253    /// uncached case.
254    #[track_caller]
255    pub fn cached(self, style: StyleRefinement) -> ViewElement<Entity<T>> {
256        crate::fast::splice::cached(self.clone(), self.into(), style)
257    }
258}
259
260/// The element type for [`View`] implementations. Wraps a `View` and hooks it
261/// into layout, prepaint, and paint. Constructed via [`ViewElement::new`].
262#[doc(hidden)]
263pub struct ViewElement<V: View> {
264    pub(crate) view: Option<V>,
265    pub(crate) entity_id: Option<EntityId>,
266    pub(crate) cached_style: Option<StyleRefinement>,
267    pub(crate) rebuild: crate::fast::splice::RebuildHandle,
268    #[cfg(feature = "profiler")]
269    pub(crate) view_type_name: &'static str,
270    #[cfg(debug_assertions)]
271    source: &'static core::panic::Location<'static>,
272}
273
274impl<V: View> ViewElement<V> {
275    /// Wrap a [`View`] as an element.
276    #[track_caller]
277    pub fn new(view: V) -> Self {
278        Self::with_type_name(view, type_name::<V>())
279    }
280
281    /// Wraps a view whose draw time profiling attributes to `view_type_name`,
282    /// such as an entity's type rather than [`Entity`]'s.
283    #[track_caller]
284    #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
285    pub(crate) fn with_type_name(view: V, view_type_name: &'static str) -> Self {
286        let entity_id = view.entity_id();
287        ViewElement {
288            entity_id,
289            cached_style: None,
290            rebuild: crate::fast::splice::RebuildHandle::default(),
291            #[cfg(feature = "profiler")]
292            view_type_name,
293            view: Some(view),
294            #[cfg(debug_assertions)]
295            source: core::panic::Location::caller(),
296        }
297    }
298
299    /// Enable caching of this view's rendered subtree, laid out at `style`.
300    /// The composer supplies the layout style because caching skips rendering
301    /// the contents to measure them.
302    ///
303    /// Crate-private on purpose: caching is only sound for entity-backed views,
304    /// where [`Context::notify`] is the contract that busts the cache. A stateless
305    /// view has no such contract, so a frozen subtree could never be invalidated.
306    /// Reach this through [`Entity::cached`] or [`AnyView::cached`], which are
307    /// entity-backed by construction.
308    pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
309        self.cached_style = Some(style);
310        self
311    }
312}
313
314impl<V: View> IntoElement for ViewElement<V> {
315    type Element = Self;
316
317    fn into_element(self) -> Self::Element {
318        self
319    }
320}
321
322#[cfg(not(gpui_hot_reload))]
323#[inline]
324pub(crate) fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
325    view.render(window, cx).into_any_element()
326}
327
328/// Every view and component render passes through this hot-patchable boundary, so the
329/// patched code for that render and everything it calls runs on the next frame.
330#[cfg(gpui_hot_reload)]
331pub(crate) fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
332    #[inline(never)]
333    fn render_view_impl<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
334        view.render(window, cx).into_any_element()
335    }
336
337    subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))
338}
339
340impl<V: View> Element for ViewElement<V> {
341    type RequestLayoutState = crate::fast::retained::ViewLayoutState;
342    type PrepaintState = crate::fast::retained::ViewPrepaintState;
343
344    fn id(&self) -> Option<ElementId> {
345        self.entity_id.map(ElementId::View)
346    }
347
348    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
349        #[cfg(debug_assertions)]
350        return Some(self.source);
351
352        #[cfg(not(debug_assertions))]
353        return None;
354    }
355
356    fn request_layout(
357        &mut self,
358        _id: Option<&GlobalElementId>,
359        _inspector_id: Option<&InspectorElementId>,
360        window: &mut Window,
361        cx: &mut App,
362    ) -> (LayoutId, Self::RequestLayoutState) {
363        crate::fast::retained::request_view_layout(self, _id, window, cx)
364    }
365
366    fn prepaint(
367        &mut self,
368        global_id: Option<&GlobalElementId>,
369        _inspector_id: Option<&InspectorElementId>,
370        bounds: Bounds<Pixels>,
371        element: &mut Self::RequestLayoutState,
372        window: &mut Window,
373        cx: &mut App,
374    ) -> Self::PrepaintState {
375        crate::fast::retained::prepaint_view(self, global_id, bounds, element, window, cx)
376    }
377
378    fn paint(
379        &mut self,
380        global_id: Option<&GlobalElementId>,
381        _inspector_id: Option<&InspectorElementId>,
382        _bounds: Bounds<Pixels>,
383        _request_layout: &mut Self::RequestLayoutState,
384        element: &mut Self::PrepaintState,
385        window: &mut Window,
386        cx: &mut App,
387    ) {
388        crate::fast::retained::paint_view(self, global_id, element, window, cx)
389    }
390}
391
392/// A view that renders nothing
393pub struct EmptyView;
394
395impl Render for EmptyView {
396    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
397        Empty
398    }
399}