Skip to main content

gpui/
view.rs

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, TransformationMatrix, 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/// A dynamically-typed view handle that can be downcast to a specific `Entity<V>`.
19///
20/// This is the type-erased counterpart to [`ViewElement`]: it holds an entity plus
21/// a function pointer to its render, and is itself a [`View`], so embedding it as an
22/// element goes through the same [`ViewElement`] machinery as any other view.
23#[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    /// Embed this view as a cached [`ViewElement`] laid out at `style`.
42    ///
43    /// The rendered subtree is recycled from the previous frame unless
44    /// [Context::notify] was called on the backing entity since it was rendered
45    /// (or [Window::refresh] is called, which ignores caching).
46    pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
47        self.into_element().cached(style)
48    }
49
50    /// Convert this to a weak handle.
51    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    /// Convert this to a [Entity] of a specific type.
60    /// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
61    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    /// Gets the [TypeId] of the underlying view.
73    pub fn entity_type(&self) -> TypeId {
74        self.entity.entity_type
75    }
76
77    /// The [`EntityId`] of this view.
78    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
91/// `AnyView` is the type-erased [`View`]: its `render` is a function pointer rather
92/// than a concrete type, but it participates in the reactive graph exactly like any
93/// other view via [`ViewElement`].
94impl 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    // The stored function pointer was captured from the original binary, so it must be looked up
105    // in the jump table to reach the patched render.
106    #[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
134/// A weak, dynamically-typed view handle.
135pub 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    /// Upgrade to a strong `AnyView` handle, if the view is still alive.
143    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        // Record the view's Render type name so the accessibility debug dump can
187        // attribute nodes to the view that produced them.
188        #[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
197/// A renderable that participates in GPUI's reactive graph — the unifying model
198/// behind [`Render`] and [`RenderOnce`].
199///
200/// When `entity_id()` returns `Some`, that id becomes the view's identity: it gets
201/// a unique element-id space (so internal `use_state` / `.id(..)` never collide
202/// across siblings) and `cx.notify()` on that entity re-renders only this view's
203/// subtree. `None` behaves like a stateless component.
204///
205/// You rarely implement `View` directly. `Entity<T: Render>` and any `T: RenderOnce`
206/// get a blanket impl below; implement it by hand only when a component needs both
207/// parent-supplied props *and* a backing entity for identity.
208pub trait View: 'static + Sized {
209    /// This view's identity, if it has one. A view typically holds the backing
210    /// entity as a field and returns its [`EntityId`] here.
211    ///
212    /// The id becomes this view's [`ElementId`], so two views keyed on the same
213    /// entity must not be rendered at the same position in the element tree
214    /// (e.g. as siblings under the same parent): their internal element state
215    /// (`use_state`, scroll offsets, etc.) would silently collide. Nesting is
216    /// fine — the id is scoped by the parent path.
217    fn entity_id(&self) -> Option<EntityId>;
218
219    /// Render this view into an element tree, consuming `self`.
220    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
221}
222
223/// A stateless component (`RenderOnce`) is a `View` with no identity.
224impl<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
235/// An entity that renders itself (`Render`) is a `View` keyed on its own id.
236impl<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    /// Embed this entity as a cached [`ViewElement`] laid out at `style`.
251    ///
252    /// The rendered subtree is reused until the entity is notified (or the
253    /// cached bounds / text style change). Caching requires a definite size:
254    /// a cached view is laid out from `style` and is *not* measured from its
255    /// contents. Use [`ViewElement::new`] (or `.child(entity)`) for the
256    /// uncached case.
257    #[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/// The element type for [`View`] implementations. Wraps a `View` and hooks it
264/// into layout, prepaint, and paint. Constructed via [`ViewElement::new`].
265#[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    /// Wrap a [`View`] as an element.
278    #[track_caller]
279    pub fn new(view: V) -> Self {
280        Self::with_type_name(view, type_name::<V>())
281    }
282
283    /// Wraps a view whose draw time profiling attributes to `view_type_name`,
284    /// such as an entity's type rather than [`Entity`]'s.
285    #[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    /// Enable caching of this view's rendered subtree, laid out at `style`.
301    /// The composer supplies the layout style because caching skips rendering
302    /// the contents to measure them.
303    ///
304    /// Crate-private on purpose: caching is only sound for entity-backed views,
305    /// where [`Context::notify`] is the contract that busts the cache. A stateless
306    /// view has no such contract, so a frozen subtree could never be invalidated.
307    /// Reach this through [`Entity::cached`] or [`AnyView::cached`], which are
308    /// entity-backed by construction.
309    pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
310        self.cached_style = Some(style);
311        self
312    }
313}
314
315struct ViewElementState {
316    prepaint_range: Range<PrepaintStateIndex>,
317    paint_range: Range<PaintIndex>,
318    cache_key: ViewElementCacheKey,
319    /// The entities the view accessed while it was last drawn, in any phase,
320    /// restored when its prepaint is reused so the window stays subscribed.
321    accessed_entities: FxHashSet<EntityId>,
322}
323
324struct ViewElementCacheKey {
325    bounds: Bounds<Pixels>,
326    content_mask: ContentMask<Pixels>,
327    text_style: TextStyle,
328    /// vue-native fork: the opacity and the CSS `transform` the ancestors
329    /// composed. Both are multiplied into every primitive the view paints (and
330    /// the transform into its hitboxes), so a replay under a different one
331    /// paints the recording's: a subtree cached while its dialog faded in
332    /// stayed at the fade's first frames, dim, after the fade had ended. Both
333    /// are pushed in prepaint as well as in paint (`Interactivity::prepaint`),
334    /// to predict the paint state; hover opacity is corrected after painting.
335    opacity: f32,
336    transform: TransformationMatrix,
337    /// vue-native fork: the `clip-path` shapes around the view, which its
338    /// hitboxes carry (`Window::vn_with_clip_shape`).
339    vn_clip: Option<std::sync::Arc<crate::VnClipNode>>,
340}
341
342#[cfg(not(gpui_hot_reload))]
343#[inline]
344fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
345    view.render(window, cx).into_any_element()
346}
347
348/// Every view and component render passes through this hot-patchable boundary, so the
349/// patched code for that render and everything it calls runs on the next frame.
350#[cfg(gpui_hot_reload)]
351fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
352    #[inline(never)]
353    fn render_view_impl<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
354        view.render(window, cx).into_any_element()
355    }
356
357    subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))
358}
359
360impl<V: View> Element for ViewElement<V> {
361    type RequestLayoutState = Option<AnyElement>;
362    type PrepaintState = Option<AnyElement>;
363
364    fn id(&self) -> Option<ElementId> {
365        self.entity_id.map(ElementId::View)
366    }
367
368    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
369        #[cfg(debug_assertions)]
370        return Some(self.source);
371
372        #[cfg(not(debug_assertions))]
373        return None;
374    }
375
376    fn request_layout(
377        &mut self,
378        _id: Option<&GlobalElementId>,
379        _inspector_id: Option<&InspectorElementId>,
380        window: &mut Window,
381        cx: &mut App,
382    ) -> (LayoutId, Self::RequestLayoutState) {
383        if let Some(entity_id) = self.entity_id {
384            // Stateful path: create a reactive boundary.
385            #[cfg(feature = "profiler")]
386            let start = window.window_profiler.begin_view();
387            let view = &mut self.view;
388            let layout = request_layout_view(
389                entity_id,
390                self.cached_style.as_ref(),
391                window,
392                cx,
393                &mut |window, cx| render_view(view.take().unwrap(), window, cx),
394            );
395            #[cfg(feature = "profiler")]
396            window.window_profiler.end_view(
397                start,
398                self.view_type_name,
399                crate::profiler::ViewPhase::RequestLayout,
400            );
401            layout
402        } else {
403            // Stateless path: isolate subtree via type name (no entity identity).
404            request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
405                render_view(self.view.take().unwrap(), window, cx)
406            })
407        }
408    }
409
410    fn prepaint(
411        &mut self,
412        global_id: Option<&GlobalElementId>,
413        _inspector_id: Option<&InspectorElementId>,
414        bounds: Bounds<Pixels>,
415        element: &mut Self::RequestLayoutState,
416        window: &mut Window,
417        cx: &mut App,
418    ) -> Option<AnyElement> {
419        if let Some(entity_id) = self.entity_id {
420            // Stateful path.
421            #[cfg(feature = "profiler")]
422            let start = window.window_profiler.begin_view();
423            let prepainted = prepaint_view(
424                entity_id,
425                global_id,
426                bounds,
427                element,
428                window,
429                cx,
430                &mut |window, cx| render_view(self.view.take().unwrap(), window, cx),
431            );
432            #[cfg(feature = "profiler")]
433            window.window_profiler.end_view(
434                start,
435                self.view_type_name,
436                crate::profiler::ViewPhase::Prepaint,
437            );
438            prepainted
439        } else {
440            // Stateless path: just prepaint the element.
441            prepaint_component(type_name::<V>(), element, window, cx)
442        }
443    }
444
445    fn paint(
446        &mut self,
447        global_id: Option<&GlobalElementId>,
448        _inspector_id: Option<&InspectorElementId>,
449        _bounds: Bounds<Pixels>,
450        _request_layout: &mut Self::RequestLayoutState,
451        element: &mut Self::PrepaintState,
452        window: &mut Window,
453        cx: &mut App,
454    ) {
455        if let Some(entity_id) = self.entity_id {
456            // Stateful path.
457            #[cfg(feature = "profiler")]
458            let start = window.window_profiler.begin_view();
459            paint_view(
460                entity_id,
461                self.cached_style.is_some(),
462                global_id,
463                element,
464                window,
465                cx,
466            );
467            #[cfg(feature = "profiler")]
468            window.window_profiler.end_view(
469                start,
470                self.view_type_name,
471                crate::profiler::ViewPhase::Paint,
472            );
473        } else {
474            // Stateless path: just paint the element.
475            paint_component(std::any::type_name::<V>(), element, window, cx);
476        }
477    }
478}
479
480/// A view that renders nothing
481pub struct EmptyView;
482
483impl Render for EmptyView {
484    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
485        Empty
486    }
487}
488
489#[inline(never)]
490fn request_layout_view(
491    entity_id: EntityId,
492    cached_style: Option<&StyleRefinement>,
493    window: &mut Window,
494    cx: &mut App,
495    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
496) -> (LayoutId, Option<AnyElement>) {
497    window.with_rendered_view(entity_id, |window| {
498        let caching_disabled = window.is_inspector_picking(cx);
499        match cached_style {
500            Some(style) if !caching_disabled => {
501                let mut root_style = Style::default();
502                root_style.refine(style);
503                let layout_id = window.request_layout(root_style, None, cx);
504                (layout_id, None)
505            }
506            _ => {
507                let mut element = render(window, cx);
508                let layout_id = element.request_layout(window, cx);
509                (layout_id, Some(element))
510            }
511        }
512    })
513}
514
515#[inline(never)]
516fn request_layout_component(
517    name: &'static str,
518    window: &mut Window,
519    cx: &mut App,
520    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
521) -> (LayoutId, Option<AnyElement>) {
522    window.with_id(ElementId::from(name), |window| {
523        let mut element = render(window, cx);
524        let layout_id = element.request_layout(window, cx);
525        (layout_id, Some(element))
526    })
527}
528
529#[inline(never)]
530fn prepaint_view(
531    entity_id: EntityId,
532    global_id: Option<&GlobalElementId>,
533    bounds: Bounds<Pixels>,
534    element: &mut Option<AnyElement>,
535    window: &mut Window,
536    cx: &mut App,
537    render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
538) -> Option<AnyElement> {
539    window.set_view_id(entity_id);
540    window.with_rendered_view(entity_id, |window| {
541        if let Some(mut element) = element.take() {
542            element.prepaint(window, cx);
543            return Some(element);
544        }
545
546        window.with_element_state::<ViewElementState, _>(
547            global_id.unwrap(),
548            |element_state, window| {
549                let content_mask = window.content_mask();
550                let text_style = window.text_style();
551                let opacity = window.element_opacity();
552                let transform = window.element_transform();
553                let vn_clip = window.vn_clip_stack.clone();
554
555                // Opacity is compared by bits so that a NaN opacity still matches itself
556                // and the view keeps using its cache.
557                if let Some(mut element_state) = element_state
558                    && element_state.cache_key.bounds == bounds
559                    && element_state.cache_key.content_mask == content_mask
560                    && element_state.cache_key.text_style == text_style
561                    && element_state.cache_key.opacity.to_bits() == opacity.to_bits()
562                    && element_state.cache_key.transform == transform
563                    && crate::VnClipNode::same(&element_state.cache_key.vn_clip, &vn_clip)
564                    && !window.dirty_views.contains(&entity_id)
565                    && !window.refreshing
566                {
567                    let prepaint_start = window.prepaint_index();
568                    window.reuse_prepaint(element_state.prepaint_range.clone());
569                    cx.entities
570                        .extend_accessed(element_state.accessed_entities.iter().copied());
571                    let prepaint_end = window.prepaint_index();
572                    element_state.prepaint_range = prepaint_start..prepaint_end;
573
574                    return (None, element_state);
575                }
576
577                let refreshing = mem::replace(&mut window.refreshing, true);
578                let prepaint_start = window.prepaint_index();
579                let (element, accessed_entities) = cx.detect_accessed_entities(|cx| {
580                    let mut element = render(window, cx);
581                    element.layout_as_root(Size::<AvailableSpace>::from(bounds.size), window, cx);
582                    element.prepaint_at(bounds.origin, window, cx);
583                    element
584                });
585
586                let prepaint_end = window.prepaint_index();
587                window.refreshing = refreshing;
588
589                (
590                    Some(element),
591                    ViewElementState {
592                        accessed_entities,
593                        prepaint_range: prepaint_start..prepaint_end,
594                        paint_range: PaintIndex::default()..PaintIndex::default(),
595                        cache_key: ViewElementCacheKey {
596                            bounds,
597                            content_mask,
598                            text_style,
599                            opacity,
600                            transform,
601                            vn_clip,
602                        },
603                    },
604                )
605            },
606        )
607    })
608}
609
610#[inline(never)]
611fn prepaint_component(
612    name: &'static str,
613    element: &mut Option<AnyElement>,
614    window: &mut Window,
615    cx: &mut App,
616) -> Option<AnyElement> {
617    window.with_id(ElementId::from(name), |window| {
618        element.as_mut().unwrap().prepaint(window, cx);
619    });
620    Some(element.take().unwrap())
621}
622
623#[inline(never)]
624fn paint_view(
625    entity_id: EntityId,
626    cached: bool,
627    global_id: Option<&GlobalElementId>,
628    element: &mut Option<AnyElement>,
629    window: &mut Window,
630    cx: &mut App,
631) {
632    window.with_rendered_view(entity_id, |window| {
633        let caching_disabled = window.is_inspector_picking(cx);
634        if cached && !caching_disabled {
635            window.with_element_state::<ViewElementState, _>(
636                global_id.unwrap(),
637                |element_state, window| {
638                    let mut element_state = element_state.unwrap();
639
640                    let paint_start = window.paint_index();
641                    let opacity = window.element_opacity();
642
643                    // Prepaint can only predict the opacity paint applies: an ancestor's
644                    // hover or drag-over style depends on this frame's hit test, which
645                    // isn't known until prepaint finishes. The key records what was
646                    // actually painted, and output replayed under a different opacity is
647                    // redrawn on the next frame.
648                    if let Some(element) = element {
649                        let refreshing = mem::replace(&mut window.refreshing, true);
650                        let ((), accessed_entities) =
651                            cx.detect_accessed_entities(|cx| element.paint(window, cx));
652                        element_state.accessed_entities.extend(accessed_entities);
653                        window.refreshing = refreshing;
654                        element_state.cache_key.opacity = opacity;
655                    } else {
656                        window.reuse_paint(element_state.paint_range.clone());
657                        if element_state.cache_key.opacity.to_bits() != opacity.to_bits() {
658                            window.request_animation_frame();
659                        }
660                    }
661
662                    let paint_end = window.paint_index();
663                    element_state.paint_range = paint_start..paint_end;
664
665                    ((), element_state)
666                },
667            )
668        } else {
669            element.as_mut().unwrap().paint(window, cx);
670        }
671    });
672}
673
674#[inline(never)]
675fn paint_component(
676    name: &'static str,
677    element: &mut Option<AnyElement>,
678    window: &mut Window,
679    cx: &mut App,
680) {
681    window.with_id(ElementId::Name(name.into()), |window| {
682        element.as_mut().unwrap().paint(window, cx);
683    });
684}
685
686/// vue-native fork: [`ViewElementCacheKey`]'s opacity and transform.
687#[cfg(test)]
688mod vn_cache_key_tests {
689    use crate::{
690        AnyWindowHandle, Context, Entity, Render, StyleRefinement, TestAppContext,
691        TransformSpec, Window, div, prelude::*, px, size,
692    };
693    use std::{cell::Cell, rc::Rc};
694
695    struct CaptionRoot {
696        child: Entity<CaptionChild>,
697        uncached_drag_parent: bool,
698    }
699    struct CaptionChild {
700        renders: Rc<Cell<u32>>,
701        own_drag_region: bool,
702    }
703    impl Render for CaptionRoot {
704        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
705            div().size_full()
706                .when(self.uncached_drag_parent, |element| element.window_control_area(crate::WindowControlArea::Drag))
707                .child(self.child.clone().cached(StyleRefinement::default().w(px(200.)).h(px(40.))))
708        }
709    }
710    impl Render for CaptionChild {
711        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
712            self.renders.set(self.renders.get() + 1);
713            div().size_full()
714                .when(self.own_drag_region, |element| element.window_control_area(crate::WindowControlArea::Drag))
715                .child(div().w(px(50.)).h(px(40.)).window_control_area(crate::WindowControlArea::NoDrag))
716        }
717    }
718    fn caption_frame(handle: AnyWindowHandle, cx: &mut TestAppContext) {
719        cx.update_window(handle, |root, window, cx| {
720            root.downcast::<CaptionRoot>().expect("caption root").update(cx, |_, cx| cx.notify());
721            window.draw(cx).clear(cx);
722            assert_eq!(window.window_control_area_at(crate::point(px(100.), px(20.))), Some(crate::WindowControlArea::Drag));
723            assert_eq!(window.window_control_area_at(crate::point(px(25.), px(20.))), Some(crate::WindowControlArea::NoDrag));
724        }).expect("draw caption");
725    }
726    #[gpui::test]
727    fn cached_caption_replays_drag_and_no_drag_regions(cx: &mut TestAppContext) {
728        let renders = Rc::new(Cell::new(0));
729        let counter = renders.clone();
730        let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
731            child: cx.new(|_| CaptionChild { renders: counter, own_drag_region: true }),
732            uncached_drag_parent: false,
733        }).into();
734        caption_frame(handle, cx);
735        let first = renders.get();
736        for _ in 0..20 { caption_frame(handle, cx); }
737        assert_eq!(renders.get(), first, "caption must replay rather than being rebuilt to keep dragging");
738    }
739    #[gpui::test]
740    fn cached_no_drag_cutout_does_not_become_its_uncached_drag_parent(cx: &mut TestAppContext) {
741        let renders = Rc::new(Cell::new(0));
742        let counter = renders.clone();
743        let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
744            child: cx.new(|_| CaptionChild { renders: counter, own_drag_region: false }),
745            uncached_drag_parent: true,
746        }).into();
747        caption_frame(handle, cx);
748        let first = renders.get();
749        for _ in 0..20 { caption_frame(handle, cx); }
750        assert_eq!(renders.get(), first);
751    }
752    #[gpui::test]
753    fn caption_hit_test_uses_requested_point_without_a_preceding_move(cx: &mut TestAppContext) {
754        let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
755            child: cx.new(|_| CaptionChild { renders: Rc::new(Cell::new(0)), own_drag_region: true }),
756            uncached_drag_parent: false,
757        });
758        caption_frame(handle.into(), cx);
759        handle.update(cx, |_, window, cx| {
760            window.dispatch_event(crate::PlatformInput::MouseMove(crate::MouseMoveEvent {
761                position: crate::point(px(25.), px(20.)),
762                pressed_button: None,
763                modifiers: Default::default(),
764            }), cx);
765            assert_eq!(window.window_control_area_at(crate::point(px(100.), px(20.))), Some(crate::WindowControlArea::Drag));
766            assert_eq!(window.window_control_area_at(crate::point(px(25.), px(20.))), Some(crate::WindowControlArea::NoDrag));
767        }).expect("hit test without another mouse move");
768    }
769
770    struct Root {
771        child: Entity<Child>,
772        opacity: f32,
773        scale: f32,
774    }
775
776    impl Render for Root {
777        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
778            let mut outer = div().size_full().opacity(self.opacity);
779            outer.style().vn_transform = Some(TransformSpec {
780                scale: (self.scale, self.scale),
781                ..TransformSpec::IDENTITY
782            });
783            outer.child(
784                self.child
785                    .clone()
786                    .cached(StyleRefinement::default().size(px(50.))),
787            )
788        }
789    }
790
791    struct Child {
792        renders: Rc<Cell<u32>>,
793    }
794
795    impl Render for Child {
796        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
797            self.renders.set(self.renders.get() + 1);
798            div().size_full().bg(crate::red())
799        }
800    }
801
802    /// Sets the root's opacity and scale, rebuilds it, and draws.
803    fn frame(window: AnyWindowHandle, cx: &mut TestAppContext, opacity: f32, scale: f32) {
804        cx.update_window(window, |root, window, cx| {
805            let root = root.downcast::<Root>().expect("test root");
806            root.update(cx, |root, cx| {
807                root.opacity = opacity;
808                root.scale = scale;
809                cx.notify();
810            });
811            window.draw(cx).clear(cx);
812        })
813        .expect("draw");
814    }
815
816    #[gpui::test]
817    fn a_cached_view_renders_again_under_a_new_opacity_or_transform(cx: &mut TestAppContext) {
818        let renders = Rc::new(Cell::new(0u32));
819        let counter = renders.clone();
820        let window = cx.open_window(size(px(200.), px(200.)), move |_, cx| Root {
821            child: cx.new(|_| Child { renders: counter }),
822            opacity: 0.1,
823            scale: 1.0,
824        });
825        let window: AnyWindowHandle = window.into();
826        frame(window, cx, 0.1, 1.0);
827        let first = renders.get();
828        assert!(first >= 1, "the first frame renders the child");
829
830        // Nothing it composes changed: the recording replays.
831        frame(window, cx, 0.1, 1.0);
832        assert_eq!(renders.get(), first, "same opacity and transform: replayed");
833
834        // The parent fades in: the recording holds 0.1 in every primitive.
835        frame(window, cx, 0.6, 1.0);
836        assert_eq!(renders.get(), first + 1, "a new opacity renders");
837        frame(window, cx, 1.0, 1.0);
838        assert_eq!(renders.get(), first + 2, "and the next one");
839        frame(window, cx, 1.0, 1.0);
840        assert_eq!(renders.get(), first + 2, "the fade over: replayed again");
841
842        // The parent zooms: its matrix is in every primitive and hitbox.
843        frame(window, cx, 1.0, 0.95);
844        assert_eq!(renders.get(), first + 3, "a new transform renders");
845        frame(window, cx, 1.0, 0.95);
846        assert_eq!(renders.get(), first + 3, "the same transform replays");
847    }
848}