1use crate::{
2 seal::Sealed, AfterLayoutIndex, AnyElement, AnyModel, AnyWeakModel, AppContext, Bounds,
3 ContentMask, Element, ElementContext, ElementId, Entity, EntityId, Flatten, FocusHandle,
4 FocusableView, IntoElement, LayoutId, Model, PaintIndex, Pixels, Render, Style,
5 StyleRefinement, 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 after_layout_range: Range<AfterLayoutIndex>,
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 BeforeLayout = AnyElement;
94 type AfterLayout = ();
95
96 fn before_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::BeforeLayout) {
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.before_layout(cx);
100 (layout_id, element)
101 })
102 }
103
104 fn after_layout(
105 &mut self,
106 _: Bounds<Pixels>,
107 element: &mut Self::BeforeLayout,
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.after_layout(cx)
113 })
114 }
115
116 fn paint(
117 &mut self,
118 _: Bounds<Pixels>,
119 element: &mut Self::BeforeLayout,
120 _: &mut Self::AfterLayout,
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 BeforeLayout = Option<AnyElement>;
280 type AfterLayout = Option<AnyElement>;
281
282 fn before_layout(&mut self, cx: &mut ElementContext) -> (LayoutId, Self::BeforeLayout) {
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.before_layout(cx);
292 (layout_id, Some(element))
293 })
294 }
295 }
296
297 fn after_layout(
298 &mut self,
299 bounds: Bounds<Pixels>,
300 element: &mut Self::BeforeLayout,
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 after_layout_start = cx.after_layout_index();
321 cx.reuse_after_layout(element_state.after_layout_range.clone());
322 let after_layout_end = cx.after_layout_index();
323 element_state.after_layout_range = after_layout_start..after_layout_end;
324 return (None, Some(element_state));
325 }
326 }
327
328 let after_layout_start = cx.after_layout_index();
329 let mut element = (self.render)(self, cx);
330 element.layout(bounds.origin, bounds.size.into(), cx);
331 let after_layout_end = cx.after_layout_index();
332
333 (
334 Some(element),
335 Some(AnyViewState {
336 after_layout_range: after_layout_start..after_layout_end,
337 paint_range: PaintIndex::default()..PaintIndex::default(),
338 cache_key: ViewCacheKey {
339 bounds,
340 content_mask,
341 text_style,
342 },
343 }),
344 )
345 },
346 )
347 } else {
348 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
349 let mut element = element.take().unwrap();
350 element.after_layout(cx);
351 Some(element)
352 })
353 }
354 }
355
356 fn paint(
357 &mut self,
358 _bounds: Bounds<Pixels>,
359 _: &mut Self::BeforeLayout,
360 element: &mut Self::AfterLayout,
361 cx: &mut ElementContext,
362 ) {
363 if self.cached_style.is_some() {
364 cx.with_element_state::<AnyViewState, _>(
365 Some(ElementId::View(self.entity_id())),
366 |element_state, cx| {
367 let mut element_state = element_state.unwrap().unwrap();
368
369 let paint_start = cx.paint_index();
370
371 if let Some(element) = element {
372 element.paint(cx);
373 } else {
374 cx.reuse_paint(element_state.paint_range.clone());
375 }
376
377 let paint_end = cx.paint_index();
378 element_state.paint_range = paint_start..paint_end;
379
380 ((), Some(element_state))
381 },
382 )
383 } else {
384 cx.with_element_id(Some(ElementId::View(self.entity_id())), |cx| {
385 element.as_mut().unwrap().paint(cx);
386 })
387 }
388 }
389}
390
391impl<V: 'static + Render> IntoElement for View<V> {
392 type Element = View<V>;
393
394 fn into_element(self) -> Self::Element {
395 self
396 }
397}
398
399impl IntoElement for AnyView {
400 type Element = Self;
401
402 fn into_element(self) -> Self::Element {
403 self
404 }
405}
406
407/// A weak, dynamically-typed view handle that does not prevent the view from being released.
408pub struct AnyWeakView {
409 model: AnyWeakModel,
410 render: fn(&AnyView, &mut ElementContext) -> AnyElement,
411}
412
413impl AnyWeakView {
414 /// Convert to a strongly-typed handle if the referenced view has not yet been released.
415 pub fn upgrade(&self) -> Option<AnyView> {
416 let model = self.model.upgrade()?;
417 Some(AnyView {
418 model,
419 render: self.render,
420 cached_style: None,
421 })
422 }
423}
424
425impl<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
426 fn from(view: WeakView<V>) -> Self {
427 Self {
428 model: view.model.into(),
429 render: any_view::render::<V>,
430 }
431 }
432}
433
434impl PartialEq for AnyWeakView {
435 fn eq(&self, other: &Self) -> bool {
436 self.model == other.model
437 }
438}
439
440impl std::fmt::Debug for AnyWeakView {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 f.debug_struct("AnyWeakView")
443 .field("entity_id", &self.model.entity_id)
444 .finish_non_exhaustive()
445 }
446}
447
448mod any_view {
449 use crate::{AnyElement, AnyView, ElementContext, IntoElement, Render};
450
451 pub(crate) fn render<V: 'static + Render>(
452 view: &AnyView,
453 cx: &mut ElementContext,
454 ) -> AnyElement {
455 let view = view.clone().downcast::<V>().unwrap();
456 view.update(cx, |view, cx| view.render(cx).into_any_element())
457 }
458}