view.rs

  1use crate::{
  2    seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, Bounds, ContentMask, Element,
  3    ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, GlobalElementId, IntoElement,
  4    LayoutId, Model, PaintIndex, Pixels, PrepaintStateIndex, Render, Style, StyleRefinement,
  5    TextStyle, ViewContext, VisualContext, WeakModel, WindowContext,
  6};
  7use anyhow::{Context, Result};
  8use refineable::Refineable;
  9use std::{
 10    any::{type_name, TypeId},
 11    fmt,
 12    hash::{Hash, Hasher},
 13    ops::Range,
 14};
 15
 16/// A view is a piece of state that can be presented on screen by implementing the [Render] trait.
 17/// Views implement [Element] and can composed with other views, and every window is created with a root view.
 18pub struct View<V> {
 19    /// A view is just a [Model] whose type implements `Render`, and the model is accessible via this field.
 20    pub model: Model<V>,
 21}
 22
 23impl<V> Sealed for View<V> {}
 24
 25struct AnyViewState {
 26    prepaint_range: Range<PrepaintStateIndex>,
 27    paint_range: Range<PaintIndex>,
 28    cache_key: ViewCacheKey,
 29}
 30
 31#[derive(Default)]
 32struct ViewCacheKey {
 33    bounds: Bounds<Pixels>,
 34    content_mask: ContentMask<Pixels>,
 35    text_style: TextStyle,
 36}
 37
 38impl<V: 'static> Entity<V> for View<V> {
 39    type Weak = WeakView<V>;
 40
 41    fn entity_id(&self) -> EntityId {
 42        self.model.entity_id
 43    }
 44
 45    fn downgrade(&self) -> Self::Weak {
 46        WeakView {
 47            model: self.model.downgrade(),
 48        }
 49    }
 50
 51    fn upgrade_from(weak: &Self::Weak) -> Option<Self>
 52    where
 53        Self: Sized,
 54    {
 55        let model = weak.model.upgrade()?;
 56        Some(View { model })
 57    }
 58}
 59
 60impl<V: 'static> View<V> {
 61    /// Convert this strong view reference into a weak view reference.
 62    pub fn downgrade(&self) -> WeakView<V> {
 63        Entity::downgrade(self)
 64    }
 65
 66    /// Updates the view's state with the given function, which is passed a mutable reference and a context.
 67    pub fn update<C, R>(
 68        &self,
 69        cx: &mut C,
 70        f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
 71    ) -> C::Result<R>
 72    where
 73        C: VisualContext,
 74    {
 75        cx.update_view(self, f)
 76    }
 77
 78    /// Obtain a read-only reference to this view's state.
 79    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
 80        self.model.read(cx)
 81    }
 82
 83    /// Gets a [FocusHandle] for this view when its state implements [FocusableView].
 84    pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
 85    where
 86        V: FocusableView,
 87    {
 88        self.read(cx).focus_handle(cx)
 89    }
 90}
 91
 92impl<V: Render> Element for View<V> {
 93    type RequestLayoutState = AnyElement;
 94    type PrepaintState = ();
 95
 96    fn id(&self) -> Option<ElementId> {
 97        Some(ElementId::View(self.entity_id()))
 98    }
 99
100    fn request_layout(
101        &mut self,
102        _id: Option<&GlobalElementId>,
103        cx: &mut WindowContext,
104    ) -> (LayoutId, Self::RequestLayoutState) {
105        let mut element = self.update(cx, |view, cx| view.render(cx).into_any_element());
106        let layout_id = element.request_layout(cx);
107        (layout_id, element)
108    }
109
110    fn prepaint(
111        &mut self,
112        _id: Option<&GlobalElementId>,
113        _: Bounds<Pixels>,
114        element: &mut Self::RequestLayoutState,
115        cx: &mut WindowContext,
116    ) {
117        cx.set_view_id(self.entity_id());
118        element.prepaint(cx);
119    }
120
121    fn paint(
122        &mut self,
123        _id: Option<&GlobalElementId>,
124        _: Bounds<Pixels>,
125        element: &mut Self::RequestLayoutState,
126        _: &mut Self::PrepaintState,
127        cx: &mut WindowContext,
128    ) {
129        element.paint(cx);
130    }
131}
132
133impl<V> Clone for View<V> {
134    fn clone(&self) -> Self {
135        Self {
136            model: self.model.clone(),
137        }
138    }
139}
140
141impl<T> std::fmt::Debug for View<T> {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct(&format!("View<{}>", type_name::<T>()))
144            .field("entity_id", &self.model.entity_id)
145            .finish_non_exhaustive()
146    }
147}
148
149impl<V> Hash for View<V> {
150    fn hash<H: Hasher>(&self, state: &mut H) {
151        self.model.hash(state);
152    }
153}
154
155impl<V> PartialEq for View<V> {
156    fn eq(&self, other: &Self) -> bool {
157        self.model == other.model
158    }
159}
160
161impl<V> Eq for View<V> {}
162
163/// A weak variant of [View] which does not prevent the view from being released.
164pub struct WeakView<V> {
165    pub(crate) model: WeakModel<V>,
166}
167
168impl<V: 'static> WeakView<V> {
169    /// Gets the entity id associated with this handle.
170    pub fn entity_id(&self) -> EntityId {
171        self.model.entity_id
172    }
173
174    /// Obtain a strong handle for the view if it hasn't been released.
175    pub fn upgrade(&self) -> Option<View<V>> {
176        Entity::upgrade_from(self)
177    }
178
179    /// Updates this view's state if it hasn't been released.
180    /// Returns an error if this view has been released.
181    pub fn update<C, R>(
182        &self,
183        cx: &mut C,
184        f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
185    ) -> Result<R>
186    where
187        C: VisualContext,
188        Result<C::Result<R>>: Flatten<R>,
189    {
190        let view = self.upgrade().context("error upgrading view")?;
191        Ok(view.update(cx, f)).flatten()
192    }
193
194    /// Assert that the view referenced by this handle has been released.
195    #[cfg(any(test, feature = "test-support"))]
196    pub fn assert_released(&self) {
197        self.model.assert_released()
198    }
199}
200
201impl<V> Clone for WeakView<V> {
202    fn clone(&self) -> Self {
203        Self {
204            model: self.model.clone(),
205        }
206    }
207}
208
209impl<V> Hash for WeakView<V> {
210    fn hash<H: Hasher>(&self, state: &mut H) {
211        self.model.hash(state);
212    }
213}
214
215impl<V> PartialEq for WeakView<V> {
216    fn eq(&self, other: &Self) -> bool {
217        self.model == other.model
218    }
219}
220
221impl<V> Eq for WeakView<V> {}
222
223/// A dynamically-typed handle to a view, which can be downcast to a [View] for a specific type.
224#[derive(Clone, Debug)]
225pub struct AnyView {
226    model: AnyModel,
227    render: fn(&AnyView, &mut WindowContext) -> AnyElement,
228    cached_style: Option<StyleRefinement>,
229}
230
231impl AnyView {
232    /// Indicate that this view should be cached when using it as an element.
233    /// When using this method, the view's previous layout and paint will be recycled from the previous frame if [ViewContext::notify] has not been called since it was rendered.
234    /// The one exception is when [WindowContext::refresh] is called, in which case caching is ignored.
235    pub fn cached(mut self, style: StyleRefinement) -> Self {
236        self.cached_style = Some(style);
237        self
238    }
239
240    /// Convert this to a weak handle.
241    pub fn downgrade(&self) -> AnyWeakView {
242        AnyWeakView {
243            model: self.model.downgrade(),
244            render: self.render,
245        }
246    }
247
248    /// Convert this to a [View] of a specific type.
249    /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
250    pub fn downcast<T: 'static>(self) -> Result<View<T>, Self> {
251        match self.model.downcast() {
252            Ok(model) => Ok(View { model }),
253            Err(model) => Err(Self {
254                model,
255                render: self.render,
256                cached_style: self.cached_style,
257            }),
258        }
259    }
260
261    /// Gets the [TypeId] of the underlying view.
262    pub fn entity_type(&self) -> TypeId {
263        self.model.entity_type
264    }
265
266    /// Gets the entity id of this handle.
267    pub fn entity_id(&self) -> EntityId {
268        self.model.entity_id()
269    }
270}
271
272impl<V: Render> From<View<V>> for AnyView {
273    fn from(value: View<V>) -> Self {
274        AnyView {
275            model: value.model.into_any(),
276            render: any_view::render::<V>,
277            cached_style: None,
278        }
279    }
280}
281
282impl Element for AnyView {
283    type RequestLayoutState = Option<AnyElement>;
284    type PrepaintState = Option<AnyElement>;
285
286    fn id(&self) -> Option<ElementId> {
287        Some(ElementId::View(self.entity_id()))
288    }
289
290    fn request_layout(
291        &mut self,
292        _id: Option<&GlobalElementId>,
293        cx: &mut WindowContext,
294    ) -> (LayoutId, Self::RequestLayoutState) {
295        if let Some(style) = self.cached_style.as_ref() {
296            let mut root_style = Style::default();
297            root_style.refine(style);
298            let layout_id = cx.request_layout(&root_style, None);
299            (layout_id, None)
300        } else {
301            let mut element = (self.render)(self, cx);
302            let layout_id = element.request_layout(cx);
303            (layout_id, Some(element))
304        }
305    }
306
307    fn prepaint(
308        &mut self,
309        global_id: Option<&GlobalElementId>,
310        bounds: Bounds<Pixels>,
311        element: &mut Self::RequestLayoutState,
312        cx: &mut WindowContext,
313    ) -> Option<AnyElement> {
314        cx.set_view_id(self.entity_id());
315        if self.cached_style.is_some() {
316            cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
317                let content_mask = cx.content_mask();
318                let text_style = cx.text_style();
319
320                if let Some(mut element_state) = element_state {
321                    if element_state.cache_key.bounds == bounds
322                        && element_state.cache_key.content_mask == content_mask
323                        && element_state.cache_key.text_style == text_style
324                        && !cx.window.dirty_views.contains(&self.entity_id())
325                        && !cx.window.refreshing
326                    {
327                        let prepaint_start = cx.prepaint_index();
328                        cx.reuse_prepaint(element_state.prepaint_range.clone());
329                        let prepaint_end = cx.prepaint_index();
330                        element_state.prepaint_range = prepaint_start..prepaint_end;
331                        return (None, element_state);
332                    }
333                }
334
335                let prepaint_start = cx.prepaint_index();
336                let mut element = (self.render)(self, cx);
337                element.layout_as_root(bounds.size.into(), cx);
338                element.prepaint_at(bounds.origin, cx);
339                let prepaint_end = cx.prepaint_index();
340
341                (
342                    Some(element),
343                    AnyViewState {
344                        prepaint_range: prepaint_start..prepaint_end,
345                        paint_range: PaintIndex::default()..PaintIndex::default(),
346                        cache_key: ViewCacheKey {
347                            bounds,
348                            content_mask,
349                            text_style,
350                        },
351                    },
352                )
353            })
354        } else {
355            let mut element = element.take().unwrap();
356            element.prepaint(cx);
357            Some(element)
358        }
359    }
360
361    fn paint(
362        &mut self,
363        global_id: Option<&GlobalElementId>,
364        _bounds: Bounds<Pixels>,
365        _: &mut Self::RequestLayoutState,
366        element: &mut Self::PrepaintState,
367        cx: &mut WindowContext,
368    ) {
369        if self.cached_style.is_some() {
370            cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
371                let mut element_state = element_state.unwrap();
372
373                let paint_start = cx.paint_index();
374
375                if let Some(element) = element {
376                    element.paint(cx);
377                } else {
378                    cx.reuse_paint(element_state.paint_range.clone());
379                }
380
381                let paint_end = cx.paint_index();
382                element_state.paint_range = paint_start..paint_end;
383
384                ((), element_state)
385            })
386        } else {
387            element.as_mut().unwrap().paint(cx);
388        }
389    }
390}
391
392impl<V: 'static + Render> IntoElement for View<V> {
393    type Element = View<V>;
394
395    fn into_element(self) -> Self::Element {
396        self
397    }
398}
399
400impl IntoElement for AnyView {
401    type Element = Self;
402
403    fn into_element(self) -> Self::Element {
404        self
405    }
406}
407
408/// A weak, dynamically-typed view handle that does not prevent the view from being released.
409pub struct AnyWeakView {
410    model: AnyWeakModel,
411    render: fn(&AnyView, &mut WindowContext) -> AnyElement,
412}
413
414impl AnyWeakView {
415    /// Convert to a strongly-typed handle if the referenced view has not yet been released.
416    pub fn upgrade(&self) -> Option<AnyView> {
417        let model = self.model.upgrade()?;
418        Some(AnyView {
419            model,
420            render: self.render,
421            cached_style: None,
422        })
423    }
424}
425
426impl<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
427    fn from(view: WeakView<V>) -> Self {
428        Self {
429            model: view.model.into(),
430            render: any_view::render::<V>,
431        }
432    }
433}
434
435impl PartialEq for AnyWeakView {
436    fn eq(&self, other: &Self) -> bool {
437        self.model == other.model
438    }
439}
440
441impl std::fmt::Debug for AnyWeakView {
442    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443        f.debug_struct("AnyWeakView")
444            .field("entity_id", &self.model.entity_id)
445            .finish_non_exhaustive()
446    }
447}
448
449mod any_view {
450    use crate::{AnyElement, AnyView, IntoElement, Render, WindowContext};
451
452    pub(crate) fn render<V: 'static + Render>(
453        view: &AnyView,
454        cx: &mut WindowContext,
455    ) -> AnyElement {
456        let view = view.clone().downcast::<V>().unwrap();
457        view.update(cx, |view, cx| view.render(cx).into_any_element())
458    }
459}