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