1use crate::{
2 private::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace, BorrowWindow,
3 Bounds, Element, ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, IntoElement,
4 LayoutId, Model, Pixels, Point, Render, Size, ViewContext, VisualContext, WeakModel,
5 WindowContext,
6};
7use anyhow::{Context, Result};
8use std::{
9 any::TypeId,
10 fmt,
11 hash::{Hash, Hasher},
12};
13
14pub struct View<V> {
15 pub model: Model<V>,
16}
17
18impl<V> Sealed for View<V> {}
19
20impl<V: 'static> Entity<V> for View<V> {
21 type Weak = WeakView<V>;
22
23 fn entity_id(&self) -> EntityId {
24 self.model.entity_id
25 }
26
27 fn downgrade(&self) -> Self::Weak {
28 WeakView {
29 model: self.model.downgrade(),
30 }
31 }
32
33 fn upgrade_from(weak: &Self::Weak) -> Option<Self>
34 where
35 Self: Sized,
36 {
37 let model = weak.model.upgrade()?;
38 Some(View { model })
39 }
40}
41
42impl<V: 'static> View<V> {
43 /// Convert this strong view reference into a weak view reference.
44 pub fn downgrade(&self) -> WeakView<V> {
45 Entity::downgrade(self)
46 }
47
48 pub fn update<C, R>(
49 &self,
50 cx: &mut C,
51 f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
52 ) -> C::Result<R>
53 where
54 C: VisualContext,
55 {
56 cx.update_view(self, f)
57 }
58
59 pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
60 self.model.read(cx)
61 }
62
63 // pub fn render_with<E>(&self, component: E) -> RenderViewWith<E, V>
64 // where
65 // E: 'static + Element,
66 // {
67 // RenderViewWith {
68 // view: self.clone(),
69 // element: Some(component),
70 // }
71 // }
72
73 pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
74 where
75 V: FocusableView,
76 {
77 self.read(cx).focus_handle(cx)
78 }
79}
80
81impl<V: Render> Element for View<V> {
82 type State = Option<AnyElement>;
83
84 fn request_layout(
85 &mut self,
86 _state: Option<Self::State>,
87 cx: &mut WindowContext,
88 ) -> (LayoutId, Self::State) {
89 let mut element = self.update(cx, |view, cx| view.render(cx).into_any_element());
90 let layout_id = element.request_layout(cx);
91 (layout_id, Some(element))
92 }
93
94 fn paint(&mut self, _: Bounds<Pixels>, element: &mut Self::State, cx: &mut WindowContext) {
95 element.take().unwrap().paint(cx);
96 }
97}
98
99impl<V> Clone for View<V> {
100 fn clone(&self) -> Self {
101 Self {
102 model: self.model.clone(),
103 }
104 }
105}
106
107impl<V> Hash for View<V> {
108 fn hash<H: Hasher>(&self, state: &mut H) {
109 self.model.hash(state);
110 }
111}
112
113impl<V> PartialEq for View<V> {
114 fn eq(&self, other: &Self) -> bool {
115 self.model == other.model
116 }
117}
118
119impl<V> Eq for View<V> {}
120
121pub struct WeakView<V> {
122 pub(crate) model: WeakModel<V>,
123}
124
125impl<V: 'static> WeakView<V> {
126 pub fn entity_id(&self) -> EntityId {
127 self.model.entity_id
128 }
129
130 pub fn upgrade(&self) -> Option<View<V>> {
131 Entity::upgrade_from(self)
132 }
133
134 pub fn update<C, R>(
135 &self,
136 cx: &mut C,
137 f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
138 ) -> Result<R>
139 where
140 C: VisualContext,
141 Result<C::Result<R>>: Flatten<R>,
142 {
143 let view = self.upgrade().context("error upgrading view")?;
144 Ok(view.update(cx, f)).flatten()
145 }
146
147 #[cfg(any(test, feature = "test-support"))]
148 pub fn assert_dropped(&self) {
149 self.model.assert_dropped()
150 }
151}
152
153impl<V> Clone for WeakView<V> {
154 fn clone(&self) -> Self {
155 Self {
156 model: self.model.clone(),
157 }
158 }
159}
160
161impl<V> Hash for WeakView<V> {
162 fn hash<H: Hasher>(&self, state: &mut H) {
163 self.model.hash(state);
164 }
165}
166
167impl<V> PartialEq for WeakView<V> {
168 fn eq(&self, other: &Self) -> bool {
169 self.model == other.model
170 }
171}
172
173impl<V> Eq for WeakView<V> {}
174
175#[derive(Clone, Debug)]
176pub struct AnyView {
177 model: AnyModel,
178 layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement),
179 paint: fn(&AnyView, &mut AnyElement, &mut WindowContext),
180}
181
182impl AnyView {
183 pub fn downgrade(&self) -> AnyWeakView {
184 AnyWeakView {
185 model: self.model.downgrade(),
186 layout: self.layout,
187 paint: self.paint,
188 }
189 }
190
191 pub fn downcast<T: 'static>(self) -> Result<View<T>, Self> {
192 match self.model.downcast() {
193 Ok(model) => Ok(View { model }),
194 Err(model) => Err(Self {
195 model,
196 layout: self.layout,
197 paint: self.paint,
198 }),
199 }
200 }
201
202 pub fn entity_type(&self) -> TypeId {
203 self.model.entity_type
204 }
205
206 pub fn entity_id(&self) -> EntityId {
207 self.model.entity_id()
208 }
209
210 pub(crate) fn draw(
211 &self,
212 origin: Point<Pixels>,
213 available_space: Size<AvailableSpace>,
214 cx: &mut WindowContext,
215 ) {
216 cx.with_absolute_element_offset(origin, |cx| {
217 let (layout_id, mut rendered_element) = (self.layout)(self, cx);
218 cx.compute_layout(layout_id, available_space);
219 (self.paint)(self, &mut rendered_element, cx);
220 })
221 }
222}
223
224impl<V: Render> From<View<V>> for AnyView {
225 fn from(value: View<V>) -> Self {
226 AnyView {
227 model: value.model.into_any(),
228 layout: any_view::layout::<V>,
229 paint: any_view::paint,
230 }
231 }
232}
233
234impl Element for AnyView {
235 type State = Option<AnyElement>;
236
237 fn request_layout(
238 &mut self,
239 _state: Option<Self::State>,
240 cx: &mut WindowContext,
241 ) -> (LayoutId, Self::State) {
242 let (layout_id, state) = (self.layout)(self, cx);
243 (layout_id, Some(state))
244 }
245
246 fn paint(&mut self, _: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
247 debug_assert!(
248 state.is_some(),
249 "state is None. Did you include an AnyView twice in the tree?"
250 );
251 (self.paint)(self, state.as_mut().unwrap(), cx)
252 }
253}
254
255impl<V: 'static + Render> IntoElement for View<V> {
256 type Element = View<V>;
257
258 fn element_id(&self) -> Option<ElementId> {
259 Some(ElementId::from_entity_id(self.model.entity_id))
260 }
261
262 fn into_element(self) -> Self::Element {
263 self
264 }
265}
266
267impl IntoElement for AnyView {
268 type Element = Self;
269
270 fn element_id(&self) -> Option<ElementId> {
271 Some(ElementId::from_entity_id(self.model.entity_id))
272 }
273
274 fn into_element(self) -> Self::Element {
275 self
276 }
277}
278
279pub struct AnyWeakView {
280 model: AnyWeakModel,
281 layout: fn(&AnyView, &mut WindowContext) -> (LayoutId, AnyElement),
282 paint: fn(&AnyView, &mut AnyElement, &mut WindowContext),
283}
284
285impl AnyWeakView {
286 pub fn upgrade(&self) -> Option<AnyView> {
287 let model = self.model.upgrade()?;
288 Some(AnyView {
289 model,
290 layout: self.layout,
291 paint: self.paint,
292 })
293 }
294}
295
296impl<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
297 fn from(view: WeakView<V>) -> Self {
298 Self {
299 model: view.model.into(),
300 layout: any_view::layout::<V>,
301 paint: any_view::paint,
302 }
303 }
304}
305
306impl PartialEq for AnyWeakView {
307 fn eq(&self, other: &Self) -> bool {
308 self.model == other.model
309 }
310}
311
312impl std::fmt::Debug for AnyWeakView {
313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314 f.debug_struct("AnyWeakView")
315 .field("entity_id", &self.model.entity_id)
316 .finish_non_exhaustive()
317 }
318}
319
320mod any_view {
321 use crate::{AnyElement, AnyView, IntoElement, LayoutId, Render, WindowContext};
322
323 pub(crate) fn layout<V: 'static + Render>(
324 view: &AnyView,
325 cx: &mut WindowContext,
326 ) -> (LayoutId, AnyElement) {
327 let view = view.clone().downcast::<V>().unwrap();
328 let mut element = view.update(cx, |view, cx| view.render(cx).into_any_element());
329 let layout_id = element.request_layout(cx);
330 (layout_id, element)
331 }
332
333 pub(crate) fn paint(_view: &AnyView, element: &mut AnyElement, cx: &mut WindowContext) {
334 element.paint(cx);
335 }
336}