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 Scene {
420    /// Returns whether the scene contains no drawable primitives.
421    ///
422    /// A scene may have paint operations that only open and close empty layers,
423    /// so `len() == 0` is not equivalent to having no visible/input-relevant
424    /// overlay content.
425    pub fn is_empty(&self) -> bool {
426        self.shadows.is_empty()
427            && self.quads.is_empty()
428            && self.paths.is_empty()
429            && self.underlines.is_empty()
430            && self.monochrome_sprites.is_empty()
431            && self.subpixel_sprites.is_empty()
432            && self.polychrome_sprites.is_empty()
433            && self.surfaces.is_empty()
434    }
435
436    /// Replays a range as a self-contained scene, restoring any layers that
437    /// were active at the start of the range and closing those still active at
438    /// its end. The scroll layers whose tiles the range composites come along.
439    pub fn replay_balanced(&mut self, range: Range<usize>, previous_scene: &Scene) -> Result<()> {
440        anyhow::ensure!(
441            range.start <= range.end,
442            "scene replay range starts after its end"
443        );
444        let prefix = previous_scene
445            .paint_operations
446            .get(..range.start)
447            .context("scene replay range starts past the scene")?;
448        let operations = previous_scene
449            .paint_operations
450            .get(range.clone())
451            .context("scene replay range ends past the scene")?;
452        let mut active_layers = Vec::new();
453        for operation in prefix {
454            match operation {
455                PaintOperation::StartLayer(bounds) => active_layers.push(*bounds),
456                PaintOperation::EndLayer => {
457                    anyhow::ensure!(
458                        active_layers.pop().is_some(),
459                        "source scene closes a layer that is not open"
460                    );
461                }
462                PaintOperation::Primitive(_) => {}
463            }
464        }
465
466        crate::fast::layers::paint::replay_layers(self, range, previous_scene);
467        for bounds in &active_layers {
468            self.push_layer(*bounds);
469        }
470        for operation in operations {
471            match operation {
472                PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()),
473                PaintOperation::StartLayer(bounds) => {
474                    active_layers.push(*bounds);
475                    self.push_layer(*bounds);
476                }
477                PaintOperation::EndLayer => {
478                    anyhow::ensure!(
479                        active_layers.pop().is_some(),
480                        "scene replay range closes a layer that is not open"
481                    );
482                    self.pop_layer();
483                }
484            }
485        }
486        for _ in active_layers {
487            self.pop_layer();
488        }
489        Ok(())
490    }
491}
492
493/// Where each stretch of a frame's scene is presented: the GPUI surface
494/// painting switched to, and the scene length at the switch.
495#[derive(Default)]
496pub(crate) struct SurfaceStarts(Vec<(CompositionSurfaceId, usize)>);
497
498impl SurfaceStarts {
499    pub(crate) fn clear(&mut self) {
500        self.0.clear();
501    }
502
503    fn current(&self) -> Option<CompositionSurfaceId> {
504        self.0.last().map(|(surface, _)| *surface)
505    }
506
507    fn switch_to(&mut self, surface: CompositionSurfaceId, scene_len: usize) {
508        if self.current() == Some(surface) {
509            return;
510        }
511        self.0.push((surface, scene_len));
512    }
513}
514
515/// A window's composition: its surface tree, the platform surfaces in it and
516/// whether the window presents through it.
517pub(crate) struct WindowCompositionState {
518    tree: CompositionTree,
519    platform_surfaces: FxHashMap<CompositionSurfaceId, Rc<dyn PlatformSurfaceAttachment>>,
520    base_surface: CompositionSurfaceId,
521    overlay_surface: CompositionSurfaceId,
522    geometry_dirty: Rc<Cell<bool>>,
523    enabled: bool,
524}
525
526/// The [`Window`] field holding its composition.
527pub(crate) struct WindowCompositionHandle(Rc<RefCell<WindowCompositionState>>);
528
529impl Default for WindowCompositionHandle {
530    fn default() -> Self {
531        let mut tree = CompositionTree::new();
532        let base_surface = tree
533            .insert(CompositionSurfaceKind::Gpui, None)
534            .expect("a root can always be inserted");
535        let overlay_surface = tree
536            .insert(CompositionSurfaceKind::Gpui, None)
537            .expect("a root can always be inserted");
538        Self(Rc::new(RefCell::new(WindowCompositionState {
539            tree,
540            platform_surfaces: FxHashMap::default(),
541            base_surface,
542            overlay_surface,
543            geometry_dirty: Rc::new(Cell::new(false)),
544            enabled: false,
545        })))
546    }
547}
548
549/// A platform surface whose bounds changes mark the window's composition
550/// geometry for synchronization at the next present.
551struct ManagedPlatformSurface {
552    platform_surface: Rc<dyn PlatformSurfaceAttachment>,
553    bounds: Cell<Bounds<DevicePixels>>,
554    geometry_dirty: Rc<Cell<bool>>,
555}
556
557impl PlatformSurfaceAttachment for ManagedPlatformSurface {
558    fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
559        self.platform_surface.set_bounds(bounds)?;
560        self.bounds.set(bounds);
561        self.geometry_dirty.set(true);
562        Ok(())
563    }
564
565    fn bounds(&self) -> Bounds<DevicePixels> {
566        self.bounds.get()
567    }
568
569    fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
570        self.platform_surface.set_parent_origin(origin)
571    }
572
573    fn compositor_recreated(&self, platform_context: &dyn Any) -> Result<()> {
574        self.platform_surface.compositor_recreated(platform_context)
575    }
576
577    fn set_compositor_recreated_callback(
578        &self,
579        callback: Rc<dyn Fn(Box<dyn Any>) -> Result<()>>,
580    ) -> Result<()> {
581        self.platform_surface
582            .set_compositor_recreated_callback(callback)
583    }
584
585    fn set_visible(&self, visible: bool) -> Result<()> {
586        self.platform_surface.set_visible(visible)
587    }
588
589    fn platform_handle(&self) -> Result<Box<dyn Any>> {
590        self.platform_surface.platform_handle()
591    }
592}
593
594struct WindowCompositionSurfaceInner {
595    id: CompositionSurfaceId,
596    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
597}
598
599/// A stable handle to a surface in a window composition tree.
600#[derive(Clone)]
601pub struct WindowCompositionSurface(Rc<WindowCompositionSurfaceInner>);
602
603impl WindowCompositionSurface {
604    /// Returns this surface's stable identity.
605    pub fn id(&self) -> CompositionSurfaceId {
606        self.0.id
607    }
608
609    /// Returns the platform surface used to attach native content.
610    pub fn platform_surface(&self) -> Result<&dyn PlatformSurfaceAttachment> {
611        self.0
612            .platform_surface
613            .as_deref()
614            .context("this composition surface is rendered by GPUI")
615    }
616}
617
618/// Controls the surface tree composited into a window.
619pub struct WindowComposition<'a> {
620    platform_window: &'a dyn PlatformWindow,
621    state: Rc<RefCell<WindowCompositionState>>,
622}
623
624impl WindowComposition<'_> {
625    /// Returns the GPUI surface initially rendered below native content.
626    pub fn base_surface(&self) -> CompositionSurfaceId {
627        self.state.borrow().base_surface
628    }
629
630    /// Returns the GPUI surface initially rendered above native content.
631    pub fn overlay_surface(&self) -> CompositionSurfaceId {
632        self.state.borrow().overlay_surface
633    }
634
635    /// Creates a platform-native surface as a root of the composition tree,
636    /// below the overlay surface.
637    pub fn create_native_surface(&self) -> Result<WindowCompositionSurface> {
638        let platform_surface = self.platform_window.create_native_surface()?;
639        self.register_platform_surface(CompositionSurfaceKind::Native, platform_surface)
640    }
641
642    /// Registers an externally produced GPU surface as a root of the
643    /// composition tree, below the overlay surface.
644    ///
645    /// The producer owns the platform attachment and its synchronization. GPUI
646    /// owns its placement in the window composition tree.
647    pub fn create_external_gpu_surface(
648        &self,
649        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
650    ) -> Result<WindowCompositionSurface> {
651        self.register_platform_surface(CompositionSurfaceKind::ExternalGpu, platform_surface)
652    }
653
654    /// Creates another GPUI-rendered surface in the composition tree. Paint
655    /// onto it with [`Window::with_composition_surface`].
656    pub fn create_gpui_surface(
657        &self,
658        parent: Option<CompositionSurfaceId>,
659    ) -> Result<WindowCompositionSurface> {
660        let id = self
661            .state
662            .borrow_mut()
663            .tree
664            .insert(CompositionSurfaceKind::Gpui, parent)?;
665        if let Err(error) = self.synchronize_platform_order() {
666            self.state.borrow_mut().tree.remove(id)?;
667            self.synchronize_platform_order().log_err();
668            return Err(error);
669        }
670        Ok(surface_handle(id, None))
671    }
672
673    /// Places `surface` immediately above `sibling`.
674    pub fn place_above(
675        &self,
676        surface: CompositionSurfaceId,
677        sibling: CompositionSurfaceId,
678    ) -> Result<()> {
679        anyhow::ensure!(
680            surface != self.state.borrow().base_surface,
681            "the GPUI base surface cannot be reordered"
682        );
683        self.change_tree(|tree| tree.place_above(surface, sibling))
684    }
685
686    /// Places `surface` immediately below `sibling`.
687    pub fn place_below(
688        &self,
689        surface: CompositionSurfaceId,
690        sibling: CompositionSurfaceId,
691    ) -> Result<()> {
692        let base_surface = self.state.borrow().base_surface;
693        anyhow::ensure!(
694            surface != base_surface && sibling != base_surface,
695            "surfaces cannot be placed below or move the GPUI base surface"
696        );
697        self.change_tree(|tree| tree.place_below(surface, sibling))
698    }
699
700    /// Moves `surface` under a new parent, placing it above existing children.
701    pub fn reparent(
702        &self,
703        surface: CompositionSurfaceId,
704        parent: Option<CompositionSurfaceId>,
705    ) -> Result<()> {
706        anyhow::ensure!(
707            surface != self.state.borrow().base_surface,
708            "the GPUI base surface cannot be reparented"
709        );
710        self.change_tree(|tree| tree.reparent(surface, parent))
711    }
712
713    /// Removes a surface while preserving its children at the removed
714    /// surface's previous position.
715    pub fn remove_surface(&self, surface: CompositionSurfaceId) -> Result<()> {
716        let mut state = self.state.borrow_mut();
717        if surface == state.base_surface || surface == state.overlay_surface {
718            bail!("the default GPUI composition surfaces cannot be removed");
719        }
720        let previous_tree = state.tree.clone();
721        let platform_surface = state.platform_surfaces.get(&surface).cloned();
722        if let Some(platform_surface) = &platform_surface {
723            platform_surface.set_visible(false)?;
724        }
725        state.tree.remove(surface)?;
726        state.platform_surfaces.remove(&surface);
727        drop(state);
728        if let Err(error) = self.synchronize_platform_order() {
729            let mut state = self.state.borrow_mut();
730            state.tree = previous_tree;
731            if let Some(platform_surface) = platform_surface {
732                platform_surface.set_visible(true).log_err();
733                state.platform_surfaces.insert(surface, platform_surface);
734            }
735            drop(state);
736            self.synchronize_platform_order().log_err();
737            return Err(error);
738        }
739        Ok(())
740    }
741
742    /// Returns the renderer kind for a surface.
743    pub fn surface_kind(&self, surface: CompositionSurfaceId) -> Result<CompositionSurfaceKind> {
744        self.state.borrow().tree.kind(surface)
745    }
746
747    /// Returns a surface's parent.
748    pub fn parent(&self, surface: CompositionSurfaceId) -> Result<Option<CompositionSurfaceId>> {
749        self.state.borrow().tree.parent(surface)
750    }
751
752    /// Returns the ordered children of a surface, or the root surfaces when
753    /// `parent` is `None`.
754    pub fn children(
755        &self,
756        parent: Option<CompositionSurfaceId>,
757    ) -> Result<Vec<CompositionSurfaceId>> {
758        Ok(self.state.borrow().tree.children(parent)?.to_vec())
759    }
760
761    /// Applies `change` to the tree and the platform, or neither.
762    fn change_tree(&self, change: impl FnOnce(&mut CompositionTree) -> Result<()>) -> Result<()> {
763        let previous_tree = self.state.borrow().tree.clone();
764        change(&mut self.state.borrow_mut().tree)?;
765        if let Err(error) = self.synchronize_platform_order() {
766            self.state.borrow_mut().tree = previous_tree;
767            self.synchronize_platform_order().log_err();
768            return Err(error);
769        }
770        Ok(())
771    }
772
773    fn register_platform_surface(
774        &self,
775        kind: CompositionSurfaceKind,
776        platform_surface: Rc<dyn PlatformSurfaceAttachment>,
777    ) -> Result<WindowCompositionSurface> {
778        let initial_bounds = platform_surface.bounds();
779        let geometry_dirty = self.state.borrow().geometry_dirty.clone();
780        let platform_surface: Rc<dyn PlatformSurfaceAttachment> = Rc::new(ManagedPlatformSurface {
781            platform_surface,
782            bounds: Cell::new(initial_bounds),
783            geometry_dirty,
784        });
785        let mut state = self.state.borrow_mut();
786        let id = state.tree.insert(kind, None)?;
787        let overlay_surface = state.overlay_surface;
788        state.tree.place_below(id, overlay_surface)?;
789        state.platform_surfaces.insert(id, platform_surface.clone());
790        drop(state);
791        if let Err(error) = self.synchronize_platform_order() {
792            platform_surface.set_visible(false).log_err();
793            let mut state = self.state.borrow_mut();
794            state.platform_surfaces.remove(&id);
795            state.tree.remove(id)?;
796            drop(state);
797            self.synchronize_platform_order().log_err();
798            return Err(error);
799        }
800        Ok(surface_handle(id, Some(platform_surface)))
801    }
802
803    /// Hands the platform the tree's order and every surface's geometry.
804    fn synchronize_platform_order(&self) -> Result<()> {
805        let state = self.state.borrow();
806        let mut origins = FxHashMap::default();
807        let mut surfaces = Vec::new();
808        for id in state.tree.flattened() {
809            let parent = state.tree.parent(id)?;
810            let parent_origin = parent
811                .and_then(|parent| origins.get(&parent).copied())
812                .unwrap_or_default();
813            let content = match state.tree.kind(id)? {
814                CompositionSurfaceKind::Gpui => PlatformCompositionSurfaceContent::Gpui,
815                CompositionSurfaceKind::Native => PlatformCompositionSurfaceContent::Native(
816                    state
817                        .platform_surfaces
818                        .get(&id)
819                        .context("native composition surface is missing")?
820                        .clone(),
821                ),
822                CompositionSurfaceKind::ExternalGpu => {
823                    PlatformCompositionSurfaceContent::ExternalGpu(
824                        state
825                            .platform_surfaces
826                            .get(&id)
827                            .context("external GPU composition surface is missing")?
828                            .clone(),
829                    )
830                }
831            };
832            let window_bounds = match &content {
833                PlatformCompositionSurfaceContent::Gpui => None,
834                PlatformCompositionSurfaceContent::Native(platform_surface)
835                | PlatformCompositionSurfaceContent::ExternalGpu(platform_surface) => {
836                    Some(platform_surface.bounds())
837                }
838            };
839            let window_origin = window_bounds.map_or_else(Point::default, |bounds| bounds.origin);
840            origins.insert(id, window_origin);
841            surfaces.push(PlatformCompositionSurface {
842                id,
843                parent,
844                window_origin,
845                parent_origin,
846                window_bounds,
847                content,
848            });
849        }
850        self.platform_window.set_composition_order(&surfaces)?;
851        state.geometry_dirty.set(false);
852        Ok(())
853    }
854}
855
856fn surface_handle(
857    id: CompositionSurfaceId,
858    platform_surface: Option<Rc<dyn PlatformSurfaceAttachment>>,
859) -> WindowCompositionSurface {
860    WindowCompositionSurface(Rc::new(WindowCompositionSurfaceInner {
861        id,
862        platform_surface,
863    }))
864}
865
866impl Window {
867    /// Enables native window composition and returns its controller.
868    ///
869    /// GPUI's root scene is rendered below surfaces created by the controller,
870    /// while deferred and window-level overlays are rendered above them.
871    pub fn enable_window_composition(&self) -> Result<WindowComposition<'_>> {
872        self.platform_window.enable_window_composition()?;
873        let composition = WindowComposition {
874            platform_window: self.platform_window.as_ref(),
875            state: self.fast_composition.0.clone(),
876        };
877        composition.synchronize_platform_order()?;
878        composition.state.borrow_mut().enabled = true;
879        Ok(composition)
880    }
881
882    /// Paints a scope of scene operations onto a GPUI surface in this window's
883    /// composition tree, then restores the previous surface.
884    ///
885    /// Inside a scroll layer, whose content is composited from tiles, the
886    /// scope paints where the layer does.
887    pub fn with_composition_surface<R>(
888        &mut self,
889        surface: CompositionSurfaceId,
890        paint: impl FnOnce(&mut Self) -> R,
891    ) -> Result<R> {
892        self.invalidator.debug_assert_paint();
893        anyhow::ensure!(
894            self.fast_composition.0.borrow().tree.kind(surface)? == CompositionSurfaceKind::Gpui,
895            "paint operations can only target GPUI composition surfaces"
896        );
897        if self.fast_layers.painting.is_some() {
898            return Ok(paint(self));
899        }
900        let previous_surface = self
901            .next_frame
902            .fast_composition_starts
903            .current()
904            .context("composition paint scope has no base surface")?;
905        switch_surface(self, surface);
906        let result = paint(self);
907        switch_surface(self, previous_surface);
908        Ok(result)
909    }
910}
911
912fn switch_surface(window: &mut Window, surface: CompositionSurfaceId) {
913    let scene_len = window.next_frame.scene.len();
914    window
915        .next_frame
916        .fast_composition_starts
917        .switch_to(surface, scene_len);
918}
919
920/// Paints what follows, the root view, onto the base surface.
921pub(crate) fn begin_base(window: &mut Window) {
922    let surface = window.fast_composition.0.borrow().base_surface;
923    switch_surface(window, surface);
924}
925
926/// Paints what follows, deferred and window-level draws, onto the overlay
927/// surface.
928pub(crate) fn begin_overlay(window: &mut Window) {
929    let surface = window.fast_composition.0.borrow().overlay_surface;
930    switch_surface(window, surface);
931}
932
933/// Carries the surface switches last frame made within `range` into the
934/// frame being drawn, as [`Window::reuse_paint`] replays its scene, and
935/// leaves painting on the surface it was on before.
936pub(crate) fn reuse_starts(window: &mut Window, range: &Range<PaintIndex>) {
937    let scenes = range.start.scene_index..range.end.scene_index;
938    let starts = &window.rendered_frame.fast_composition_starts.0;
939    let first = starts.partition_point(|(_, start)| *start < scenes.start);
940    let last = starts.partition_point(|(_, start)| *start < scenes.end);
941    if first == last {
942        return;
943    }
944    let Some(surface) = window.next_frame.fast_composition_starts.current() else {
945        return;
946    };
947    let offset = window.next_frame.scene.len();
948    for index in first..last {
949        let (reused, start) = window.rendered_frame.fast_composition_starts.0[index];
950        window
951            .next_frame
952            .fast_composition_starts
953            .switch_to(reused, start - scenes.start + offset);
954    }
955    let end = offset + scenes.len();
956    window
957        .next_frame
958        .fast_composition_starts
959        .switch_to(surface, end);
960}
961
962/// Presents the frame last drawn: on its one surface, or split along the
963/// composition tree once the window composes.
964pub(crate) fn present(window: &mut Window) {
965    let state = window.fast_composition.0.clone();
966    if !state.borrow().enabled {
967        window.platform_window.draw(&window.rendered_frame.scene);
968        return;
969    }
970    if state.borrow().geometry_dirty.get() {
971        let composition = WindowComposition {
972            platform_window: window.platform_window.as_ref(),
973            state: state.clone(),
974        };
975        if let Err(error) = composition.synchronize_platform_order() {
976            log::error!("updating window composition geometry: {error:#}");
977        }
978    }
979    let state = state.borrow();
980    let scene = &window.rendered_frame.scene;
981    let layers = composed_scene_layers(
982        &state.tree,
983        &window.rendered_frame.fast_composition_starts.0,
984        scene.len(),
985    )
986    .unwrap_or_else(|error| {
987        log::error!("invalid window composition scene: {error:#}");
988        vec![ComposedSceneLayer {
989            surface: state.base_surface,
990            ranges: vec![0..scene.len()],
991        }]
992    });
993    drop(state);
994    window
995        .platform_window
996        .draw_composed(ComposedScene::new(scene, layers));
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::{
1002        CompositionSurfaceId, CompositionSurfaceKind, CompositionTree, ManagedPlatformSurface,
1003        PlatformSurfaceAttachment, composed_scene_layers,
1004    };
1005    use crate::{
1006        AppContext as _, Bounds, ContentMask, Context, DevicePixels, Entity, IntoElement,
1007        ParentElement as _, Point, Quad, Render, ScaledPixels, Scene, Size, StyleRefinement,
1008        Styled as _, TestAppContext, Window, canvas, div, fill, px, scene::PaintOperation, size,
1009    };
1010    use anyhow::Result;
1011    use std::{any::Any, cell::Cell, rc::Rc};
1012
1013    #[test]
1014    fn composition_surfaces_have_stable_identity_and_explicit_order() -> Result<()> {
1015        let mut tree = CompositionTree::new();
1016        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1017        let webview = tree.insert(CompositionSurfaceKind::Native, None)?;
1018        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1019
1020        tree.place_below(overlay, webview)?;
1021
1022        assert_eq!(tree.flattened(), [base, overlay, webview]);
1023        assert_eq!(tree.kind(webview)?, CompositionSurfaceKind::Native);
1024        Ok(())
1025    }
1026
1027    #[test]
1028    fn composition_surfaces_can_be_nested_and_reparented() -> Result<()> {
1029        let mut tree = CompositionTree::new();
1030        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1031        let pane = tree.insert(CompositionSurfaceKind::Native, Some(base))?;
1032        let video = tree.insert(CompositionSurfaceKind::ExternalGpu, None)?;
1033
1034        tree.reparent(video, Some(pane))?;
1035
1036        assert_eq!(tree.parent(video)?, Some(pane));
1037        assert_eq!(tree.children(Some(pane))?, [video]);
1038        assert_eq!(tree.flattened(), [base, pane, video]);
1039        Ok(())
1040    }
1041
1042    #[test]
1043    fn composition_tree_rejects_cycles_and_cross_parent_ordering() -> Result<()> {
1044        let mut tree = CompositionTree::new();
1045        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1046        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1047        let sibling = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1048
1049        assert!(tree.reparent(parent, Some(child)).is_err());
1050        assert!(tree.place_above(child, sibling).is_err());
1051        assert_eq!(tree.parent(parent)?, None);
1052        assert_eq!(tree.parent(child)?, Some(parent));
1053        Ok(())
1054    }
1055
1056    #[test]
1057    fn removing_a_surface_preserves_and_reparents_its_children() -> Result<()> {
1058        let mut tree = CompositionTree::new();
1059        let parent = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1060        let child = tree.insert(CompositionSurfaceKind::Native, Some(parent))?;
1061
1062        tree.remove(parent)?;
1063
1064        assert_eq!(tree.parent(child)?, None);
1065        assert_eq!(tree.flattened(), [child]);
1066        Ok(())
1067    }
1068
1069    #[test]
1070    fn scene_ranges_follow_tree_order_and_preserve_repeated_segments() -> Result<()> {
1071        let mut tree = CompositionTree::new();
1072        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1073        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1074        let overlay = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1075        let starts = [(base, 0), (overlay, 4), (base, 7)];
1076
1077        let layers = composed_scene_layers(&tree, &starts, 10)?;
1078
1079        let [base_layer, overlay_layer] = layers.as_slice() else {
1080            panic!("expected base and overlay scene layers");
1081        };
1082        assert_eq!(base_layer.surface, base);
1083        assert_eq!(base_layer.ranges, [0..4, 7..10]);
1084        assert_eq!(overlay_layer.surface, overlay);
1085        assert_eq!(overlay_layer.ranges, [4..7]);
1086        assert_eq!(tree.kind(native)?, CompositionSurfaceKind::Native);
1087        Ok(())
1088    }
1089
1090    #[test]
1091    fn scene_ranges_reject_non_gpui_targets_and_non_monotonic_markers() -> Result<()> {
1092        let mut tree = CompositionTree::new();
1093        let base = tree.insert(CompositionSurfaceKind::Gpui, None)?;
1094        let native = tree.insert(CompositionSurfaceKind::Native, None)?;
1095
1096        assert!(composed_scene_layers(&tree, &[(native, 0)], 1).is_err());
1097        assert!(composed_scene_layers(&tree, &[(base, 2), (base, 1)], 2).is_err());
1098        Ok(())
1099    }
1100
1101    struct TestPlatformSurface {
1102        bounds: Cell<Bounds<DevicePixels>>,
1103        parent_origin: Cell<Point<DevicePixels>>,
1104    }
1105
1106    impl PlatformSurfaceAttachment for TestPlatformSurface {
1107        fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> Result<()> {
1108            self.bounds.set(bounds);
1109            Ok(())
1110        }
1111
1112        fn bounds(&self) -> Bounds<DevicePixels> {
1113            self.bounds.get()
1114        }
1115
1116        fn set_parent_origin(&self, origin: Point<DevicePixels>) -> Result<()> {
1117            self.parent_origin.set(origin);
1118            Ok(())
1119        }
1120
1121        fn set_visible(&self, _visible: bool) -> Result<()> {
1122            Ok(())
1123        }
1124
1125        fn platform_handle(&self) -> Result<Box<dyn Any>> {
1126            Ok(Box::new(()))
1127        }
1128    }
1129
1130    #[test]
1131    fn managed_composition_surface_tracks_window_geometry_changes() {
1132        let platform_surface = Rc::new(TestPlatformSurface {
1133            bounds: Cell::new(Bounds::default()),
1134            parent_origin: Cell::new(Point::default()),
1135        });
1136        let geometry_dirty = Rc::new(Cell::new(false));
1137        let surface = ManagedPlatformSurface {
1138            platform_surface: platform_surface.clone(),
1139            bounds: Cell::new(Bounds::default()),
1140            geometry_dirty: geometry_dirty.clone(),
1141        };
1142        let bounds = Bounds {
1143            origin: Point {
1144                x: DevicePixels(25),
1145                y: DevicePixels(40),
1146            },
1147            size: size(DevicePixels(300), DevicePixels(200)),
1148        };
1149        let parent_origin = Point {
1150            x: DevicePixels(10),
1151            y: DevicePixels(15),
1152        };
1153
1154        assert!(surface.set_bounds(bounds).is_ok());
1155        assert!(surface.set_parent_origin(parent_origin).is_ok());
1156
1157        assert_eq!(surface.bounds(), bounds);
1158        assert_eq!(platform_surface.bounds.get(), bounds);
1159        assert_eq!(platform_surface.parent_origin.get(), parent_origin);
1160        assert!(geometry_dirty.get());
1161    }
1162
1163    fn square(side: f32) -> Bounds<ScaledPixels> {
1164        Bounds {
1165            origin: Point::default(),
1166            size: Size {
1167                width: ScaledPixels::from(side),
1168                height: ScaledPixels::from(side),
1169            },
1170        }
1171    }
1172
1173    #[test]
1174    fn empty_layers_do_not_make_a_scene_drawable() {
1175        let mut scene = Scene::default();
1176        scene.push_layer(square(100.));
1177        scene.pop_layer();
1178
1179        assert_ne!(scene.len(), 0);
1180        assert!(scene.is_empty());
1181    }
1182
1183    #[test]
1184    fn drawable_primitives_make_a_scene_non_empty() {
1185        let mut scene = Scene::default();
1186        let bounds = square(100.);
1187        scene.insert_primitive(Quad {
1188            bounds,
1189            content_mask: ContentMask { bounds },
1190            ..Default::default()
1191        });
1192
1193        assert!(!scene.is_empty());
1194    }
1195
1196    #[test]
1197    fn replay_preserves_scene_emptiness() {
1198        let mut source = Scene::default();
1199        source.push_layer(square(100.));
1200        source.pop_layer();
1201
1202        let mut replayed = Scene::default();
1203        replayed.replay(0..source.len(), &source);
1204
1205        assert!(replayed.is_empty());
1206    }
1207
1208    #[test]
1209    fn balanced_replay_restores_layers_crossing_the_range_boundary() {
1210        let mut source = Scene::default();
1211        let inner_bounds = square(50.);
1212        source.push_layer(square(100.));
1213        source.push_layer(inner_bounds);
1214        source.insert_primitive(Quad {
1215            bounds: inner_bounds,
1216            content_mask: ContentMask {
1217                bounds: inner_bounds,
1218            },
1219            ..Default::default()
1220        });
1221        source.pop_layer();
1222        source.pop_layer();
1223
1224        let mut replayed = Scene::default();
1225        assert!(replayed.replay_balanced(2..3, &source).is_ok());
1226
1227        assert_eq!(replayed.paint_operations.len(), 5);
1228        assert!(matches!(
1229            replayed.paint_operations.as_slice(),
1230            [
1231                PaintOperation::StartLayer(_),
1232                PaintOperation::StartLayer(_),
1233                PaintOperation::Primitive(_),
1234                PaintOperation::EndLayer,
1235                PaintOperation::EndLayer
1236            ]
1237        ));
1238    }
1239
1240    #[test]
1241    fn balanced_replay_rejects_invalid_ranges() {
1242        let source = Scene::default();
1243        let mut replayed = Scene::default();
1244        let start = 1;
1245        let end = 0;
1246
1247        assert!(replayed.replay_balanced(start..end, &source).is_err());
1248        assert!(replayed.replay_balanced(0..1, &source).is_err());
1249    }
1250
1251    struct Badge {
1252        overlay: CompositionSurfaceId,
1253        builds: Rc<Cell<usize>>,
1254    }
1255
1256    impl Render for Badge {
1257        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1258            self.builds.set(self.builds.get() + 1);
1259            let overlay = self.overlay;
1260            div()
1261                .size_full()
1262                .bg(crate::black())
1263                .child(
1264                    canvas(
1265                        |_, _, _| (),
1266                        move |bounds, _, window, _| {
1267                            window
1268                                .with_composition_surface(overlay, |window| {
1269                                    window.paint_quad(fill(bounds, crate::red()))
1270                                })
1271                                .unwrap();
1272                        },
1273                    )
1274                    .size(px(20.)),
1275                )
1276                .child(div().size(px(10.)).bg(crate::white()))
1277        }
1278    }
1279
1280    struct Panel {
1281        badge: Entity<Badge>,
1282    }
1283
1284    impl Render for Panel {
1285        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1286            div()
1287                .size(px(300.))
1288                .bg(crate::white())
1289                .child(
1290                    self.badge
1291                        .clone()
1292                        .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
1293                )
1294                .child(div().size(px(30.)).bg(crate::black()))
1295        }
1296    }
1297
1298    fn surface_of_each_operation(window: &Window) -> Vec<CompositionSurfaceId> {
1299        let state = window.fast_composition.0.borrow();
1300        let frame = &window.rendered_frame;
1301        let layers = composed_scene_layers(
1302            &state.tree,
1303            &frame.fast_composition_starts.0,
1304            frame.scene.len(),
1305        )
1306        .unwrap();
1307        let mut surfaces = vec![None; frame.scene.len()];
1308        for layer in layers {
1309            for range in layer.ranges {
1310                for surface in &mut surfaces[range] {
1311                    *surface = Some(layer.surface);
1312                }
1313            }
1314        }
1315        surfaces.into_iter().map(Option::unwrap).collect()
1316    }
1317
1318    /// A retained view that painted onto the overlay surface still does when
1319    /// it is drawn again from last frame: its surface switches come along
1320    /// with its scene, and painting returns to the base surface after it.
1321    #[crate::test]
1322    fn reused_views_keep_their_composition_surfaces(cx: &mut TestAppContext) {
1323        let builds = Rc::new(Cell::new(0));
1324        let window = cx.add_window({
1325            let builds = builds.clone();
1326            move |window, cx| {
1327                let overlay = window.fast_composition.0.borrow().overlay_surface;
1328                Panel {
1329                    badge: cx.new(|_| Badge { overlay, builds }),
1330                }
1331            }
1332        });
1333        let draw = |cx: &mut TestAppContext| {
1334            cx.update_window(window.into(), |_, window, cx| {
1335                window.draw(cx).clear(cx);
1336                let state = window.fast_composition.0.borrow();
1337                (
1338                    surface_of_each_operation(window),
1339                    state.base_surface,
1340                    state.overlay_surface,
1341                )
1342            })
1343            .unwrap()
1344        };
1345
1346        let (first, base, overlay) = draw(cx);
1347        assert_eq!(builds.get(), 1);
1348        assert_eq!(first.iter().filter(|s| **s == overlay).count(), 1);
1349        assert_eq!(first.last(), Some(&base));
1350
1351        window.update(cx, |_, _, cx| cx.notify()).unwrap();
1352        let (second, _, _) = draw(cx);
1353        assert_eq!(builds.get(), 1, "the badge is drawn again from last frame");
1354        assert_eq!(second, first);
1355    }
1356}