1use crate::{
2 seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, Bounds, ContentMask, Element,
3 ElementContext, ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, IntoElement,
4 LayoutId, Model, PaintIndex, Pixels, PrepaintStateIndex, Render, Style, StyleRefinement,
5 TextStyle, ViewContext, VisualContext, WeakModel,
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 request_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::RequestLayoutState) {
97 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
98 let mut element = self.update(cx, |view, cx| view.render(cx).into_any_element());
99 let layout_id = element.request_layout(cx);
100 (layout_id, element)
101 })
102 }
103
104 fn prepaint(
105 &mut self,
106 _: Bounds<Pixels>,
107 element: &mut Self::RequestLayoutState,
108 cx: &mut ElementContext,
109 ) {
110 cx.set_view_id(self.entity_id());
111 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
112 element.prepaint(cx)
113 })
114 }
115
116 fn paint(
117 &mut self,
118 _: Bounds<Pixels>,
119 element: &mut Self::RequestLayoutState,
120 _: &mut Self::PrepaintState,
121 cx: &mut ElementContext,
122 ) {
123 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
124 element.paint(cx)
125 })
126 }
127}
128
129impl<V> Clone for View<V> {
130 fn clone(&self) -> Self {
131 Self {
132 model: self.model.clone(),
133 }
134 }
135}
136
137impl<T> std::fmt::Debug for View<T> {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.debug_struct(&format!("View<{}>", type_name::<T>()))
140 .field("entity_id", &self.model.entity_id)
141 .finish_non_exhaustive()
142 }
143}
144
145impl<V> Hash for View<V> {
146 fn hash<H: Hasher>(&self, state: &mut H) {
147 self.model.hash(state);
148 }
149}
150
151impl<V> PartialEq for View<V> {
152 fn eq(&self, other: &Self) -> bool {
153 self.model == other.model
154 }
155}
156
157impl<V> Eq for View<V> {}
158
159/// A weak variant of [View] which does not prevent the view from being released.
160pub struct WeakView<V> {
161 pub(crate) model: WeakModel<V>,
162}
163
164impl<V: 'static> WeakView<V> {
165 /// Gets the entity id associated with this handle.
166 pub fn entity_id(&self) -> EntityId {
167 self.model.entity_id
168 }
169
170 /// Obtain a strong handle for the view if it hasn't been released.
171 pub fn upgrade(&self) -> Option<View<V>> {
172 Entity::upgrade_from(self)
173 }
174
175 /// Updates this view's state if it hasn't been released.
176 /// Returns an error if this view has been released.
177 pub fn update<C, R>(
178 &self,
179 cx: &mut C,
180 f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
181 ) -> Result<R>
182 where
183 C: VisualContext,
184 Result<C::Result<R>>: Flatten<R>,
185 {
186 let view = self.upgrade().context("error upgrading view")?;
187 Ok(view.update(cx, f)).flatten()
188 }
189
190 /// Assert that the view referenced by this handle has been released.
191 #[cfg(any(test, feature = "test-support"))]
192 pub fn assert_released(&self) {
193 self.model.assert_released()
194 }
195}
196
197impl<V> Clone for WeakView<V> {
198 fn clone(&self) -> Self {
199 Self {
200 model: self.model.clone(),
201 }
202 }
203}
204
205impl<V> Hash for WeakView<V> {
206 fn hash<H: Hasher>(&self, state: &mut H) {
207 self.model.hash(state);
208 }
209}
210
211impl<V> PartialEq for WeakView<V> {
212 fn eq(&self, other: &Self) -> bool {
213 self.model == other.model
214 }
215}
216
217impl<V> Eq for WeakView<V> {}
218
219/// A dynamically-typed handle to a view, which can be downcast to a [View] for a specific type.
220#[derive(Clone, Debug)]
221pub struct AnyView {
222 model: AnyModel,
223 render: fn(&AnyView, &mut ElementContext) -> AnyElement,
224 cached_style: Option<StyleRefinement>,
225}
226
227impl AnyView {
228 /// Indicate that this view should be cached when using it as an element.
229 /// 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.
230 /// The one exception is when [WindowContext::refresh] is called, in which case caching is ignored.
231 pub fn cached(mut self, style: StyleRefinement) -> Self {
232 self.cached_style = Some(style);
233 self
234 }
235
236 /// Convert this to a weak handle.
237 pub fn downgrade(&self) -> AnyWeakView {
238 AnyWeakView {
239 model: self.model.downgrade(),
240 render: self.render,
241 }
242 }
243
244 /// Convert this to a [View] of a specific type.
245 /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
246 pub fn downcast<T: 'static>(self) -> Result<View<T>, Self> {
247 match self.model.downcast() {
248 Ok(model) => Ok(View { model }),
249 Err(model) => Err(Self {
250 model,
251 render: self.render,
252 cached_style: self.cached_style,
253 }),
254 }
255 }
256
257 /// Gets the [TypeId] of the underlying view.
258 pub fn entity_type(&self) -> TypeId {
259 self.model.entity_type
260 }
261
262 /// Gets the entity id of this handle.
263 pub fn entity_id(&self) -> EntityId {
264 self.model.entity_id()
265 }
266}
267
268impl<V: Render> From<View<V>> for AnyView {
269 fn from(value: View<V>) -> Self {
270 AnyView {
271 model: value.model.into_any(),
272 render: any_view::render::<V>,
273 cached_style: None,
274 }
275 }
276}
277
278impl Element for AnyView {
279 type RequestLayoutState = Option<AnyElement>;
280 type PrepaintState = Option<AnyElement>;
281
282 fn request_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::RequestLayoutState) {
283 if let Some(style) = self.cached_style.as_ref() {
284 let mut root_style = Style::default();
285 root_style.refine(style);
286 let layout_id = cx.request_layout(&root_style, None);
287 (layout_id, None)
288 } else {
289 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
290 let mut element = (self.render)(self, cx);
291 let layout_id = element.request_layout(cx);
292 (layout_id, Some(element))
293 })
294 }
295 }
296
297 fn prepaint(
298 &mut self,
299 bounds: Bounds<Pixels>,
300 element: &mut Self::RequestLayoutState,
301 cx: &mut ElementContext,
302 ) -> Option<AnyElement> {
303 cx.set_view_id(self.entity_id());
304 if self.cached_style.is_some() {
305 cx.with_element_state::<AnyViewState, _>(
306 Some(ElementId::View(self.entity_id())),
307 |element_state, cx| {
308 let mut element_state = element_state.unwrap();
309
310 let content_mask = cx.content_mask();
311 let text_style = cx.text_style();
312
313 if let Some(mut element_state) = element_state {
314 if element_state.cache_key.bounds == bounds
315 && element_state.cache_key.content_mask == content_mask
316 && element_state.cache_key.text_style == text_style
317 && !cx.window.dirty_views.contains(&self.entity_id())
318 && !cx.window.refreshing
319 {
320 let prepaint_start = cx.prepaint_index();
321 cx.reuse_prepaint(element_state.prepaint_range.clone());
322 let prepaint_end = cx.prepaint_index();
323 element_state.prepaint_range = prepaint_start..prepaint_end;
324 return (None, Some(element_state));
325 }
326 }
327
328 let prepaint_start = cx.prepaint_index();
329 let mut element = (self.render)(self, cx);
330 element.layout_as_root(bounds.size.into(), cx);
331 element.prepaint_at(bounds.origin, cx);
332 let prepaint_end = cx.prepaint_index();
333
334 (
335 Some(element),
336 Some(AnyViewState {
337 prepaint_range: prepaint_start..prepaint_end,
338 paint_range: PaintIndex::default()..PaintIndex::default(),
339 cache_key: ViewCacheKey {
340 bounds,
341 content_mask,
342 text_style,
343 },
344 }),
345 )
346 },
347 )
348 } else {
349 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
350 let mut element = element.take().unwrap();
351 element.prepaint(cx);
352 Some(element)
353 })
354 }
355 }
356
357 fn paint(
358 &mut self,
359 _bounds: Bounds<Pixels>,
360 _: &mut Self::RequestLayoutState,
361 element: &mut Self::PrepaintState,
362 cx: &mut ElementContext,
363 ) {
364 if self.cached_style.is_some() {
365 cx.with_element_state::<AnyViewState, _>(
366 Some(ElementId::View(self.entity_id())),
367 |element_state, cx| {
368 let mut element_state = element_state.unwrap().unwrap();
369
370 let paint_start = cx.paint_index();
371
372 if let Some(element) = element {
373 element.paint(cx);
374 } else {
375 cx.reuse_paint(element_state.paint_range.clone());
376 }
377
378 let paint_end = cx.paint_index();
379 element_state.paint_range = paint_start..paint_end;
380
381 ((), Some(element_state))
382 },
383 )
384 } else {
385 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
386 element.as_mut().unwrap().paint(cx);
387 })
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 ElementContext) -> 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, ElementContext, IntoElement, Render};
451
452 pub(crate) fn render<V: 'static + Render>(
453 view: &AnyView,
454 cx: &mut ElementContext,
455 ) -> AnyElement {
456 let view = view.clone().downcast::<V>().unwrap();
457 view.update(cx, |view, cx| view.render(cx).into_any_element())
458 }
459}