Skip to main content

gpui/fast/
composition.rs

1// Modified by Longbridge for gpui-fast.
2//! Window composition: native views between GPUI's content and its overlays.
3//!
4//! Ported from zed-industries/zed#62379. A window paints one scene, as
5//! always, but can present it on several ordered surfaces, so that a
6//! platform-native view (a `WKWebView`, a WebView2, a Wayland subsurface fed
7//! by another GPU producer) sits above GPUI's base content and below its
8//! overlays — popovers, dialogs, menus, tooltips:
9//!
10//! ```text
11//! front  GPUI overlay   deferred and window-level draws
12//!        native surface  WKWebView / WebView2 / wl_subsurface / X11 child
13//! back   GPUI base       the root view
14//! ```
15//!
16//! [`CompositionTree`] holds each surface's identity, parent and sibling
17//! order. The frame records, as it paints, which GPUI surface each stretch
18//! of the scene targets ([`SurfaceStarts`]); presenting splits the scene
19//! along those stretches into a [`ComposedScene`], and the platform draws
20//! each surface's part onto its own layer, visual or subsurface.
21//!
22//! Composition is opt-in: until [`Window::enable_window_composition`] is
23//! called, a window presents its scene with `PlatformWindow::draw`, as
24//! upstream does.
25//!
26//! Unlike the upstream pull request, a view drawn again from last frame
27//! (every retained view, here) carries the surface switches it made with it:
28//! [`reuse_starts`] copies them along with its scene.
29//!
30//! Also unlike it, a native surface stacks with the element hosting it. One
31//! positioned while a deferred draw is prepainted, a web page in a dialog or
32//! sheet, is hosted on the overlay surface, so it moves above that surface
33//! instead of under the dialog's own background; positioned while the root
34//! view is prepainted, it moves back below it. Overlays drawn over a native
35//! surface hosted on the overlay surface are then covered by it.
36
37use crate::window::PaintIndex;
38use crate::{Bounds, DevicePixels, PlatformWindow, Point, Scene, Window, scene::PaintOperation};
39use anyhow::{Context as _, Result, anyhow, bail};
40use collections::FxHashMap;
41use gpui_util::ResultExt as _;
42use slotmap::SlotMap;
43use std::{
44    any::Any,
45    cell::{Cell, RefCell},
46    ops::Range,
47    rc::Rc,
48};
49
50slotmap::new_key_type! {
51    /// Stable identity for a surface in a window composition tree.
52    pub struct CompositionSurfaceId;
53}
54
55/// The renderer or platform facility responsible for a composition surface.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum CompositionSurfaceKind {
58    /// A surface rendered from a range of GPUI scene operations.
59    Gpui,
60    /// A surface whose content is supplied by a platform-native view or visual.
61    Native,
62    /// A surface whose content is supplied by an external GPU producer.
63    ExternalGpu,
64}
65
66#[derive(Clone)]
67struct CompositionSurfaceNode {
68    kind: CompositionSurfaceKind,
69    parent: Option<CompositionSurfaceId>,
70    children: Vec<CompositionSurfaceId>,
71}
72
73/// The surfaces of a window, as a forest ordered bottom to top.
74#[derive(Clone)]
75pub(crate) struct CompositionTree {
76    surfaces: SlotMap<CompositionSurfaceId, CompositionSurfaceNode>,
77    roots: Vec<CompositionSurfaceId>,
78}
79
80impl CompositionTree {
81    pub(crate) fn new() -> Self {
82        Self {
83            surfaces: SlotMap::with_key(),
84            roots: Vec::new(),
85        }
86    }
87
88    /// Adds a surface above its future siblings.
89    pub(crate) fn insert(
90        &mut self,
91        kind: CompositionSurfaceKind,
92        parent: Option<CompositionSurfaceId>,
93    ) -> Result<CompositionSurfaceId> {
94        if let Some(parent) = parent {
95            self.surface(parent)?;
96        }
97
98        let surface = self.surfaces.insert(CompositionSurfaceNode {
99            kind,
100            parent,
101            children: Vec::new(),
102        });
103        self.siblings_mut(parent)?.push(surface);
104        Ok(surface)
105    }
106
107    /// Removes a surface, putting its children where it was.
108    pub(crate) fn remove(&mut self, surface: CompositionSurfaceId) -> Result<()> {
109        let parent = self.surface(surface)?.parent;
110        let children = self.surface(surface)?.children.clone();
111        let siblings = self.siblings_mut(parent)?;
112        let index = siblings
113            .iter()
114            .position(|candidate| *candidate == surface)
115            .ok_or_else(|| anyhow!("composition surface is missing from its parent"))?;
116        siblings.splice(index..=index, children.iter().copied());
117        for child in children {
118            self.surface_mut(child)?.parent = parent;
119        }
120        self.surfaces.remove(surface);
121        Ok(())
122    }
123
124    pub(crate) fn place_above(
125        &mut self,
126        surface: CompositionSurfaceId,
127        sibling: CompositionSurfaceId,
128    ) -> Result<()> {
129        self.place_relative(surface, sibling, true)
130    }
131
132    pub(crate) fn place_below(
133        &mut self,
134        surface: CompositionSurfaceId,
135        sibling: CompositionSurfaceId,
136    ) -> Result<()> {
137        self.place_relative(surface, sibling, false)
138    }
139
140    /// Moves a surface under `parent`, above the children it has.
141    pub(crate) fn reparent(
142        &mut self,
143        surface: CompositionSurfaceId,
144        parent: Option<CompositionSurfaceId>,
145    ) -> Result<()> {
146        self.surface(surface)?;
147        if let Some(parent) = parent {
148            self.surface(parent)?;
149            if parent == surface || self.is_descendant(parent, surface)? {
150                bail!("composition surfaces cannot contain themselves");
151            }
152        }
153
154        let previous_parent = self.surface(surface)?.parent;
155        self.siblings_mut(previous_parent)?
156            .retain(|candidate| *candidate != surface);
157        self.surface_mut(surface)?.parent = parent;
158        self.siblings_mut(parent)?.push(surface);
159        Ok(())
160    }
161
162    pub(crate) fn kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
163        Ok(self.surface(surface)?.kind)
164    }
165
166    pub(crate) fn parent(
167        &self,
168        surface: CompositionSurfaceId,
169    ) -> Result<Option<CompositionSurfaceId>> {
170        Ok(self.surface(surface)?.parent)
171    }
172
173    /// The children of `parent`, or the roots when it is `None`, bottom to top.
174    pub(crate) fn children(
175        &self,
176        parent: Option<CompositionSurfaceId>,
177    ) -> Result<&[CompositionSurfaceId]> {
178        match parent {
179            Some(parent) => Ok(&self.surface(parent)?.children),
180            None => Ok(&self.roots),
181        }
182    }
183
184    /// Every surface, parents before their children, bottom to top.
185    pub(crate) fn flattened(&self) -> Vec<CompositionSurfaceId> {
186        let mut surfaces = Vec::with_capacity(self.surfaces.len());
187        for root in &self.roots {
188            self.flatten_into(*root, &mut surfaces);
189        }
190        surfaces
191    }
192
193    fn place_relative(
194        &mut self,
195        surface: CompositionSurfaceId,
196        sibling: CompositionSurfaceId,
197        above: bool,
198    ) -> Result<()> {
199        if surface == sibling {
200            bail!("a composition surface cannot be ordered relative to itself");
201        }
202        let parent = self.surface(surface)?.parent;
203        if self.surface(sibling)?.parent != parent {
204            bail!("composition surfaces must share a parent to be reordered");
205        }
206
207        let siblings = self.siblings_mut(parent)?;
208        siblings.retain(|candidate| *candidate != surface);
209        let sibling_index = siblings
210            .iter()
211            .position(|candidate| *candidate == sibling)
212            .ok_or_else(|| anyhow!("composition sibling is missing from its parent"))?;
213        let index = sibling_index + usize::from(above);
214        siblings.insert(index, surface);
215        Ok(())
216    }
217
218    fn is_descendant(
219        &self,
220        candidate: CompositionSurfaceId,
221        ancestor: CompositionSurfaceId,
222    ) -> Result<bool> {
223        let mut parent = Some(candidate);
224        while let Some(surface) = parent {
225            if surface == ancestor {
226                return Ok(true);
227            }
228            parent = self.surface(surface)?.parent;
229        }
230        Ok(false)
231    }
232
233    fn surface(&self, surface: CompositionSurfaceId) -> Result<&CompositionSurfaceNode> {
234        self.surfaces
235            .get(surface)
236            .ok_or_else(|| anyhow!("composition surface does not exist"))
237    }
238
239    fn surface_mut(
240        &mut self,
241        surface: CompositionSurfaceId,
242    ) -> Result<&mut CompositionSurfaceNode> {
243        self.surfaces
244            .get_mut(surface)
245            .ok_or_else(|| anyhow!("composition surface does not exist"))
246    }
247
248    fn siblings_mut(
249        &mut self,
250        parent: Option<CompositionSurfaceId>,
251    ) -> Result<&mut Vec<CompositionSurfaceId>> {
252        match parent {
253            Some(parent) => Ok(&mut self.surface_mut(parent)?.children),
254            None => Ok(&mut self.roots),
255        }
256    }
257
258    fn flatten_into(
259        &self,
260        surface: CompositionSurfaceId,
261        flattened: &mut Vec<CompositionSurfaceId>,
262    ) {
263        flattened.push(surface);
264        if let Some(surface) = self.surfaces.get(surface) {
265            for child in &surface.children {
266                self.flatten_into(*child, flattened);
267            }
268        }
269    }
270}
271
272/// Splits a scene of `scene_len` operations along `starts`, the points where
273/// painting switched GPUI surface, into one layer per GPUI surface of `tree`,
274/// in composition order.
275pub(crate) fn composed_scene_layers(
276    tree: &CompositionTree,
277    starts: &[(CompositionSurfaceId, usize)],
278    scene_len: usize,
279) -> Result<Vec<ComposedSceneLayer>> {
280    let mut ranges_by_surface = FxHashMap::<_, Vec<Range<usize>>>::default();
281    for (index, (surface, start)) in starts.iter().enumerate() {
282        if tree.kind(*surface)? != CompositionSurfaceKind::Gpui {
283            bail!("scene operations target a non-GPUI composition surface");
284        }
285        let end = starts
286            .get(index + 1)
287            .map_or(scene_len, |(_, next_start)| *next_start);
288        if *start > end || end > scene_len {
289            bail!("composition scene ranges are not monotonic");
290        }
291        if *start < end {
292            ranges_by_surface
293                .entry(*surface)
294                .or_default()
295                .push(*start..end);
296        }
297    }
298
299    let mut layers = Vec::new();
300    for surface in tree.flattened() {
301        if tree.kind(surface)? == CompositionSurfaceKind::Gpui {
302            layers.push(ComposedSceneLayer {
303                surface,
304                ranges: ranges_by_surface.remove(&surface).unwrap_or_default(),
305            });
306        }
307    }
308    Ok(layers)
309}
310
311/// A platform attachment participating in a window composition tree.
312pub trait PlatformSurfaceAttachment {
313    /// Updates the native surface geometry in window-content device pixels.
314    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()>;
315    /// Returns the native surface geometry in window-content device pixels.
316    fn bounds(&self) -> Bounds<DevicePixels>;
317    /// Updates the window-content origin of the surface's composition parent.
318    /// Platform adapters use this to preserve window-coordinate geometry when
319    /// a surface is nested.
320    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()>;
321    /// Rebinds externally owned content after the platform compositor has been
322    /// recreated. Native surfaces managed by GPUI may use the default no-op.
323    fn compositor_recreated(&self, _platform_context: &dyn Any) -> Result<()> {
324        Ok(())
325    }
326    /// Registers a callback that reattaches native content when the platform
327    /// attachment object changes after compositor recovery.
328    fn set_compositor_recreated_callback(
329        &self,
330        _callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
331    ) -> Result<()> {
332        bail!("compositor recreation callbacks are not supported")
333    }
334    /// Updates whether the native surface participates in composition.
335    fn set_visible(&self, visible: bool) -> Result<()>;
336    /// Returns the platform attachment object: an `NSView` pointer as `usize`
337    /// on macOS, an `IDCompositionVisual` as `windows::core::IUnknown` on
338    /// Windows, a `raw_window_handle::RawWindowHandle` on Linux.
339    fn platform_handle(&self) -> Result<Box<dyn Any>>;
340}
341
342/// The ranges of a GPUI scene rendered onto one composition surface.
343#[derive(Clone, Debug)]
344pub struct ComposedSceneLayer {
345    /// The GPUI composition surface receiving these scene ranges.
346    pub surface: CompositionSurfaceId,
347    /// Paint-operation ranges belonging to the surface.
348    pub ranges: Vec<Range<usize>>,
349}
350
351/// A scene split across GPUI surfaces in composition order.
352pub struct ComposedScene<'a> {
353    scene: &'a Scene,
354    layers: Vec<ComposedSceneLayer>,
355}
356
357impl<'a> ComposedScene<'a> {
358    pub(crate) fn new(scene: &'a Scene, layers: Vec<ComposedSceneLayer>) -> Self {
359        Self { scene, layers }
360    }
361
362    /// Returns the complete scene containing all GPUI planes.
363    pub fn scene(&self) -> &'a Scene {
364        self.scene
365    }
366
367    /// Returns the GPUI surface layers in composition order.
368    pub fn layers(&self) -> &[ComposedSceneLayer] {
369        &self.layers
370    }
371
372    /// Returns the part of the scene `layer` covers as a finished scene of
373    /// its own, ready to draw onto the layer's surface.
374    pub fn layer_scene(&self, layer: &ComposedSceneLayer) -> Result<Scene> {
375        let mut scene = Scene::default();
376        for range in &layer.ranges {
377            scene.replay_balanced(range.clone(), self.scene)?;
378        }
379        scene.finish();
380        Ok(scene)
381    }
382}
383
384/// A platform surface participating in window composition.
385#[derive(Clone)]
386pub struct PlatformCompositionSurface {
387    /// Stable identity in the window composition tree.
388    pub id: CompositionSurfaceId,
389    /// Parent surface, or `None` for a root surface.
390    pub parent: Option<CompositionSurfaceId>,
391    /// This surface's origin in window-content device pixels. GPUI surfaces
392    /// use the window origin because their backing scenes remain window-based.
393    pub window_origin: Point<DevicePixels>,
394    /// The parent surface's origin in window-content device pixels.
395    pub parent_origin: Point<DevicePixels>,
396    /// Native or external surface bounds in window-content device pixels.
397    /// GPUI surfaces use the full window and therefore have no explicit bounds.
398    pub window_bounds: Option<Bounds<DevicePixels>>,
399    /// Renderer or attachment supplying this surface's content.
400    pub content: PlatformCompositionSurfaceContent,
401}
402
403/// Content attached to a platform composition surface.
404#[derive(Clone)]
405pub enum PlatformCompositionSurfaceContent {
406    /// A surface rendered by GPUI.
407    Gpui,
408    /// A surface backed by a platform-native view or visual.
409    Native(Rc<dyn PlatformSurfaceAttachment>),
410    /// A surface backed by an external GPU producer.
411    ExternalGpu(Rc<dyn PlatformSurfaceAttachment>),
412}
413
414/// What `PlatformWindow::draw_composed` does on a platform without
415/// composition: draws the whole scene on the window's one surface.
416pub(crate) fn draw_uncomposed<W: PlatformWindow + ?Sized>(window: &W, scene: ComposedScene<'_>) {
417    window.draw(scene.scene());
418}
419
420/// What the `PlatformWindow` composition methods return on a platform
421/// without composition.
422pub(crate) fn unsupported<T>(what: &str) -> Result<T> {
423    bail!("{what} is not supported on this platform")
424}
425
426impl crate::Background {
427    /// Returns whether the background covers its bounds with no translucency,
428    /// so a platform compositing native content below it can cut that
429    /// content out instead of blending it.
430    pub fn is_opaque(&self) -> bool {
431        match self.tag {
432            crate::color::BackgroundTag::Solid => self.solid.is_opaque(),
433            crate::color::BackgroundTag::LinearGradient => {
434                self.colors.iter().all(|stop| stop.color.is_opaque())
435            }
436            crate::color::BackgroundTag::PatternSlash
437            | crate::color::BackgroundTag::Checkerboard => false,
438        }
439    }
440}
441
442impl Scene {
443    /// Returns whether the scene contains no drawable primitives.
444    ///
445    /// A scene may have paint operations that only open and close empty layers,
446    /// so `len() == 0` is not equivalent to having no visible/input-relevant
447    /// overlay content.
448    pub fn is_empty(&self) -> bool {
449        self.shadows.is_empty()
450            && self.quads.is_empty()
451            && self.paths.is_empty()
452            && self.underlines.is_empty()
453            && self.monochrome_sprites.is_empty()
454            && self.subpixel_sprites.is_empty()
455            && self.polychrome_sprites.is_empty()
456            && self.surfaces.is_empty()
457    }
458
459    /// Replays a range as a self-contained scene, restoring any layers that
460    /// were active at the start of the range and closing those still active at
461    /// its end. The scroll layers whose tiles the range composites come along.
462    pub fn replay_balanced(&mut self, range: Range<usize>, previous_scene: &Scene) -> Result<()> {
463        anyhow::ensure!(
464            range.start <= range.end,
465            "scene replay range starts after its end"
466        );
467        let prefix = previous_scene
468            .paint_operations
469            .get(..range.start)
470            .context("scene replay range starts past the scene")?;
471        let operations = previous_scene
472            .paint_operations
473            .get(range.clone())
474            .context("scene replay range ends past the scene")?;
475        let mut active_layers = Vec::new();
476        for operation in prefix {
477            match operation {
478                PaintOperation::StartLayer(bounds) => active_layers.push(*bounds),
479                PaintOperation::EndLayer => {
480                    anyhow::ensure!(
481                        active_layers.pop().is_some(),
482                        "source scene closes a layer that is not open"
483                    );
484                }
485                PaintOperation::Primitive(_) => {}
486            }
487        }
488
489        crate::fast::layers::paint::replay_layers(self, range, previous_scene);
490        for bounds in &active_layers {
491            self.push_layer(*bounds);
492        }
493        for operation in operations {
494            match operation {
495                PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()),
496                PaintOperation::StartLayer(bounds) => {
497                    active_layers.push(*bounds);
498                    self.push_layer(*bounds);
499                }
500                PaintOperation::EndLayer => {
501                    anyhow::ensure!(
502                        active_layers.pop().is_some(),
503                        "scene replay range closes a layer that is not open"
504                    );
505                    self.pop_layer();
506                }
507            }
508        }
509        for _ in active_layers {
510            self.pop_layer();
511        }
512        Ok(())
513    }
514}
515
516/// Where each stretch of a frame's scene is presented: the GPUI surface
517/// painting switched to, and the scene length at the switch.
518#[derive(Default)]
519pub(crate) struct SurfaceStarts(Vec<(CompositionSurfaceId, usize)>);
520
521impl SurfaceStarts {
522    pub(crate) fn clear(&mut self) {
523        self.0.clear();
524    }
525
526    fn current(&self) -> Option<CompositionSurfaceId> {
527        self.0.last().map(|(surface, _)| *surface)
528    }
529
530    fn switch_to(&mut self, surface: CompositionSurfaceId, scene_len: usize) {
531        if self.current() == Some(surface) {
532            return;
533        }
534        self.0.push((surface, scene_len));
535    }
536}
537
538/// The GPUI surface an element hosting a native surface is drawn on.
539#[derive(Clone, Copy, Debug, PartialEq, Eq)]
540enum Host {
541    /// The root view, drawn on the base surface.
542    Base,
543    /// A deferred or window-level draw, drawn on the overlay surface.
544    Overlay,
545}
546
547/// A window's composition: its surface tree, the platform surfaces in it and
548/// whether the window presents through it.
549pub(crate) struct WindowCompositionState {
550    tree: CompositionTree,
551    platform_surfaces: FxHashMap<CompositionSurfaceId, Rc<ManagedPlatformSurface>>,
552    base_surface: CompositionSurfaceId,
553    overlay_surface: CompositionSurfaceId,
554    geometry_dirty: Rc<Cell<bool>>,
555    /// What the window is prepainting, while it prepaints a frame.
556    prepainting: Rc<Cell<Option<Host>>>,
557    enabled: bool,
558}
559
560/// The [`Window`] field holding its composition.
561pub(crate) struct WindowCompositionHandle(Rc<RefCell<WindowCompositionState>>);
562
563impl Default for WindowCompositionHandle {
564    fn default() -> Self {
565        let mut tree = CompositionTree::new();
566        let base_surface = tree
567            .insert(CompositionSurfaceKind::Gpui, None)
568            .expect("a root can always be inserted");
569        let overlay_surface = tree
570            .insert(CompositionSurfaceKind::Gpui, None)
571            .expect("a root can always be inserted");
572        Self(Rc::new(RefCell::new(WindowCompositionState {
573            tree,
574            platform_surfaces: FxHashMap::default(),
575            base_surface,
576            overlay_surface,
577            geometry_dirty: Rc::new(Cell::new(false)),
578            prepainting: Rc::new(Cell::new(None)),
579            enabled: false,
580        })))
581    }
582}
583
584/// A platform surface whose bounds changes mark the window's composition
585/// geometry for synchronization at the next present.
586struct ManagedPlatformSurface {
587    platform_surface: Rc<dyn PlatformSurfaceAttachment>,
588    bounds: Cell<Bounds<DevicePixels>>,
589    geometry_dirty: Rc<Cell<bool>>,
590    prepainting: Rc<Cell<Option<Host>>>,
591    /// The surface its host was last prepainted on.
592    host: Cell<Host>,
593    /// Whether `host` changed since the surface was last restacked.
594    restack: Cell<bool>,
595}
596
597impl ManagedPlatformSurface {
598    fn new(
599        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
600        state: &WindowCompositionState,
601    ) -> Self {
602        Self {
603            bounds: Cell::new(platform_surface.bounds()),
604            platform_surface,
605            geometry_dirty: state.geometry_dirty.clone(),
606            prepainting: state.prepainting.clone(),
607            host: Cell::new(Host::Base),
608            restack: Cell::new(false),
609        }
610    }
611}
612
613impl PlatformSurfaceAttachment for ManagedPlatformSurface {
614    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
615        if let Some(host) = self.prepainting.get()
616            && self.host.replace(host) != host
617        {
618            self.restack.set(true);
619            self.geometry_dirty.set(true);
620        }
621        if self.bounds.get() == bounds {
622            return Ok(());
623        }
624        self.platform_surface.set_bounds(bounds)?;
625        self.bounds.set(bounds);
626        self.geometry_dirty.set(true);
627        Ok(())
628    }
629
630    fn bounds(&self) -> Bounds<DevicePixels> {
631        self.bounds.get()
632    }
633
634    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
635        self.platform_surface.set_parent_origin(origin)
636    }
637
638    fn compositor_recreated(&self, platform_context: &dyn Any) -> Result<()> {
639        self.platform_surface.compositor_recreated(platform_context)
640    }
641
642    fn set_compositor_recreated_callback(
643        &self,
644        callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
645    ) -> Result<()> {
646        self.platform_surface
647            .set_compositor_recreated_callback(callback)
648    }
649
650    fn set_visible(&self, visible: bool) -> Result<()> {
651        self.platform_surface.set_visible(visible)
652    }
653
654    fn platform_handle(&self) -> Result<Box<dyn Any>> {
655        self.platform_surface.platform_handle()
656    }
657}
658
659struct WindowCompositionSurfaceInner {
660    id: CompositionSurfaceId,
661    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
662}
663
664/// A stable handle to a surface in a window composition tree.
665#[derive(Clone)]
666pub struct WindowCompositionSurface(Rc<WindowCompositionSurfaceInner>);
667
668impl WindowCompositionSurface {
669    /// Returns this surface's stable identity.
670    pub fn id(&self) -> CompositionSurfaceId {
671        self.0.id
672    }
673
674    /// Returns the platform surface used to attach native content.
675    pub fn platform_surface(&self) -> Result<&dyn PlatformSurfaceAttachment> {
676        self.0
677            .platform_surface
678            .as_deref()
679            .context("this composition surface is rendered by GPUI")
680    }
681}
682
683/// Controls the surface tree composited into a window.
684pub struct WindowComposition<'a> {
685    platform_window: &'a dyn PlatformWindow,
686    state: Rc<RefCell<WindowCompositionState>>,
687}
688
689impl WindowComposition<'_> {
690    /// Returns the GPUI surface initially rendered below native content.
691    pub fn base_surface(&self) -> CompositionSurfaceId {
692        self.state.borrow().base_surface
693    }
694
695    /// Returns the GPUI surface initially rendered above native content.
696    pub fn overlay_surface(&self) -> CompositionSurfaceId {
697        self.state.borrow().overlay_surface
698    }
699
700    /// Creates a platform-native surface as a root of the composition tree,
701    /// below the overlay surface.
702    pub fn create_native_surface(&self) -> Result<WindowCompositionSurface> {
703        let platform_surface = self.platform_window.create_native_surface()?;
704        self.register_platform_surface(CompositionSurfaceKind::Native, platform_surface)
705    }
706
707    /// Registers an externally produced GPU surface as a root of the
708    /// composition tree, below the overlay surface.
709    ///
710    /// The producer owns the platform attachment and its synchronization. GPUI
711    /// owns its placement in the window composition tree.
712    pub fn create_external_gpu_surface(
713        &self,
714        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
715    ) -> Result<WindowCompositionSurface> {
716        self.register_platform_surface(CompositionSurfaceKind::ExternalGpu, platform_surface)
717    }
718
719    /// Creates another GPUI-rendered surface in the composition tree. Paint
720    /// onto it with [`Window::with_composition_surface`].
721    pub fn create_gpui_surface(
722        &self,
723        parent: Option<CompositionSurfaceId>,
724    ) -> Result<WindowCompositionSurface> {
725        let id = self
726            .state
727            .borrow_mut()
728            .tree
729            .insert(CompositionSurfaceKind::Gpui, parent)?;
730        if let Err(error) = self.synchronize_platform_order() {
731            self.state.borrow_mut().tree.remove(id)?;
732            self.synchronize_platform_order().log_err();
733            return Err(error);
734        }
735        Ok(surface_handle(id, None))
736    }
737
738    /// Places `surface` immediately above `sibling`.
739    pub fn place_above(
740        &self,
741        surface: CompositionSurfaceId,
742        sibling: CompositionSurfaceId,
743    ) -> Result<()> {
744        anyhow::ensure!(
745            surface != self.state.borrow().base_surface,
746            "the GPUI base surface cannot be reordered"
747        );
748        self.change_tree(|tree| tree.place_above(surface, sibling))
749    }
750
751    /// Places `surface` immediately below `sibling`.
752    pub fn place_below(
753        &self,
754        surface: CompositionSurfaceId,
755        sibling: CompositionSurfaceId,
756    ) -> Result<()> {
757        let base_surface = self.state.borrow().base_surface;
758        anyhow::ensure!(
759            surface != base_surface && sibling != base_surface,
760            "surfaces cannot be placed below or move the GPUI base surface"
761        );
762        self.change_tree(|tree| tree.place_below(surface, sibling))
763    }
764
765    /// Moves `surface` under a new parent, placing it above existing children.
766    pub fn reparent(
767        &self,
768        surface: CompositionSurfaceId,
769        parent: Option<CompositionSurfaceId>,
770    ) -> Result<()> {
771        anyhow::ensure!(
772            surface != self.state.borrow().base_surface,
773            "the GPUI base surface cannot be reparented"
774        );
775        self.change_tree(|tree| tree.reparent(surface, parent))
776    }
777
778    /// Removes a surface while preserving its children at the removed
779    /// surface's previous position.
780    pub fn remove_surface(&self, surface: CompositionSurfaceId) -> Result<()> {
781        let mut state = self.state.borrow_mut();
782        if surface == state.base_surface || surface == state.overlay_surface {
783            bail!("the default GPUI composition surfaces cannot be removed");
784        }
785        let previous_tree = state.tree.clone();
786        let platform_surface = state.platform_surfaces.get(&surface).cloned();
787        if let Some(platform_surface) = &platform_surface {
788            platform_surface.set_visible(false)?;
789        }
790        state.tree.remove(surface)?;
791        state.platform_surfaces.remove(&surface);
792        drop(state);
793        if let Err(error) = self.synchronize_platform_order() {
794            let mut state = self.state.borrow_mut();
795            state.tree = previous_tree;
796            if let Some(platform_surface) = platform_surface {
797                platform_surface.set_visible(true).log_err();
798                state.platform_surfaces.insert(surface, platform_surface);
799            }
800            drop(state);
801            self.synchronize_platform_order().log_err();
802            return Err(error);
803        }
804        Ok(())
805    }
806
807    /// Returns the renderer kind for a surface.
808    pub fn surface_kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
809        self.state.borrow().tree.kind(surface)
810    }
811
812    /// Returns a surface's parent.
813    pub fn parent(&self, surface: CompositionSurfaceId) -> Result<Option<CompositionSurfaceId>> {
814        self.state.borrow().tree.parent(surface)
815    }
816
817    /// Returns the ordered children of a surface, or the root surfaces when
818    /// `parent` is `None`.
819    pub fn children(
820        &self,
821        parent: Option<CompositionSurfaceId>,
822    ) -> Result<Vec<CompositionSurfaceId>> {
823        Ok(self.state.borrow().tree.children(parent)?.to_vec())
824    }
825
826    /// Applies `change` to the tree and the platform, or neither.
827    fn change_tree(&self, change: impl FnOnce(&mut CompositionTree) -> Result<()>) -> Result<()> {
828        let previous_tree = self.state.borrow().tree.clone();
829        change(&mut self.state.borrow_mut().tree)?;
830        if let Err(error) = self.synchronize_platform_order() {
831            self.state.borrow_mut().tree = previous_tree;
832            self.synchronize_platform_order().log_err();
833            return Err(error);
834        }
835        Ok(())
836    }
837
838    fn register_platform_surface(
839        &self,
840        kind: CompositionSurfaceKind,
841        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
842    ) -> Result<WindowCompositionSurface> {
843        let platform_surface = Rc::new(ManagedPlatformSurface::new(
844            platform_surface,
845            &self.state.borrow(),
846        ));
847        let mut state = self.state.borrow_mut();
848        let id = state.tree.insert(kind, None)?;
849        let overlay_surface = state.overlay_surface;
850        state.tree.place_below(id, overlay_surface)?;
851        state.platform_surfaces.insert(id, platform_surface.clone());
852        drop(state);
853        if let Err(error) = self.synchronize_platform_order() {
854            platform_surface.set_visible(false).log_err();
855            let mut state = self.state.borrow_mut();
856            state.platform_surfaces.remove(&id);
857            state.tree.remove(id)?;
858            drop(state);
859            self.synchronize_platform_order().log_err();
860            return Err(error);
861        }
862        Ok(surface_handle(id, Some(platform_surface)))
863    }
864
865    /// Hands the platform the tree's order and every surface's geometry.
866    fn synchronize_platform_order(&self) -> Result<()> {
867        let state = self.state.borrow();
868        let mut origins = FxHashMap::default();
869        let mut surfaces = Vec::new();
870        for id in state.tree.flattened() {
871            let parent = state.tree.parent(id)?;
872            let parent_origin = parent
873                .and_then(|parent| origins.get(&parent).copied())
874                .unwrap_or_default();
875            let content = match state.tree.kind(id)? {
876                CompositionSurfaceKind::Gpui => PlatformCompositionSurfaceContent::Gpui,
877                CompositionSurfaceKind::Native => PlatformCompositionSurfaceContent::Native(
878                    state
879                        .platform_surfaces
880                        .get(&id)
881                        .context("native composition surface is missing")?
882                        .clone(),
883                ),
884                CompositionSurfaceKind::ExternalGpu => {
885                    PlatformCompositionSurfaceContent::ExternalGpu(
886                        state
887                            .platform_surfaces
888                            .get(&id)
889                            .context("external GPU composition surface is missing")?
890                            .clone(),
891                    )
892                }
893            };
894            let window_bounds = match &content {
895                PlatformCompositionSurfaceContent::Gpui => None,
896                PlatformCompositionSurfaceContent::Native(platform_surface)
897                | PlatformCompositionSurfaceContent::ExternalGpu(platform_surface) => {
898                    Some(platform_surface.bounds())
899                }
900            };
901            let window_origin = window_bounds.map_or_else(Point::default, |bounds| bounds.origin);
902            origins.insert(id, window_origin);
903            surfaces.push(PlatformCompositionSurface {
904                id,
905                parent,
906                window_origin,
907                parent_origin,
908                window_bounds,
909                content,
910            });
911        }
912        self.platform_window.set_composition_order(&surfaces)?;
913        state.geometry_dirty.set(false);
914        Ok(())
915    }
916}
917
918fn surface_handle(
919    id: CompositionSurfaceId,
920    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
921) -> WindowCompositionSurface {
922    WindowCompositionSurface(Rc::new(WindowCompositionSurfaceInner {
923        id,
924        platform_surface,
925    }))
926}
927
928impl Window {
929    /// Enables native window composition and returns its controller.
930    ///
931    /// GPUI's root scene is rendered below surfaces created by the controller,
932    /// while deferred and window-level overlays are rendered above them.
933    pub fn enable_window_composition(&self) -> Result<WindowComposition<'_>> {
934        self.platform_window.enable_window_composition()?;
935        let composition = WindowComposition {
936            platform_window: self.platform_window.as_ref(),
937            state: self.fast_composition.0.clone(),
938        };
939        composition.synchronize_platform_order()?;
940        composition.state.borrow_mut().enabled = true;
941        Ok(composition)
942    }
943
944    /// Paints a scope of scene operations onto a GPUI surface in this window's
945    /// composition tree, then restores the previous surface.
946    ///
947    /// Inside a scroll layer, whose content is composited from tiles, the
948    /// scope paints where the layer does.
949    pub fn with_composition_surface<R>(
950        &mut self,
951        surface: CompositionSurfaceId,
952        paint: impl FnOnce(&mut Self) -> R,
953    ) -> Result<R> {
954        self.invalidator.debug_assert_paint();
955        anyhow::ensure!(
956            self.fast_composition.0.borrow().tree.kind(surface)? == CompositionSurfaceKind::Gpui,
957            "paint operations can only target GPUI composition surfaces"
958        );
959        if self.fast_layers.painting.is_some() {
960            return Ok(paint(self));
961        }
962        let previous_surface = self
963            .next_frame
964            .fast_composition_starts
965            .current()
966            .context("composition paint scope has no base surface")?;
967        switch_surface(self, surface);
968        let result = paint(self);
969        switch_surface(self, previous_surface);
970        Ok(result)
971    }
972}
973
974fn switch_surface(window: &mut Window, surface: CompositionSurfaceId) {
975    let scene_len = window.next_frame.scene.len();
976    window
977        .next_frame
978        .fast_composition_starts
979        .switch_to(surface, scene_len);
980}
981
982/// Stacks what the root view positions, as it prepaints, below the overlay
983/// surface.
984pub(crate) fn begin_base_prepaint(window: &mut Window) {
985    let state = window.fast_composition.0.borrow();
986    state.prepainting.set(Some(Host::Base));
987}
988
989/// Stacks what deferred and window-level draws position, as they prepaint,
990/// above the overlay surface.
991pub(crate) fn begin_overlay_prepaint(window: &mut Window) {
992    let state = window.fast_composition.0.borrow();
993    state.prepainting.set(Some(Host::Overlay));
994}
995
996/// Paints what follows, the root view, onto the base surface.
997pub(crate) fn begin_base(window: &mut Window) {
998    let state = window.fast_composition.0.borrow();
999    state.prepainting.set(None);
1000    let surface = state.base_surface;
1001    drop(state);
1002    switch_surface(window, surface);
1003}
1004
1005/// Moves each root native surface whose host changed surface to that
1006/// surface's side of the overlay surface.
1007fn restack_native_surfaces(state: &mut WindowCompositionState) -> Result<()> {
1008    let overlay = state.overlay_surface;
1009    for (id, surface) in &state.platform_surfaces {
1010        if !surface.restack.replace(false) || state.tree.parent(*id)?.is_some() {
1011            continue;
1012        }
1013        match surface.host.get() {
1014            Host::Base => state.tree.place_below(*id, overlay)?,
1015            Host::Overlay => state.tree.place_above(*id, overlay)?,
1016        }
1017    }
1018    Ok(())
1019}
1020
1021/// Paints what follows, deferred and window-level draws, onto the overlay
1022/// surface.
1023pub(crate) fn begin_overlay(window: &mut Window) {
1024    let surface = window.fast_composition.0.borrow().overlay_surface;
1025    switch_surface(window, surface);
1026}
1027
1028/// Carries the surface switches last frame made within `range` into the
1029/// frame being drawn, as [`Window::reuse_paint`] replays its scene, and
1030/// leaves painting on the surface it was on before.
1031pub(crate) fn reuse_starts(window: &mut Window, range: &Range<PaintIndex>) {
1032    let scenes = range.start.scene_index..range.end.scene_index;
1033    let starts = &window.rendered_frame.fast_composition_starts.0;
1034    let first = starts.partition_point(|(_, start)| *start < scenes.start);
1035    let last = starts.partition_point(|(_, start)| *start < scenes.end);
1036    if first == last {
1037        return;
1038    }
1039    let Some(surface) = window.next_frame.fast_composition_starts.current() else {
1040        return;
1041    };
1042    let offset = window.next_frame.scene.len();
1043    for index in first..last {
1044        let (reused, start) = window.rendered_frame.fast_composition_starts.0[index];
1045        window
1046            .next_frame
1047            .fast_composition_starts
1048            .switch_to(reused, start - scenes.start + offset);
1049    }
1050    let end = offset + scenes.len();
1051    window
1052        .next_frame
1053        .fast_composition_starts
1054        .switch_to(surface, end);
1055}
1056
1057/// Presents the frame last drawn: on its one surface, or split along the
1058/// composition tree once the window composes.
1059pub(crate) fn present(window: &mut Window) {
1060    let state = window.fast_composition.0.clone();
1061    if !state.borrow().enabled {
1062        window.platform_window.draw(&window.rendered_frame.scene);
1063        return;
1064    }
1065    if state.borrow().geometry_dirty.get() {
1066        if let Err(error) = restack_native_surfaces(&mut state.borrow_mut()) {
1067            log::error!("restacking native composition surfaces: {error:#}");
1068        }
1069        let composition = WindowComposition {
1070            platform_window: window.platform_window.as_ref(),
1071            state: state.clone(),
1072        };
1073        if let Err(error) = composition.synchronize_platform_order() {
1074            log::error!("updating window composition geometry: {error:#}");
1075        }
1076    }
1077    let state = state.borrow();
1078    let scene = &window.rendered_frame.scene;
1079    let layers = composed_scene_layers(
1080        &state.tree,
1081        &window.rendered_frame.fast_composition_starts.0,
1082        scene.len(),
1083    )
1084    .unwrap_or_else(|error| {
1085        log::error!("invalid window composition scene: {error:#}");
1086        vec![ComposedSceneLayer {
1087            surface: state.base_surface,
1088            ranges: vec![0..scene.len()],
1089        }]
1090    });
1091    drop(state);
1092    window
1093        .platform_window
1094        .draw_composed(ComposedScene::new(scene, layers));
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099    use super::{
1100        CompositionSurfaceId, CompositionSurfaceKind, CompositionTree, Host,
1101        ManagedPlatformSurface, PlatformSurfaceAttachment, composed_scene_layers,
1102        restack_native_surfaces,
1103    };
1104    use crate::{
1105        AppContext as _, Bounds, ContentMask, Context, DevicePixels, Entity, IntoElement,
1106        ParentElement as _, Point, Quad, Render, ScaledPixels, Scene, Size, StyleRefinement,
1107        Styled as _, TestAppContext, Window, canvas, deferred, div, fill, px,
1108        scene::PaintOperation, size,
1109    };
1110    use anyhow::Result;
1111    use std::{any::Any, cell::Cell, rc::Rc};
1112
1113    #[test]
1114    fn composition_surfaces_have_stable_identity_and_explicit_order() -> Result<()> {
1115        let mut tree = CompositionTree::new();
1116        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1117        let webview = tree.insert(CompositionSurfaceKind::Native, None)?;
1118        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1119
1120        tree.place_below(overlay, webview)?;
1121
1122        assert_eq!(tree.flattened(), [base, overlay, webview]);
1123        assert_eq!(tree.kind(webview)?, CompositionSurfaceKind::Native);
1124        Ok(())
1125    }
1126
1127    #[test]
1128    fn composition_surfaces_can_be_nested_and_reparented() -> Result<()> {
1129        let mut tree = CompositionTree::new();
1130        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1131        let pane = tree.insert(CompositionSurfaceKind::Native, Some(base))?;
1132        let video = tree.insert(CompositionSurfaceKind::ExternalGpu, None)?;
1133
1134        tree.reparent(video, Some(pane))?;
1135
1136        assert_eq!(tree.parent(video)?, Some(pane));
1137        assert_eq!(tree.children(Some(pane))?, [video]);
1138        assert_eq!(tree.flattened(), [base, pane, video]);
1139        Ok(())
1140    }
1141
1142    #[test]
1143    fn composition_tree_rejects_cycles_and_cross_parent_ordering() -> Result<()> {
1144        let mut tree = CompositionTree::new();
1145        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1146        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1147        let sibling = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1148
1149        assert!(tree.reparent(parent, Some(child)).is_err());
1150        assert!(tree.place_above(child, sibling).is_err());
1151        assert_eq!(tree.parent(parent)?, None);
1152        assert_eq!(tree.parent(child)?, Some(parent));
1153        Ok(())
1154    }
1155
1156    #[test]
1157    fn removing_a_surface_preserves_and_reparents_its_children() -> Result<()> {
1158        let mut tree = CompositionTree::new();
1159        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1160        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1161
1162        tree.remove(parent)?;
1163
1164        assert_eq!(tree.parent(child)?, None);
1165        assert_eq!(tree.flattened(), [child]);
1166        Ok(())
1167    }
1168
1169    #[test]
1170    fn scene_ranges_follow_tree_order_and_preserve_repeated_segments() -> Result<()> {
1171        let mut tree = CompositionTree::new();
1172        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1173        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1174        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1175        let starts = [(base, 0), (overlay, 4), (base, 7)];
1176
1177        let layers = composed_scene_layers(&tree, &starts, 10)?;
1178
1179        let [base_layer, overlay_layer] = layers.as_slice() else {
1180            panic!("expected base and overlay scene layers");
1181        };
1182        assert_eq!(base_layer.surface, base);
1183        assert_eq!(base_layer.ranges, [0..4, 7..10]);
1184        assert_eq!(overlay_layer.surface, overlay);
1185        assert_eq!(overlay_layer.ranges, [4..7]);
1186        assert_eq!(tree.kind(native)?, CompositionSurfaceKind::Native);
1187        Ok(())
1188    }
1189
1190    #[test]
1191    fn scene_ranges_reject_non_gpui_targets_and_non_monotonic_markers() -> Result<()> {
1192        let mut tree = CompositionTree::new();
1193        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1194        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1195
1196        assert!(composed_scene_layers(&tree, &[(native, 0)], 1).is_err());
1197        assert!(composed_scene_layers(&tree, &[(base, 2), (base, 1)], 2).is_err());
1198        Ok(())
1199    }
1200
1201    struct TestPlatformSurface {
1202        bounds_writes: Cell<usize>,
1203        fail_next_bounds: Cell<bool>,
1204        bounds: Cell<Bounds<DevicePixels>>,
1205        parent_origin: Cell<Point<DevicePixels>>,
1206    }
1207
1208    impl PlatformSurfaceAttachment for TestPlatformSurface {
1209        fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
1210            self.bounds_writes.set(self.bounds_writes.get() + 1);
1211            if self.fail_next_bounds.replace(false) {
1212                return Err(anyhow::anyhow!("test bounds failure"));
1213            }
1214            self.bounds.set(bounds);
1215            Ok(())
1216        }
1217
1218        fn bounds(&self) -> Bounds<DevicePixels> {
1219            self.bounds.get()
1220        }
1221
1222        fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
1223            self.parent_origin.set(origin);
1224            Ok(())
1225        }
1226
1227        fn set_visible(&self, _visible: bool) -> Result<()> {
1228            Ok(())
1229        }
1230
1231        fn platform_handle(&self) -> Result<Box<dyn Any>> {
1232            Ok(Box::new(()))
1233        }
1234    }
1235
1236    #[test]
1237    fn managed_composition_surface_tracks_window_geometry_changes() {
1238        let platform_surface = Rc::new(TestPlatformSurface {
1239            bounds_writes: Cell::new(0),
1240            fail_next_bounds: Cell::new(false),
1241            bounds: Cell::new(Bounds::default()),
1242            parent_origin: Cell::new(Point::default()),
1243        });
1244        let geometry_dirty = Rc::new(Cell::new(false));
1245        let surface = ManagedPlatformSurface {
1246            platform_surface: platform_surface.clone(),
1247            bounds: Cell::new(Bounds::default()),
1248            geometry_dirty: geometry_dirty.clone(),
1249            prepainting: Rc::new(Cell::new(None)),
1250            host: Cell::new(Host::Base),
1251            restack: Cell::new(false),
1252        };
1253        let bounds = Bounds {
1254            origin: Point {
1255                x: DevicePixels(25),
1256                y: DevicePixels(40),
1257            },
1258            size: size(DevicePixels(300), DevicePixels(200)),
1259        };
1260        let parent_origin = Point {
1261            x: DevicePixels(10),
1262            y: DevicePixels(15),
1263        };
1264
1265        assert!(surface.set_bounds(bounds).is_ok());
1266        assert!(surface.set_parent_origin(parent_origin).is_ok());
1267
1268        assert_eq!(surface.bounds(), bounds);
1269        assert_eq!(platform_surface.bounds.get(), bounds);
1270        assert_eq!(platform_surface.parent_origin.get(), parent_origin);
1271        assert!(geometry_dirty.get());
1272    }
1273
1274    #[test]
1275    fn unchanged_native_bounds_do_not_resynchronize_composition() -> Result<()> {
1276        let bounds = Bounds::new(Point::default(), size(DevicePixels(300), DevicePixels(200)));
1277        let platform = Rc::new(TestPlatformSurface {
1278            bounds_writes: Cell::new(0),
1279            fail_next_bounds: Cell::new(false),
1280            bounds: Cell::new(Bounds::default()),
1281            parent_origin: Cell::new(Point::default()),
1282        });
1283        let dirty = Rc::new(Cell::new(false));
1284        let surface = ManagedPlatformSurface {
1285            platform_surface: platform.clone(),
1286            bounds: Cell::new(Bounds::default()),
1287            geometry_dirty: dirty.clone(),
1288            prepainting: Rc::new(Cell::new(None)),
1289            host: Cell::new(Host::Base),
1290            restack: Cell::new(false),
1291        };
1292        surface.set_bounds(bounds)?;
1293        dirty.set(false);
1294        for _ in 0..10 {
1295            surface.set_bounds(bounds)?;
1296        }
1297        assert!(
1298            !dirty.get(),
1299            "unchanged layout must not remount native views between mouse down and up"
1300        );
1301        assert_eq!(platform.bounds_writes.get(), 1);
1302        let moved = Bounds::new(
1303            Point {
1304                x: DevicePixels(20),
1305                y: DevicePixels(15),
1306            },
1307            bounds.size,
1308        );
1309        surface.set_bounds(moved)?;
1310        assert!(dirty.get());
1311        assert_eq!(platform.bounds_writes.get(), 2);
1312        assert_eq!(surface.bounds(), moved);
1313        Ok(())
1314    }
1315
1316    #[test]
1317    fn failed_native_bounds_updates_remain_retryable() -> Result<()> {
1318        let bounds = Bounds::new(Point::default(), size(DevicePixels(600), DevicePixels(400)));
1319        let platform = Rc::new(TestPlatformSurface {
1320            bounds_writes: Cell::new(0),
1321            fail_next_bounds: Cell::new(true),
1322            bounds: Cell::new(Bounds::default()),
1323            parent_origin: Cell::new(Point::default()),
1324        });
1325        let dirty = Rc::new(Cell::new(false));
1326        let surface = ManagedPlatformSurface {
1327            platform_surface: platform.clone(),
1328            bounds: Cell::new(Bounds::default()),
1329            geometry_dirty: dirty.clone(),
1330            prepainting: Rc::new(Cell::new(None)),
1331            host: Cell::new(Host::Base),
1332            restack: Cell::new(false),
1333        };
1334        assert!(surface.set_bounds(bounds).is_err());
1335        assert_eq!(surface.bounds(), Bounds::default());
1336        assert!(!dirty.get());
1337        surface.set_bounds(bounds)?;
1338        assert!(dirty.get());
1339        assert_eq!(surface.bounds(), bounds);
1340        assert_eq!(platform.bounds_writes.get(), 2);
1341        dirty.set(false);
1342        surface.set_bounds(bounds)?;
1343        assert!(!dirty.get());
1344        assert_eq!(platform.bounds_writes.get(), 2);
1345        Ok(())
1346    }
1347
1348    fn square(side: f32) -> Bounds<ScaledPixels> {
1349        Bounds {
1350            origin: Point::default(),
1351            size: Size {
1352                width: ScaledPixels::from(side),
1353                height: ScaledPixels::from(side),
1354            },
1355        }
1356    }
1357
1358    #[test]
1359    fn empty_layers_do_not_make_a_scene_drawable() {
1360        let mut scene = Scene::default();
1361        scene.push_layer(square(100.));
1362        scene.pop_layer();
1363
1364        assert_ne!(scene.len(), 0);
1365        assert!(scene.is_empty());
1366    }
1367
1368    #[test]
1369    fn drawable_primitives_make_a_scene_non_empty() {
1370        let mut scene = Scene::default();
1371        let bounds = square(100.);
1372        scene.insert_primitive(Quad {
1373            bounds,
1374            content_mask: ContentMask { bounds },
1375            ..Default::default()
1376        });
1377
1378        assert!(!scene.is_empty());
1379    }
1380
1381    #[test]
1382    fn replay_preserves_scene_emptiness() {
1383        let mut source = Scene::default();
1384        source.push_layer(square(100.));
1385        source.pop_layer();
1386
1387        let mut replayed = Scene::default();
1388        replayed.replay(0..source.len(), &source);
1389
1390        assert!(replayed.is_empty());
1391    }
1392
1393    #[test]
1394    fn balanced_replay_restores_layers_crossing_the_range_boundary() {
1395        let mut source = Scene::default();
1396        let inner_bounds = square(50.);
1397        source.push_layer(square(100.));
1398        source.push_layer(inner_bounds);
1399        source.insert_primitive(Quad {
1400            bounds: inner_bounds,
1401            content_mask: ContentMask {
1402                bounds: inner_bounds,
1403            },
1404            ..Default::default()
1405        });
1406        source.pop_layer();
1407        source.pop_layer();
1408
1409        let mut replayed = Scene::default();
1410        assert!(replayed.replay_balanced(2..3, &source).is_ok());
1411
1412        assert_eq!(replayed.paint_operations.len(), 5);
1413        assert!(matches!(
1414            replayed.paint_operations.as_slice(),
1415            [
1416                PaintOperation::StartLayer(_),
1417                PaintOperation::StartLayer(_),
1418                PaintOperation::Primitive(_),
1419                PaintOperation::EndLayer,
1420                PaintOperation::EndLayer
1421            ]
1422        ));
1423    }
1424
1425    #[test]
1426    fn balanced_replay_rejects_invalid_ranges() {
1427        let source = Scene::default();
1428        let mut replayed = Scene::default();
1429        let start = 1;
1430        let end = 0;
1431
1432        assert!(replayed.replay_balanced(start..end, &source).is_err());
1433        assert!(replayed.replay_balanced(0..1, &source).is_err());
1434    }
1435
1436    struct Badge {
1437        overlay: CompositionSurfaceId,
1438        builds: Rc<Cell<usize>>,
1439    }
1440
1441    impl Render for Badge {
1442        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1443            self.builds.set(self.builds.get() + 1);
1444            let overlay = self.overlay;
1445            div()
1446                .size_full()
1447                .bg(crate::black())
1448                .child(
1449                    canvas(
1450                        |_, _, _| (),
1451                        move |bounds, _, window, _| {
1452                            window
1453                                .with_composition_surface(overlay, |window| {
1454                                    window.paint_quad(fill(bounds, crate::red()))
1455                                })
1456                                .unwrap();
1457                        },
1458                    )
1459                    .size(px(20.)),
1460                )
1461                .child(div().size(px(10.)).bg(crate::white()))
1462        }
1463    }
1464
1465    struct Panel {
1466        badge: Entity<Badge>,
1467    }
1468
1469    impl Render for Panel {
1470        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1471            div()
1472                .size(px(300.))
1473                .bg(crate::white())
1474                .child(
1475                    self.badge
1476                        .clone()
1477                        .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
1478                )
1479                .child(div().size(px(30.)).bg(crate::black()))
1480        }
1481    }
1482
1483    fn surface_of_each_operation(window: &Window) -> Vec<CompositionSurfaceId> {
1484        let state = window.fast_composition.0.borrow();
1485        let frame = &window.rendered_frame;
1486        let layers = composed_scene_layers(
1487            &state.tree,
1488            &frame.fast_composition_starts.0,
1489            frame.scene.len(),
1490        )
1491        .unwrap();
1492        let mut surfaces = vec![None; frame.scene.len()];
1493        for layer in layers {
1494            for range in layer.ranges {
1495                for surface in &mut surfaces[range] {
1496                    *surface = Some(layer.surface);
1497                }
1498            }
1499        }
1500        surfaces.into_iter().map(Option::unwrap).collect()
1501    }
1502
1503    /// A retained view that painted onto the overlay surface still does when
1504    /// it is drawn again from last frame: its surface switches come along
1505    /// with its scene, and painting returns to the base surface after it.
1506    #[crate::test]
1507    fn reused_views_keep_their_composition_surfaces(cx: &mut TestAppContext) {
1508        let builds = Rc::new(Cell::new(0));
1509        let window = cx.add_window({
1510            let builds = builds.clone();
1511            move |window, cx| {
1512                let overlay = window.fast_composition.0.borrow().overlay_surface;
1513                Panel {
1514                    badge: cx.new(|_| Badge { overlay, builds }),
1515                }
1516            }
1517        });
1518        let draw = |cx: &mut TestAppContext| {
1519            cx.update_window(window.into(), |_, window, cx| {
1520                window.draw(cx).clear(cx);
1521                let state = window.fast_composition.0.borrow();
1522                (
1523                    surface_of_each_operation(window),
1524                    state.base_surface,
1525                    state.overlay_surface,
1526                )
1527            })
1528            .unwrap()
1529        };
1530
1531        let (first, base, overlay) = draw(cx);
1532        assert_eq!(builds.get(), 1);
1533        assert_eq!(first.iter().filter(|s| **s == overlay).count(), 1);
1534        assert_eq!(first.last(), Some(&base));
1535
1536        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1537        let (second, _, _) = draw(cx);
1538        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
1539        assert_eq!(second, first);
1540    }
1541
1542    fn test_platform_surface() -> Rc<TestPlatformSurface> {
1543        Rc::new(TestPlatformSurface {
1544            bounds_writes: Cell::new(0),
1545            fail_next_bounds: Cell::new(false),
1546            bounds: Cell::new(Bounds::default()),
1547            parent_origin: Cell::new(Point::default()),
1548        })
1549    }
1550
1551    /// Positions one native surface from the root view and another from a
1552    /// deferred draw, or both from the root view.
1553    struct Hosts {
1554        page: Rc<ManagedPlatformSurface>,
1555        dialog_page: Rc<ManagedPlatformSurface>,
1556        dialog_open: bool,
1557    }
1558
1559    fn native_host(surface: Rc<ManagedPlatformSurface>) -> impl IntoElement {
1560        canvas(
1561            move |bounds, window, _| {
1562                surface
1563                    .set_bounds(bounds.to_device_pixels(window.scale_factor()))
1564                    .unwrap()
1565            },
1566            |_, _, _, _| {},
1567        )
1568        .size(px(50.))
1569    }
1570
1571    impl Render for Hosts {
1572        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1573            let dialog_page = native_host(self.dialog_page.clone());
1574            let root = div().size_full().child(native_host(self.page.clone()));
1575            if self.dialog_open {
1576                root.child(deferred(
1577                    div().size(px(80.)).bg(crate::white()).child(dialog_page),
1578                ))
1579            } else {
1580                root.child(dialog_page)
1581            }
1582        }
1583    }
1584
1585    /// A native surface hosted in a deferred draw, a web page in a dialog,
1586    /// stacks above the overlay surface the dialog's background is drawn on,
1587    /// and returns below it once hosted by the root view again.
1588    #[crate::test]
1589    fn native_surfaces_stack_with_their_hosts(cx: &mut TestAppContext) {
1590        let names = Rc::new(std::cell::RefCell::new(Vec::new()));
1591        let window = cx.add_window({
1592            let names = names.clone();
1593            move |window, _| {
1594                let mut state = window.fast_composition.0.borrow_mut();
1595                let overlay = state.overlay_surface;
1596                let mut names = names.borrow_mut();
1597                names.push((state.base_surface, "base"));
1598                names.push((overlay, "overlay"));
1599                let mut native = |name| {
1600                    let id = state
1601                        .tree
1602                        .insert(CompositionSurfaceKind::Native, None)
1603                        .unwrap();
1604                    state.tree.place_below(id, overlay).unwrap();
1605                    let surface =
1606                        Rc::new(ManagedPlatformSurface::new(test_platform_surface(), &state));
1607                    state.platform_surfaces.insert(id, surface.clone());
1608                    names.push((id, name));
1609                    surface
1610                };
1611                Hosts {
1612                    page: native("page"),
1613                    dialog_page: native("dialog page"),
1614                    dialog_open: true,
1615                }
1616            }
1617        });
1618        let draw = |cx: &mut TestAppContext| {
1619            cx.update_window(window.into(), |_, window, cx| {
1620                window.draw(cx).clear(cx);
1621                let mut state = window.fast_composition.0.borrow_mut();
1622                restack_native_surfaces(&mut state).unwrap();
1623                let names = names.borrow();
1624                state
1625                    .tree
1626                    .flattened()
1627                    .into_iter()
1628                    .map(|id| names.iter().find(|(named, _)| *named == id).unwrap().1)
1629                    .collect::<Vec<_>>()
1630            })
1631            .unwrap()
1632        };
1633
1634        assert_eq!(draw(cx), ["base", "page", "overlay", "dialog page"]);
1635
1636        window
1637            .update(cx, |hosts, _, cx| {
1638                hosts.dialog_open = false;
1639                cx.notify();
1640            })
1641            .unwrap();
1642        assert_eq!(draw(cx), ["base", "page", "dialog page", "overlay"]);
1643    }
1644}