1use crate::{
2 AnyElement, AnyEntity, AnyWeakEntity, App, AvailableSpace, Bounds, ContentMask, Context,
3 Element, ElementId, Entity, EntityId, GlobalElementId, InspectorElementId, IntoElement,
4 LayoutId, PaintIndex, Pixels, PrepaintStateIndex, Render, RenderOnce, Size, Style,
5 StyleRefinement, TextStyle, WeakEntity,
6};
7use crate::{Empty, Window};
8use anyhow::Result;
9use collections::FxHashSet;
10use refineable::Refineable;
11use std::mem;
12use std::{
13 any::{TypeId, type_name},
14 fmt,
15 ops::Range,
16};
17
18#[derive(Clone, Debug)]
24pub struct AnyView {
25 entity: AnyEntity,
26 render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
27 view_type_name: &'static str,
28}
29
30impl<V: Render> From<Entity<V>> for AnyView {
31 fn from(value: Entity<V>) -> Self {
32 AnyView {
33 entity: value.into_any(),
34 render: any_view::render::<V>,
35 view_type_name: type_name::<V>(),
36 }
37 }
38}
39
40impl AnyView {
41 pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
47 self.into_element().cached(style)
48 }
49
50 pub fn downgrade(&self) -> AnyWeakView {
52 AnyWeakView {
53 entity: self.entity.downgrade(),
54 render: self.render,
55 view_type_name: self.view_type_name,
56 }
57 }
58
59 pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
62 match self.entity.downcast() {
63 Ok(entity) => Ok(entity),
64 Err(entity) => Err(Self {
65 entity,
66 render: self.render,
67 view_type_name: self.view_type_name,
68 }),
69 }
70 }
71
72 pub fn entity_type(&self) -> TypeId {
74 self.entity.entity_type
75 }
76
77 pub fn entity_id(&self) -> EntityId {
79 self.entity.entity_id()
80 }
81}
82
83impl PartialEq for AnyView {
84 fn eq(&self, other: &Self) -> bool {
85 self.entity == other.entity
86 }
87}
88
89impl Eq for AnyView {}
90
91impl View for AnyView {
95 fn entity_id(&self) -> Option<EntityId> {
96 Some(self.entity.entity_id())
97 }
98
99 #[cfg(not(gpui_hot_reload))]
100 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
101 (self.render)(&self, window, cx)
102 }
103
104 #[cfg(gpui_hot_reload)]
107 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
108 subsecond::HotFn::current(self.render).call((&self, window, cx))
109 }
110}
111
112impl<V: 'static + Render> IntoElement for Entity<V> {
113 type Element = ViewElement<Entity<V>>;
114
115 fn into_element(self) -> Self::Element {
116 ViewElement::with_type_name(self, type_name::<V>())
117 }
118
119 #[inline(never)]
120 fn into_any_element(self) -> AnyElement {
121 self.into_element().into_any()
122 }
123}
124
125impl IntoElement for AnyView {
126 type Element = ViewElement<AnyView>;
127
128 fn into_element(self) -> Self::Element {
129 let view_type_name = self.view_type_name;
130 ViewElement::with_type_name(self, view_type_name)
131 }
132}
133
134pub struct AnyWeakView {
136 entity: AnyWeakEntity,
137 render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
138 view_type_name: &'static str,
139}
140
141impl AnyWeakView {
142 pub fn upgrade(&self) -> Option<AnyView> {
144 let entity = self.entity.upgrade()?;
145 Some(AnyView {
146 entity,
147 render: self.render,
148 view_type_name: self.view_type_name,
149 })
150 }
151}
152
153impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
154 fn from(view: WeakEntity<V>) -> Self {
155 AnyWeakView {
156 entity: view.into(),
157 render: any_view::render::<V>,
158 view_type_name: type_name::<V>(),
159 }
160 }
161}
162
163impl PartialEq for AnyWeakView {
164 fn eq(&self, other: &Self) -> bool {
165 self.entity == other.entity
166 }
167}
168
169impl std::fmt::Debug for AnyWeakView {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.debug_struct("AnyWeakView")
172 .field("entity_id", &self.entity.entity_id)
173 .finish_non_exhaustive()
174 }
175}
176
177mod any_view {
178 use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
179
180 pub(crate) fn render<V: 'static + Render>(
181 view: &AnyView,
182 window: &mut Window,
183 cx: &mut App,
184 ) -> AnyElement {
185 let view = view.clone().downcast::<V>().unwrap();
186 #[cfg(debug_assertions)]
189 window
190 .a11y
191 .view_type_names
192 .insert(view.entity_id(), std::any::type_name::<V>());
193 view.update(cx, |view, cx| view.render(window, cx).into_any_element())
194 }
195}
196
197pub trait View: 'static + Sized {
209 fn entity_id(&self) -> Option<EntityId>;
218
219 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
221}
222
223impl<T: RenderOnce> View for T {
225 fn entity_id(&self) -> Option<EntityId> {
226 None
227 }
228
229 #[inline]
230 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
231 RenderOnce::render(self, window, cx)
232 }
233}
234
235impl<T: Render> View for Entity<T> {
237 fn entity_id(&self) -> Option<EntityId> {
238 Some(Entity::entity_id(self))
239 }
240
241 #[inline]
242 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
243 self.update(cx, |this, cx| {
244 Render::render(this, window, cx).into_any_element()
245 })
246 }
247}
248
249impl<T: Render> Entity<T> {
250 #[track_caller]
258 pub fn cached(self, style: StyleRefinement) -> ViewElement<Entity<T>> {
259 ViewElement::with_type_name(self, type_name::<T>()).cached(style)
260 }
261}
262
263#[doc(hidden)]
266pub struct ViewElement<V: View> {
267 view: Option<V>,
268 entity_id: Option<EntityId>,
269 cached_style: Option<StyleRefinement>,
270 #[cfg(feature = "profiler")]
271 view_type_name: &'static str,
272 #[cfg(debug_assertions)]
273 source: &'static core::panic::Location<'static>,
274}
275
276impl<V: View> ViewElement<V> {
277 #[track_caller]
279 pub fn new(view: V) -> Self {
280 Self::with_type_name(view, type_name::<V>())
281 }
282
283 #[track_caller]
286 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
287 pub(crate) fn with_type_name(view: V, view_type_name: &'static str) -> Self {
288 let entity_id = view.entity_id();
289 ViewElement {
290 entity_id,
291 cached_style: None,
292 #[cfg(feature = "profiler")]
293 view_type_name,
294 view: Some(view),
295 #[cfg(debug_assertions)]
296 source: core::panic::Location::caller(),
297 }
298 }
299
300 pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
310 self.cached_style = Some(style);
311 self
312 }
313}
314
315impl<V: View> IntoElement for ViewElement<V> {
316 type Element = Self;
317
318 fn into_element(self) -> Self::Element {
319 self
320 }
321}
322
323struct ViewElementState {
324 prepaint_range: Range<PrepaintStateIndex>,
325 paint_range: Range<PaintIndex>,
326 cache_key: ViewElementCacheKey,
327 accessed_entities: FxHashSet<EntityId>,
328}
329
330struct ViewElementCacheKey {
331 bounds: Bounds<Pixels>,
332 content_mask: ContentMask<Pixels>,
333 text_style: TextStyle,
334 glyph_brush: Option<crate::window::GlyphBrushCacheKey>,
335 layer_captured: bool,
336 layer_clip: Option<Bounds<Pixels>>,
337}
338
339#[cfg(not(gpui_hot_reload))]
340#[inline]
341fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
342 view.render(window, cx).into_any_element()
343}
344
345#[cfg(gpui_hot_reload)]
348fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
349 #[inline(never)]
350 fn render_view_impl<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
351 view.render(window, cx).into_any_element()
352 }
353
354 subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))
355}
356
357impl<V: View> Element for ViewElement<V> {
358 type RequestLayoutState = Option<AnyElement>;
359 type PrepaintState = Option<AnyElement>;
360
361 fn id(&self) -> Option<ElementId> {
362 self.entity_id.map(ElementId::View)
363 }
364
365 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
366 #[cfg(debug_assertions)]
367 return Some(self.source);
368
369 #[cfg(not(debug_assertions))]
370 return None;
371 }
372
373 fn request_layout(
374 &mut self,
375 _id: Option<&GlobalElementId>,
376 _inspector_id: Option<&InspectorElementId>,
377 window: &mut Window,
378 cx: &mut App,
379 ) -> (LayoutId, Self::RequestLayoutState) {
380 if let Some(entity_id) = self.entity_id {
381 #[cfg(feature = "profiler")]
383 let start = window.window_profiler.begin_view();
384 let view = &mut self.view;
385 let layout = request_layout_view(
386 entity_id,
387 self.cached_style.as_ref(),
388 window,
389 cx,
390 &mut |window, cx| render_view(view.take().unwrap(), window, cx),
391 );
392 #[cfg(feature = "profiler")]
393 window.window_profiler.end_view(
394 start,
395 self.view_type_name,
396 crate::profiler::ViewPhase::RequestLayout,
397 );
398 layout
399 } else {
400 request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
402 render_view(self.view.take().unwrap(), window, cx)
403 })
404 }
405 }
406
407 fn prepaint(
408 &mut self,
409 global_id: Option<&GlobalElementId>,
410 _inspector_id: Option<&InspectorElementId>,
411 bounds: Bounds<Pixels>,
412 element: &mut Self::RequestLayoutState,
413 window: &mut Window,
414 cx: &mut App,
415 ) -> Option<AnyElement> {
416 if let Some(entity_id) = self.entity_id {
417 #[cfg(feature = "profiler")]
419 let start = window.window_profiler.begin_view();
420 let prepainted = prepaint_view(
421 entity_id,
422 global_id,
423 bounds,
424 element,
425 window,
426 cx,
427 &mut |window, cx| render_view(self.view.take().unwrap(), window, cx),
428 );
429 #[cfg(feature = "profiler")]
430 window.window_profiler.end_view(
431 start,
432 self.view_type_name,
433 crate::profiler::ViewPhase::Prepaint,
434 );
435 prepainted
436 } else {
437 prepaint_component(type_name::<V>(), element, window, cx)
439 }
440 }
441
442 fn paint(
443 &mut self,
444 global_id: Option<&GlobalElementId>,
445 _inspector_id: Option<&InspectorElementId>,
446 _bounds: Bounds<Pixels>,
447 _request_layout: &mut Self::RequestLayoutState,
448 element: &mut Self::PrepaintState,
449 window: &mut Window,
450 cx: &mut App,
451 ) {
452 if let Some(entity_id) = self.entity_id {
453 #[cfg(feature = "profiler")]
455 let start = window.window_profiler.begin_view();
456 paint_view(
457 entity_id,
458 self.cached_style.is_some(),
459 global_id,
460 element,
461 window,
462 cx,
463 );
464 #[cfg(feature = "profiler")]
465 window.window_profiler.end_view(
466 start,
467 self.view_type_name,
468 crate::profiler::ViewPhase::Paint,
469 );
470 } else {
471 paint_component(std::any::type_name::<V>(), element, window, cx);
473 }
474 }
475}
476
477pub struct EmptyView;
479
480impl Render for EmptyView {
481 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
482 Empty
483 }
484}
485
486#[inline(never)]
487fn request_layout_view(
488 entity_id: EntityId,
489 cached_style: Option<&StyleRefinement>,
490 window: &mut Window,
491 cx: &mut App,
492 render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
493) -> (LayoutId, Option<AnyElement>) {
494 window.with_rendered_view(entity_id, |window| {
495 let caching_disabled = window.is_inspector_picking(cx);
496 match cached_style {
497 Some(style) if !caching_disabled => {
498 let mut root_style = Style::default();
499 root_style.refine(style);
500 let layout_id = window.request_layout(root_style, None, cx);
501 (layout_id, None)
502 }
503 _ => {
504 let mut element = render(window, cx);
505 let layout_id = element.request_layout(window, cx);
506 (layout_id, Some(element))
507 }
508 }
509 })
510}
511
512#[inline(never)]
513fn request_layout_component(
514 name: &'static str,
515 window: &mut Window,
516 cx: &mut App,
517 render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
518) -> (LayoutId, Option<AnyElement>) {
519 window.with_id(ElementId::from(name), |window| {
520 let mut element = render(window, cx);
521 let layout_id = element.request_layout(window, cx);
522 (layout_id, Some(element))
523 })
524}
525
526#[inline(never)]
527fn prepaint_view(
528 entity_id: EntityId,
529 global_id: Option<&GlobalElementId>,
530 bounds: Bounds<Pixels>,
531 element: &mut Option<AnyElement>,
532 window: &mut Window,
533 cx: &mut App,
534 render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
535) -> Option<AnyElement> {
536 window.set_view_id(entity_id);
537 window.with_rendered_view(entity_id, |window| {
538 if let Some(mut element) = element.take() {
539 element.prepaint(window, cx);
540 return Some(element);
541 }
542
543 window.with_element_state::<ViewElementState, _>(
544 global_id.unwrap(),
545 |element_state, window| {
546 let content_mask = window.content_mask();
547 let text_style = window.text_style();
548 let glyph_brush = window.glyph_brush_cache_key();
549 let layer_captured = window.is_layer_captured();
550 let layer_clip = window.layer_capture_visible_bounds();
551
552 if let Some(mut element_state) = element_state
553 && element_state.cache_key.bounds == bounds
554 && element_state.cache_key.content_mask == content_mask
555 && element_state.cache_key.text_style == text_style
556 && element_state.cache_key.glyph_brush == glyph_brush
557 && element_state.cache_key.layer_captured == layer_captured
558 && element_state.cache_key.layer_clip == layer_clip
559 && !window.dirty_views.contains(&entity_id)
560 && !window.refreshing
561 {
562 let prepaint_start = window.prepaint_index();
563 window.reuse_prepaint(element_state.prepaint_range.clone());
564 cx.entities
565 .extend_accessed(&element_state.accessed_entities);
566 let prepaint_end = window.prepaint_index();
567 element_state.prepaint_range = prepaint_start..prepaint_end;
568
569 return (None, element_state);
570 }
571
572 let refreshing = mem::replace(&mut window.refreshing, true);
573 let prepaint_start = window.prepaint_index();
574 let (element, accessed_entities) = cx.detect_accessed_entities(|cx| {
575 let mut element = render(window, cx);
576 element.layout_as_root(Size::<AvailableSpace>::from(bounds.size), window, cx);
577 element.prepaint_at(bounds.origin, window, cx);
578 element
579 });
580
581 let prepaint_end = window.prepaint_index();
582 window.refreshing = refreshing;
583
584 (
585 Some(element),
586 ViewElementState {
587 accessed_entities,
588 prepaint_range: prepaint_start..prepaint_end,
589 paint_range: PaintIndex::default()..PaintIndex::default(),
590 cache_key: ViewElementCacheKey {
591 bounds,
592 content_mask,
593 text_style,
594 glyph_brush,
595 layer_captured,
596 layer_clip,
597 },
598 },
599 )
600 },
601 )
602 })
603}
604
605#[inline(never)]
606fn prepaint_component(
607 name: &'static str,
608 element: &mut Option<AnyElement>,
609 window: &mut Window,
610 cx: &mut App,
611) -> Option<AnyElement> {
612 window.with_id(ElementId::from(name), |window| {
613 element.as_mut().unwrap().prepaint(window, cx);
614 });
615 Some(element.take().unwrap())
616}
617
618#[inline(never)]
619fn paint_view(
620 entity_id: EntityId,
621 cached: bool,
622 global_id: Option<&GlobalElementId>,
623 element: &mut Option<AnyElement>,
624 window: &mut Window,
625 cx: &mut App,
626) {
627 window.with_rendered_view(entity_id, |window| {
628 let caching_disabled = window.is_inspector_picking(cx);
629 if cached && !caching_disabled {
630 window.with_element_state::<ViewElementState, _>(
631 global_id.unwrap(),
632 |element_state, window| {
633 let mut element_state = element_state.unwrap();
634
635 let paint_start = window.paint_index();
636
637 if let Some(element) = element {
638 let refreshing = mem::replace(&mut window.refreshing, true);
639 element.paint(window, cx);
640 window.refreshing = refreshing;
641 } else {
642 window.reuse_paint(element_state.paint_range.clone());
643 }
644
645 let paint_end = window.paint_index();
646 element_state.paint_range = paint_start..paint_end;
647
648 ((), element_state)
649 },
650 )
651 } else {
652 element.as_mut().unwrap().paint(window, cx);
653 }
654 });
655}
656
657#[inline(never)]
658fn paint_component(
659 name: &'static str,
660 element: &mut Option<AnyElement>,
661 window: &mut Window,
662 cx: &mut App,
663) {
664 window.with_id(ElementId::Name(name.into()), |window| {
665 element.as_mut().unwrap().paint(window, cx);
666 });
667}