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