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