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/// Stacks what the root view positions, as it prepaints, below the overlay
1323/// surface.
1324pub(crate) fn begin_base_prepaint(window: &mut Window) {
1325    begin_input(window, false);
1326}
1327
1328/// Stacks what deferred and window-level draws position, as they prepaint,
1329/// above the overlay surface.
1330pub(crate) fn begin_overlay_prepaint(window: &mut Window) {
1331    begin_input(window, true);
1332}
1333
1334/// Paints what follows, the root view, onto the base surface.
1335pub(crate) fn begin_base(window: &mut Window) {
1336    let state = window.fast_composition.0.borrow();
1337    state.prepainting.set(None);
1338    let surface = state.base_surface;
1339    drop(state);
1340    switch_surface(window, surface);
1341}
1342
1343/// Moves each root native surface whose host changed surface to that
1344/// surface's side of the overlay surface.
1345fn restack_native_surfaces(state: &mut WindowCompositionState) -> Result<()> {
1346    let overlay = state.overlay_surface;
1347    for (id, surface) in &state.platform_surfaces {
1348        if !surface.restack.replace(false) || state.tree.parent(*id)?.is_some() {
1349            continue;
1350        }
1351        match surface.host.get() {
1352            Host::Base => state.tree.place_below(*id, overlay)?,
1353            Host::Overlay => state.tree.place_above(*id, overlay)?,
1354        }
1355    }
1356    Ok(())
1357}
1358
1359/// Paints what follows, deferred and window-level draws, onto the overlay
1360/// surface.
1361pub(crate) fn begin_overlay(window: &mut Window) {
1362    let surface = window.fast_composition.0.borrow().overlay_surface;
1363    switch_surface(window, surface);
1364}
1365
1366/// Carries the surface switches last frame made within `range` into the
1367/// frame being drawn, as [`Window::reuse_paint`] replays its scene, and
1368/// leaves painting on the surface it was on before.
1369pub(crate) fn reuse_starts(window: &mut Window, range: &Range<PaintIndex>) {
1370    let scenes = range.start.scene_index..range.end.scene_index;
1371    let starts = &window.rendered_frame.fast_composition_starts.0;
1372    let first = starts.partition_point(|(_, start)| *start < scenes.start);
1373    let last = starts.partition_point(|(_, start)| *start < scenes.end);
1374    if first == last {
1375        return;
1376    }
1377    let Some(surface) = window.next_frame.fast_composition_starts.current() else {
1378        return;
1379    };
1380    let offset = window.next_frame.scene.len();
1381    for index in first..last {
1382        let (reused, start) = window.rendered_frame.fast_composition_starts.0[index];
1383        window
1384            .next_frame
1385            .fast_composition_starts
1386            .switch_to(reused, start - scenes.start + offset);
1387    }
1388    let end = offset + scenes.len();
1389    window
1390        .next_frame
1391        .fast_composition_starts
1392        .switch_to(surface, end);
1393}
1394
1395// Host changes must reach input ownership before the frame's hit test.
1396fn synchronize_geometry(window: &mut Window) {
1397    let state = window.fast_composition.0.clone();
1398    if !state.borrow().enabled {
1399        return;
1400    }
1401    if state.borrow().geometry_dirty.get() {
1402        if let Err(error) = restack_native_surfaces(&mut state.borrow_mut()) {
1403            log::error!("restacking native composition surfaces: {error:#}");
1404        }
1405        let composition = WindowComposition {
1406            platform_window: window.platform_window.as_ref(),
1407            state,
1408        };
1409        if let Err(error) = composition.synchronize_platform_order() {
1410            log::error!("updating window composition geometry: {error:#}");
1411        }
1412    }
1413}
1414
1415/// Reorder only scenes that return to the base after painting the overlay.
1416/// The common base-then-overlay scene can be presented without copying it.
1417fn ordered_plain_scene(
1418    state: &WindowCompositionState,
1419    starts: &[(CompositionSurfaceId, usize)],
1420    scene: &Scene,
1421) -> Result<Option<Scene>> {
1422    let mut seen_overlay = false;
1423    let mut out_of_order = false;
1424    for (index, &(surface, start)) in starts.iter().enumerate() {
1425        let end = starts.get(index + 1).map_or(scene.len(), |(_, end)| *end);
1426        if start >= end {
1427            continue;
1428        }
1429        if surface == state.overlay_surface {
1430            seen_overlay = true;
1431        } else if surface == state.base_surface && seen_overlay {
1432            out_of_order = true;
1433            break;
1434        }
1435    }
1436    if !out_of_order {
1437        return Ok(None);
1438    }
1439    let layers = composed_scene_layers(&state.tree, starts, scene.len())?;
1440    let mut ordered = Scene::default();
1441    for layer in layers {
1442        for range in layer.ranges {
1443            ordered.replay_balanced(range, scene)?;
1444        }
1445    }
1446    ordered.finish();
1447    Ok(Some(ordered))
1448}
1449
1450/// Presents the frame last drawn: on its one surface, or split along the
1451/// composition tree while the window composes around another surface.
1452pub(crate) fn present(window: &mut Window) {
1453    let state = window.fast_composition.0.clone();
1454    let splits = {
1455        let state = state.borrow();
1456        state.enabled && state.splits()
1457    };
1458    if !splits {
1459        let frame = &window.rendered_frame;
1460        let ordered = if state.borrow().enabled {
1461            ordered_plain_scene(
1462                &state.borrow(),
1463                &frame.fast_composition_starts.0,
1464                &frame.scene,
1465            )
1466            .log_err()
1467            .flatten()
1468        } else {
1469            None
1470        };
1471        window
1472            .platform_window
1473            .draw(ordered.as_ref().unwrap_or(&frame.scene));
1474        return;
1475    }
1476    synchronize_geometry(window);
1477    let state = state.borrow();
1478    let scene = &window.rendered_frame.scene;
1479    let layers = composed_scene_layers(
1480        &state.tree,
1481        &window.rendered_frame.fast_composition_starts.0,
1482        scene.len(),
1483    )
1484    .unwrap_or_else(|error| {
1485        log::error!("invalid window composition scene: {error:#}");
1486        vec![ComposedSceneLayer {
1487            surface: state.base_surface,
1488            ranges: vec![0..scene.len()],
1489        }]
1490    });
1491    drop(state);
1492    window.platform_window.draw_composed(ComposedScene::new(
1493        scene,
1494        layers,
1495        &window.rendered_frame.fast_composition_input,
1496    ));
1497}
1498
1499/// Visibility and ancestor clips come from the existing managed surface tree.
1500fn input_bounds(
1501    state: &WindowCompositionState,
1502    surface: CompositionSurfaceId,
1503    mut bounds: Bounds<Pixels>,
1504    scale: f32,
1505) -> Option<Bounds<Pixels>> {
1506    let mut current = Some(surface);
1507    while let Some(id) = current {
1508        state.tree.kind(id).ok()?;
1509        if state.visible.get(&id).is_some_and(|visible| !visible.get()) {
1510            return None;
1511        }
1512        if let Some(native) = state.platform_surfaces.get(&id) {
1513            bounds = bounds.intersect(&native.bounds().to_pixels(scale));
1514        }
1515        current = state.tree.parent(id).ok()?;
1516    }
1517    (!bounds.is_empty()).then_some(bounds)
1518}
1519
1520fn visible_surface(state: &WindowCompositionState, surface: CompositionSurfaceId) -> bool {
1521    let mut current = Some(surface);
1522    while let Some(id) = current {
1523        if state.tree.kind(id).is_err() || state.visible.get(&id).is_some_and(|v| !v.get()) {
1524            return false;
1525        }
1526        current = state.tree.parent(id).ok().flatten();
1527    }
1528    true
1529}
1530
1531fn native_target(window: &Window, scroll: bool) -> Option<CompositionSurfaceId> {
1532    let state = window.fast_composition.0.borrow();
1533    if !state.enabled || state.platform_surfaces.is_empty() {
1534        return None;
1535    }
1536    if !scroll {
1537        if let Some(captured) = state
1538            .pointer_capture
1539            .filter(|id| visible_surface(&state, *id))
1540        {
1541            return Some(captured);
1542        }
1543    }
1544    let point = window.mouse_position;
1545    for surface in state.input_order.iter().rev().copied() {
1546        if !visible_surface(&state, surface) {
1547            continue;
1548        }
1549        if let Some(native) = state.platform_surfaces.get(&surface) {
1550            if input_bounds(
1551                &state,
1552                surface,
1553                native.bounds().to_pixels(window.scale_factor()),
1554                window.scale_factor(),
1555            )
1556            .is_some_and(|bounds| bounds.contains(&point))
1557            {
1558                return Some(surface);
1559            }
1560        } else if let Some(regions) = window
1561            .rendered_frame
1562            .fast_composition_input
1563            .hitboxes
1564            .get(&surface)
1565        {
1566            if regions.iter().rev().any(|hitbox| {
1567                hitbox.bounds.contains(&point)
1568                    && (!scroll || hitbox.behavior == HitboxBehavior::BlockMouse)
1569            }) {
1570                return None;
1571            }
1572        }
1573    }
1574    None
1575}
1576
1577/// OS-directed native events still run GPUI capture, but cannot activate
1578/// unrelated GPUI widgets underneath the native view.
1579fn native_mouse(window: &Window, event: &dyn Any) -> bool {
1580    if window.captured_hitbox.is_some() {
1581        let state = window.fast_composition.0.borrow();
1582        return state
1583            .pointer_capture
1584            .is_some_and(|id| visible_surface(&state, id));
1585    }
1586    if event
1587        .downcast_ref::<MouseMoveEvent>()
1588        .is_some_and(|event| event.pressed_button.is_some())
1589        && window.fast_composition.0.borrow().pointer_capture.is_none()
1590    {
1591        return false;
1592    }
1593    native_target(window, false).is_some()
1594}
1595
1596pub(crate) fn bubble_mouse(window: &Window, event: &dyn Any, cx: &crate::App) -> bool {
1597    cx.propagate_event && (cx.has_active_drag() || !native_mouse(window, event))
1598}
1599
1600pub(crate) fn event_target(window: &Window, event: &PlatformInput) -> Option<CompositionSurfaceId> {
1601    if !matches!(
1602        event,
1603        PlatformInput::MouseDown(_)
1604            | PlatformInput::MouseUp(_)
1605            | PlatformInput::MouseMove(_)
1606            | PlatformInput::Scroll(_)
1607    ) {
1608        return None;
1609    }
1610    let scroll = matches!(event, PlatformInput::Scroll(_));
1611    if !scroll {
1612        let state = window.fast_composition.0.borrow();
1613        if let Some(captured) = state.pointer_capture {
1614            return visible_surface(&state, captured).then_some(captured);
1615        }
1616    }
1617    if window.captured_hitbox.is_some() || matches!(event, PlatformInput::MouseUp(_)) {
1618        return None;
1619    }
1620    if matches!(
1621        event,
1622        PlatformInput::MouseMove(MouseMoveEvent {
1623            pressed_button: Some(_),
1624            ..
1625        })
1626    ) && window.fast_composition.0.borrow().pointer_capture.is_none()
1627    {
1628        return None;
1629    }
1630    native_target(window, scroll)
1631}
1632
1633/// Called after the existing dispatcher; windowless producers get one delivery,
1634/// while OS-managed views continue through the platform's original event path.
1635pub(crate) fn dispatch_native(
1636    window: &mut Window,
1637    event: &PlatformInput,
1638    target: Option<CompositionSurfaceId>,
1639    propagate: &mut bool,
1640) {
1641    let pointer = matches!(
1642        event,
1643        PlatformInput::MouseDown(_)
1644            | PlatformInput::MouseUp(_)
1645            | PlatformInput::MouseMove(_)
1646            | PlatformInput::MouseExited(_)
1647            | PlatformInput::Scroll(_)
1648    );
1649    if !pointer || !window.fast_composition.0.borrow().enabled {
1650        return;
1651    }
1652    let target = target.filter(|id| visible_surface(&window.fast_composition.0.borrow(), *id));
1653    let (handler, leave) = {
1654        let mut state = window.fast_composition.0.borrow_mut();
1655        let leave = if matches!(
1656            event,
1657            PlatformInput::MouseMove(_) | PlatformInput::MouseExited(_)
1658        ) {
1659            let current = if matches!(event, PlatformInput::MouseExited(_)) {
1660                None
1661            } else {
1662                target
1663            };
1664            let previous = std::mem::replace(&mut state.hovered_native, current);
1665            previous
1666                .filter(|old| Some(*old) != current)
1667                .and_then(|id| state.input_handlers.get(&id).cloned())
1668        } else {
1669            None
1670        };
1671        if *propagate && !window.default_prevented {
1672            if let PlatformInput::MouseDown(down) = event {
1673                if let Some(id) = target {
1674                    state.pointer_capture = Some(id);
1675                    if !state.pressed_buttons.contains(&down.button) {
1676                        state.pressed_buttons.push(down.button);
1677                    }
1678                }
1679            }
1680        }
1681        let owned_release = matches!(event, PlatformInput::MouseUp(_))
1682            && target.is_some()
1683            && state.pointer_capture == target;
1684        let handler = if (*propagate && !window.default_prevented) || owned_release {
1685            target.and_then(|id| state.input_handlers.get(&id).cloned())
1686        } else {
1687            None
1688        };
1689        if let PlatformInput::MouseUp(up) = event {
1690            // A single press ends even if platform normalization changed its button
1691            // (AppKit ctrl-click with Control released before mouse-up).
1692            if state.pressed_buttons.len() == 1 {
1693                state.pressed_buttons.clear();
1694            } else {
1695                state.pressed_buttons.retain(|button| *button != up.button);
1696            }
1697            if state.pressed_buttons.is_empty() {
1698                state.pointer_capture = None;
1699            }
1700        }
1701        (handler, leave)
1702    };
1703    if let Some(leave) = leave {
1704        let (position, pressed_button, modifiers) = match event {
1705            PlatformInput::MouseMove(event) => {
1706                (event.position, event.pressed_button, event.modifiers)
1707            }
1708            PlatformInput::MouseExited(event) => {
1709                (event.position, event.pressed_button, event.modifiers)
1710            }
1711            _ => unreachable!(),
1712        };
1713        leave.borrow_mut()(&PlatformInput::MouseExited(MouseExitEvent {
1714            position,
1715            pressed_button,
1716            modifiers,
1717        }));
1718    }
1719    if let Some(handler) = handler {
1720        let result = handler.borrow_mut()(event);
1721        *propagate &= result.propagate;
1722        window.default_prevented |= result.default_prevented;
1723    }
1724}
1725
1726#[cfg(test)]
1727pub(crate) mod tests {
1728    use super::{
1729        CompositionSurfaceId, CompositionSurfaceKind, CompositionTree, ManagedPlatformSurface,
1730        PlatformSurfaceAttachment, WindowComposition, WindowCompositionHandle,
1731        composed_scene_layers, ordered_plain_scene, restack_native_surfaces,
1732    };
1733    use crate::{
1734        AppContext as _, Bounds, ContentMask, Context, DevicePixels, Entity, IntoElement,
1735        ParentElement as _, Point, Quad, Render, ScaledPixels, Scene, Size, StyleRefinement,
1736        Styled as _, TestAppContext, Window, canvas, deferred, div, fill, px,
1737        scene::PaintOperation, size,
1738    };
1739    use anyhow::Result;
1740    use std::{any::Any, cell::Cell, rc::Rc};
1741
1742    #[test]
1743    fn composition_surfaces_have_stable_identity_and_explicit_order() -> Result<()> {
1744        let mut tree = CompositionTree::new();
1745        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1746        let webview = tree.insert(CompositionSurfaceKind::Native, None)?;
1747        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1748
1749        tree.place_below(overlay, webview)?;
1750
1751        assert_eq!(tree.flattened(), [base, overlay, webview]);
1752        assert_eq!(tree.kind(webview)?, CompositionSurfaceKind::Native);
1753        Ok(())
1754    }
1755
1756    #[test]
1757    fn composition_surfaces_can_be_nested_and_reparented() -> Result<()> {
1758        let mut tree = CompositionTree::new();
1759        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1760        let pane = tree.insert(CompositionSurfaceKind::Native, Some(base))?;
1761        let video = tree.insert(CompositionSurfaceKind::ExternalGpu, None)?;
1762
1763        tree.reparent(video, Some(pane))?;
1764
1765        assert_eq!(tree.parent(video)?, Some(pane));
1766        assert_eq!(tree.children(Some(pane))?, [video]);
1767        assert_eq!(tree.flattened(), [base, pane, video]);
1768        Ok(())
1769    }
1770
1771    #[test]
1772    fn composition_tree_rejects_cycles_and_cross_parent_ordering() -> Result<()> {
1773        let mut tree = CompositionTree::new();
1774        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1775        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1776        let sibling = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1777
1778        assert!(tree.reparent(parent, Some(child)).is_err());
1779        assert!(tree.place_above(child, sibling).is_err());
1780        assert_eq!(tree.parent(parent)?, None);
1781        assert_eq!(tree.parent(child)?, Some(parent));
1782        Ok(())
1783    }
1784
1785    #[test]
1786    fn removing_a_surface_preserves_and_reparents_its_children() -> Result<()> {
1787        let mut tree = CompositionTree::new();
1788        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1789        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1790
1791        tree.remove(parent)?;
1792
1793        assert_eq!(tree.parent(child)?, None);
1794        assert_eq!(tree.flattened(), [child]);
1795        Ok(())
1796    }
1797
1798    #[test]
1799    fn scene_ranges_follow_tree_order_and_preserve_repeated_segments() -> Result<()> {
1800        let mut tree = CompositionTree::new();
1801        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1802        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1803        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1804        let starts = [(base, 0), (overlay, 4), (base, 7)];
1805
1806        let layers = composed_scene_layers(&tree, &starts, 10)?;
1807
1808        let [base_layer, overlay_layer] = layers.as_slice() else {
1809            panic!("expected base and overlay scene layers");
1810        };
1811        assert_eq!(base_layer.surface, base);
1812        assert_eq!(base_layer.ranges, [0..4, 7..10]);
1813        assert_eq!(overlay_layer.surface, overlay);
1814        assert_eq!(overlay_layer.ranges, [4..7]);
1815        assert_eq!(tree.kind(native)?, CompositionSurfaceKind::Native);
1816        Ok(())
1817    }
1818
1819    #[test]
1820    fn scene_ranges_reject_non_gpui_targets_and_non_monotonic_markers() -> Result<()> {
1821        let mut tree = CompositionTree::new();
1822        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1823        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1824
1825        assert!(composed_scene_layers(&tree, &[(native, 0)], 1).is_err());
1826        assert!(composed_scene_layers(&tree, &[(base, 2), (base, 1)], 2).is_err());
1827        Ok(())
1828    }
1829
1830    struct TestPlatformSurface {
1831        bounds_writes: Cell<usize>,
1832        fail_next_bounds: Cell<bool>,
1833        bounds: Cell<Bounds<DevicePixels>>,
1834        parent_origin: Cell<Point<DevicePixels>>,
1835    }
1836
1837    impl PlatformSurfaceAttachment for TestPlatformSurface {
1838        fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
1839            self.bounds_writes.set(self.bounds_writes.get() + 1);
1840            if self.fail_next_bounds.replace(false) {
1841                return Err(anyhow::anyhow!("test bounds failure"));
1842            }
1843            self.bounds.set(bounds);
1844            Ok(())
1845        }
1846
1847        fn bounds(&self) -> Bounds<DevicePixels> {
1848            self.bounds.get()
1849        }
1850
1851        fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
1852            self.parent_origin.set(origin);
1853            Ok(())
1854        }
1855
1856        fn set_visible(&self, _visible: bool) -> Result<()> {
1857            Ok(())
1858        }
1859
1860        fn platform_handle(&self) -> Result<Box<dyn Any>> {
1861            Ok(Box::new(()))
1862        }
1863    }
1864
1865    #[test]
1866    fn managed_composition_surface_tracks_window_geometry_changes() {
1867        let platform_surface = Rc::new(TestPlatformSurface {
1868            bounds_writes: Cell::new(0),
1869            fail_next_bounds: Cell::new(false),
1870            bounds: Cell::new(Bounds::default()),
1871            parent_origin: Cell::new(Point::default()),
1872        });
1873        let composition = WindowCompositionHandle::default();
1874        let state = composition.0.borrow();
1875        let geometry_dirty = state.geometry_dirty.clone();
1876        let surface = ManagedPlatformSurface::new(platform_surface.clone(), &state);
1877        let bounds = Bounds {
1878            origin: Point {
1879                x: DevicePixels(25),
1880                y: DevicePixels(40),
1881            },
1882            size: size(DevicePixels(300), DevicePixels(200)),
1883        };
1884        let parent_origin = Point {
1885            x: DevicePixels(10),
1886            y: DevicePixels(15),
1887        };
1888
1889        assert!(surface.set_bounds(bounds).is_ok());
1890        assert!(surface.set_parent_origin(parent_origin).is_ok());
1891
1892        assert_eq!(surface.bounds(), bounds);
1893        assert_eq!(platform_surface.bounds.get(), bounds);
1894        assert_eq!(platform_surface.parent_origin.get(), parent_origin);
1895        assert!(geometry_dirty.get());
1896    }
1897
1898    #[test]
1899    fn unchanged_native_bounds_do_not_resynchronize_composition() -> Result<()> {
1900        let bounds = Bounds::new(Point::default(), size(DevicePixels(300), DevicePixels(200)));
1901        let platform = Rc::new(TestPlatformSurface {
1902            bounds_writes: Cell::new(0),
1903            fail_next_bounds: Cell::new(false),
1904            bounds: Cell::new(Bounds::default()),
1905            parent_origin: Cell::new(Point::default()),
1906        });
1907        let composition = WindowCompositionHandle::default();
1908        let state = composition.0.borrow();
1909        let dirty = state.geometry_dirty.clone();
1910        let surface = ManagedPlatformSurface::new(platform.clone(), &state);
1911        surface.set_bounds(bounds)?;
1912        dirty.set(false);
1913        for _ in 0..10 {
1914            surface.set_bounds(bounds)?;
1915        }
1916        assert!(
1917            !dirty.get(),
1918            "unchanged layout must not remount native views between mouse down and up"
1919        );
1920        assert_eq!(platform.bounds_writes.get(), 1);
1921        let moved = Bounds::new(
1922            Point {
1923                x: DevicePixels(20),
1924                y: DevicePixels(15),
1925            },
1926            bounds.size,
1927        );
1928        surface.set_bounds(moved)?;
1929        assert!(dirty.get());
1930        assert_eq!(platform.bounds_writes.get(), 2);
1931        assert_eq!(surface.bounds(), moved);
1932        Ok(())
1933    }
1934
1935    #[test]
1936    fn failed_native_bounds_updates_remain_retryable() -> Result<()> {
1937        let bounds = Bounds::new(Point::default(), size(DevicePixels(600), DevicePixels(400)));
1938        let platform = Rc::new(TestPlatformSurface {
1939            bounds_writes: Cell::new(0),
1940            fail_next_bounds: Cell::new(true),
1941            bounds: Cell::new(Bounds::default()),
1942            parent_origin: Cell::new(Point::default()),
1943        });
1944        let composition = WindowCompositionHandle::default();
1945        let state = composition.0.borrow();
1946        let dirty = state.geometry_dirty.clone();
1947        let surface = ManagedPlatformSurface::new(platform.clone(), &state);
1948        assert!(surface.set_bounds(bounds).is_err());
1949        assert_eq!(surface.bounds(), Bounds::default());
1950        assert!(!dirty.get());
1951        surface.set_bounds(bounds)?;
1952        assert!(dirty.get());
1953        assert_eq!(surface.bounds(), bounds);
1954        assert_eq!(platform.bounds_writes.get(), 2);
1955        dirty.set(false);
1956        surface.set_bounds(bounds)?;
1957        assert!(!dirty.get());
1958        assert_eq!(platform.bounds_writes.get(), 2);
1959        Ok(())
1960    }
1961
1962    fn square(side: f32) -> Bounds<ScaledPixels> {
1963        Bounds {
1964            origin: Point::default(),
1965            size: Size {
1966                width: ScaledPixels::from(side),
1967                height: ScaledPixels::from(side),
1968            },
1969        }
1970    }
1971
1972    #[test]
1973    fn empty_layers_do_not_make_a_scene_drawable() {
1974        let mut scene = Scene::default();
1975        scene.push_layer(square(100.));
1976        scene.pop_layer();
1977
1978        assert_ne!(scene.len(), 0);
1979        assert!(scene.is_empty());
1980    }
1981
1982    #[test]
1983    fn drawable_primitives_make_a_scene_non_empty() {
1984        let mut scene = Scene::default();
1985        let bounds = square(100.);
1986        scene.insert_primitive(Quad {
1987            bounds,
1988            content_mask: ContentMask { bounds },
1989            ..Default::default()
1990        });
1991
1992        assert!(!scene.is_empty());
1993    }
1994
1995    #[test]
1996    fn replay_preserves_scene_emptiness() {
1997        let mut source = Scene::default();
1998        source.push_layer(square(100.));
1999        source.pop_layer();
2000
2001        let mut replayed = Scene::default();
2002        replayed.replay(0..source.len(), &source);
2003
2004        assert!(replayed.is_empty());
2005    }
2006
2007    #[test]
2008    fn balanced_replay_restores_layers_crossing_the_range_boundary() {
2009        let mut source = Scene::default();
2010        let inner_bounds = square(50.);
2011        source.push_layer(square(100.));
2012        source.push_layer(inner_bounds);
2013        source.insert_primitive(Quad {
2014            bounds: inner_bounds,
2015            content_mask: ContentMask {
2016                bounds: inner_bounds,
2017            },
2018            ..Default::default()
2019        });
2020        source.pop_layer();
2021        source.pop_layer();
2022
2023        let mut replayed = Scene::default();
2024        assert!(replayed.replay_balanced(2..3, &source).is_ok());
2025
2026        assert_eq!(replayed.paint_operations.len(), 5);
2027        assert!(matches!(
2028            replayed.paint_operations.as_slice(),
2029            [
2030                PaintOperation::StartLayer(_),
2031                PaintOperation::StartLayer(_),
2032                PaintOperation::Primitive(_),
2033                PaintOperation::EndLayer,
2034                PaintOperation::EndLayer
2035            ]
2036        ));
2037    }
2038
2039    #[test]
2040    fn plain_present_keeps_overlay_above_later_base_content() -> Result<()> {
2041        let handle = WindowCompositionHandle::default();
2042        let state = handle.0.borrow();
2043        let mut scene = Scene::default();
2044        for side in [10., 20., 30.] {
2045            let bounds = square(side);
2046            scene.insert_primitive(Quad {
2047                bounds,
2048                content_mask: ContentMask { bounds },
2049                ..Default::default()
2050            });
2051        }
2052        scene.finish();
2053        let starts = [
2054            (state.base_surface, 0),
2055            (state.overlay_surface, 1),
2056            (state.base_surface, 2),
2057        ];
2058        let ordered = ordered_plain_scene(&state, &starts, &scene)?.unwrap();
2059        let sides: Vec<_> = ordered
2060            .quads
2061            .iter()
2062            .map(|quad| quad.bounds.size.width)
2063            .collect();
2064        assert_eq!(
2065            sides,
2066            [
2067                ScaledPixels::from(10.),
2068                ScaledPixels::from(30.),
2069                ScaledPixels::from(20.)
2070            ]
2071        );
2072        let in_order = [(state.base_surface, 0), (state.overlay_surface, 2)];
2073        assert!(ordered_plain_scene(&state, &in_order, &scene)?.is_none());
2074        Ok(())
2075    }
2076
2077    #[test]
2078    fn balanced_replay_rejects_invalid_ranges() {
2079        let source = Scene::default();
2080        let mut replayed = Scene::default();
2081        let start = 1;
2082        let end = 0;
2083
2084        assert!(replayed.replay_balanced(start..end, &source).is_err());
2085        assert!(replayed.replay_balanced(0..1, &source).is_err());
2086    }
2087
2088    struct Badge {
2089        overlay: CompositionSurfaceId,
2090        builds: Rc<Cell<usize>>,
2091    }
2092
2093    impl Render for Badge {
2094        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2095            self.builds.set(self.builds.get() + 1);
2096            let overlay = self.overlay;
2097            div()
2098                .size_full()
2099                .bg(crate::black())
2100                .child(
2101                    canvas(
2102                        |_, _, _| (),
2103                        move |bounds, _, window, _| {
2104                            window
2105                                .with_composition_surface(overlay, |window| {
2106                                    window.paint_quad(fill(bounds, crate::red()))
2107                                })
2108                                .unwrap();
2109                        },
2110                    )
2111                    .size(px(20.)),
2112                )
2113                .child(div().size(px(10.)).bg(crate::white()))
2114        }
2115    }
2116
2117    struct Panel {
2118        badge: Entity<Badge>,
2119    }
2120
2121    impl Render for Panel {
2122        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2123            div()
2124                .size(px(300.))
2125                .bg(crate::white())
2126                .child(
2127                    self.badge
2128                        .clone()
2129                        .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
2130                )
2131                .child(div().size(px(30.)).bg(crate::black()))
2132        }
2133    }
2134
2135    fn surface_of_each_operation(window: &Window) -> Vec<CompositionSurfaceId> {
2136        let state = window.fast_composition.0.borrow();
2137        let frame = &window.rendered_frame;
2138        let layers = composed_scene_layers(
2139            &state.tree,
2140            &frame.fast_composition_starts.0,
2141            frame.scene.len(),
2142        )
2143        .unwrap();
2144        let mut surfaces = vec![None; frame.scene.len()];
2145        for layer in layers {
2146            for range in layer.ranges {
2147                for surface in &mut surfaces[range] {
2148                    *surface = Some(layer.surface);
2149                }
2150            }
2151        }
2152        surfaces.into_iter().map(Option::unwrap).collect()
2153    }
2154
2155    /// A retained view that painted onto the overlay surface still does when
2156    /// it is drawn again from last frame: its surface switches come along
2157    /// with its scene, and painting returns to the base surface after it.
2158    #[crate::test]
2159    fn reused_views_keep_their_composition_surfaces(cx: &mut TestAppContext) {
2160        let builds = Rc::new(Cell::new(0));
2161        let window = cx.add_window({
2162            let builds = builds.clone();
2163            move |window, cx| {
2164                let overlay = window.fast_composition.0.borrow().overlay_surface;
2165                Panel {
2166                    badge: cx.new(|_| Badge { overlay, builds }),
2167                }
2168            }
2169        });
2170        let draw = |cx: &mut TestAppContext| {
2171            cx.update_window(window.into(), |_, window, cx| {
2172                window.draw(cx).clear(cx);
2173                let state = window.fast_composition.0.borrow();
2174                (
2175                    surface_of_each_operation(window),
2176                    state.base_surface,
2177                    state.overlay_surface,
2178                )
2179            })
2180            .unwrap()
2181        };
2182
2183        let (first, base, overlay) = draw(cx);
2184        assert_eq!(builds.get(), 1);
2185        assert_eq!(first.iter().filter(|s| **s == overlay).count(), 1);
2186        assert_eq!(first.last(), Some(&base));
2187
2188        window.update(cx, |_, _, cx| cx.notify()).unwrap();
2189        let (second, _, _) = draw(cx);
2190        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
2191        assert_eq!(second, first);
2192    }
2193
2194    fn test_platform_surface() -> Rc<TestPlatformSurface> {
2195        Rc::new(TestPlatformSurface {
2196            bounds_writes: Cell::new(0),
2197            fail_next_bounds: Cell::new(false),
2198            bounds: Cell::new(Bounds::default()),
2199            parent_origin: Cell::new(Point::default()),
2200        })
2201    }
2202
2203    /// What [`WindowComposition::create_native_surface`] hands the element
2204    /// hosting a native surface in `window`, without the platform view the
2205    /// test platform cannot create.
2206    pub(crate) fn native_surface(window: &Window) -> Rc<dyn PlatformSurfaceAttachment> {
2207        let state = window.fast_composition.0.borrow();
2208        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state))
2209    }
2210
2211    /// Positions one native surface from the root view and another from a
2212    /// deferred draw, or both from the root view.
2213    struct Hosts {
2214        page: Rc<ManagedPlatformSurface>,
2215        dialog_page: Rc<ManagedPlatformSurface>,
2216        dialog_open: bool,
2217    }
2218
2219    /// Places `surface` over itself as it is prepainted, as a web view does,
2220    /// without clipping it.
2221    pub(crate) fn native_host(surface: Rc<dyn PlatformSurfaceAttachment>) -> impl IntoElement {
2222        canvas(
2223            move |bounds, window, _| {
2224                surface
2225                    .set_bounds(bounds.to_device_pixels(window.scale_factor()))
2226                    .unwrap()
2227            },
2228            |_, _, _, _| {},
2229        )
2230        .size(px(50.))
2231    }
2232
2233    impl Render for Hosts {
2234        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2235            let dialog_page = native_host(self.dialog_page.clone());
2236            let root = div().size_full().child(native_host(self.page.clone()));
2237            if self.dialog_open {
2238                root.child(deferred(
2239                    div().size(px(80.)).bg(crate::white()).child(dialog_page),
2240                ))
2241            } else {
2242                root.child(dialog_page)
2243            }
2244        }
2245    }
2246
2247    /// A native surface hosted in a deferred draw, a web page in a dialog,
2248    /// stacks above the overlay surface the dialog's background is drawn on,
2249    /// and returns below it once hosted by the root view again.
2250    #[crate::test]
2251    fn native_surfaces_stack_with_their_hosts(cx: &mut TestAppContext) {
2252        let names = Rc::new(std::cell::RefCell::new(Vec::new()));
2253        let window = cx.add_window({
2254            let names = names.clone();
2255            move |window, _| {
2256                let mut state = window.fast_composition.0.borrow_mut();
2257                let overlay = state.overlay_surface;
2258                let mut names = names.borrow_mut();
2259                names.push((state.base_surface, "base"));
2260                names.push((overlay, "overlay"));
2261                let mut native = |name| {
2262                    let id = state
2263                        .tree
2264                        .insert(CompositionSurfaceKind::Native, None)
2265                        .unwrap();
2266                    state.tree.place_below(id, overlay).unwrap();
2267                    let surface =
2268                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
2269                    state.platform_surfaces.insert(id, surface.clone());
2270                    names.push((id, name));
2271                    surface
2272                };
2273                Hosts {
2274                    page: native("page"),
2275                    dialog_page: native("dialog page"),
2276                    dialog_open: true,
2277                }
2278            }
2279        });
2280        let draw = |cx: &mut TestAppContext| {
2281            cx.update_window(window.into(), |_, window, cx| {
2282                window.draw(cx).clear(cx);
2283                let mut state = window.fast_composition.0.borrow_mut();
2284                restack_native_surfaces(&mut state).unwrap();
2285                let names = names.borrow();
2286                state
2287                    .tree
2288                    .flattened()
2289                    .into_iter()
2290                    .map(|id| names.iter().find(|(named, _)| *named == id).unwrap().1)
2291                    .collect::<Vec<_>>()
2292            })
2293            .unwrap()
2294        };
2295
2296        assert_eq!(draw(cx), ["base", "page", "overlay", "dialog page"]);
2297
2298        window
2299            .update(cx, |hosts, _, cx| {
2300                hosts.dialog_open = false;
2301                cx.notify();
2302            })
2303            .unwrap();
2304        assert_eq!(draw(cx), ["base", "page", "dialog page", "overlay"]);
2305    }
2306
2307    /// A composing window splits its scene only while it holds a surface
2308    /// beyond the base and overlay surfaces, and a retained view keeps
2309    /// painting onto the overlay surface across every switch between the
2310    /// plain and the split frame.
2311    #[crate::test]
2312    fn retained_views_keep_their_split_as_surfaces_come_and_go(cx: &mut TestAppContext) {
2313        let builds = Rc::new(Cell::new(0));
2314        let window = cx.add_window({
2315            let builds = builds.clone();
2316            move |window, cx| {
2317                let mut state = window.fast_composition.0.borrow_mut();
2318                state.enabled = true;
2319                let overlay = state.overlay_surface;
2320                drop(state);
2321                Panel {
2322                    badge: cx.new(|_| Badge { overlay, builds }),
2323                }
2324            }
2325        });
2326        let draw = |cx: &mut TestAppContext| {
2327            cx.update_window(window.into(), |_, window, cx| {
2328                window.draw(cx).clear(cx);
2329                let splits = window.fast_composition.0.borrow().splits();
2330                (surface_of_each_operation(window), splits)
2331            })
2332            .unwrap()
2333        };
2334        let redraw = |cx: &mut TestAppContext| {
2335            window.update(cx, |_, _, cx| cx.notify()).unwrap();
2336            draw(cx)
2337        };
2338        // What the platform is handed: the base surface alone while the scene
2339        // is not split.
2340        let handed = |cx: &mut TestAppContext| {
2341            cx.update_window(window.into(), |_, window, _| {
2342                let composition = WindowComposition {
2343                    platform_window: window.platform_window.as_ref(),
2344                    state: window.fast_composition.0.clone(),
2345                };
2346                let ids = composition
2347                    .platform_order()
2348                    .unwrap()
2349                    .into_iter()
2350                    .map(|surface| surface.id)
2351                    .collect::<Vec<_>>();
2352                let state = window.fast_composition.0.borrow();
2353                (ids, state.base_surface, state.overlay_surface)
2354            })
2355            .unwrap()
2356        };
2357
2358        let (first, splits) = draw(cx);
2359        assert!(!splits);
2360        let (ids, base, _) = handed(cx);
2361        assert_eq!(ids, [base]);
2362        for _ in 0..3 {
2363            let added = cx
2364                .update_window(window.into(), |_, window, _| {
2365                    let mut state = window.fast_composition.0.borrow_mut();
2366                    let overlay = state.overlay_surface;
2367                    let id = state
2368                        .tree
2369                        .insert(CompositionSurfaceKind::Native, None)
2370                        .unwrap();
2371                    state.tree.place_below(id, overlay).unwrap();
2372                    let surface =
2373                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
2374                    state.platform_surfaces.insert(id, surface);
2375                    id
2376                })
2377                .unwrap();
2378            assert_eq!(redraw(cx), (first.clone(), true));
2379            let (ids, base, overlay) = handed(cx);
2380            assert_eq!(ids, [base, added, overlay]);
2381
2382            cx.update_window(window.into(), |_, window, _| {
2383                let mut state = window.fast_composition.0.borrow_mut();
2384                state.tree.remove(added).unwrap();
2385                state.platform_surfaces.remove(&added);
2386            })
2387            .unwrap();
2388            assert_eq!(redraw(cx), (first.clone(), false));
2389            let (ids, base, _) = handed(cx);
2390            assert_eq!(ids, [base]);
2391        }
2392        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
2393    }
2394}