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    }
494
495    /// Replays a range as a self-contained scene, restoring any layers that
496    /// were active at the start of the range and closing those still active at
497    /// its end. The scroll layers whose tiles the range composites come along.
498    pub fn replay_balanced(&mut self, range: Range<usize>, previous_scene: &Scene) -> Result<()> {
499        anyhow::ensure!(
500            range.start <= range.end,
501            "scene replay range starts after its end"
502        );
503        let prefix = previous_scene
504            .paint_operations
505            .get(..range.start)
506            .context("scene replay range starts past the scene")?;
507        let operations = previous_scene
508            .paint_operations
509            .get(range.clone())
510            .context("scene replay range ends past the scene")?;
511        let mut active_layers = Vec::new();
512        let mut active_clips = Vec::new();
513        for operation in prefix {
514            match operation {
515                PaintOperation::StartLayer(bounds) => active_layers.push(*bounds),
516                PaintOperation::EndLayer => {
517                    anyhow::ensure!(
518                        active_layers.pop().is_some(),
519                        "source scene closes a layer that is not open"
520                    );
521                }
522                PaintOperation::Primitive(_) => {}
523                PaintOperation::FastRoundedClip(clip) => {
524                    crate::fast::rounded_clip::track(*clip, &mut active_clips)?
525                }
526            }
527        }
528
529        crate::fast::layers::paint::replay_layers(self, range, previous_scene);
530        for bounds in &active_layers {
531            self.push_layer(*bounds);
532        }
533        for shape in &active_clips {
534            crate::fast::rounded_clip::record(
535                self,
536                crate::fast::rounded_clip::ClipOperation::Begin(*shape),
537            );
538        }
539        for operation in operations {
540            match operation {
541                PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()),
542                PaintOperation::StartLayer(bounds) => {
543                    active_layers.push(*bounds);
544                    self.push_layer(*bounds);
545                }
546                PaintOperation::EndLayer => {
547                    anyhow::ensure!(
548                        active_layers.pop().is_some(),
549                        "scene replay range closes a layer that is not open"
550                    );
551                    self.pop_layer();
552                }
553                PaintOperation::FastRoundedClip(clip) => {
554                    crate::fast::rounded_clip::track(*clip, &mut active_clips)?;
555                    crate::fast::rounded_clip::record(self, *clip);
556                }
557            }
558        }
559        for _ in active_layers {
560            self.pop_layer();
561        }
562        for _ in active_clips {
563            crate::fast::rounded_clip::record(self, crate::fast::rounded_clip::ClipOperation::End);
564        }
565        Ok(())
566    }
567}
568
569/// Where each stretch of a frame's scene is presented: the GPUI surface
570/// painting switched to, and the scene length at the switch.
571#[derive(Default)]
572pub(crate) struct SurfaceStarts(Vec<(CompositionSurfaceId, usize)>);
573
574/// Composition ownership accompanies existing hitbox identities through retained
575/// and scroll-layer replay; no second layout or input tree is built.
576#[derive(Default)]
577pub(crate) struct SurfaceInput {
578    order: Vec<(CompositionSurfaceId, Option<Bounds<Pixels>>)>,
579    scope: Option<CompositionSurfaceId>,
580    base: Option<CompositionSurfaceId>,
581    owners: FxHashMap<HitboxId, CompositionSurfaceId>,
582    hitboxes: FxHashMap<CompositionSurfaceId, Vec<Hitbox>>,
583}
584
585impl SurfaceInput {
586    pub(crate) fn clear(&mut self) {
587        self.scope = None;
588        self.base = None;
589        self.order.clear();
590        self.owners.clear();
591        for hitboxes in self.hitboxes.values_mut() {
592            hitboxes.clear();
593        }
594    }
595}
596
597fn begin_input(window: &mut Window, overlay: bool) {
598    let state = window.fast_composition.0.borrow();
599    state
600        .prepainting
601        .set(Some(if overlay { Host::Overlay } else { Host::Base }));
602    let input = &mut window.next_frame.fast_composition_input;
603    input.base = (!state.platform_surfaces.is_empty()).then_some(state.base_surface);
604    input.scope = state.enabled.then_some(if overlay {
605        state.overlay_surface
606    } else {
607        state.base_surface
608    });
609}
610
611pub(crate) fn input_surface(window: &Window) -> Option<CompositionSurfaceId> {
612    window.next_frame.fast_composition_input.scope
613}
614
615pub(crate) fn record_input(window: &mut Window, id: HitboxId) {
616    let input = &mut window.next_frame.fast_composition_input;
617    if let (Some(base), Some(surface)) = (input.base, input.scope) {
618        if surface != base {
619            input.owners.insert(id, surface);
620        }
621    }
622}
623
624pub(crate) fn finish_input(window: &mut Window) {
625    synchronize_geometry(window);
626    let scale = window.scale_factor();
627    let state = window.fast_composition.0.borrow();
628    let input = &mut window.next_frame.fast_composition_input;
629    if !state.enabled || state.platform_surfaces.is_empty() {
630        input.hitboxes.clear();
631        return;
632    }
633    input
634        .hitboxes
635        .retain(|surface, _| state.tree.kind(*surface).is_ok());
636    for surface in state.input_order.iter().copied() {
637        let native = state.platform_surfaces.get(&surface).map(|native| {
638            input_bounds(&state, surface, native.bounds().to_pixels(scale), scale)
639                .unwrap_or_default()
640        });
641        input.order.push((surface, native));
642    }
643    for hitbox in &window.next_frame.hitboxes {
644        let surface = input
645            .owners
646            .get(&hitbox.id)
647            .or_else(|| {
648                window
649                    .rendered_frame
650                    .fast_composition_input
651                    .owners
652                    .get(&hitbox.id)
653            })
654            .copied()
655            .unwrap_or(state.base_surface);
656        if !matches!(state.tree.kind(surface), Ok(CompositionSurfaceKind::Gpui)) {
657            continue;
658        }
659        if surface != state.base_surface {
660            input.owners.insert(hitbox.id, surface);
661        }
662        let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
663        let Some(bounds) = input_bounds(&state, surface, bounds, scale) else {
664            continue;
665        };
666        if !bounds.is_empty() {
667            let mut clipped = hitbox.clone();
668            clipped.bounds = bounds;
669            input.hitboxes.entry(surface).or_default().push(clipped);
670        }
671    }
672}
673
674/// Native content blocks GPUI hover and click targets behind it, while keeping
675/// the existing GPUI scroll blockers and capture dispatch unchanged.
676pub(crate) fn hit_test(
677    frame: &crate::window::Frame,
678    point: Point<Pixels>,
679) -> Option<crate::window::HitTest> {
680    let input = &frame.fast_composition_input;
681    if input.order.is_empty() {
682        return None;
683    }
684    let mut result = crate::window::HitTest::default();
685    let mut hover = None;
686    'surfaces: for (surface, native) in input.order.iter().rev() {
687        if let Some(bounds) = native {
688            if bounds.contains(&point) {
689                break;
690            }
691            continue;
692        }
693        let Some(hitboxes) = input.hitboxes.get(surface) else {
694            continue;
695        };
696        for hitbox in hitboxes.iter().rev() {
697            if hitbox.bounds.contains(&point) {
698                result.ids.push(hitbox.id);
699                if hover.is_none() && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll {
700                    hover = Some(result.ids.len());
701                }
702                if hitbox.behavior == HitboxBehavior::BlockMouse {
703                    break 'surfaces;
704                }
705            }
706        }
707    }
708    result.hover_hitbox_count = hover.unwrap_or(result.ids.len());
709    Some(result)
710}
711
712impl SurfaceStarts {
713    pub(crate) fn clear(&mut self) {
714        self.0.clear();
715    }
716
717    fn current(&self) -> Option<CompositionSurfaceId> {
718        self.0.last().map(|(surface, _)| *surface)
719    }
720
721    fn switch_to(&mut self, surface: CompositionSurfaceId, scene_len: usize) {
722        if self.current() == Some(surface) {
723            return;
724        }
725        self.0.push((surface, scene_len));
726    }
727}
728
729/// The GPUI surface an element hosting a native surface is drawn on.
730#[derive(Clone, Copy, Debug, PartialEq, Eq)]
731enum Host {
732    /// The root view, drawn on the base surface.
733    Base,
734    /// A deferred or window-level draw, drawn on the overlay surface.
735    Overlay,
736}
737
738/// A window's composition: its surface tree, the platform surfaces in it and
739/// whether the window presents through it.
740pub(crate) struct WindowCompositionState {
741    tree: CompositionTree,
742    platform_surfaces: FxHashMap<CompositionSurfaceId, Rc<ManagedPlatformSurface>>,
743    base_surface: CompositionSurfaceId,
744    overlay_surface: CompositionSurfaceId,
745    geometry_dirty: Rc<Cell<bool>>,
746    /// What the window is prepainting, while it prepaints a frame.
747    prepainting: Rc<Cell<Option<Host>>>,
748    /// Whether [`Window::enable_window_composition`] was called; the window
749    /// presents through its composition only while it also
750    /// [`splits`](Self::splits).
751    enabled: bool,
752    input_order: Vec<CompositionSurfaceId>,
753    visible: FxHashMap<CompositionSurfaceId, Rc<Cell<bool>>>,
754    input_handlers: FxHashMap<CompositionSurfaceId, Rc<RefCell<NativeInputHandler>>>,
755    pointer_capture: Option<CompositionSurfaceId>,
756    pressed_buttons: Vec<MouseButton>,
757    hovered_native: Option<CompositionSurfaceId>,
758}
759
760/// The surfaces every composition tree holds: the base and the overlay.
761const DEFAULT_SURFACES: usize = 2;
762
763impl WindowCompositionState {
764    /// Whether the tree holds a surface beyond the base and overlay surfaces,
765    /// so the scene must be split for something to draw between or around
766    /// them. Without one, the whole scene on the base surface draws the same.
767    fn splits(&self) -> bool {
768        self.tree.len() > DEFAULT_SURFACES
769    }
770}
771
772type NativeInputHandler = Box<dyn FnMut(&PlatformInput) -> DispatchEventResult>;
773
774/// The [`Window`] field holding its composition.
775pub(crate) struct WindowCompositionHandle(Rc<RefCell<WindowCompositionState>>);
776
777impl Default for WindowCompositionHandle {
778    fn default() -> Self {
779        let mut tree = CompositionTree::new();
780        let base_surface = tree
781            .insert(CompositionSurfaceKind::Gpui, None)
782            .expect("a root can always be inserted");
783        let overlay_surface = tree
784            .insert(CompositionSurfaceKind::Gpui, None)
785            .expect("a root can always be inserted");
786        Self(Rc::new(RefCell::new(WindowCompositionState {
787            tree,
788            platform_surfaces: FxHashMap::default(),
789            base_surface,
790            overlay_surface,
791            geometry_dirty: Rc::new(Cell::new(false)),
792            prepainting: Rc::new(Cell::new(None)),
793            enabled: false,
794            input_order: Vec::new(),
795            visible: FxHashMap::default(),
796            input_handlers: FxHashMap::default(),
797            pointer_capture: None,
798            pressed_buttons: Vec::new(),
799            hovered_native: None,
800        })))
801    }
802}
803
804/// A platform surface whose bounds changes mark the window's composition
805/// geometry for synchronization at the next present.
806struct ManagedPlatformSurface {
807    platform_surface: Rc<dyn PlatformSurfaceAttachment>,
808    bounds: Cell<Bounds<DevicePixels>>,
809    geometry_dirty: Rc<Cell<bool>>,
810    visible: Rc<Cell<bool>>,
811    input_forwarding: Cell<bool>,
812    prepainting: Rc<Cell<Option<Host>>>,
813    /// The surface its host was last prepainted on.
814    host: Cell<Host>,
815    /// Whether `host` changed since the surface was last restacked.
816    restack: Cell<bool>,
817}
818
819impl ManagedPlatformSurface {
820    fn new(
821        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
822        state: &WindowCompositionState,
823    ) -> Self {
824        Self {
825            bounds: Cell::new(platform_surface.bounds()),
826            platform_surface,
827            geometry_dirty: state.geometry_dirty.clone(),
828            visible: Rc::new(Cell::new(true)),
829            input_forwarding: Cell::new(false),
830            prepainting: state.prepainting.clone(),
831            host: Cell::new(Host::Base),
832            restack: Cell::new(false),
833        }
834    }
835}
836
837impl PlatformSurfaceAttachment for ManagedPlatformSurface {
838    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
839        if let Some(host) = self.prepainting.get()
840            && self.host.replace(host) != host
841        {
842            self.restack.set(true);
843            self.geometry_dirty.set(true);
844        }
845        if self.bounds.get() == bounds {
846            return Ok(());
847        }
848        self.platform_surface.set_bounds(bounds)?;
849        self.bounds.set(bounds);
850        self.geometry_dirty.set(true);
851        Ok(())
852    }
853
854    fn bounds(&self) -> Bounds<DevicePixels> {
855        self.bounds.get()
856    }
857
858    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
859        self.platform_surface.set_parent_origin(origin)
860    }
861
862    fn compositor_recreated(&self, platform_context: &dyn Any) -> Result<()> {
863        self.platform_surface.compositor_recreated(platform_context)
864    }
865
866    fn set_compositor_recreated_callback(
867        &self,
868        callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
869    ) -> Result<()> {
870        self.platform_surface
871            .set_compositor_recreated_callback(callback)
872    }
873
874    fn set_visible(&self, visible: bool) -> Result<()> {
875        if self.visible.get() == visible {
876            return Ok(());
877        }
878        self.platform_surface.set_visible(visible)?;
879        self.visible.set(visible);
880        self.geometry_dirty.set(true);
881        Ok(())
882    }
883
884    fn input_forwarding(&self) -> bool {
885        self.input_forwarding.get() && self.visible.get()
886    }
887
888    fn platform_handle(&self) -> Result<Box<dyn Any>> {
889        self.platform_surface.platform_handle()
890    }
891}
892
893struct WindowCompositionSurfaceInner {
894    id: CompositionSurfaceId,
895    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
896}
897
898/// A stable handle to a surface in a window composition tree.
899#[derive(Clone)]
900pub struct WindowCompositionSurface(Rc<WindowCompositionSurfaceInner>);
901
902impl WindowCompositionSurface {
903    /// Returns this surface's stable identity.
904    pub fn id(&self) -> CompositionSurfaceId {
905        self.0.id
906    }
907
908    /// Returns the platform surface used to attach native content.
909    pub fn platform_surface(&self) -> Result<&dyn PlatformSurfaceAttachment> {
910        self.0
911            .platform_surface
912            .as_deref()
913            .context("this composition surface is rendered by GPUI")
914    }
915}
916
917/// Controls the surface tree composited into a window.
918pub struct WindowComposition<'a> {
919    platform_window: &'a dyn PlatformWindow,
920    state: Rc<RefCell<WindowCompositionState>>,
921}
922
923impl WindowComposition<'_> {
924    /// Registers a cooperating windowless producer's mouse/wheel consumer.
925    /// Capture runs first; coordinates are in window-content logical pixels.
926    /// OS-managed child views need no handler and keep their platform input path.
927    pub fn on_input(
928        &self,
929        surface: CompositionSurfaceId,
930        handler: impl FnMut(&PlatformInput) -> DispatchEventResult + 'static,
931    ) -> Result<()> {
932        let previous = {
933            let mut state = self.state.borrow_mut();
934            anyhow::ensure!(
935                state.platform_surfaces.contains_key(&surface),
936                "input consumer requires a native surface"
937            );
938            state.platform_surfaces[&surface].input_forwarding.set(true);
939            state
940                .input_handlers
941                .insert(surface, Rc::new(RefCell::new(Box::new(handler))))
942        };
943        if let Err(error) = self.synchronize_platform_order() {
944            let mut state = self.state.borrow_mut();
945            state.platform_surfaces[&surface]
946                .input_forwarding
947                .set(previous.is_some());
948            if let Some(previous) = previous {
949                state.input_handlers.insert(surface, previous);
950            } else {
951                state.input_handlers.remove(&surface);
952            }
953            drop(state);
954            self.synchronize_platform_order().log_err();
955            return Err(error);
956        }
957        Ok(())
958    }
959
960    /// Returns the GPUI surface initially rendered below native content.
961    pub fn base_surface(&self) -> CompositionSurfaceId {
962        self.state.borrow().base_surface
963    }
964
965    /// Returns the GPUI surface initially rendered above native content.
966    pub fn overlay_surface(&self) -> CompositionSurfaceId {
967        self.state.borrow().overlay_surface
968    }
969
970    /// Creates a platform-native surface as a root of the composition tree,
971    /// below the overlay surface.
972    pub fn create_native_surface(&self) -> Result<WindowCompositionSurface> {
973        let platform_surface = self.platform_window.create_native_surface()?;
974        self.register_platform_surface(CompositionSurfaceKind::Native, platform_surface)
975    }
976
977    /// Registers an externally produced GPU surface as a root of the
978    /// composition tree, below the overlay surface.
979    ///
980    /// The producer owns the platform attachment and its synchronization. GPUI
981    /// owns its placement in the window composition tree.
982    pub fn create_external_gpu_surface(
983        &self,
984        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
985    ) -> Result<WindowCompositionSurface> {
986        self.register_platform_surface(CompositionSurfaceKind::ExternalGpu, platform_surface)
987    }
988
989    /// Creates another GPUI-rendered surface in the composition tree. Paint
990    /// onto it with [`Window::with_composition_surface`].
991    pub fn create_gpui_surface(
992        &self,
993        parent: Option<CompositionSurfaceId>,
994    ) -> Result<WindowCompositionSurface> {
995        let id = self
996            .state
997            .borrow_mut()
998            .tree
999            .insert(CompositionSurfaceKind::Gpui, parent)?;
1000        if let Err(error) = self.synchronize_platform_order() {
1001            self.state.borrow_mut().tree.remove(id)?;
1002            self.synchronize_platform_order().log_err();
1003            return Err(error);
1004        }
1005        Ok(surface_handle(id, None))
1006    }
1007
1008    /// Places `surface` immediately above `sibling`.
1009    pub fn place_above(
1010        &self,
1011        surface: CompositionSurfaceId,
1012        sibling: CompositionSurfaceId,
1013    ) -> Result<()> {
1014        anyhow::ensure!(
1015            surface != self.state.borrow().base_surface,
1016            "the GPUI base surface cannot be reordered"
1017        );
1018        self.change_tree(|tree| tree.place_above(surface, sibling))
1019    }
1020
1021    /// Places `surface` immediately below `sibling`.
1022    pub fn place_below(
1023        &self,
1024        surface: CompositionSurfaceId,
1025        sibling: CompositionSurfaceId,
1026    ) -> Result<()> {
1027        let base_surface = self.state.borrow().base_surface;
1028        anyhow::ensure!(
1029            surface != base_surface && sibling != base_surface,
1030            "surfaces cannot be placed below or move the GPUI base surface"
1031        );
1032        self.change_tree(|tree| tree.place_below(surface, sibling))
1033    }
1034
1035    /// Moves `surface` under a new parent, placing it above existing children.
1036    pub fn reparent(
1037        &self,
1038        surface: CompositionSurfaceId,
1039        parent: Option<CompositionSurfaceId>,
1040    ) -> Result<()> {
1041        anyhow::ensure!(
1042            surface != self.state.borrow().base_surface,
1043            "the GPUI base surface cannot be reparented"
1044        );
1045        self.change_tree(|tree| tree.reparent(surface, parent))
1046    }
1047
1048    /// Removes a surface while preserving its children at the removed
1049    /// surface's previous position.
1050    pub fn remove_surface(&self, surface: CompositionSurfaceId) -> Result<()> {
1051        let mut state = self.state.borrow_mut();
1052        if surface == state.base_surface || surface == state.overlay_surface {
1053            bail!("the default GPUI composition surfaces cannot be removed");
1054        }
1055        let previous_tree = state.tree.clone();
1056        let platform_surface = state.platform_surfaces.get(&surface).cloned();
1057        let was_visible = state
1058            .visible
1059            .get(&surface)
1060            .is_none_or(|visible| visible.get());
1061        if let Some(platform_surface) = &platform_surface {
1062            platform_surface.set_visible(false)?;
1063        }
1064        state.tree.remove(surface)?;
1065        state.platform_surfaces.remove(&surface);
1066        drop(state);
1067        if let Err(error) = self.synchronize_platform_order() {
1068            let mut state = self.state.borrow_mut();
1069            state.tree = previous_tree;
1070            if let Some(platform_surface) = platform_surface {
1071                platform_surface.set_visible(was_visible).log_err();
1072                state.platform_surfaces.insert(surface, platform_surface);
1073            }
1074            drop(state);
1075            self.synchronize_platform_order().log_err();
1076            return Err(error);
1077        }
1078        let mut state = self.state.borrow_mut();
1079        state.visible.remove(&surface);
1080        state.input_handlers.remove(&surface);
1081        if state.pointer_capture == Some(surface) {
1082            state.pointer_capture = None;
1083            state.pressed_buttons.clear();
1084        }
1085        if state.hovered_native == Some(surface) {
1086            state.hovered_native = None;
1087        }
1088        Ok(())
1089    }
1090
1091    /// Returns the renderer kind for a surface.
1092    pub fn surface_kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
1093        self.state.borrow().tree.kind(surface)
1094    }
1095
1096    /// Returns a surface's parent.
1097    pub fn parent(&self, surface: CompositionSurfaceId) -> Result<Option<CompositionSurfaceId>> {
1098        self.state.borrow().tree.parent(surface)
1099    }
1100
1101    /// Returns the ordered children of a surface, or the root surfaces when
1102    /// `parent` is `None`.
1103    pub fn children(
1104        &self,
1105        parent: Option<CompositionSurfaceId>,
1106    ) -> Result<Vec<CompositionSurfaceId>> {
1107        Ok(self.state.borrow().tree.children(parent)?.to_vec())
1108    }
1109
1110    /// Applies `change` to the tree and the platform, or neither.
1111    fn change_tree(&self, change: impl FnOnce(&mut CompositionTree) -> Result<()>) -> Result<()> {
1112        let previous_tree = self.state.borrow().tree.clone();
1113        change(&mut self.state.borrow_mut().tree)?;
1114        if let Err(error) = self.synchronize_platform_order() {
1115            self.state.borrow_mut().tree = previous_tree;
1116            self.synchronize_platform_order().log_err();
1117            return Err(error);
1118        }
1119        Ok(())
1120    }
1121
1122    fn register_platform_surface(
1123        &self,
1124        kind: CompositionSurfaceKind,
1125        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
1126    ) -> Result<WindowCompositionSurface> {
1127        let platform_surface = Rc::new(ManagedPlatformSurface::new(
1128            platform_surface,
1129            &self.state.borrow(),
1130        ));
1131        let visible = platform_surface.visible.clone();
1132        let mut state = self.state.borrow_mut();
1133        let id = state.tree.insert(kind, None)?;
1134        let overlay_surface = state.overlay_surface;
1135        state.tree.place_below(id, overlay_surface)?;
1136        state.platform_surfaces.insert(id, platform_surface.clone());
1137        state.visible.insert(id, visible);
1138        drop(state);
1139        if let Err(error) = self.synchronize_platform_order() {
1140            platform_surface.set_visible(false).log_err();
1141            let mut state = self.state.borrow_mut();
1142            state.platform_surfaces.remove(&id);
1143            state.visible.remove(&id);
1144            state.tree.remove(id)?;
1145            drop(state);
1146            self.synchronize_platform_order().log_err();
1147            return Err(error);
1148        }
1149        Ok(surface_handle(id, Some(platform_surface)))
1150    }
1151
1152    /// Hands the platform the tree's order and every surface's geometry.
1153    fn synchronize_platform_order(&self) -> Result<()> {
1154        let surfaces = self.platform_order()?;
1155        self.platform_window.set_composition_order(&surfaces)?;
1156        let state = self.state.borrow();
1157        state.geometry_dirty.set(false);
1158        drop(state);
1159        self.state.borrow_mut().input_order = surfaces.iter().map(|surface| surface.id).collect();
1160        Ok(())
1161    }
1162
1163    /// The tree's surfaces in order, with their geometry, as the platform is
1164    /// handed them. The overlay surface is left out while the scene is not
1165    /// split, so the platform releases what draws it.
1166    fn platform_order(&self) -> Result<Vec<PlatformCompositionSurface>> {
1167        let state = self.state.borrow();
1168        let mut origins = FxHashMap::default();
1169        let mut surfaces = Vec::new();
1170        let splits = state.splits();
1171        for id in state.tree.flattened() {
1172            if !splits && id == state.overlay_surface {
1173                continue;
1174            }
1175            let parent = state.tree.parent(id)?;
1176            let parent_origin = parent
1177                .and_then(|parent| origins.get(&parent).copied())
1178                .unwrap_or_default();
1179            let content = match state.tree.kind(id)? {
1180                CompositionSurfaceKind::Gpui => PlatformCompositionSurfaceContent::Gpui,
1181                CompositionSurfaceKind::Native => PlatformCompositionSurfaceContent::Native(
1182                    state
1183                        .platform_surfaces
1184                        .get(&id)
1185                        .context("native composition surface is missing")?
1186                        .clone(),
1187                ),
1188                CompositionSurfaceKind::ExternalGpu => {
1189                    PlatformCompositionSurfaceContent::ExternalGpu(
1190                        state
1191                            .platform_surfaces
1192                            .get(&id)
1193                            .context("external GPU composition surface is missing")?
1194                            .clone(),
1195                    )
1196                }
1197            };
1198            let window_bounds = match &content {
1199                PlatformCompositionSurfaceContent::Gpui => None,
1200                PlatformCompositionSurfaceContent::Native(platform_surface)
1201                | PlatformCompositionSurfaceContent::ExternalGpu(platform_surface) => {
1202                    Some(platform_surface.bounds())
1203                }
1204            };
1205            let window_origin = window_bounds.map_or_else(Point::default, |bounds| bounds.origin);
1206            origins.insert(id, window_origin);
1207            surfaces.push(PlatformCompositionSurface {
1208                id,
1209                parent,
1210                window_origin,
1211                parent_origin,
1212                window_bounds,
1213                content,
1214            });
1215        }
1216        Ok(surfaces)
1217    }
1218}
1219
1220fn surface_handle(
1221    id: CompositionSurfaceId,
1222    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
1223) -> WindowCompositionSurface {
1224    WindowCompositionSurface(Rc::new(WindowCompositionSurfaceInner {
1225        id,
1226        platform_surface,
1227    }))
1228}
1229
1230impl Window {
1231    /// Enables native window composition and returns its controller.
1232    ///
1233    /// GPUI's root scene is rendered below surfaces created by the controller,
1234    /// while deferred and window-level overlays are rendered above them.
1235    pub fn enable_window_composition(&self) -> Result<WindowComposition<'_>> {
1236        self.platform_window.enable_window_composition()?;
1237        let composition = WindowComposition {
1238            platform_window: self.platform_window.as_ref(),
1239            state: self.fast_composition.0.clone(),
1240        };
1241        composition.synchronize_platform_order()?;
1242        composition.state.borrow_mut().enabled = true;
1243        Ok(composition)
1244    }
1245
1246    /// Prepaints or paints an element scope on a GPUI composition surface,
1247    /// then restores the previous surface. Wrap both phases when selecting a
1248    /// surface explicitly so its input regions follow its painted content.
1249    ///
1250    /// Inside a scroll layer, whose content is composited from tiles, the
1251    /// scope paints where the layer does.
1252    pub fn with_composition_surface<R>(
1253        &mut self,
1254        surface: CompositionSurfaceId,
1255        paint: impl FnOnce(&mut Self) -> R,
1256    ) -> Result<R> {
1257        self.invalidator.debug_assert_paint_or_prepaint();
1258        anyhow::ensure!(
1259            self.fast_composition.0.borrow().tree.kind(surface)? == CompositionSurfaceKind::Gpui,
1260            "paint operations can only target GPUI composition surfaces"
1261        );
1262        if self.fast_layers.painting.is_some() {
1263            return Ok(paint(self));
1264        }
1265        if self.invalidator.inner.borrow().draw_phase == crate::window::DrawPhase::Prepaint {
1266            let previous = self
1267                .next_frame
1268                .fast_composition_input
1269                .scope
1270                .replace(surface);
1271            let result = paint(self);
1272            self.next_frame.fast_composition_input.scope = previous;
1273            return Ok(result);
1274        }
1275        let previous_surface = self
1276            .next_frame
1277            .fast_composition_starts
1278            .current()
1279            .context("composition paint scope has no base surface")?;
1280        switch_surface(self, surface);
1281        let result = paint(self);
1282        switch_surface(self, previous_surface);
1283        Ok(result)
1284    }
1285}
1286
1287fn switch_surface(window: &mut Window, surface: CompositionSurfaceId) {
1288    let scene_len = window.next_frame.scene.len();
1289    window
1290        .next_frame
1291        .fast_composition_starts
1292        .switch_to(surface, scene_len);
1293}
1294
1295/// Stacks what the root view positions, as it prepaints, below the overlay
1296/// surface.
1297pub(crate) fn begin_base_prepaint(window: &mut Window) {
1298    begin_input(window, false);
1299}
1300
1301/// Stacks what deferred and window-level draws position, as they prepaint,
1302/// above the overlay surface.
1303pub(crate) fn begin_overlay_prepaint(window: &mut Window) {
1304    begin_input(window, true);
1305}
1306
1307/// Paints what follows, the root view, onto the base surface.
1308pub(crate) fn begin_base(window: &mut Window) {
1309    let state = window.fast_composition.0.borrow();
1310    state.prepainting.set(None);
1311    let surface = state.base_surface;
1312    drop(state);
1313    switch_surface(window, surface);
1314}
1315
1316/// Moves each root native surface whose host changed surface to that
1317/// surface's side of the overlay surface.
1318fn restack_native_surfaces(state: &mut WindowCompositionState) -> Result<()> {
1319    let overlay = state.overlay_surface;
1320    for (id, surface) in &state.platform_surfaces {
1321        if !surface.restack.replace(false) || state.tree.parent(*id)?.is_some() {
1322            continue;
1323        }
1324        match surface.host.get() {
1325            Host::Base => state.tree.place_below(*id, overlay)?,
1326            Host::Overlay => state.tree.place_above(*id, overlay)?,
1327        }
1328    }
1329    Ok(())
1330}
1331
1332/// Paints what follows, deferred and window-level draws, onto the overlay
1333/// surface.
1334pub(crate) fn begin_overlay(window: &mut Window) {
1335    let surface = window.fast_composition.0.borrow().overlay_surface;
1336    switch_surface(window, surface);
1337}
1338
1339/// Carries the surface switches last frame made within `range` into the
1340/// frame being drawn, as [`Window::reuse_paint`] replays its scene, and
1341/// leaves painting on the surface it was on before.
1342pub(crate) fn reuse_starts(window: &mut Window, range: &Range<PaintIndex>) {
1343    let scenes = range.start.scene_index..range.end.scene_index;
1344    let starts = &window.rendered_frame.fast_composition_starts.0;
1345    let first = starts.partition_point(|(_, start)| *start < scenes.start);
1346    let last = starts.partition_point(|(_, start)| *start < scenes.end);
1347    if first == last {
1348        return;
1349    }
1350    let Some(surface) = window.next_frame.fast_composition_starts.current() else {
1351        return;
1352    };
1353    let offset = window.next_frame.scene.len();
1354    for index in first..last {
1355        let (reused, start) = window.rendered_frame.fast_composition_starts.0[index];
1356        window
1357            .next_frame
1358            .fast_composition_starts
1359            .switch_to(reused, start - scenes.start + offset);
1360    }
1361    let end = offset + scenes.len();
1362    window
1363        .next_frame
1364        .fast_composition_starts
1365        .switch_to(surface, end);
1366}
1367
1368// Host changes must reach input ownership before the frame's hit test.
1369fn synchronize_geometry(window: &mut Window) {
1370    let state = window.fast_composition.0.clone();
1371    if !state.borrow().enabled {
1372        return;
1373    }
1374    if state.borrow().geometry_dirty.get() {
1375        if let Err(error) = restack_native_surfaces(&mut state.borrow_mut()) {
1376            log::error!("restacking native composition surfaces: {error:#}");
1377        }
1378        let composition = WindowComposition {
1379            platform_window: window.platform_window.as_ref(),
1380            state,
1381        };
1382        if let Err(error) = composition.synchronize_platform_order() {
1383            log::error!("updating window composition geometry: {error:#}");
1384        }
1385    }
1386}
1387
1388/// Reorder only scenes that return to the base after painting the overlay.
1389/// The common base-then-overlay scene can be presented without copying it.
1390fn ordered_plain_scene(
1391    state: &WindowCompositionState,
1392    starts: &[(CompositionSurfaceId, usize)],
1393    scene: &Scene,
1394) -> Result<Option<Scene>> {
1395    let mut seen_overlay = false;
1396    let mut out_of_order = false;
1397    for (index, &(surface, start)) in starts.iter().enumerate() {
1398        let end = starts.get(index + 1).map_or(scene.len(), |(_, end)| *end);
1399        if start >= end {
1400            continue;
1401        }
1402        if surface == state.overlay_surface {
1403            seen_overlay = true;
1404        } else if surface == state.base_surface && seen_overlay {
1405            out_of_order = true;
1406            break;
1407        }
1408    }
1409    if !out_of_order {
1410        return Ok(None);
1411    }
1412    let layers = composed_scene_layers(&state.tree, starts, scene.len())?;
1413    let mut ordered = Scene::default();
1414    for layer in layers {
1415        for range in layer.ranges {
1416            ordered.replay_balanced(range, scene)?;
1417        }
1418    }
1419    ordered.finish();
1420    Ok(Some(ordered))
1421}
1422
1423/// Presents the frame last drawn: on its one surface, or split along the
1424/// composition tree while the window composes around another surface.
1425pub(crate) fn present(window: &mut Window) {
1426    let state = window.fast_composition.0.clone();
1427    let splits = {
1428        let state = state.borrow();
1429        state.enabled && state.splits()
1430    };
1431    if !splits {
1432        let frame = &window.rendered_frame;
1433        let ordered = if state.borrow().enabled {
1434            ordered_plain_scene(
1435                &state.borrow(),
1436                &frame.fast_composition_starts.0,
1437                &frame.scene,
1438            )
1439            .log_err()
1440            .flatten()
1441        } else {
1442            None
1443        };
1444        window
1445            .platform_window
1446            .draw(ordered.as_ref().unwrap_or(&frame.scene));
1447        return;
1448    }
1449    synchronize_geometry(window);
1450    let state = state.borrow();
1451    let scene = &window.rendered_frame.scene;
1452    let layers = composed_scene_layers(
1453        &state.tree,
1454        &window.rendered_frame.fast_composition_starts.0,
1455        scene.len(),
1456    )
1457    .unwrap_or_else(|error| {
1458        log::error!("invalid window composition scene: {error:#}");
1459        vec![ComposedSceneLayer {
1460            surface: state.base_surface,
1461            ranges: vec![0..scene.len()],
1462        }]
1463    });
1464    drop(state);
1465    window.platform_window.draw_composed(ComposedScene::new(
1466        scene,
1467        layers,
1468        &window.rendered_frame.fast_composition_input,
1469    ));
1470}
1471
1472/// Visibility and ancestor clips come from the existing managed surface tree.
1473fn input_bounds(
1474    state: &WindowCompositionState,
1475    surface: CompositionSurfaceId,
1476    mut bounds: Bounds<Pixels>,
1477    scale: f32,
1478) -> Option<Bounds<Pixels>> {
1479    let mut current = Some(surface);
1480    while let Some(id) = current {
1481        state.tree.kind(id).ok()?;
1482        if state.visible.get(&id).is_some_and(|visible| !visible.get()) {
1483            return None;
1484        }
1485        if let Some(native) = state.platform_surfaces.get(&id) {
1486            bounds = bounds.intersect(&native.bounds().to_pixels(scale));
1487        }
1488        current = state.tree.parent(id).ok()?;
1489    }
1490    (!bounds.is_empty()).then_some(bounds)
1491}
1492
1493fn visible_surface(state: &WindowCompositionState, surface: CompositionSurfaceId) -> bool {
1494    let mut current = Some(surface);
1495    while let Some(id) = current {
1496        if state.tree.kind(id).is_err() || state.visible.get(&id).is_some_and(|v| !v.get()) {
1497            return false;
1498        }
1499        current = state.tree.parent(id).ok().flatten();
1500    }
1501    true
1502}
1503
1504fn native_target(window: &Window, scroll: bool) -> Option<CompositionSurfaceId> {
1505    let state = window.fast_composition.0.borrow();
1506    if !state.enabled || state.platform_surfaces.is_empty() {
1507        return None;
1508    }
1509    if !scroll {
1510        if let Some(captured) = state
1511            .pointer_capture
1512            .filter(|id| visible_surface(&state, *id))
1513        {
1514            return Some(captured);
1515        }
1516    }
1517    let point = window.mouse_position;
1518    for surface in state.input_order.iter().rev().copied() {
1519        if !visible_surface(&state, surface) {
1520            continue;
1521        }
1522        if let Some(native) = state.platform_surfaces.get(&surface) {
1523            if input_bounds(
1524                &state,
1525                surface,
1526                native.bounds().to_pixels(window.scale_factor()),
1527                window.scale_factor(),
1528            )
1529            .is_some_and(|bounds| bounds.contains(&point))
1530            {
1531                return Some(surface);
1532            }
1533        } else if let Some(regions) = window
1534            .rendered_frame
1535            .fast_composition_input
1536            .hitboxes
1537            .get(&surface)
1538        {
1539            if regions.iter().rev().any(|hitbox| {
1540                hitbox.bounds.contains(&point)
1541                    && (!scroll || hitbox.behavior == HitboxBehavior::BlockMouse)
1542            }) {
1543                return None;
1544            }
1545        }
1546    }
1547    None
1548}
1549
1550/// OS-directed native events still run GPUI capture, but cannot activate
1551/// unrelated GPUI widgets underneath the native view.
1552fn native_mouse(window: &Window, event: &dyn Any) -> bool {
1553    if window.captured_hitbox.is_some() {
1554        let state = window.fast_composition.0.borrow();
1555        return state
1556            .pointer_capture
1557            .is_some_and(|id| visible_surface(&state, id));
1558    }
1559    if event
1560        .downcast_ref::<MouseMoveEvent>()
1561        .is_some_and(|event| event.pressed_button.is_some())
1562        && window.fast_composition.0.borrow().pointer_capture.is_none()
1563    {
1564        return false;
1565    }
1566    native_target(window, false).is_some()
1567}
1568
1569pub(crate) fn bubble_mouse(window: &Window, event: &dyn Any, cx: &crate::App) -> bool {
1570    cx.propagate_event && (cx.has_active_drag() || !native_mouse(window, event))
1571}
1572
1573pub(crate) fn event_target(window: &Window, event: &PlatformInput) -> Option<CompositionSurfaceId> {
1574    if !matches!(
1575        event,
1576        PlatformInput::MouseDown(_)
1577            | PlatformInput::MouseUp(_)
1578            | PlatformInput::MouseMove(_)
1579            | PlatformInput::Scroll(_)
1580    ) {
1581        return None;
1582    }
1583    let scroll = matches!(event, PlatformInput::Scroll(_));
1584    if !scroll {
1585        let state = window.fast_composition.0.borrow();
1586        if let Some(captured) = state.pointer_capture {
1587            return visible_surface(&state, captured).then_some(captured);
1588        }
1589    }
1590    if window.captured_hitbox.is_some() || matches!(event, PlatformInput::MouseUp(_)) {
1591        return None;
1592    }
1593    if matches!(
1594        event,
1595        PlatformInput::MouseMove(MouseMoveEvent {
1596            pressed_button: Some(_),
1597            ..
1598        })
1599    ) && window.fast_composition.0.borrow().pointer_capture.is_none()
1600    {
1601        return None;
1602    }
1603    native_target(window, scroll)
1604}
1605
1606/// Called after the existing dispatcher; windowless producers get one delivery,
1607/// while OS-managed views continue through the platform's original event path.
1608pub(crate) fn dispatch_native(
1609    window: &mut Window,
1610    event: &PlatformInput,
1611    target: Option<CompositionSurfaceId>,
1612    propagate: &mut bool,
1613) {
1614    let pointer = matches!(
1615        event,
1616        PlatformInput::MouseDown(_)
1617            | PlatformInput::MouseUp(_)
1618            | PlatformInput::MouseMove(_)
1619            | PlatformInput::MouseExited(_)
1620            | PlatformInput::Scroll(_)
1621    );
1622    if !pointer || !window.fast_composition.0.borrow().enabled {
1623        return;
1624    }
1625    let target = target.filter(|id| visible_surface(&window.fast_composition.0.borrow(), *id));
1626    let (handler, leave) = {
1627        let mut state = window.fast_composition.0.borrow_mut();
1628        let leave = if matches!(
1629            event,
1630            PlatformInput::MouseMove(_) | PlatformInput::MouseExited(_)
1631        ) {
1632            let current = if matches!(event, PlatformInput::MouseExited(_)) {
1633                None
1634            } else {
1635                target
1636            };
1637            let previous = std::mem::replace(&mut state.hovered_native, current);
1638            previous
1639                .filter(|old| Some(*old) != current)
1640                .and_then(|id| state.input_handlers.get(&id).cloned())
1641        } else {
1642            None
1643        };
1644        if *propagate && !window.default_prevented {
1645            if let PlatformInput::MouseDown(down) = event {
1646                if let Some(id) = target {
1647                    state.pointer_capture = Some(id);
1648                    if !state.pressed_buttons.contains(&down.button) {
1649                        state.pressed_buttons.push(down.button);
1650                    }
1651                }
1652            }
1653        }
1654        let owned_release = matches!(event, PlatformInput::MouseUp(_))
1655            && target.is_some()
1656            && state.pointer_capture == target;
1657        let handler = if (*propagate && !window.default_prevented) || owned_release {
1658            target.and_then(|id| state.input_handlers.get(&id).cloned())
1659        } else {
1660            None
1661        };
1662        if let PlatformInput::MouseUp(up) = event {
1663            // A single press ends even if platform normalization changed its button
1664            // (AppKit ctrl-click with Control released before mouse-up).
1665            if state.pressed_buttons.len() == 1 {
1666                state.pressed_buttons.clear();
1667            } else {
1668                state.pressed_buttons.retain(|button| *button != up.button);
1669            }
1670            if state.pressed_buttons.is_empty() {
1671                state.pointer_capture = None;
1672            }
1673        }
1674        (handler, leave)
1675    };
1676    if let Some(leave) = leave {
1677        let (position, pressed_button, modifiers) = match event {
1678            PlatformInput::MouseMove(event) => {
1679                (event.position, event.pressed_button, event.modifiers)
1680            }
1681            PlatformInput::MouseExited(event) => {
1682                (event.position, event.pressed_button, event.modifiers)
1683            }
1684            _ => unreachable!(),
1685        };
1686        leave.borrow_mut()(&PlatformInput::MouseExited(MouseExitEvent {
1687            position,
1688            pressed_button,
1689            modifiers,
1690        }));
1691    }
1692    if let Some(handler) = handler {
1693        let result = handler.borrow_mut()(event);
1694        *propagate &= result.propagate;
1695        window.default_prevented |= result.default_prevented;
1696    }
1697}
1698
1699#[cfg(test)]
1700mod tests {
1701    use super::{
1702        CompositionSurfaceId, CompositionSurfaceKind, CompositionTree, Host,
1703        ManagedPlatformSurface, PlatformSurfaceAttachment, WindowComposition,
1704        WindowCompositionHandle, composed_scene_layers, ordered_plain_scene,
1705        restack_native_surfaces,
1706    };
1707    use crate::{
1708        AppContext as _, Bounds, ContentMask, Context, DevicePixels, Entity, IntoElement,
1709        ParentElement as _, Point, Quad, Render, ScaledPixels, Scene, Size, StyleRefinement,
1710        Styled as _, TestAppContext, Window, canvas, deferred, div, fill, px,
1711        scene::PaintOperation, size,
1712    };
1713    use anyhow::Result;
1714    use std::{any::Any, cell::Cell, rc::Rc};
1715
1716    #[test]
1717    fn composition_surfaces_have_stable_identity_and_explicit_order() -> Result<()> {
1718        let mut tree = CompositionTree::new();
1719        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1720        let webview = tree.insert(CompositionSurfaceKind::Native, None)?;
1721        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1722
1723        tree.place_below(overlay, webview)?;
1724
1725        assert_eq!(tree.flattened(), [base, overlay, webview]);
1726        assert_eq!(tree.kind(webview)?, CompositionSurfaceKind::Native);
1727        Ok(())
1728    }
1729
1730    #[test]
1731    fn composition_surfaces_can_be_nested_and_reparented() -> Result<()> {
1732        let mut tree = CompositionTree::new();
1733        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1734        let pane = tree.insert(CompositionSurfaceKind::Native, Some(base))?;
1735        let video = tree.insert(CompositionSurfaceKind::ExternalGpu, None)?;
1736
1737        tree.reparent(video, Some(pane))?;
1738
1739        assert_eq!(tree.parent(video)?, Some(pane));
1740        assert_eq!(tree.children(Some(pane))?, [video]);
1741        assert_eq!(tree.flattened(), [base, pane, video]);
1742        Ok(())
1743    }
1744
1745    #[test]
1746    fn composition_tree_rejects_cycles_and_cross_parent_ordering() -> Result<()> {
1747        let mut tree = CompositionTree::new();
1748        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1749        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1750        let sibling = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1751
1752        assert!(tree.reparent(parent, Some(child)).is_err());
1753        assert!(tree.place_above(child, sibling).is_err());
1754        assert_eq!(tree.parent(parent)?, None);
1755        assert_eq!(tree.parent(child)?, Some(parent));
1756        Ok(())
1757    }
1758
1759    #[test]
1760    fn removing_a_surface_preserves_and_reparents_its_children() -> Result<()> {
1761        let mut tree = CompositionTree::new();
1762        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1763        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1764
1765        tree.remove(parent)?;
1766
1767        assert_eq!(tree.parent(child)?, None);
1768        assert_eq!(tree.flattened(), [child]);
1769        Ok(())
1770    }
1771
1772    #[test]
1773    fn scene_ranges_follow_tree_order_and_preserve_repeated_segments() -> Result<()> {
1774        let mut tree = CompositionTree::new();
1775        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1776        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1777        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1778        let starts = [(base, 0), (overlay, 4), (base, 7)];
1779
1780        let layers = composed_scene_layers(&tree, &starts, 10)?;
1781
1782        let [base_layer, overlay_layer] = layers.as_slice() else {
1783            panic!("expected base and overlay scene layers");
1784        };
1785        assert_eq!(base_layer.surface, base);
1786        assert_eq!(base_layer.ranges, [0..4, 7..10]);
1787        assert_eq!(overlay_layer.surface, overlay);
1788        assert_eq!(overlay_layer.ranges, [4..7]);
1789        assert_eq!(tree.kind(native)?, CompositionSurfaceKind::Native);
1790        Ok(())
1791    }
1792
1793    #[test]
1794    fn scene_ranges_reject_non_gpui_targets_and_non_monotonic_markers() -> Result<()> {
1795        let mut tree = CompositionTree::new();
1796        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1797        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1798
1799        assert!(composed_scene_layers(&tree, &[(native, 0)], 1).is_err());
1800        assert!(composed_scene_layers(&tree, &[(base, 2), (base, 1)], 2).is_err());
1801        Ok(())
1802    }
1803
1804    struct TestPlatformSurface {
1805        bounds_writes: Cell<usize>,
1806        fail_next_bounds: Cell<bool>,
1807        bounds: Cell<Bounds<DevicePixels>>,
1808        parent_origin: Cell<Point<DevicePixels>>,
1809    }
1810
1811    impl PlatformSurfaceAttachment for TestPlatformSurface {
1812        fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
1813            self.bounds_writes.set(self.bounds_writes.get() + 1);
1814            if self.fail_next_bounds.replace(false) {
1815                return Err(anyhow::anyhow!("test bounds failure"));
1816            }
1817            self.bounds.set(bounds);
1818            Ok(())
1819        }
1820
1821        fn bounds(&self) -> Bounds<DevicePixels> {
1822            self.bounds.get()
1823        }
1824
1825        fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
1826            self.parent_origin.set(origin);
1827            Ok(())
1828        }
1829
1830        fn set_visible(&self, _visible: bool) -> Result<()> {
1831            Ok(())
1832        }
1833
1834        fn platform_handle(&self) -> Result<Box<dyn Any>> {
1835            Ok(Box::new(()))
1836        }
1837    }
1838
1839    #[test]
1840    fn managed_composition_surface_tracks_window_geometry_changes() {
1841        let platform_surface = Rc::new(TestPlatformSurface {
1842            bounds_writes: Cell::new(0),
1843            fail_next_bounds: Cell::new(false),
1844            bounds: Cell::new(Bounds::default()),
1845            parent_origin: Cell::new(Point::default()),
1846        });
1847        let geometry_dirty = Rc::new(Cell::new(false));
1848        let surface = ManagedPlatformSurface {
1849            platform_surface: platform_surface.clone(),
1850            bounds: Cell::new(Bounds::default()),
1851            geometry_dirty: geometry_dirty.clone(),
1852            visible: Rc::new(Cell::new(true)),
1853            input_forwarding: Cell::new(false),
1854            prepainting: Rc::new(Cell::new(None)),
1855            host: Cell::new(Host::Base),
1856            restack: Cell::new(false),
1857        };
1858        let bounds = Bounds {
1859            origin: Point {
1860                x: DevicePixels(25),
1861                y: DevicePixels(40),
1862            },
1863            size: size(DevicePixels(300), DevicePixels(200)),
1864        };
1865        let parent_origin = Point {
1866            x: DevicePixels(10),
1867            y: DevicePixels(15),
1868        };
1869
1870        assert!(surface.set_bounds(bounds).is_ok());
1871        assert!(surface.set_parent_origin(parent_origin).is_ok());
1872
1873        assert_eq!(surface.bounds(), bounds);
1874        assert_eq!(platform_surface.bounds.get(), bounds);
1875        assert_eq!(platform_surface.parent_origin.get(), parent_origin);
1876        assert!(geometry_dirty.get());
1877    }
1878
1879    #[test]
1880    fn unchanged_native_bounds_do_not_resynchronize_composition() -> Result<()> {
1881        let bounds = Bounds::new(Point::default(), size(DevicePixels(300), DevicePixels(200)));
1882        let platform = Rc::new(TestPlatformSurface {
1883            bounds_writes: Cell::new(0),
1884            fail_next_bounds: Cell::new(false),
1885            bounds: Cell::new(Bounds::default()),
1886            parent_origin: Cell::new(Point::default()),
1887        });
1888        let dirty = Rc::new(Cell::new(false));
1889        let surface = ManagedPlatformSurface {
1890            platform_surface: platform.clone(),
1891            bounds: Cell::new(Bounds::default()),
1892            geometry_dirty: dirty.clone(),
1893            visible: Rc::new(Cell::new(true)),
1894            input_forwarding: Cell::new(false),
1895            prepainting: Rc::new(Cell::new(None)),
1896            host: Cell::new(Host::Base),
1897            restack: Cell::new(false),
1898        };
1899        surface.set_bounds(bounds)?;
1900        dirty.set(false);
1901        for _ in 0..10 {
1902            surface.set_bounds(bounds)?;
1903        }
1904        assert!(
1905            !dirty.get(),
1906            "unchanged layout must not remount native views between mouse down and up"
1907        );
1908        assert_eq!(platform.bounds_writes.get(), 1);
1909        let moved = Bounds::new(
1910            Point {
1911                x: DevicePixels(20),
1912                y: DevicePixels(15),
1913            },
1914            bounds.size,
1915        );
1916        surface.set_bounds(moved)?;
1917        assert!(dirty.get());
1918        assert_eq!(platform.bounds_writes.get(), 2);
1919        assert_eq!(surface.bounds(), moved);
1920        Ok(())
1921    }
1922
1923    #[test]
1924    fn failed_native_bounds_updates_remain_retryable() -> Result<()> {
1925        let bounds = Bounds::new(Point::default(), size(DevicePixels(600), DevicePixels(400)));
1926        let platform = Rc::new(TestPlatformSurface {
1927            bounds_writes: Cell::new(0),
1928            fail_next_bounds: Cell::new(true),
1929            bounds: Cell::new(Bounds::default()),
1930            parent_origin: Cell::new(Point::default()),
1931        });
1932        let dirty = Rc::new(Cell::new(false));
1933        let surface = ManagedPlatformSurface {
1934            platform_surface: platform.clone(),
1935            bounds: Cell::new(Bounds::default()),
1936            geometry_dirty: dirty.clone(),
1937            visible: Rc::new(Cell::new(true)),
1938            input_forwarding: Cell::new(false),
1939            prepainting: Rc::new(Cell::new(None)),
1940            host: Cell::new(Host::Base),
1941            restack: Cell::new(false),
1942        };
1943        assert!(surface.set_bounds(bounds).is_err());
1944        assert_eq!(surface.bounds(), Bounds::default());
1945        assert!(!dirty.get());
1946        surface.set_bounds(bounds)?;
1947        assert!(dirty.get());
1948        assert_eq!(surface.bounds(), bounds);
1949        assert_eq!(platform.bounds_writes.get(), 2);
1950        dirty.set(false);
1951        surface.set_bounds(bounds)?;
1952        assert!(!dirty.get());
1953        assert_eq!(platform.bounds_writes.get(), 2);
1954        Ok(())
1955    }
1956
1957    fn square(side: f32) -> Bounds<ScaledPixels> {
1958        Bounds {
1959            origin: Point::default(),
1960            size: Size {
1961                width: ScaledPixels::from(side),
1962                height: ScaledPixels::from(side),
1963            },
1964        }
1965    }
1966
1967    #[test]
1968    fn empty_layers_do_not_make_a_scene_drawable() {
1969        let mut scene = Scene::default();
1970        scene.push_layer(square(100.));
1971        scene.pop_layer();
1972
1973        assert_ne!(scene.len(), 0);
1974        assert!(scene.is_empty());
1975    }
1976
1977    #[test]
1978    fn drawable_primitives_make_a_scene_non_empty() {
1979        let mut scene = Scene::default();
1980        let bounds = square(100.);
1981        scene.insert_primitive(Quad {
1982            bounds,
1983            content_mask: ContentMask { bounds },
1984            ..Default::default()
1985        });
1986
1987        assert!(!scene.is_empty());
1988    }
1989
1990    #[test]
1991    fn replay_preserves_scene_emptiness() {
1992        let mut source = Scene::default();
1993        source.push_layer(square(100.));
1994        source.pop_layer();
1995
1996        let mut replayed = Scene::default();
1997        replayed.replay(0..source.len(), &source);
1998
1999        assert!(replayed.is_empty());
2000    }
2001
2002    #[test]
2003    fn balanced_replay_restores_layers_crossing_the_range_boundary() {
2004        let mut source = Scene::default();
2005        let inner_bounds = square(50.);
2006        source.push_layer(square(100.));
2007        source.push_layer(inner_bounds);
2008        source.insert_primitive(Quad {
2009            bounds: inner_bounds,
2010            content_mask: ContentMask {
2011                bounds: inner_bounds,
2012            },
2013            ..Default::default()
2014        });
2015        source.pop_layer();
2016        source.pop_layer();
2017
2018        let mut replayed = Scene::default();
2019        assert!(replayed.replay_balanced(2..3, &source).is_ok());
2020
2021        assert_eq!(replayed.paint_operations.len(), 5);
2022        assert!(matches!(
2023            replayed.paint_operations.as_slice(),
2024            [
2025                PaintOperation::StartLayer(_),
2026                PaintOperation::StartLayer(_),
2027                PaintOperation::Primitive(_),
2028                PaintOperation::EndLayer,
2029                PaintOperation::EndLayer
2030            ]
2031        ));
2032    }
2033
2034    #[test]
2035    fn plain_present_keeps_overlay_above_later_base_content() -> Result<()> {
2036        let handle = WindowCompositionHandle::default();
2037        let state = handle.0.borrow();
2038        let mut scene = Scene::default();
2039        for side in [10., 20., 30.] {
2040            let bounds = square(side);
2041            scene.insert_primitive(Quad {
2042                bounds,
2043                content_mask: ContentMask { bounds },
2044                ..Default::default()
2045            });
2046        }
2047        scene.finish();
2048        let starts = [
2049            (state.base_surface, 0),
2050            (state.overlay_surface, 1),
2051            (state.base_surface, 2),
2052        ];
2053        let ordered = ordered_plain_scene(&state, &starts, &scene)?.unwrap();
2054        let sides: Vec<_> = ordered
2055            .quads
2056            .iter()
2057            .map(|quad| quad.bounds.size.width)
2058            .collect();
2059        assert_eq!(
2060            sides,
2061            [
2062                ScaledPixels::from(10.),
2063                ScaledPixels::from(30.),
2064                ScaledPixels::from(20.)
2065            ]
2066        );
2067        let in_order = [(state.base_surface, 0), (state.overlay_surface, 2)];
2068        assert!(ordered_plain_scene(&state, &in_order, &scene)?.is_none());
2069        Ok(())
2070    }
2071
2072    #[test]
2073    fn balanced_replay_rejects_invalid_ranges() {
2074        let source = Scene::default();
2075        let mut replayed = Scene::default();
2076        let start = 1;
2077        let end = 0;
2078
2079        assert!(replayed.replay_balanced(start..end, &source).is_err());
2080        assert!(replayed.replay_balanced(0..1, &source).is_err());
2081    }
2082
2083    struct Badge {
2084        overlay: CompositionSurfaceId,
2085        builds: Rc<Cell<usize>>,
2086    }
2087
2088    impl Render for Badge {
2089        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2090            self.builds.set(self.builds.get() + 1);
2091            let overlay = self.overlay;
2092            div()
2093                .size_full()
2094                .bg(crate::black())
2095                .child(
2096                    canvas(
2097                        |_, _, _| (),
2098                        move |bounds, _, window, _| {
2099                            window
2100                                .with_composition_surface(overlay, |window| {
2101                                    window.paint_quad(fill(bounds, crate::red()))
2102                                })
2103                                .unwrap();
2104                        },
2105                    )
2106                    .size(px(20.)),
2107                )
2108                .child(div().size(px(10.)).bg(crate::white()))
2109        }
2110    }
2111
2112    struct Panel {
2113        badge: Entity<Badge>,
2114    }
2115
2116    impl Render for Panel {
2117        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2118            div()
2119                .size(px(300.))
2120                .bg(crate::white())
2121                .child(
2122                    self.badge
2123                        .clone()
2124                        .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
2125                )
2126                .child(div().size(px(30.)).bg(crate::black()))
2127        }
2128    }
2129
2130    fn surface_of_each_operation(window: &Window) -> Vec<CompositionSurfaceId> {
2131        let state = window.fast_composition.0.borrow();
2132        let frame = &window.rendered_frame;
2133        let layers = composed_scene_layers(
2134            &state.tree,
2135            &frame.fast_composition_starts.0,
2136            frame.scene.len(),
2137        )
2138        .unwrap();
2139        let mut surfaces = vec![None; frame.scene.len()];
2140        for layer in layers {
2141            for range in layer.ranges {
2142                for surface in &mut surfaces[range] {
2143                    *surface = Some(layer.surface);
2144                }
2145            }
2146        }
2147        surfaces.into_iter().map(Option::unwrap).collect()
2148    }
2149
2150    /// A retained view that painted onto the overlay surface still does when
2151    /// it is drawn again from last frame: its surface switches come along
2152    /// with its scene, and painting returns to the base surface after it.
2153    #[crate::test]
2154    fn reused_views_keep_their_composition_surfaces(cx: &mut TestAppContext) {
2155        let builds = Rc::new(Cell::new(0));
2156        let window = cx.add_window({
2157            let builds = builds.clone();
2158            move |window, cx| {
2159                let overlay = window.fast_composition.0.borrow().overlay_surface;
2160                Panel {
2161                    badge: cx.new(|_| Badge { overlay, builds }),
2162                }
2163            }
2164        });
2165        let draw = |cx: &mut TestAppContext| {
2166            cx.update_window(window.into(), |_, window, cx| {
2167                window.draw(cx).clear(cx);
2168                let state = window.fast_composition.0.borrow();
2169                (
2170                    surface_of_each_operation(window),
2171                    state.base_surface,
2172                    state.overlay_surface,
2173                )
2174            })
2175            .unwrap()
2176        };
2177
2178        let (first, base, overlay) = draw(cx);
2179        assert_eq!(builds.get(), 1);
2180        assert_eq!(first.iter().filter(|s| **s == overlay).count(), 1);
2181        assert_eq!(first.last(), Some(&base));
2182
2183        window.update(cx, |_, _, cx| cx.notify()).unwrap();
2184        let (second, _, _) = draw(cx);
2185        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
2186        assert_eq!(second, first);
2187    }
2188
2189    fn test_platform_surface() -> Rc<TestPlatformSurface> {
2190        Rc::new(TestPlatformSurface {
2191            bounds_writes: Cell::new(0),
2192            fail_next_bounds: Cell::new(false),
2193            bounds: Cell::new(Bounds::default()),
2194            parent_origin: Cell::new(Point::default()),
2195        })
2196    }
2197
2198    /// Positions one native surface from the root view and another from a
2199    /// deferred draw, or both from the root view.
2200    struct Hosts {
2201        page: Rc<ManagedPlatformSurface>,
2202        dialog_page: Rc<ManagedPlatformSurface>,
2203        dialog_open: bool,
2204    }
2205
2206    fn native_host(surface: Rc<ManagedPlatformSurface>) -> impl IntoElement {
2207        canvas(
2208            move |bounds, window, _| {
2209                surface
2210                    .set_bounds(bounds.to_device_pixels(window.scale_factor()))
2211                    .unwrap()
2212            },
2213            |_, _, _, _| {},
2214        )
2215        .size(px(50.))
2216    }
2217
2218    impl Render for Hosts {
2219        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2220            let dialog_page = native_host(self.dialog_page.clone());
2221            let root = div().size_full().child(native_host(self.page.clone()));
2222            if self.dialog_open {
2223                root.child(deferred(
2224                    div().size(px(80.)).bg(crate::white()).child(dialog_page),
2225                ))
2226            } else {
2227                root.child(dialog_page)
2228            }
2229        }
2230    }
2231
2232    /// A native surface hosted in a deferred draw, a web page in a dialog,
2233    /// stacks above the overlay surface the dialog's background is drawn on,
2234    /// and returns below it once hosted by the root view again.
2235    #[crate::test]
2236    fn native_surfaces_stack_with_their_hosts(cx: &mut TestAppContext) {
2237        let names = Rc::new(std::cell::RefCell::new(Vec::new()));
2238        let window = cx.add_window({
2239            let names = names.clone();
2240            move |window, _| {
2241                let mut state = window.fast_composition.0.borrow_mut();
2242                let overlay = state.overlay_surface;
2243                let mut names = names.borrow_mut();
2244                names.push((state.base_surface, "base"));
2245                names.push((overlay, "overlay"));
2246                let mut native = |name| {
2247                    let id = state
2248                        .tree
2249                        .insert(CompositionSurfaceKind::Native, None)
2250                        .unwrap();
2251                    state.tree.place_below(id, overlay).unwrap();
2252                    let surface =
2253                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
2254                    state.platform_surfaces.insert(id, surface.clone());
2255                    names.push((id, name));
2256                    surface
2257                };
2258                Hosts {
2259                    page: native("page"),
2260                    dialog_page: native("dialog page"),
2261                    dialog_open: true,
2262                }
2263            }
2264        });
2265        let draw = |cx: &mut TestAppContext| {
2266            cx.update_window(window.into(), |_, window, cx| {
2267                window.draw(cx).clear(cx);
2268                let mut state = window.fast_composition.0.borrow_mut();
2269                restack_native_surfaces(&mut state).unwrap();
2270                let names = names.borrow();
2271                state
2272                    .tree
2273                    .flattened()
2274                    .into_iter()
2275                    .map(|id| names.iter().find(|(named, _)| *named == id).unwrap().1)
2276                    .collect::<Vec<_>>()
2277            })
2278            .unwrap()
2279        };
2280
2281        assert_eq!(draw(cx), ["base", "page", "overlay", "dialog page"]);
2282
2283        window
2284            .update(cx, |hosts, _, cx| {
2285                hosts.dialog_open = false;
2286                cx.notify();
2287            })
2288            .unwrap();
2289        assert_eq!(draw(cx), ["base", "page", "dialog page", "overlay"]);
2290    }
2291
2292    /// A composing window splits its scene only while it holds a surface
2293    /// beyond the base and overlay surfaces, and a retained view keeps
2294    /// painting onto the overlay surface across every switch between the
2295    /// plain and the split frame.
2296    #[crate::test]
2297    fn retained_views_keep_their_split_as_surfaces_come_and_go(cx: &mut TestAppContext) {
2298        let builds = Rc::new(Cell::new(0));
2299        let window = cx.add_window({
2300            let builds = builds.clone();
2301            move |window, cx| {
2302                let mut state = window.fast_composition.0.borrow_mut();
2303                state.enabled = true;
2304                let overlay = state.overlay_surface;
2305                drop(state);
2306                Panel {
2307                    badge: cx.new(|_| Badge { overlay, builds }),
2308                }
2309            }
2310        });
2311        let draw = |cx: &mut TestAppContext| {
2312            cx.update_window(window.into(), |_, window, cx| {
2313                window.draw(cx).clear(cx);
2314                let splits = window.fast_composition.0.borrow().splits();
2315                (surface_of_each_operation(window), splits)
2316            })
2317            .unwrap()
2318        };
2319        let redraw = |cx: &mut TestAppContext| {
2320            window.update(cx, |_, _, cx| cx.notify()).unwrap();
2321            draw(cx)
2322        };
2323        // What the platform is handed: the base surface alone while the scene
2324        // is not split.
2325        let handed = |cx: &mut TestAppContext| {
2326            cx.update_window(window.into(), |_, window, _| {
2327                let composition = WindowComposition {
2328                    platform_window: window.platform_window.as_ref(),
2329                    state: window.fast_composition.0.clone(),
2330                };
2331                let ids = composition
2332                    .platform_order()
2333                    .unwrap()
2334                    .into_iter()
2335                    .map(|surface| surface.id)
2336                    .collect::<Vec<_>>();
2337                let state = window.fast_composition.0.borrow();
2338                (ids, state.base_surface, state.overlay_surface)
2339            })
2340            .unwrap()
2341        };
2342
2343        let (first, splits) = draw(cx);
2344        assert!(!splits);
2345        let (ids, base, _) = handed(cx);
2346        assert_eq!(ids, [base]);
2347        for _ in 0..3 {
2348            let added = cx
2349                .update_window(window.into(), |_, window, _| {
2350                    let mut state = window.fast_composition.0.borrow_mut();
2351                    let overlay = state.overlay_surface;
2352                    let id = state
2353                        .tree
2354                        .insert(CompositionSurfaceKind::Native, None)
2355                        .unwrap();
2356                    state.tree.place_below(id, overlay).unwrap();
2357                    let surface =
2358                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
2359                    state.platform_surfaces.insert(id, surface);
2360                    id
2361                })
2362                .unwrap();
2363            assert_eq!(redraw(cx), (first.clone(), true));
2364            let (ids, base, overlay) = handed(cx);
2365            assert_eq!(ids, [base, added, overlay]);
2366
2367            cx.update_window(window.into(), |_, window, _| {
2368                let mut state = window.fast_composition.0.borrow_mut();
2369                state.tree.remove(added).unwrap();
2370                state.platform_surfaces.remove(&added);
2371            })
2372            .unwrap();
2373            assert_eq!(redraw(cx), (first.clone(), false));
2374            let (ids, base, _) = handed(cx);
2375            assert_eq!(ids, [base]);
2376        }
2377        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
2378    }
2379}