Skip to main content

gpui/fast/
composition.rs

1// Modified by Longbridge for gpui-fast.
2//! Window composition: native views between GPUI's content and its overlays.
3//!
4//! Ported from zed-industries/zed#62379. A window paints one scene, as
5//! always, but can present it on several ordered surfaces, so that a
6//! platform-native view (a `WKWebView`, a WebView2, a Wayland subsurface fed
7//! by another GPU producer) sits above GPUI's base content and below its
8//! overlays — popovers, dialogs, menus, tooltips:
9//!
10//! ```text
11//! front  GPUI overlay   deferred and window-level draws
12//!        native surface  WKWebView / WebView2 / wl_subsurface / X11 child
13//! back   GPUI base       the root view
14//! ```
15//!
16//! [`CompositionTree`] holds each surface's identity, parent and sibling
17//! order. The frame records, as it paints, which GPUI surface each stretch
18//! of the scene targets ([`SurfaceStarts`]); presenting splits the scene
19//! along those stretches into a [`ComposedScene`], and the platform draws
20//! each surface's part onto its own layer, visual or subsurface.
21//!
22//! Composition is opt-in: until [`Window::enable_window_composition`] is
23//! called, a window presents its scene with `PlatformWindow::draw`, as
24//! upstream does.
25//!
26//! Unlike the upstream pull request, a view drawn again from last frame
27//! (every retained view, here) carries the surface switches it made with it:
28//! [`reuse_starts`] copies them along with its scene.
29//!
30//! Also unlike it, a native surface stacks with the element hosting it. One
31//! positioned while a deferred draw is prepainted, a web page in a dialog or
32//! sheet, is hosted on the overlay surface, so it moves above that surface
33//! instead of under the dialog's own background; positioned while the root
34//! view is prepainted, it moves back below it. Overlays drawn over a native
35//! surface hosted on the overlay surface are then covered by it.
36
37use crate::window::PaintIndex;
38use crate::{
39    Bounds, DevicePixels, DispatchEventResult, Hitbox, HitboxBehavior, HitboxId, MouseButton,
40    MouseExitEvent, MouseMoveEvent, Pixels, PlatformInput, PlatformWindow, Point, Scene, Window,
41    scene::PaintOperation,
42};
43use anyhow::{Context as _, Result, anyhow, bail};
44use collections::FxHashMap;
45use gpui_util::ResultExt as _;
46use slotmap::SlotMap;
47use std::{
48    any::Any,
49    cell::{Cell, RefCell},
50    ops::Range,
51    rc::Rc,
52};
53
54slotmap::new_key_type! {
55    /// Stable identity for a surface in a window composition tree.
56    pub struct CompositionSurfaceId;
57}
58
59/// The renderer or platform facility responsible for a composition surface.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum CompositionSurfaceKind {
62    /// A surface rendered from a range of GPUI scene operations.
63    Gpui,
64    /// A surface whose content is supplied by a platform-native view or visual.
65    Native,
66    /// A surface whose content is supplied by an external GPU producer.
67    ExternalGpu,
68}
69
70#[derive(Clone)]
71struct CompositionSurfaceNode {
72    kind: CompositionSurfaceKind,
73    parent: Option<CompositionSurfaceId>,
74    children: Vec<CompositionSurfaceId>,
75}
76
77/// The surfaces of a window, as a forest ordered bottom to top.
78#[derive(Clone)]
79pub(crate) struct CompositionTree {
80    surfaces: SlotMap<CompositionSurfaceId, CompositionSurfaceNode>,
81    roots: Vec<CompositionSurfaceId>,
82}
83
84impl CompositionTree {
85    pub(crate) fn new() -> Self {
86        Self {
87            surfaces: SlotMap::with_key(),
88            roots: Vec::new(),
89        }
90    }
91
92    /// Adds a surface above its future siblings.
93    pub(crate) fn insert(
94        &mut self,
95        kind: CompositionSurfaceKind,
96        parent: Option<CompositionSurfaceId>,
97    ) -> Result<CompositionSurfaceId> {
98        if let Some(parent) = parent {
99            self.surface(parent)?;
100        }
101
102        let surface = self.surfaces.insert(CompositionSurfaceNode {
103            kind,
104            parent,
105            children: Vec::new(),
106        });
107        self.siblings_mut(parent)?.push(surface);
108        Ok(surface)
109    }
110
111    /// Removes a surface, putting its children where it was.
112    pub(crate) fn remove(&mut self, surface: CompositionSurfaceId) -> Result<()> {
113        let parent = self.surface(surface)?.parent;
114        let children = self.surface(surface)?.children.clone();
115        let siblings = self.siblings_mut(parent)?;
116        let index = siblings
117            .iter()
118            .position(|candidate| *candidate == surface)
119            .ok_or_else(|| anyhow!("composition surface is missing from its parent"))?;
120        siblings.splice(index..=index, children.iter().copied());
121        for child in children {
122            self.surface_mut(child)?.parent = parent;
123        }
124        self.surfaces.remove(surface);
125        Ok(())
126    }
127
128    pub(crate) fn place_above(
129        &mut self,
130        surface: CompositionSurfaceId,
131        sibling: CompositionSurfaceId,
132    ) -> Result<()> {
133        self.place_relative(surface, sibling, true)
134    }
135
136    pub(crate) fn place_below(
137        &mut self,
138        surface: CompositionSurfaceId,
139        sibling: CompositionSurfaceId,
140    ) -> Result<()> {
141        self.place_relative(surface, sibling, false)
142    }
143
144    /// Moves a surface under `parent`, above the children it has.
145    pub(crate) fn reparent(
146        &mut self,
147        surface: CompositionSurfaceId,
148        parent: Option<CompositionSurfaceId>,
149    ) -> Result<()> {
150        self.surface(surface)?;
151        if let Some(parent) = parent {
152            self.surface(parent)?;
153            if parent == surface || self.is_descendant(parent, surface)? {
154                bail!("composition surfaces cannot contain themselves");
155            }
156        }
157
158        let previous_parent = self.surface(surface)?.parent;
159        self.siblings_mut(previous_parent)?
160            .retain(|candidate| *candidate != surface);
161        self.surface_mut(surface)?.parent = parent;
162        self.siblings_mut(parent)?.push(surface);
163        Ok(())
164    }
165
166    pub(crate) fn kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
167        Ok(self.surface(surface)?.kind)
168    }
169
170    pub(crate) fn parent(
171        &self,
172        surface: CompositionSurfaceId,
173    ) -> Result<Option<CompositionSurfaceId>> {
174        Ok(self.surface(surface)?.parent)
175    }
176
177    /// The children of `parent`, or the roots when it is `None`, bottom to top.
178    pub(crate) fn children(
179        &self,
180        parent: Option<CompositionSurfaceId>,
181    ) -> Result<&[CompositionSurfaceId]> {
182        match parent {
183            Some(parent) => Ok(&self.surface(parent)?.children),
184            None => Ok(&self.roots),
185        }
186    }
187
188    /// Every surface, parents before their children, bottom to top.
189    pub(crate) fn flattened(&self) -> Vec<CompositionSurfaceId> {
190        let mut surfaces = Vec::with_capacity(self.surfaces.len());
191        for root in &self.roots {
192            self.flatten_into(*root, &mut surfaces);
193        }
194        surfaces
195    }
196
197    fn place_relative(
198        &mut self,
199        surface: CompositionSurfaceId,
200        sibling: CompositionSurfaceId,
201        above: bool,
202    ) -> Result<()> {
203        if surface == sibling {
204            bail!("a composition surface cannot be ordered relative to itself");
205        }
206        let parent = self.surface(surface)?.parent;
207        if self.surface(sibling)?.parent != parent {
208            bail!("composition surfaces must share a parent to be reordered");
209        }
210
211        let siblings = self.siblings_mut(parent)?;
212        siblings.retain(|candidate| *candidate != surface);
213        let sibling_index = siblings
214            .iter()
215            .position(|candidate| *candidate == sibling)
216            .ok_or_else(|| anyhow!("composition sibling is missing from its parent"))?;
217        let index = sibling_index + usize::from(above);
218        siblings.insert(index, surface);
219        Ok(())
220    }
221
222    fn is_descendant(
223        &self,
224        candidate: CompositionSurfaceId,
225        ancestor: CompositionSurfaceId,
226    ) -> Result<bool> {
227        let mut parent = Some(candidate);
228        while let Some(surface) = parent {
229            if surface == ancestor {
230                return Ok(true);
231            }
232            parent = self.surface(surface)?.parent;
233        }
234        Ok(false)
235    }
236
237    fn surface(&self, surface: CompositionSurfaceId) -> Result<&CompositionSurfaceNode> {
238        self.surfaces
239            .get(surface)
240            .ok_or_else(|| anyhow!("composition surface does not exist"))
241    }
242
243    fn surface_mut(
244        &mut self,
245        surface: CompositionSurfaceId,
246    ) -> Result<&mut CompositionSurfaceNode> {
247        self.surfaces
248            .get_mut(surface)
249            .ok_or_else(|| anyhow!("composition surface does not exist"))
250    }
251
252    fn siblings_mut(
253        &mut self,
254        parent: Option<CompositionSurfaceId>,
255    ) -> Result<&mut Vec<CompositionSurfaceId>> {
256        match parent {
257            Some(parent) => Ok(&mut self.surface_mut(parent)?.children),
258            None => Ok(&mut self.roots),
259        }
260    }
261
262    fn flatten_into(
263        &self,
264        surface: CompositionSurfaceId,
265        flattened: &mut Vec<CompositionSurfaceId>,
266    ) {
267        flattened.push(surface);
268        if let Some(surface) = self.surfaces.get(surface) {
269            for child in &surface.children {
270                self.flatten_into(*child, flattened);
271            }
272        }
273    }
274}
275
276/// Splits a scene of `scene_len` operations along `starts`, the points where
277/// painting switched GPUI surface, into one layer per GPUI surface of `tree`,
278/// in composition order.
279pub(crate) fn composed_scene_layers(
280    tree: &CompositionTree,
281    starts: &[(CompositionSurfaceId, usize)],
282    scene_len: usize,
283) -> Result<Vec<ComposedSceneLayer>> {
284    let mut ranges_by_surface = FxHashMap::<_, Vec<Range<usize>>>::default();
285    for (index, (surface, start)) in starts.iter().enumerate() {
286        if tree.kind(*surface)? != CompositionSurfaceKind::Gpui {
287            bail!("scene operations target a non-GPUI composition surface");
288        }
289        let end = starts
290            .get(index + 1)
291            .map_or(scene_len, |(_, next_start)| *next_start);
292        if *start > end || end > scene_len {
293            bail!("composition scene ranges are not monotonic");
294        }
295        if *start < end {
296            ranges_by_surface
297                .entry(*surface)
298                .or_default()
299                .push(*start..end);
300        }
301    }
302
303    let mut layers = Vec::new();
304    for surface in tree.flattened() {
305        if tree.kind(surface)? == CompositionSurfaceKind::Gpui {
306            layers.push(ComposedSceneLayer {
307                surface,
308                ranges: ranges_by_surface.remove(&surface).unwrap_or_default(),
309            });
310        }
311    }
312    Ok(layers)
313}
314
315/// A platform attachment participating in a window composition tree.
316pub trait PlatformSurfaceAttachment {
317    /// Updates the native surface geometry in window-content device pixels.
318    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()>;
319    /// Returns the native surface geometry in window-content device pixels.
320    fn bounds(&self) -> Bounds<DevicePixels>;
321    /// Updates the window-content origin of the surface's composition parent.
322    /// Platform adapters use this to preserve window-coordinate geometry when
323    /// a surface is nested.
324    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()>;
325    /// Rebinds externally owned content after the platform compositor has been
326    /// recreated. Native surfaces managed by GPUI may use the default no-op.
327    fn compositor_recreated(&self, _platform_context: &dyn Any) -> Result<()> {
328        Ok(())
329    }
330    /// Registers a callback that reattaches native content when the platform
331    /// attachment object changes after compositor recovery.
332    fn set_compositor_recreated_callback(
333        &self,
334        _callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
335    ) -> Result<()> {
336        bail!("compositor recreation callbacks are not supported")
337    }
338    /// Updates whether the native surface participates in composition.
339    fn set_visible(&self, visible: bool) -> Result<()>;
340    /// Whether GPUI forwards pointer input to a windowless consumer.
341    /// OS-managed child views keep their native event path by default.
342    fn input_forwarding(&self) -> bool {
343        false
344    }
345    /// Returns the platform attachment object: an `NSView` pointer as `usize`
346    /// on macOS, an `IDCompositionVisual` as `windows::core::IUnknown` on
347    /// Windows, a `raw_window_handle::RawWindowHandle` on Linux.
348    fn platform_handle(&self) -> Result<Box<dyn Any>>;
349}
350
351/// The ranges of a GPUI scene rendered onto one composition surface.
352#[derive(Clone, Debug)]
353pub struct ComposedSceneLayer {
354    /// The GPUI composition surface receiving these scene ranges.
355    pub surface: CompositionSurfaceId,
356    /// Paint-operation ranges belonging to the surface.
357    pub ranges: Vec<Range<usize>>,
358}
359
360/// A scene split across GPUI surfaces in composition order.
361pub struct ComposedScene<'a> {
362    scene: &'a Scene,
363    layers: Vec<ComposedSceneLayer>,
364    input: &'a SurfaceInput,
365}
366
367impl<'a> ComposedScene<'a> {
368    pub(crate) fn new(
369        scene: &'a Scene,
370        layers: Vec<ComposedSceneLayer>,
371        input: &'a SurfaceInput,
372    ) -> Self {
373        Self {
374            scene,
375            layers,
376            input,
377        }
378    }
379
380    /// The prepared, clipped input regions belonging to this GPUI surface.
381    /// Regions retain their stacking order and mouse/scroll behavior.
382    pub fn layer_hitboxes(&self, layer: &ComposedSceneLayer) -> &[Hitbox] {
383        self.input
384            .hitboxes
385            .get(&layer.surface)
386            .map(Vec::as_slice)
387            .unwrap_or(&[])
388    }
389
390    /// Returns the complete scene containing all GPUI planes.
391    pub fn scene(&self) -> &'a Scene {
392        self.scene
393    }
394
395    /// Returns the GPUI surface layers in composition order.
396    pub fn layers(&self) -> &[ComposedSceneLayer] {
397        &self.layers
398    }
399
400    /// Returns the part of the scene `layer` covers as a finished scene of
401    /// its own, ready to draw onto the layer's surface.
402    pub fn layer_scene(&self, layer: &ComposedSceneLayer) -> Result<Scene> {
403        let mut scene = Scene::default();
404        for range in &layer.ranges {
405            scene.replay_balanced(range.clone(), self.scene)?;
406        }
407        scene.finish();
408        Ok(scene)
409    }
410}
411
412/// A platform surface participating in window composition.
413#[derive(Clone)]
414pub struct PlatformCompositionSurface {
415    /// Stable identity in the window composition tree.
416    pub id: CompositionSurfaceId,
417    /// Parent surface, or `None` for a root surface.
418    pub parent: Option<CompositionSurfaceId>,
419    /// This surface's origin in window-content device pixels. GPUI surfaces
420    /// use the window origin because their backing scenes remain window-based.
421    pub window_origin: Point<DevicePixels>,
422    /// The parent surface's origin in window-content device pixels.
423    pub parent_origin: Point<DevicePixels>,
424    /// Native or external surface bounds in window-content device pixels.
425    /// GPUI surfaces use the full window and therefore have no explicit bounds.
426    pub window_bounds: Option<Bounds<DevicePixels>>,
427    /// Renderer or attachment supplying this surface's content.
428    pub content: PlatformCompositionSurfaceContent,
429}
430
431/// Content attached to a platform composition surface.
432#[derive(Clone)]
433pub enum PlatformCompositionSurfaceContent {
434    /// A surface rendered by GPUI.
435    Gpui,
436    /// A surface backed by a platform-native view or visual.
437    Native(Rc<dyn PlatformSurfaceAttachment>),
438    /// A surface backed by an external GPU producer.
439    ExternalGpu(Rc<dyn PlatformSurfaceAttachment>),
440}
441
442/// What `PlatformWindow::draw_composed` does on a platform without
443/// composition: draws the whole scene on the window's one surface.
444pub(crate) fn draw_uncomposed<W: PlatformWindow + ?Sized>(window: &W, scene: ComposedScene<'_>) {
445    window.draw(scene.scene());
446}
447
448/// What the `PlatformWindow` composition methods return on a platform
449/// without composition.
450pub(crate) fn unsupported<T>(what: &str) -> Result<T> {
451    bail!("{what} is not supported on this platform")
452}
453
454impl crate::Background {
455    /// Returns whether the background covers its bounds with no translucency,
456    /// so a platform compositing native content below it can cut that
457    /// content out instead of blending it.
458    pub fn is_opaque(&self) -> bool {
459        match self.tag {
460            crate::color::BackgroundTag::Solid => self.solid.is_opaque(),
461            crate::color::BackgroundTag::LinearGradient => {
462                self.colors.iter().all(|stop| stop.color.is_opaque())
463            }
464            crate::color::BackgroundTag::PatternSlash
465            | crate::color::BackgroundTag::Checkerboard => false,
466        }
467    }
468}
469
470impl Scene {
471    /// Returns whether the scene contains no drawable primitives.
472    ///
473    /// A scene may have paint operations that only open and close empty layers,
474    /// so `len() == 0` is not equivalent to having no visible primitives.
475    /// Transparent input regions are prepared separately from this scene.
476    pub fn is_empty(&self) -> bool {
477        self.shadows.is_empty()
478            && self.quads.is_empty()
479            && self.paths.is_empty()
480            && self.underlines.is_empty()
481            && self.monochrome_sprites.is_empty()
482            && self.subpixel_sprites.is_empty()
483            && self.polychrome_sprites.is_empty()
484            && self.surfaces.is_empty()
485    }
486
487    /// Replays a range as a self-contained scene, restoring any layers that
488    /// were active at the start of the range and closing those still active at
489    /// its end. The scroll layers whose tiles the range composites come along.
490    pub fn replay_balanced(&mut self, range: Range<usize>, previous_scene: &Scene) -> Result<()> {
491        anyhow::ensure!(
492            range.start <= range.end,
493            "scene replay range starts after its end"
494        );
495        let prefix = previous_scene
496            .paint_operations
497            .get(..range.start)
498            .context("scene replay range starts past the scene")?;
499        let operations = previous_scene
500            .paint_operations
501            .get(range.clone())
502            .context("scene replay range ends past the scene")?;
503        let mut active_layers = Vec::new();
504        let mut active_clips = Vec::new();
505        for operation in prefix {
506            match operation {
507                PaintOperation::StartLayer(bounds) => active_layers.push(*bounds),
508                PaintOperation::EndLayer => {
509                    anyhow::ensure!(
510                        active_layers.pop().is_some(),
511                        "source scene closes a layer that is not open"
512                    );
513                }
514                PaintOperation::Primitive(_) => {}
515                PaintOperation::FastRoundedClip(clip) => {
516                    crate::fast::rounded_clip::track(*clip, &mut active_clips)?
517                }
518            }
519        }
520
521        crate::fast::layers::paint::replay_layers(self, range, previous_scene);
522        for bounds in &active_layers {
523            self.push_layer(*bounds);
524        }
525        for shape in &active_clips {
526            crate::fast::rounded_clip::record(
527                self,
528                crate::fast::rounded_clip::ClipOperation::Begin(*shape),
529            );
530        }
531        for operation in operations {
532            match operation {
533                PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()),
534                PaintOperation::StartLayer(bounds) => {
535                    active_layers.push(*bounds);
536                    self.push_layer(*bounds);
537                }
538                PaintOperation::EndLayer => {
539                    anyhow::ensure!(
540                        active_layers.pop().is_some(),
541                        "scene replay range closes a layer that is not open"
542                    );
543                    self.pop_layer();
544                }
545                PaintOperation::FastRoundedClip(clip) => {
546                    crate::fast::rounded_clip::track(*clip, &mut active_clips)?;
547                    crate::fast::rounded_clip::record(self, *clip);
548                }
549            }
550        }
551        for _ in active_layers {
552            self.pop_layer();
553        }
554        for _ in active_clips {
555            crate::fast::rounded_clip::record(self, crate::fast::rounded_clip::ClipOperation::End);
556        }
557        Ok(())
558    }
559}
560
561/// Where each stretch of a frame's scene is presented: the GPUI surface
562/// painting switched to, and the scene length at the switch.
563#[derive(Default)]
564pub(crate) struct SurfaceStarts(Vec<(CompositionSurfaceId, usize)>);
565
566/// Composition ownership accompanies existing hitbox identities through retained
567/// and scroll-layer replay; no second layout or input tree is built.
568#[derive(Default)]
569pub(crate) struct SurfaceInput {
570    order: Vec<(CompositionSurfaceId, Option<Bounds<Pixels>>)>,
571    scope: Option<CompositionSurfaceId>,
572    base: Option<CompositionSurfaceId>,
573    owners: FxHashMap<HitboxId, CompositionSurfaceId>,
574    hitboxes: FxHashMap<CompositionSurfaceId, Vec<Hitbox>>,
575}
576
577impl SurfaceInput {
578    pub(crate) fn clear(&mut self) {
579        self.scope = None;
580        self.base = None;
581        self.order.clear();
582        self.owners.clear();
583        for hitboxes in self.hitboxes.values_mut() {
584            hitboxes.clear();
585        }
586    }
587}
588
589fn begin_input(window: &mut Window, overlay: bool) {
590    let state = window.fast_composition.0.borrow();
591    state
592        .prepainting
593        .set(Some(if overlay { Host::Overlay } else { Host::Base }));
594    let input = &mut window.next_frame.fast_composition_input;
595    input.base = (!state.platform_surfaces.is_empty()).then_some(state.base_surface);
596    input.scope = state.enabled.then_some(if overlay {
597        state.overlay_surface
598    } else {
599        state.base_surface
600    });
601}
602
603pub(crate) fn input_surface(window: &Window) -> Option<CompositionSurfaceId> {
604    window.next_frame.fast_composition_input.scope
605}
606
607pub(crate) fn record_input(window: &mut Window, id: HitboxId) {
608    let input = &mut window.next_frame.fast_composition_input;
609    if let (Some(base), Some(surface)) = (input.base, input.scope) {
610        if surface != base {
611            input.owners.insert(id, surface);
612        }
613    }
614}
615
616pub(crate) fn finish_input(window: &mut Window) {
617    synchronize_geometry(window);
618    let scale = window.scale_factor();
619    let state = window.fast_composition.0.borrow();
620    let input = &mut window.next_frame.fast_composition_input;
621    if !state.enabled || state.platform_surfaces.is_empty() {
622        input.hitboxes.clear();
623        return;
624    }
625    input
626        .hitboxes
627        .retain(|surface, _| state.tree.kind(*surface).is_ok());
628    for surface in state.input_order.iter().copied() {
629        let native = state.platform_surfaces.get(&surface).map(|native| {
630            input_bounds(&state, surface, native.bounds().to_pixels(scale), scale)
631                .unwrap_or_default()
632        });
633        input.order.push((surface, native));
634    }
635    for hitbox in &window.next_frame.hitboxes {
636        let surface = input
637            .owners
638            .get(&hitbox.id)
639            .or_else(|| {
640                window
641                    .rendered_frame
642                    .fast_composition_input
643                    .owners
644                    .get(&hitbox.id)
645            })
646            .copied()
647            .unwrap_or(state.base_surface);
648        if !matches!(state.tree.kind(surface), Ok(CompositionSurfaceKind::Gpui)) {
649            continue;
650        }
651        if surface != state.base_surface {
652            input.owners.insert(hitbox.id, surface);
653        }
654        let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
655        let Some(bounds) = input_bounds(&state, surface, bounds, scale) else {
656            continue;
657        };
658        if !bounds.is_empty() {
659            let mut clipped = hitbox.clone();
660            clipped.bounds = bounds;
661            input.hitboxes.entry(surface).or_default().push(clipped);
662        }
663    }
664}
665
666/// Native content blocks GPUI hover and click targets behind it, while keeping
667/// the existing GPUI scroll blockers and capture dispatch unchanged.
668pub(crate) fn hit_test(
669    frame: &crate::window::Frame,
670    point: Point<Pixels>,
671) -> Option<crate::window::HitTest> {
672    let input = &frame.fast_composition_input;
673    if input.order.is_empty() {
674        return None;
675    }
676    let mut result = crate::window::HitTest::default();
677    let mut hover = None;
678    'surfaces: for (surface, native) in input.order.iter().rev() {
679        if let Some(bounds) = native {
680            if bounds.contains(&point) {
681                break;
682            }
683            continue;
684        }
685        let Some(hitboxes) = input.hitboxes.get(surface) else {
686            continue;
687        };
688        for hitbox in hitboxes.iter().rev() {
689            if hitbox.bounds.contains(&point) {
690                result.ids.push(hitbox.id);
691                if hover.is_none() && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll {
692                    hover = Some(result.ids.len());
693                }
694                if hitbox.behavior == HitboxBehavior::BlockMouse {
695                    break 'surfaces;
696                }
697            }
698        }
699    }
700    result.hover_hitbox_count = hover.unwrap_or(result.ids.len());
701    Some(result)
702}
703
704impl SurfaceStarts {
705    pub(crate) fn clear(&mut self) {
706        self.0.clear();
707    }
708
709    fn current(&self) -> Option<CompositionSurfaceId> {
710        self.0.last().map(|(surface, _)| *surface)
711    }
712
713    fn switch_to(&mut self, surface: CompositionSurfaceId, scene_len: usize) {
714        if self.current() == Some(surface) {
715            return;
716        }
717        self.0.push((surface, scene_len));
718    }
719}
720
721/// The GPUI surface an element hosting a native surface is drawn on.
722#[derive(Clone, Copy, Debug, PartialEq, Eq)]
723enum Host {
724    /// The root view, drawn on the base surface.
725    Base,
726    /// A deferred or window-level draw, drawn on the overlay surface.
727    Overlay,
728}
729
730/// A window's composition: its surface tree, the platform surfaces in it and
731/// whether the window presents through it.
732pub(crate) struct WindowCompositionState {
733    tree: CompositionTree,
734    platform_surfaces: FxHashMap<CompositionSurfaceId, Rc<ManagedPlatformSurface>>,
735    base_surface: CompositionSurfaceId,
736    overlay_surface: CompositionSurfaceId,
737    geometry_dirty: Rc<Cell<bool>>,
738    /// What the window is prepainting, while it prepaints a frame.
739    prepainting: Rc<Cell<Option<Host>>>,
740    enabled: bool,
741    input_order: Vec<CompositionSurfaceId>,
742    visible: FxHashMap<CompositionSurfaceId, Rc<Cell<bool>>>,
743    input_handlers: FxHashMap<CompositionSurfaceId, Rc<RefCell<NativeInputHandler>>>,
744    pointer_capture: Option<CompositionSurfaceId>,
745    pressed_buttons: Vec<MouseButton>,
746    hovered_native: Option<CompositionSurfaceId>,
747}
748
749type NativeInputHandler = Box<dyn FnMut(&PlatformInput) -> DispatchEventResult>;
750
751/// The [`Window`] field holding its composition.
752pub(crate) struct WindowCompositionHandle(Rc<RefCell<WindowCompositionState>>);
753
754impl Default for WindowCompositionHandle {
755    fn default() -> Self {
756        let mut tree = CompositionTree::new();
757        let base_surface = tree
758            .insert(CompositionSurfaceKind::Gpui, None)
759            .expect("a root can always be inserted");
760        let overlay_surface = tree
761            .insert(CompositionSurfaceKind::Gpui, None)
762            .expect("a root can always be inserted");
763        Self(Rc::new(RefCell::new(WindowCompositionState {
764            tree,
765            platform_surfaces: FxHashMap::default(),
766            base_surface,
767            overlay_surface,
768            geometry_dirty: Rc::new(Cell::new(false)),
769            prepainting: Rc::new(Cell::new(None)),
770            enabled: false,
771            input_order: Vec::new(),
772            visible: FxHashMap::default(),
773            input_handlers: FxHashMap::default(),
774            pointer_capture: None,
775            pressed_buttons: Vec::new(),
776            hovered_native: None,
777        })))
778    }
779}
780
781/// A platform surface whose bounds changes mark the window's composition
782/// geometry for synchronization at the next present.
783struct ManagedPlatformSurface {
784    platform_surface: Rc<dyn PlatformSurfaceAttachment>,
785    bounds: Cell<Bounds<DevicePixels>>,
786    geometry_dirty: Rc<Cell<bool>>,
787    visible: Rc<Cell<bool>>,
788    input_forwarding: Cell<bool>,
789    prepainting: Rc<Cell<Option<Host>>>,
790    /// The surface its host was last prepainted on.
791    host: Cell<Host>,
792    /// Whether `host` changed since the surface was last restacked.
793    restack: Cell<bool>,
794}
795
796impl ManagedPlatformSurface {
797    fn new(
798        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
799        state: &WindowCompositionState,
800    ) -> Self {
801        Self {
802            bounds: Cell::new(platform_surface.bounds()),
803            platform_surface,
804            geometry_dirty: state.geometry_dirty.clone(),
805            visible: Rc::new(Cell::new(true)),
806            input_forwarding: Cell::new(false),
807            prepainting: state.prepainting.clone(),
808            host: Cell::new(Host::Base),
809            restack: Cell::new(false),
810        }
811    }
812}
813
814impl PlatformSurfaceAttachment for ManagedPlatformSurface {
815    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
816        if let Some(host) = self.prepainting.get()
817            && self.host.replace(host) != host
818        {
819            self.restack.set(true);
820            self.geometry_dirty.set(true);
821        }
822        if self.bounds.get() == bounds {
823            return Ok(());
824        }
825        self.platform_surface.set_bounds(bounds)?;
826        self.bounds.set(bounds);
827        self.geometry_dirty.set(true);
828        Ok(())
829    }
830
831    fn bounds(&self) -> Bounds<DevicePixels> {
832        self.bounds.get()
833    }
834
835    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
836        self.platform_surface.set_parent_origin(origin)
837    }
838
839    fn compositor_recreated(&self, platform_context: &dyn Any) -> Result<()> {
840        self.platform_surface.compositor_recreated(platform_context)
841    }
842
843    fn set_compositor_recreated_callback(
844        &self,
845        callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
846    ) -> Result<()> {
847        self.platform_surface
848            .set_compositor_recreated_callback(callback)
849    }
850
851    fn set_visible(&self, visible: bool) -> Result<()> {
852        if self.visible.get() == visible {
853            return Ok(());
854        }
855        self.platform_surface.set_visible(visible)?;
856        self.visible.set(visible);
857        self.geometry_dirty.set(true);
858        Ok(())
859    }
860
861    fn input_forwarding(&self) -> bool {
862        self.input_forwarding.get() && self.visible.get()
863    }
864
865    fn platform_handle(&self) -> Result<Box<dyn Any>> {
866        self.platform_surface.platform_handle()
867    }
868}
869
870struct WindowCompositionSurfaceInner {
871    id: CompositionSurfaceId,
872    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
873}
874
875/// A stable handle to a surface in a window composition tree.
876#[derive(Clone)]
877pub struct WindowCompositionSurface(Rc<WindowCompositionSurfaceInner>);
878
879impl WindowCompositionSurface {
880    /// Returns this surface's stable identity.
881    pub fn id(&self) -> CompositionSurfaceId {
882        self.0.id
883    }
884
885    /// Returns the platform surface used to attach native content.
886    pub fn platform_surface(&self) -> Result<&dyn PlatformSurfaceAttachment> {
887        self.0
888            .platform_surface
889            .as_deref()
890            .context("this composition surface is rendered by GPUI")
891    }
892}
893
894/// Controls the surface tree composited into a window.
895pub struct WindowComposition<'a> {
896    platform_window: &'a dyn PlatformWindow,
897    state: Rc<RefCell<WindowCompositionState>>,
898}
899
900impl WindowComposition<'_> {
901    /// Registers a cooperating windowless producer's mouse/wheel consumer.
902    /// Capture runs first; coordinates are in window-content logical pixels.
903    /// OS-managed child views need no handler and keep their platform input path.
904    pub fn on_input(
905        &self,
906        surface: CompositionSurfaceId,
907        handler: impl FnMut(&PlatformInput) -> DispatchEventResult + 'static,
908    ) -> Result<()> {
909        let previous = {
910            let mut state = self.state.borrow_mut();
911            anyhow::ensure!(
912                state.platform_surfaces.contains_key(&surface),
913                "input consumer requires a native surface"
914            );
915            state.platform_surfaces[&surface].input_forwarding.set(true);
916            state
917                .input_handlers
918                .insert(surface, Rc::new(RefCell::new(Box::new(handler))))
919        };
920        if let Err(error) = self.synchronize_platform_order() {
921            let mut state = self.state.borrow_mut();
922            state.platform_surfaces[&surface]
923                .input_forwarding
924                .set(previous.is_some());
925            if let Some(previous) = previous {
926                state.input_handlers.insert(surface, previous);
927            } else {
928                state.input_handlers.remove(&surface);
929            }
930            drop(state);
931            self.synchronize_platform_order().log_err();
932            return Err(error);
933        }
934        Ok(())
935    }
936
937    /// Returns the GPUI surface initially rendered below native content.
938    pub fn base_surface(&self) -> CompositionSurfaceId {
939        self.state.borrow().base_surface
940    }
941
942    /// Returns the GPUI surface initially rendered above native content.
943    pub fn overlay_surface(&self) -> CompositionSurfaceId {
944        self.state.borrow().overlay_surface
945    }
946
947    /// Creates a platform-native surface as a root of the composition tree,
948    /// below the overlay surface.
949    pub fn create_native_surface(&self) -> Result<WindowCompositionSurface> {
950        let platform_surface = self.platform_window.create_native_surface()?;
951        self.register_platform_surface(CompositionSurfaceKind::Native, platform_surface)
952    }
953
954    /// Registers an externally produced GPU surface as a root of the
955    /// composition tree, below the overlay surface.
956    ///
957    /// The producer owns the platform attachment and its synchronization. GPUI
958    /// owns its placement in the window composition tree.
959    pub fn create_external_gpu_surface(
960        &self,
961        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
962    ) -> Result<WindowCompositionSurface> {
963        self.register_platform_surface(CompositionSurfaceKind::ExternalGpu, platform_surface)
964    }
965
966    /// Creates another GPUI-rendered surface in the composition tree. Paint
967    /// onto it with [`Window::with_composition_surface`].
968    pub fn create_gpui_surface(
969        &self,
970        parent: Option<CompositionSurfaceId>,
971    ) -> Result<WindowCompositionSurface> {
972        let id = self
973            .state
974            .borrow_mut()
975            .tree
976            .insert(CompositionSurfaceKind::Gpui, parent)?;
977        if let Err(error) = self.synchronize_platform_order() {
978            self.state.borrow_mut().tree.remove(id)?;
979            self.synchronize_platform_order().log_err();
980            return Err(error);
981        }
982        Ok(surface_handle(id, None))
983    }
984
985    /// Places `surface` immediately above `sibling`.
986    pub fn place_above(
987        &self,
988        surface: CompositionSurfaceId,
989        sibling: CompositionSurfaceId,
990    ) -> Result<()> {
991        anyhow::ensure!(
992            surface != self.state.borrow().base_surface,
993            "the GPUI base surface cannot be reordered"
994        );
995        self.change_tree(|tree| tree.place_above(surface, sibling))
996    }
997
998    /// Places `surface` immediately below `sibling`.
999    pub fn place_below(
1000        &self,
1001        surface: CompositionSurfaceId,
1002        sibling: CompositionSurfaceId,
1003    ) -> Result<()> {
1004        let base_surface = self.state.borrow().base_surface;
1005        anyhow::ensure!(
1006            surface != base_surface && sibling != base_surface,
1007            "surfaces cannot be placed below or move the GPUI base surface"
1008        );
1009        self.change_tree(|tree| tree.place_below(surface, sibling))
1010    }
1011
1012    /// Moves `surface` under a new parent, placing it above existing children.
1013    pub fn reparent(
1014        &self,
1015        surface: CompositionSurfaceId,
1016        parent: Option<CompositionSurfaceId>,
1017    ) -> Result<()> {
1018        anyhow::ensure!(
1019            surface != self.state.borrow().base_surface,
1020            "the GPUI base surface cannot be reparented"
1021        );
1022        self.change_tree(|tree| tree.reparent(surface, parent))
1023    }
1024
1025    /// Removes a surface while preserving its children at the removed
1026    /// surface's previous position.
1027    pub fn remove_surface(&self, surface: CompositionSurfaceId) -> Result<()> {
1028        let mut state = self.state.borrow_mut();
1029        if surface == state.base_surface || surface == state.overlay_surface {
1030            bail!("the default GPUI composition surfaces cannot be removed");
1031        }
1032        let previous_tree = state.tree.clone();
1033        let platform_surface = state.platform_surfaces.get(&surface).cloned();
1034        let was_visible = state
1035            .visible
1036            .get(&surface)
1037            .is_none_or(|visible| visible.get());
1038        if let Some(platform_surface) = &platform_surface {
1039            platform_surface.set_visible(false)?;
1040        }
1041        state.tree.remove(surface)?;
1042        state.platform_surfaces.remove(&surface);
1043        drop(state);
1044        if let Err(error) = self.synchronize_platform_order() {
1045            let mut state = self.state.borrow_mut();
1046            state.tree = previous_tree;
1047            if let Some(platform_surface) = platform_surface {
1048                platform_surface.set_visible(was_visible).log_err();
1049                state.platform_surfaces.insert(surface, platform_surface);
1050            }
1051            drop(state);
1052            self.synchronize_platform_order().log_err();
1053            return Err(error);
1054        }
1055        let mut state = self.state.borrow_mut();
1056        state.visible.remove(&surface);
1057        state.input_handlers.remove(&surface);
1058        if state.pointer_capture == Some(surface) {
1059            state.pointer_capture = None;
1060            state.pressed_buttons.clear();
1061        }
1062        if state.hovered_native == Some(surface) {
1063            state.hovered_native = None;
1064        }
1065        Ok(())
1066    }
1067
1068    /// Returns the renderer kind for a surface.
1069    pub fn surface_kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
1070        self.state.borrow().tree.kind(surface)
1071    }
1072
1073    /// Returns a surface's parent.
1074    pub fn parent(&self, surface: CompositionSurfaceId) -> Result<Option<CompositionSurfaceId>> {
1075        self.state.borrow().tree.parent(surface)
1076    }
1077
1078    /// Returns the ordered children of a surface, or the root surfaces when
1079    /// `parent` is `None`.
1080    pub fn children(
1081        &self,
1082        parent: Option<CompositionSurfaceId>,
1083    ) -> Result<Vec<CompositionSurfaceId>> {
1084        Ok(self.state.borrow().tree.children(parent)?.to_vec())
1085    }
1086
1087    /// Applies `change` to the tree and the platform, or neither.
1088    fn change_tree(&self, change: impl FnOnce(&mut CompositionTree) -> Result<()>) -> Result<()> {
1089        let previous_tree = self.state.borrow().tree.clone();
1090        change(&mut self.state.borrow_mut().tree)?;
1091        if let Err(error) = self.synchronize_platform_order() {
1092            self.state.borrow_mut().tree = previous_tree;
1093            self.synchronize_platform_order().log_err();
1094            return Err(error);
1095        }
1096        Ok(())
1097    }
1098
1099    fn register_platform_surface(
1100        &self,
1101        kind: CompositionSurfaceKind,
1102        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
1103    ) -> Result<WindowCompositionSurface> {
1104        let platform_surface = Rc::new(ManagedPlatformSurface::new(
1105            platform_surface,
1106            &self.state.borrow(),
1107        ));
1108        let visible = platform_surface.visible.clone();
1109        let mut state = self.state.borrow_mut();
1110        let id = state.tree.insert(kind, None)?;
1111        let overlay_surface = state.overlay_surface;
1112        state.tree.place_below(id, overlay_surface)?;
1113        state.platform_surfaces.insert(id, platform_surface.clone());
1114        state.visible.insert(id, visible);
1115        drop(state);
1116        if let Err(error) = self.synchronize_platform_order() {
1117            platform_surface.set_visible(false).log_err();
1118            let mut state = self.state.borrow_mut();
1119            state.platform_surfaces.remove(&id);
1120            state.visible.remove(&id);
1121            state.tree.remove(id)?;
1122            drop(state);
1123            self.synchronize_platform_order().log_err();
1124            return Err(error);
1125        }
1126        Ok(surface_handle(id, Some(platform_surface)))
1127    }
1128
1129    /// Hands the platform the tree's order and every surface's geometry.
1130    fn synchronize_platform_order(&self) -> Result<()> {
1131        let state = self.state.borrow();
1132        let mut origins = FxHashMap::default();
1133        let mut surfaces = Vec::new();
1134        for id in state.tree.flattened() {
1135            let parent = state.tree.parent(id)?;
1136            let parent_origin = parent
1137                .and_then(|parent| origins.get(&parent).copied())
1138                .unwrap_or_default();
1139            let content = match state.tree.kind(id)? {
1140                CompositionSurfaceKind::Gpui => PlatformCompositionSurfaceContent::Gpui,
1141                CompositionSurfaceKind::Native => PlatformCompositionSurfaceContent::Native(
1142                    state
1143                        .platform_surfaces
1144                        .get(&id)
1145                        .context("native composition surface is missing")?
1146                        .clone(),
1147                ),
1148                CompositionSurfaceKind::ExternalGpu => {
1149                    PlatformCompositionSurfaceContent::ExternalGpu(
1150                        state
1151                            .platform_surfaces
1152                            .get(&id)
1153                            .context("external GPU composition surface is missing")?
1154                            .clone(),
1155                    )
1156                }
1157            };
1158            let window_bounds = match &content {
1159                PlatformCompositionSurfaceContent::Gpui => None,
1160                PlatformCompositionSurfaceContent::Native(platform_surface)
1161                | PlatformCompositionSurfaceContent::ExternalGpu(platform_surface) => {
1162                    Some(platform_surface.bounds())
1163                }
1164            };
1165            let window_origin = window_bounds.map_or_else(Point::default, |bounds| bounds.origin);
1166            origins.insert(id, window_origin);
1167            surfaces.push(PlatformCompositionSurface {
1168                id,
1169                parent,
1170                window_origin,
1171                parent_origin,
1172                window_bounds,
1173                content,
1174            });
1175        }
1176        self.platform_window.set_composition_order(&surfaces)?;
1177        state.geometry_dirty.set(false);
1178        drop(state);
1179        self.state.borrow_mut().input_order = surfaces.iter().map(|surface| surface.id).collect();
1180        Ok(())
1181    }
1182}
1183
1184fn surface_handle(
1185    id: CompositionSurfaceId,
1186    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
1187) -> WindowCompositionSurface {
1188    WindowCompositionSurface(Rc::new(WindowCompositionSurfaceInner {
1189        id,
1190        platform_surface,
1191    }))
1192}
1193
1194impl Window {
1195    /// Enables native window composition and returns its controller.
1196    ///
1197    /// GPUI's root scene is rendered below surfaces created by the controller,
1198    /// while deferred and window-level overlays are rendered above them.
1199    pub fn enable_window_composition(&self) -> Result<WindowComposition<'_>> {
1200        self.platform_window.enable_window_composition()?;
1201        let composition = WindowComposition {
1202            platform_window: self.platform_window.as_ref(),
1203            state: self.fast_composition.0.clone(),
1204        };
1205        composition.synchronize_platform_order()?;
1206        composition.state.borrow_mut().enabled = true;
1207        Ok(composition)
1208    }
1209
1210    /// Prepaints or paints an element scope on a GPUI composition surface,
1211    /// then restores the previous surface. Wrap both phases when selecting a
1212    /// surface explicitly so its input regions follow its painted content.
1213    ///
1214    /// Inside a scroll layer, whose content is composited from tiles, the
1215    /// scope paints where the layer does.
1216    pub fn with_composition_surface<R>(
1217        &mut self,
1218        surface: CompositionSurfaceId,
1219        paint: impl FnOnce(&mut Self) -> R,
1220    ) -> Result<R> {
1221        self.invalidator.debug_assert_paint_or_prepaint();
1222        anyhow::ensure!(
1223            self.fast_composition.0.borrow().tree.kind(surface)? == CompositionSurfaceKind::Gpui,
1224            "paint operations can only target GPUI composition surfaces"
1225        );
1226        if self.fast_layers.painting.is_some() {
1227            return Ok(paint(self));
1228        }
1229        if self.invalidator.inner.borrow().draw_phase == crate::window::DrawPhase::Prepaint {
1230            let previous = self
1231                .next_frame
1232                .fast_composition_input
1233                .scope
1234                .replace(surface);
1235            let result = paint(self);
1236            self.next_frame.fast_composition_input.scope = previous;
1237            return Ok(result);
1238        }
1239        let previous_surface = self
1240            .next_frame
1241            .fast_composition_starts
1242            .current()
1243            .context("composition paint scope has no base surface")?;
1244        switch_surface(self, surface);
1245        let result = paint(self);
1246        switch_surface(self, previous_surface);
1247        Ok(result)
1248    }
1249}
1250
1251fn switch_surface(window: &mut Window, surface: CompositionSurfaceId) {
1252    let scene_len = window.next_frame.scene.len();
1253    window
1254        .next_frame
1255        .fast_composition_starts
1256        .switch_to(surface, scene_len);
1257}
1258
1259/// Stacks what the root view positions, as it prepaints, below the overlay
1260/// surface.
1261pub(crate) fn begin_base_prepaint(window: &mut Window) {
1262    begin_input(window, false);
1263}
1264
1265/// Stacks what deferred and window-level draws position, as they prepaint,
1266/// above the overlay surface.
1267pub(crate) fn begin_overlay_prepaint(window: &mut Window) {
1268    begin_input(window, true);
1269}
1270
1271/// Paints what follows, the root view, onto the base surface.
1272pub(crate) fn begin_base(window: &mut Window) {
1273    let state = window.fast_composition.0.borrow();
1274    state.prepainting.set(None);
1275    let surface = state.base_surface;
1276    drop(state);
1277    switch_surface(window, surface);
1278}
1279
1280/// Moves each root native surface whose host changed surface to that
1281/// surface's side of the overlay surface.
1282fn restack_native_surfaces(state: &mut WindowCompositionState) -> Result<()> {
1283    let overlay = state.overlay_surface;
1284    for (id, surface) in &state.platform_surfaces {
1285        if !surface.restack.replace(false) || state.tree.parent(*id)?.is_some() {
1286            continue;
1287        }
1288        match surface.host.get() {
1289            Host::Base => state.tree.place_below(*id, overlay)?,
1290            Host::Overlay => state.tree.place_above(*id, overlay)?,
1291        }
1292    }
1293    Ok(())
1294}
1295
1296/// Paints what follows, deferred and window-level draws, onto the overlay
1297/// surface.
1298pub(crate) fn begin_overlay(window: &mut Window) {
1299    let surface = window.fast_composition.0.borrow().overlay_surface;
1300    switch_surface(window, surface);
1301}
1302
1303/// Carries the surface switches last frame made within `range` into the
1304/// frame being drawn, as [`Window::reuse_paint`] replays its scene, and
1305/// leaves painting on the surface it was on before.
1306pub(crate) fn reuse_starts(window: &mut Window, range: &Range<PaintIndex>) {
1307    let scenes = range.start.scene_index..range.end.scene_index;
1308    let starts = &window.rendered_frame.fast_composition_starts.0;
1309    let first = starts.partition_point(|(_, start)| *start < scenes.start);
1310    let last = starts.partition_point(|(_, start)| *start < scenes.end);
1311    if first == last {
1312        return;
1313    }
1314    let Some(surface) = window.next_frame.fast_composition_starts.current() else {
1315        return;
1316    };
1317    let offset = window.next_frame.scene.len();
1318    for index in first..last {
1319        let (reused, start) = window.rendered_frame.fast_composition_starts.0[index];
1320        window
1321            .next_frame
1322            .fast_composition_starts
1323            .switch_to(reused, start - scenes.start + offset);
1324    }
1325    let end = offset + scenes.len();
1326    window
1327        .next_frame
1328        .fast_composition_starts
1329        .switch_to(surface, end);
1330}
1331
1332// Host changes must reach input ownership before the frame's hit test.
1333fn synchronize_geometry(window: &mut Window) {
1334    let state = window.fast_composition.0.clone();
1335    if !state.borrow().enabled {
1336        return;
1337    }
1338    if state.borrow().geometry_dirty.get() {
1339        if let Err(error) = restack_native_surfaces(&mut state.borrow_mut()) {
1340            log::error!("restacking native composition surfaces: {error:#}");
1341        }
1342        let composition = WindowComposition {
1343            platform_window: window.platform_window.as_ref(),
1344            state,
1345        };
1346        if let Err(error) = composition.synchronize_platform_order() {
1347            log::error!("updating window composition geometry: {error:#}");
1348        }
1349    }
1350}
1351
1352/// Presents the frame last drawn: on its one surface, or split along the
1353/// composition tree once the window composes.
1354pub(crate) fn present(window: &mut Window) {
1355    let state = window.fast_composition.0.clone();
1356    if !state.borrow().enabled {
1357        window.platform_window.draw(&window.rendered_frame.scene);
1358        return;
1359    }
1360    synchronize_geometry(window);
1361    let state = state.borrow();
1362    let scene = &window.rendered_frame.scene;
1363    let layers = composed_scene_layers(
1364        &state.tree,
1365        &window.rendered_frame.fast_composition_starts.0,
1366        scene.len(),
1367    )
1368    .unwrap_or_else(|error| {
1369        log::error!("invalid window composition scene: {error:#}");
1370        vec![ComposedSceneLayer {
1371            surface: state.base_surface,
1372            ranges: vec![0..scene.len()],
1373        }]
1374    });
1375    drop(state);
1376    window.platform_window.draw_composed(ComposedScene::new(
1377        scene,
1378        layers,
1379        &window.rendered_frame.fast_composition_input,
1380    ));
1381}
1382
1383/// Visibility and ancestor clips come from the existing managed surface tree.
1384fn input_bounds(
1385    state: &WindowCompositionState,
1386    surface: CompositionSurfaceId,
1387    mut bounds: Bounds<Pixels>,
1388    scale: f32,
1389) -> Option<Bounds<Pixels>> {
1390    let mut current = Some(surface);
1391    while let Some(id) = current {
1392        state.tree.kind(id).ok()?;
1393        if state.visible.get(&id).is_some_and(|visible| !visible.get()) {
1394            return None;
1395        }
1396        if let Some(native) = state.platform_surfaces.get(&id) {
1397            bounds = bounds.intersect(&native.bounds().to_pixels(scale));
1398        }
1399        current = state.tree.parent(id).ok()?;
1400    }
1401    (!bounds.is_empty()).then_some(bounds)
1402}
1403
1404fn visible_surface(state: &WindowCompositionState, surface: CompositionSurfaceId) -> bool {
1405    let mut current = Some(surface);
1406    while let Some(id) = current {
1407        if state.tree.kind(id).is_err() || state.visible.get(&id).is_some_and(|v| !v.get()) {
1408            return false;
1409        }
1410        current = state.tree.parent(id).ok().flatten();
1411    }
1412    true
1413}
1414
1415fn native_target(window: &Window, scroll: bool) -> Option<CompositionSurfaceId> {
1416    let state = window.fast_composition.0.borrow();
1417    if !state.enabled || state.platform_surfaces.is_empty() {
1418        return None;
1419    }
1420    if !scroll {
1421        if let Some(captured) = state
1422            .pointer_capture
1423            .filter(|id| visible_surface(&state, *id))
1424        {
1425            return Some(captured);
1426        }
1427    }
1428    let point = window.mouse_position;
1429    for surface in state.input_order.iter().rev().copied() {
1430        if !visible_surface(&state, surface) {
1431            continue;
1432        }
1433        if let Some(native) = state.platform_surfaces.get(&surface) {
1434            if input_bounds(
1435                &state,
1436                surface,
1437                native.bounds().to_pixels(window.scale_factor()),
1438                window.scale_factor(),
1439            )
1440            .is_some_and(|bounds| bounds.contains(&point))
1441            {
1442                return Some(surface);
1443            }
1444        } else if let Some(regions) = window
1445            .rendered_frame
1446            .fast_composition_input
1447            .hitboxes
1448            .get(&surface)
1449        {
1450            if regions.iter().rev().any(|hitbox| {
1451                hitbox.bounds.contains(&point)
1452                    && (!scroll || hitbox.behavior == HitboxBehavior::BlockMouse)
1453            }) {
1454                return None;
1455            }
1456        }
1457    }
1458    None
1459}
1460
1461/// OS-directed native events still run GPUI capture, but cannot activate
1462/// unrelated GPUI widgets underneath the native view.
1463fn native_mouse(window: &Window, event: &dyn Any) -> bool {
1464    if window.captured_hitbox.is_some() {
1465        let state = window.fast_composition.0.borrow();
1466        return state
1467            .pointer_capture
1468            .is_some_and(|id| visible_surface(&state, id));
1469    }
1470    if event
1471        .downcast_ref::<MouseMoveEvent>()
1472        .is_some_and(|event| event.pressed_button.is_some())
1473        && window.fast_composition.0.borrow().pointer_capture.is_none()
1474    {
1475        return false;
1476    }
1477    native_target(window, false).is_some()
1478}
1479
1480pub(crate) fn bubble_mouse(window: &Window, event: &dyn Any, cx: &crate::App) -> bool {
1481    cx.propagate_event && (cx.has_active_drag() || !native_mouse(window, event))
1482}
1483
1484pub(crate) fn event_target(window: &Window, event: &PlatformInput) -> Option<CompositionSurfaceId> {
1485    if !matches!(
1486        event,
1487        PlatformInput::MouseDown(_)
1488            | PlatformInput::MouseUp(_)
1489            | PlatformInput::MouseMove(_)
1490            | PlatformInput::ScrollWheel(_)
1491    ) {
1492        return None;
1493    }
1494    let scroll = matches!(event, PlatformInput::ScrollWheel(_));
1495    if !scroll {
1496        let state = window.fast_composition.0.borrow();
1497        if let Some(captured) = state.pointer_capture {
1498            return visible_surface(&state, captured).then_some(captured);
1499        }
1500    }
1501    if window.captured_hitbox.is_some() || matches!(event, PlatformInput::MouseUp(_)) {
1502        return None;
1503    }
1504    if matches!(
1505        event,
1506        PlatformInput::MouseMove(MouseMoveEvent {
1507            pressed_button: Some(_),
1508            ..
1509        })
1510    ) && window.fast_composition.0.borrow().pointer_capture.is_none()
1511    {
1512        return None;
1513    }
1514    native_target(window, scroll)
1515}
1516
1517/// Called after the existing dispatcher; windowless producers get one delivery,
1518/// while OS-managed views continue through the platform's original event path.
1519pub(crate) fn dispatch_native(
1520    window: &mut Window,
1521    event: &PlatformInput,
1522    target: Option<CompositionSurfaceId>,
1523    propagate: &mut bool,
1524) {
1525    let pointer = matches!(
1526        event,
1527        PlatformInput::MouseDown(_)
1528            | PlatformInput::MouseUp(_)
1529            | PlatformInput::MouseMove(_)
1530            | PlatformInput::MouseExited(_)
1531            | PlatformInput::ScrollWheel(_)
1532    );
1533    if !pointer || !window.fast_composition.0.borrow().enabled {
1534        return;
1535    }
1536    let target = target.filter(|id| visible_surface(&window.fast_composition.0.borrow(), *id));
1537    let (handler, leave) = {
1538        let mut state = window.fast_composition.0.borrow_mut();
1539        let leave = if matches!(
1540            event,
1541            PlatformInput::MouseMove(_) | PlatformInput::MouseExited(_)
1542        ) {
1543            let current = if matches!(event, PlatformInput::MouseExited(_)) {
1544                None
1545            } else {
1546                target
1547            };
1548            let previous = std::mem::replace(&mut state.hovered_native, current);
1549            previous
1550                .filter(|old| Some(*old) != current)
1551                .and_then(|id| state.input_handlers.get(&id).cloned())
1552        } else {
1553            None
1554        };
1555        if *propagate && !window.default_prevented {
1556            if let PlatformInput::MouseDown(down) = event {
1557                if let Some(id) = target {
1558                    state.pointer_capture = Some(id);
1559                    if !state.pressed_buttons.contains(&down.button) {
1560                        state.pressed_buttons.push(down.button);
1561                    }
1562                }
1563            }
1564        }
1565        let owned_release = matches!(event, PlatformInput::MouseUp(_))
1566            && target.is_some()
1567            && state.pointer_capture == target;
1568        let handler = if (*propagate && !window.default_prevented) || owned_release {
1569            target.and_then(|id| state.input_handlers.get(&id).cloned())
1570        } else {
1571            None
1572        };
1573        if let PlatformInput::MouseUp(up) = event {
1574            // A single press ends even if platform normalization changed its button
1575            // (AppKit ctrl-click with Control released before mouse-up).
1576            if state.pressed_buttons.len() == 1 {
1577                state.pressed_buttons.clear();
1578            } else {
1579                state.pressed_buttons.retain(|button| *button != up.button);
1580            }
1581            if state.pressed_buttons.is_empty() {
1582                state.pointer_capture = None;
1583            }
1584        }
1585        (handler, leave)
1586    };
1587    if let Some(leave) = leave {
1588        let (position, pressed_button, modifiers) = match event {
1589            PlatformInput::MouseMove(event) => {
1590                (event.position, event.pressed_button, event.modifiers)
1591            }
1592            PlatformInput::MouseExited(event) => {
1593                (event.position, event.pressed_button, event.modifiers)
1594            }
1595            _ => unreachable!(),
1596        };
1597        leave.borrow_mut()(&PlatformInput::MouseExited(MouseExitEvent {
1598            position,
1599            pressed_button,
1600            modifiers,
1601        }));
1602    }
1603    if let Some(handler) = handler {
1604        let result = handler.borrow_mut()(event);
1605        *propagate &= result.propagate;
1606        window.default_prevented |= result.default_prevented;
1607    }
1608}
1609
1610#[cfg(test)]
1611mod tests {
1612    use super::{
1613        CompositionSurfaceId, CompositionSurfaceKind, CompositionTree, Host,
1614        ManagedPlatformSurface, PlatformSurfaceAttachment, composed_scene_layers,
1615        restack_native_surfaces,
1616    };
1617    use crate::{
1618        AppContext as _, Bounds, ContentMask, Context, DevicePixels, Entity, IntoElement,
1619        ParentElement as _, Point, Quad, Render, ScaledPixels, Scene, Size, StyleRefinement,
1620        Styled as _, TestAppContext, Window, canvas, deferred, div, fill, px,
1621        scene::PaintOperation, size,
1622    };
1623    use anyhow::Result;
1624    use std::{any::Any, cell::Cell, rc::Rc};
1625
1626    #[test]
1627    fn composition_surfaces_have_stable_identity_and_explicit_order() -> Result<()> {
1628        let mut tree = CompositionTree::new();
1629        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1630        let webview = tree.insert(CompositionSurfaceKind::Native, None)?;
1631        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1632
1633        tree.place_below(overlay, webview)?;
1634
1635        assert_eq!(tree.flattened(), [base, overlay, webview]);
1636        assert_eq!(tree.kind(webview)?, CompositionSurfaceKind::Native);
1637        Ok(())
1638    }
1639
1640    #[test]
1641    fn composition_surfaces_can_be_nested_and_reparented() -> Result<()> {
1642        let mut tree = CompositionTree::new();
1643        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1644        let pane = tree.insert(CompositionSurfaceKind::Native, Some(base))?;
1645        let video = tree.insert(CompositionSurfaceKind::ExternalGpu, None)?;
1646
1647        tree.reparent(video, Some(pane))?;
1648
1649        assert_eq!(tree.parent(video)?, Some(pane));
1650        assert_eq!(tree.children(Some(pane))?, [video]);
1651        assert_eq!(tree.flattened(), [base, pane, video]);
1652        Ok(())
1653    }
1654
1655    #[test]
1656    fn composition_tree_rejects_cycles_and_cross_parent_ordering() -> Result<()> {
1657        let mut tree = CompositionTree::new();
1658        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1659        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1660        let sibling = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1661
1662        assert!(tree.reparent(parent, Some(child)).is_err());
1663        assert!(tree.place_above(child, sibling).is_err());
1664        assert_eq!(tree.parent(parent)?, None);
1665        assert_eq!(tree.parent(child)?, Some(parent));
1666        Ok(())
1667    }
1668
1669    #[test]
1670    fn removing_a_surface_preserves_and_reparents_its_children() -> Result<()> {
1671        let mut tree = CompositionTree::new();
1672        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1673        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1674
1675        tree.remove(parent)?;
1676
1677        assert_eq!(tree.parent(child)?, None);
1678        assert_eq!(tree.flattened(), [child]);
1679        Ok(())
1680    }
1681
1682    #[test]
1683    fn scene_ranges_follow_tree_order_and_preserve_repeated_segments() -> Result<()> {
1684        let mut tree = CompositionTree::new();
1685        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1686        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1687        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1688        let starts = [(base, 0), (overlay, 4), (base, 7)];
1689
1690        let layers = composed_scene_layers(&tree, &starts, 10)?;
1691
1692        let [base_layer, overlay_layer] = layers.as_slice() else {
1693            panic!("expected base and overlay scene layers");
1694        };
1695        assert_eq!(base_layer.surface, base);
1696        assert_eq!(base_layer.ranges, [0..4, 7..10]);
1697        assert_eq!(overlay_layer.surface, overlay);
1698        assert_eq!(overlay_layer.ranges, [4..7]);
1699        assert_eq!(tree.kind(native)?, CompositionSurfaceKind::Native);
1700        Ok(())
1701    }
1702
1703    #[test]
1704    fn scene_ranges_reject_non_gpui_targets_and_non_monotonic_markers() -> Result<()> {
1705        let mut tree = CompositionTree::new();
1706        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1707        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1708
1709        assert!(composed_scene_layers(&tree, &[(native, 0)], 1).is_err());
1710        assert!(composed_scene_layers(&tree, &[(base, 2), (base, 1)], 2).is_err());
1711        Ok(())
1712    }
1713
1714    struct TestPlatformSurface {
1715        bounds_writes: Cell<usize>,
1716        fail_next_bounds: Cell<bool>,
1717        bounds: Cell<Bounds<DevicePixels>>,
1718        parent_origin: Cell<Point<DevicePixels>>,
1719    }
1720
1721    impl PlatformSurfaceAttachment for TestPlatformSurface {
1722        fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
1723            self.bounds_writes.set(self.bounds_writes.get() + 1);
1724            if self.fail_next_bounds.replace(false) {
1725                return Err(anyhow::anyhow!("test bounds failure"));
1726            }
1727            self.bounds.set(bounds);
1728            Ok(())
1729        }
1730
1731        fn bounds(&self) -> Bounds<DevicePixels> {
1732            self.bounds.get()
1733        }
1734
1735        fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
1736            self.parent_origin.set(origin);
1737            Ok(())
1738        }
1739
1740        fn set_visible(&self, _visible: bool) -> Result<()> {
1741            Ok(())
1742        }
1743
1744        fn platform_handle(&self) -> Result<Box<dyn Any>> {
1745            Ok(Box::new(()))
1746        }
1747    }
1748
1749    #[test]
1750    fn managed_composition_surface_tracks_window_geometry_changes() {
1751        let platform_surface = Rc::new(TestPlatformSurface {
1752            bounds_writes: Cell::new(0),
1753            fail_next_bounds: Cell::new(false),
1754            bounds: Cell::new(Bounds::default()),
1755            parent_origin: Cell::new(Point::default()),
1756        });
1757        let geometry_dirty = Rc::new(Cell::new(false));
1758        let surface = ManagedPlatformSurface {
1759            platform_surface: platform_surface.clone(),
1760            bounds: Cell::new(Bounds::default()),
1761            geometry_dirty: geometry_dirty.clone(),
1762            visible: Rc::new(Cell::new(true)),
1763            input_forwarding: Cell::new(false),
1764            prepainting: Rc::new(Cell::new(None)),
1765            host: Cell::new(Host::Base),
1766            restack: Cell::new(false),
1767        };
1768        let bounds = Bounds {
1769            origin: Point {
1770                x: DevicePixels(25),
1771                y: DevicePixels(40),
1772            },
1773            size: size(DevicePixels(300), DevicePixels(200)),
1774        };
1775        let parent_origin = Point {
1776            x: DevicePixels(10),
1777            y: DevicePixels(15),
1778        };
1779
1780        assert!(surface.set_bounds(bounds).is_ok());
1781        assert!(surface.set_parent_origin(parent_origin).is_ok());
1782
1783        assert_eq!(surface.bounds(), bounds);
1784        assert_eq!(platform_surface.bounds.get(), bounds);
1785        assert_eq!(platform_surface.parent_origin.get(), parent_origin);
1786        assert!(geometry_dirty.get());
1787    }
1788
1789    #[test]
1790    fn unchanged_native_bounds_do_not_resynchronize_composition() -> Result<()> {
1791        let bounds = Bounds::new(Point::default(), size(DevicePixels(300), DevicePixels(200)));
1792        let platform = Rc::new(TestPlatformSurface {
1793            bounds_writes: Cell::new(0),
1794            fail_next_bounds: Cell::new(false),
1795            bounds: Cell::new(Bounds::default()),
1796            parent_origin: Cell::new(Point::default()),
1797        });
1798        let dirty = Rc::new(Cell::new(false));
1799        let surface = ManagedPlatformSurface {
1800            platform_surface: platform.clone(),
1801            bounds: Cell::new(Bounds::default()),
1802            geometry_dirty: dirty.clone(),
1803            visible: Rc::new(Cell::new(true)),
1804            input_forwarding: Cell::new(false),
1805            prepainting: Rc::new(Cell::new(None)),
1806            host: Cell::new(Host::Base),
1807            restack: Cell::new(false),
1808        };
1809        surface.set_bounds(bounds)?;
1810        dirty.set(false);
1811        for _ in 0..10 {
1812            surface.set_bounds(bounds)?;
1813        }
1814        assert!(
1815            !dirty.get(),
1816            "unchanged layout must not remount native views between mouse down and up"
1817        );
1818        assert_eq!(platform.bounds_writes.get(), 1);
1819        let moved = Bounds::new(
1820            Point {
1821                x: DevicePixels(20),
1822                y: DevicePixels(15),
1823            },
1824            bounds.size,
1825        );
1826        surface.set_bounds(moved)?;
1827        assert!(dirty.get());
1828        assert_eq!(platform.bounds_writes.get(), 2);
1829        assert_eq!(surface.bounds(), moved);
1830        Ok(())
1831    }
1832
1833    #[test]
1834    fn failed_native_bounds_updates_remain_retryable() -> Result<()> {
1835        let bounds = Bounds::new(Point::default(), size(DevicePixels(600), DevicePixels(400)));
1836        let platform = Rc::new(TestPlatformSurface {
1837            bounds_writes: Cell::new(0),
1838            fail_next_bounds: Cell::new(true),
1839            bounds: Cell::new(Bounds::default()),
1840            parent_origin: Cell::new(Point::default()),
1841        });
1842        let dirty = Rc::new(Cell::new(false));
1843        let surface = ManagedPlatformSurface {
1844            platform_surface: platform.clone(),
1845            bounds: Cell::new(Bounds::default()),
1846            geometry_dirty: dirty.clone(),
1847            visible: Rc::new(Cell::new(true)),
1848            input_forwarding: Cell::new(false),
1849            prepainting: Rc::new(Cell::new(None)),
1850            host: Cell::new(Host::Base),
1851            restack: Cell::new(false),
1852        };
1853        assert!(surface.set_bounds(bounds).is_err());
1854        assert_eq!(surface.bounds(), Bounds::default());
1855        assert!(!dirty.get());
1856        surface.set_bounds(bounds)?;
1857        assert!(dirty.get());
1858        assert_eq!(surface.bounds(), bounds);
1859        assert_eq!(platform.bounds_writes.get(), 2);
1860        dirty.set(false);
1861        surface.set_bounds(bounds)?;
1862        assert!(!dirty.get());
1863        assert_eq!(platform.bounds_writes.get(), 2);
1864        Ok(())
1865    }
1866
1867    fn square(side: f32) -> Bounds<ScaledPixels> {
1868        Bounds {
1869            origin: Point::default(),
1870            size: Size {
1871                width: ScaledPixels::from(side),
1872                height: ScaledPixels::from(side),
1873            },
1874        }
1875    }
1876
1877    #[test]
1878    fn empty_layers_do_not_make_a_scene_drawable() {
1879        let mut scene = Scene::default();
1880        scene.push_layer(square(100.));
1881        scene.pop_layer();
1882
1883        assert_ne!(scene.len(), 0);
1884        assert!(scene.is_empty());
1885    }
1886
1887    #[test]
1888    fn drawable_primitives_make_a_scene_non_empty() {
1889        let mut scene = Scene::default();
1890        let bounds = square(100.);
1891        scene.insert_primitive(Quad {
1892            bounds,
1893            content_mask: ContentMask { bounds },
1894            ..Default::default()
1895        });
1896
1897        assert!(!scene.is_empty());
1898    }
1899
1900    #[test]
1901    fn replay_preserves_scene_emptiness() {
1902        let mut source = Scene::default();
1903        source.push_layer(square(100.));
1904        source.pop_layer();
1905
1906        let mut replayed = Scene::default();
1907        replayed.replay(0..source.len(), &source);
1908
1909        assert!(replayed.is_empty());
1910    }
1911
1912    #[test]
1913    fn balanced_replay_restores_layers_crossing_the_range_boundary() {
1914        let mut source = Scene::default();
1915        let inner_bounds = square(50.);
1916        source.push_layer(square(100.));
1917        source.push_layer(inner_bounds);
1918        source.insert_primitive(Quad {
1919            bounds: inner_bounds,
1920            content_mask: ContentMask {
1921                bounds: inner_bounds,
1922            },
1923            ..Default::default()
1924        });
1925        source.pop_layer();
1926        source.pop_layer();
1927
1928        let mut replayed = Scene::default();
1929        assert!(replayed.replay_balanced(2..3, &source).is_ok());
1930
1931        assert_eq!(replayed.paint_operations.len(), 5);
1932        assert!(matches!(
1933            replayed.paint_operations.as_slice(),
1934            [
1935                PaintOperation::StartLayer(_),
1936                PaintOperation::StartLayer(_),
1937                PaintOperation::Primitive(_),
1938                PaintOperation::EndLayer,
1939                PaintOperation::EndLayer
1940            ]
1941        ));
1942    }
1943
1944    #[test]
1945    fn balanced_replay_rejects_invalid_ranges() {
1946        let source = Scene::default();
1947        let mut replayed = Scene::default();
1948        let start = 1;
1949        let end = 0;
1950
1951        assert!(replayed.replay_balanced(start..end, &source).is_err());
1952        assert!(replayed.replay_balanced(0..1, &source).is_err());
1953    }
1954
1955    struct Badge {
1956        overlay: CompositionSurfaceId,
1957        builds: Rc<Cell<usize>>,
1958    }
1959
1960    impl Render for Badge {
1961        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1962            self.builds.set(self.builds.get() + 1);
1963            let overlay = self.overlay;
1964            div()
1965                .size_full()
1966                .bg(crate::black())
1967                .child(
1968                    canvas(
1969                        |_, _, _| (),
1970                        move |bounds, _, window, _| {
1971                            window
1972                                .with_composition_surface(overlay, |window| {
1973                                    window.paint_quad(fill(bounds, crate::red()))
1974                                })
1975                                .unwrap();
1976                        },
1977                    )
1978                    .size(px(20.)),
1979                )
1980                .child(div().size(px(10.)).bg(crate::white()))
1981        }
1982    }
1983
1984    struct Panel {
1985        badge: Entity<Badge>,
1986    }
1987
1988    impl Render for Panel {
1989        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1990            div()
1991                .size(px(300.))
1992                .bg(crate::white())
1993                .child(
1994                    self.badge
1995                        .clone()
1996                        .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
1997                )
1998                .child(div().size(px(30.)).bg(crate::black()))
1999        }
2000    }
2001
2002    fn surface_of_each_operation(window: &Window) -> Vec<CompositionSurfaceId> {
2003        let state = window.fast_composition.0.borrow();
2004        let frame = &window.rendered_frame;
2005        let layers = composed_scene_layers(
2006            &state.tree,
2007            &frame.fast_composition_starts.0,
2008            frame.scene.len(),
2009        )
2010        .unwrap();
2011        let mut surfaces = vec![None; frame.scene.len()];
2012        for layer in layers {
2013            for range in layer.ranges {
2014                for surface in &mut surfaces[range] {
2015                    *surface = Some(layer.surface);
2016                }
2017            }
2018        }
2019        surfaces.into_iter().map(Option::unwrap).collect()
2020    }
2021
2022    /// A retained view that painted onto the overlay surface still does when
2023    /// it is drawn again from last frame: its surface switches come along
2024    /// with its scene, and painting returns to the base surface after it.
2025    #[crate::test]
2026    fn reused_views_keep_their_composition_surfaces(cx: &mut TestAppContext) {
2027        let builds = Rc::new(Cell::new(0));
2028        let window = cx.add_window({
2029            let builds = builds.clone();
2030            move |window, cx| {
2031                let overlay = window.fast_composition.0.borrow().overlay_surface;
2032                Panel {
2033                    badge: cx.new(|_| Badge { overlay, builds }),
2034                }
2035            }
2036        });
2037        let draw = |cx: &mut TestAppContext| {
2038            cx.update_window(window.into(), |_, window, cx| {
2039                window.draw(cx).clear(cx);
2040                let state = window.fast_composition.0.borrow();
2041                (
2042                    surface_of_each_operation(window),
2043                    state.base_surface,
2044                    state.overlay_surface,
2045                )
2046            })
2047            .unwrap()
2048        };
2049
2050        let (first, base, overlay) = draw(cx);
2051        assert_eq!(builds.get(), 1);
2052        assert_eq!(first.iter().filter(|s| **s == overlay).count(), 1);
2053        assert_eq!(first.last(), Some(&base));
2054
2055        window.update(cx, |_, _, cx| cx.notify()).unwrap();
2056        let (second, _, _) = draw(cx);
2057        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
2058        assert_eq!(second, first);
2059    }
2060
2061    fn test_platform_surface() -> Rc<TestPlatformSurface> {
2062        Rc::new(TestPlatformSurface {
2063            bounds_writes: Cell::new(0),
2064            fail_next_bounds: Cell::new(false),
2065            bounds: Cell::new(Bounds::default()),
2066            parent_origin: Cell::new(Point::default()),
2067        })
2068    }
2069
2070    /// Positions one native surface from the root view and another from a
2071    /// deferred draw, or both from the root view.
2072    struct Hosts {
2073        page: Rc<ManagedPlatformSurface>,
2074        dialog_page: Rc<ManagedPlatformSurface>,
2075        dialog_open: bool,
2076    }
2077
2078    fn native_host(surface: Rc<ManagedPlatformSurface>) -> impl IntoElement {
2079        canvas(
2080            move |bounds, window, _| {
2081                surface
2082                    .set_bounds(bounds.to_device_pixels(window.scale_factor()))
2083                    .unwrap()
2084            },
2085            |_, _, _, _| {},
2086        )
2087        .size(px(50.))
2088    }
2089
2090    impl Render for Hosts {
2091        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2092            let dialog_page = native_host(self.dialog_page.clone());
2093            let root = div().size_full().child(native_host(self.page.clone()));
2094            if self.dialog_open {
2095                root.child(deferred(
2096                    div().size(px(80.)).bg(crate::white()).child(dialog_page),
2097                ))
2098            } else {
2099                root.child(dialog_page)
2100            }
2101        }
2102    }
2103
2104    /// A native surface hosted in a deferred draw, a web page in a dialog,
2105    /// stacks above the overlay surface the dialog's background is drawn on,
2106    /// and returns below it once hosted by the root view again.
2107    #[crate::test]
2108    fn native_surfaces_stack_with_their_hosts(cx: &mut TestAppContext) {
2109        let names = Rc::new(std::cell::RefCell::new(Vec::new()));
2110        let window = cx.add_window({
2111            let names = names.clone();
2112            move |window, _| {
2113                let mut state = window.fast_composition.0.borrow_mut();
2114                let overlay = state.overlay_surface;
2115                let mut names = names.borrow_mut();
2116                names.push((state.base_surface, "base"));
2117                names.push((overlay, "overlay"));
2118                let mut native = |name| {
2119                    let id = state
2120                        .tree
2121                        .insert(CompositionSurfaceKind::Native, None)
2122                        .unwrap();
2123                    state.tree.place_below(id, overlay).unwrap();
2124                    let surface =
2125                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
2126                    state.platform_surfaces.insert(id, surface.clone());
2127                    names.push((id, name));
2128                    surface
2129                };
2130                Hosts {
2131                    page: native("page"),
2132                    dialog_page: native("dialog page"),
2133                    dialog_open: true,
2134                }
2135            }
2136        });
2137        let draw = |cx: &mut TestAppContext| {
2138            cx.update_window(window.into(), |_, window, cx| {
2139                window.draw(cx).clear(cx);
2140                let mut state = window.fast_composition.0.borrow_mut();
2141                restack_native_surfaces(&mut state).unwrap();
2142                let names = names.borrow();
2143                state
2144                    .tree
2145                    .flattened()
2146                    .into_iter()
2147                    .map(|id| names.iter().find(|(named, _)| *named == id).unwrap().1)
2148                    .collect::<Vec<_>>()
2149            })
2150            .unwrap()
2151        };
2152
2153        assert_eq!(draw(cx), ["base", "page", "overlay", "dialog page"]);
2154
2155        window
2156            .update(cx, |hosts, _, cx| {
2157                hosts.dialog_open = false;
2158                cx.notify();
2159            })
2160            .unwrap();
2161        assert_eq!(draw(cx), ["base", "page", "dialog page", "overlay"]);
2162    }
2163}