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