Skip to main content

gpui/fast/layers/
paint.rs

1// Modified by Longbridge for gpui-fast.
2//! Painting a scroll container's children into its layer: the scene swap,
3//! the cull/clip split and inserting the tile quads (M3).
4//!
5//! A `div` that scrolls prepaints and paints its children through
6//! [`begin_children`], [`prepaint_children`], [`end_children`] and
7//! [`paint_children`]. They ask [`policy::decide`] what to do and do it:
8//!
9//! - `Bypass`: today's path.
10//! - `Repaint`: the children are prepainted and painted as today, in window
11//!   space at the current offset, but culled against the painted region (the
12//!   viewport and its overscan) instead of the viewport, and painted into the
13//!   layer's own scene, which is then stored in content space, diffed into
14//!   tiles, and composited.
15//! - `Composite`: the children are neither prepainted nor painted; the layer's
16//!   tiles are composited at the new offset.
17
18use crate::{
19    App, AtlasTile, Bounds, ContentMask, Corners, DevicePixels, GlobalElementId, Overflow, Pixels,
20    Point, PolychromeSprite, PrepaintStateIndex, Rgba, ScaledPixels, Scene, Size, Style, TileCoord,
21    Window, WindowBackgroundAppearance,
22    fast::{
23        dependencies::{DependencyRecording, RenderDependencies},
24        layers::{
25            COMPILED, Layer, active, background,
26            policy::{self, Decision},
27            record::LayerRecord,
28            scene::{
29                LayerContent, LayerFrame, LayerKey, decode_layer_tile, layer_tile_id,
30                layer_tile_texture_id, translate_primitive, visible_bounds,
31            },
32            tiles::{dirty_tiles, tile_hashes},
33        },
34    },
35    point,
36    scene::{PaintOperation, Primitive},
37    size as size2,
38};
39use collections::FxHashMap;
40use std::{mem, ops::Range, rc::Rc};
41
42/// The side of a tile, in device pixels.
43pub(crate) const TILE_SIZE: u32 = 512;
44
45/// The layer whose content is being prepainted or painted.
46pub(crate) struct Painting {
47    /// The scroll container.
48    pub(crate) id: GlobalElementId,
49    /// The container's clip rect, in window space.
50    pub(crate) viewport: Bounds<Pixels>,
51    /// The part of the content painted, in window space: the viewport and
52    /// the overscan around it, within the content.
53    pub(crate) painted_region: Bounds<Pixels>,
54    /// While the content paints, the frame's scene, swapped out for the
55    /// layer's; otherwise the layer's scene, in window space.
56    pub(crate) scene: Scene,
57    /// The offset the content is painted at, snapped.
58    pub(crate) scroll_offset: Point<Pixels>,
59    /// The layer's translation, `scroll_offset` in whole device pixels.
60    pub(crate) translation: Point<ScaledPixels>,
61    /// What prepainting the content added to the frame.
62    pub(crate) prepaint_range: Range<PrepaintStateIndex>,
63    /// The recording of what prepainting the content reads, while it runs.
64    pub(crate) recording: Option<DependencyRecording>,
65    /// What prepainting the content read.
66    pub(crate) dependencies: RenderDependencies,
67    /// What routing input into the content takes from painting it.
68    pub(crate) input: crate::fast::layers::input::PaintingInput,
69    /// How the views prepainted inside the content were laid out.
70    pub(crate) view_layouts: FxHashMap<GlobalElementId, crate::fast::layers::reuse::KeptLayout>,
71    /// What prepainting the content added to the accessibility tree.
72    pub(crate) a11y: Option<Rc<crate::fast::a11y::A11yStretch>>,
73}
74
75/// What a container's prepaint decided, for its paint to carry out.
76pub(crate) enum Prepainted {
77    /// The content was prepainted into the layer, and is painted into it.
78    Repaint(Painting),
79    /// The content was not prepainted; the layer's tiles are composited.
80    #[allow(dead_code, reason = "the input stream reads the viewport")]
81    Composite {
82        viewport: Bounds<Pixels>,
83        scroll_offset: Point<Pixels>,
84    },
85}
86
87/// What a container decided for its children this frame, from
88/// [`begin_children`] to [`end_children`].
89#[derive(Clone, Copy)]
90pub(crate) struct Children {
91    decision: Decision,
92    scroll_offset: Point<Pixels>,
93    /// Whether the container has a layer entry and bypasses it this frame:
94    /// its prepaint ends noting whether its content placed a surface.
95    without_layer: bool,
96}
97
98/// Whether the content of a layer is being prepainted or painted: nested
99/// retained views then record nothing and reuse nothing, the layer being
100/// their retention (spec §6.3).
101#[inline]
102pub(crate) fn inside_layer(window: &Window) -> bool {
103    window.fast_layers.painting.is_some()
104}
105
106impl Window {
107    /// The bounds a native or external GPU surface placed by the element
108    /// being prepainted shows within, for the element to clip the surface
109    /// to rather than [`Window::content_mask`]. While a scroll layer's
110    /// content is painted, the content mask also covers the overscan painted
111    /// around the viewport, which a surface clipped to it would show over;
112    /// hitboxes are clipped to the viewport the same way
113    /// (`fast::layers::input::hitbox_mask`).
114    pub fn surface_clip(&self) -> Bounds<Pixels> {
115        let mask = self.content_mask().bounds;
116        match &self.fast_layers.painting {
117            Some(painting) => mask.intersect(&painting.viewport),
118            None => mask,
119        }
120    }
121}
122
123/// Decides what the container `id`, prepainting its children at
124/// `scroll_offset`, does with them, and sets up their prepaint for it.
125/// `bounds` are the container's, `child_min` and `content_size` where its
126/// children lie before scrolling.
127#[allow(clippy::too_many_arguments)]
128#[inline(always)]
129pub(crate) fn begin_children(
130    window: &mut Window,
131    cx: &mut App,
132    id: Option<&GlobalElementId>,
133    bounds: Bounds<Pixels>,
134    child_min: Point<Pixels>,
135    content_size: Size<Pixels>,
136    scroll_offset: Point<Pixels>,
137    style: &Style,
138) -> Children {
139    // Nearly every div: it does not scroll, and has no offset to snap.
140    if !scrolls(style) && scroll_offset == Point::default() {
141        return Children {
142            decision: Decision::Bypass,
143            scroll_offset,
144            without_layer: false,
145        };
146    }
147    begin_scrolling_children(
148        window,
149        cx,
150        id,
151        bounds,
152        child_min,
153        content_size,
154        scroll_offset,
155        style,
156    )
157}
158
159#[allow(clippy::too_many_arguments)]
160#[inline(never)]
161fn begin_scrolling_children(
162    window: &mut Window,
163    cx: &mut App,
164    id: Option<&GlobalElementId>,
165    bounds: Bounds<Pixels>,
166    child_min: Point<Pixels>,
167    content_size: Size<Pixels>,
168    scroll_offset: Point<Pixels>,
169    style: &Style,
170) -> Children {
171    let scroll_offset = snap_scroll_offset(window, scroll_offset);
172    let bypass = Children {
173        decision: Decision::Bypass,
174        scroll_offset,
175        without_layer: false,
176    };
177    if !COMPILED {
178        return bypass;
179    }
180    let Some(id) = id else {
181        return bypass;
182    };
183    if !scrolls(style) || inside_layer(window) || !active(window, cx) {
184        return bypass;
185    }
186    let viewport = window.content_mask().bounds;
187    let decision = policy::decide(window, cx, id, bounds, content_size, scroll_offset);
188    let mut decision = crate::fast::layers::input::decide(window, id, decision);
189    if decision == Decision::Composite
190        && window.fast_layers.layers.get(id).is_none_or(|layer| {
191            layer.record.as_ref().is_none_or(|record| {
192                crate::fast::a11y::layer_needs_repaint(window, record.a11y.as_deref())
193            })
194        })
195    {
196        decision = Decision::Repaint;
197    }
198    match decision {
199        Decision::Bypass => {
200            return Children {
201                without_layer: true,
202                ..bypass
203            };
204        }
205        Decision::Composite => {
206            layer_mut(window, id).prepainted = Some(Prepainted::Composite {
207                viewport,
208                scroll_offset,
209            });
210            crate::fast::layers::reuse::carry_prepaint(window, id, viewport, scroll_offset);
211        }
212        Decision::Repaint => {
213            let content_origin = if child_min.x == Pixels::MAX {
214                bounds.origin
215            } else {
216                child_min
217            };
218            let content = Bounds {
219                origin: content_origin + scroll_offset,
220                size: content_size,
221            };
222            let painted_region = painted_region(viewport, content, style.overflow);
223            let start = window.prepaint_index();
224            window.fast_layers.painting = Some(Painting {
225                id: id.clone(),
226                viewport,
227                painted_region,
228                scene: Scene::default(),
229                scroll_offset,
230                translation: translation(window, scroll_offset),
231                prepaint_range: start.clone()..start,
232                recording: Some(cx.begin_recording_dependencies()),
233                dependencies: RenderDependencies::default(),
234                input: Default::default(),
235                view_layouts: FxHashMap::default(),
236                a11y: None,
237            });
238            // Culling works in the painted region, not in the viewport and
239            // whatever clips it; the composite clips to those.
240            window.content_mask_stack.push(ContentMask {
241                bounds: painted_region,
242            });
243        }
244    }
245    Children {
246        decision,
247        scroll_offset,
248        without_layer: false,
249    }
250}
251
252/// Prepaints a container's children as [`begin_children`] decided: `f` is
253/// the children's prepaint, run at the container's scroll offset unless
254/// the layer is composited.
255#[inline(always)]
256pub(crate) fn prepaint_children(
257    window: &mut Window,
258    children: Children,
259    f: impl FnOnce(&mut Window),
260) {
261    if children.decision != Decision::Composite {
262        window.with_element_offset(children.scroll_offset, f);
263    }
264}
265
266/// Ends what [`begin_children`] began, once the children are prepainted.
267#[inline(always)]
268pub(crate) fn end_children(
269    window: &mut Window,
270    cx: &mut App,
271    id: Option<&GlobalElementId>,
272    children: Children,
273) {
274    if children.without_layer
275        && let Some(id) = id
276    {
277        policy::note_surfaces_without_layer(window, id);
278    }
279    if children.decision != Decision::Repaint {
280        return;
281    }
282    end_repainted_children(window, cx);
283}
284
285#[inline(never)]
286fn end_repainted_children(window: &mut Window, cx: &mut App) {
287    window.content_mask_stack.pop();
288    let Some(mut painting) = window.fast_layers.painting.take() else {
289        debug_assert!(false, "a layer's prepaint ended without beginning");
290        return;
291    };
292    painting.prepaint_range.end = window.prepaint_index();
293    policy::note_surfaces_placed(window, &painting.id);
294    painting.a11y = crate::fast::a11y::capture(window, &painting.prepaint_range);
295    if let Some(recording) = painting.recording.take() {
296        painting.dependencies = cx.finish_recording_dependencies(recording).all;
297    }
298    let id = painting.id.clone();
299    layer_mut(window, &id).prepainted = Some(Prepainted::Repaint(painting));
300}
301
302/// Paints a container's children as its prepaint decided: `f` is the
303/// children's paint.
304#[inline(always)]
305pub(crate) fn paint_children(
306    window: &mut Window,
307    cx: &mut App,
308    id: Option<&GlobalElementId>,
309    f: impl FnOnce(&mut Window, &mut App),
310) {
311    if window.fast_layers.layers.is_empty() {
312        return f(window, cx);
313    }
314    paint_children_of_layers(window, cx, id, f)
315}
316
317#[inline(never)]
318fn paint_children_of_layers(
319    window: &mut Window,
320    cx: &mut App,
321    id: Option<&GlobalElementId>,
322    f: impl FnOnce(&mut Window, &mut App),
323) {
324    let prepainted = match id {
325        Some(id) if !window.fast_layers.layers.is_empty() => window
326            .fast_layers
327            .layers
328            .get_mut(id)
329            .and_then(|layer| layer.prepainted.take()),
330        _ => None,
331    };
332    match prepainted {
333        None => f(window, cx),
334        Some(Prepainted::Repaint(painting)) => match bake_background(window) {
335            Some(background) => repaint(window, cx, painting, background, f),
336            None => paint_unbaked(window, cx, painting, f),
337        },
338        Some(Prepainted::Composite { scroll_offset, .. }) => {
339            if let Some(id) = id {
340                crate::fast::layers::reuse::carry_paint(window, id);
341                composite(window, id, scroll_offset);
342            }
343        }
344    }
345}
346
347/// The opaque colour a layer's tiles are cleared with: what the frame has
348/// painted so far under the viewport, the current content mask, if it is
349/// one solid quad covering it (spec §5.2).
350/// Whether the layer of `id` replays its content into the frame rather than
351/// compositing tiles of it: a list's does. Its rows' paint operations are
352/// drawn again, moved, over the viewport, costing the frame what drawing
353/// the rows it shows costs, without rendering, laying out or prepainting
354/// them again, and without tiles to rasterize or to keep within budget.
355pub(crate) fn replays(window: &Window, id: &GlobalElementId) -> bool {
356    window
357        .fast_layers
358        .layers
359        .get(id)
360        .is_some_and(|layer| layer.rows.list)
361}
362
363pub(crate) fn bake_background(window: &Window) -> Option<Rgba> {
364    let window_opaque =
365        window.platform_window.background_appearance() == WindowBackgroundAppearance::Opaque;
366    let viewport = window.snapped_content_mask().bounds;
367    background::bake(&window.next_frame.scene, viewport, window_opaque)
368}
369
370/// Paints content prepainted for a layer straight into the frame, as
371/// without one, because the layer's tiles could not be cleared with what is
372/// under them. The layer keeps no content, so that it is painted afresh.
373fn paint_unbaked(
374    window: &mut Window,
375    cx: &mut App,
376    painting: Painting,
377    f: impl FnOnce(&mut Window, &mut App),
378) {
379    let id = painting.id.clone();
380    // Nested views were prepainted inside the layer, and are painted so.
381    window.fast_layers.painting = Some(painting);
382    f(window, cx);
383    window.fast_layers.painting = None;
384    crate::fast::layers::policy::defer_unbaked(window, &id);
385}
386
387/// Carries out a `Composite` decision for the container `id`, scrolled to
388/// `scroll_offset`: the layer's content stands, cleared with the background
389/// now under it, and is composited at the offset.
390fn composite(window: &mut Window, id: &GlobalElementId, scroll_offset: Point<Pixels>) {
391    let translation = translation(window, scroll_offset);
392    composite_at(window, id, translation);
393}
394
395/// Composites the layer of the container `id` with its content moved by
396/// `translation` into window space, its content standing, cleared with the
397/// background now under it.
398pub(crate) fn composite_at(
399    window: &mut Window,
400    id: &GlobalElementId,
401    translation: Point<ScaledPixels>,
402) {
403    if replays(window, id) {
404        insert_layer(window, id, translation, 0);
405        return;
406    }
407    let background = bake_background(window);
408    let layer = layer_mut(window, id);
409    let Some(current) = layer.record.as_ref().map(|record| record.background) else {
410        return;
411    };
412    if background.is_some_and(|background| background != current) {
413        layer.next_generation();
414    }
415    let generation = layer.generation;
416    let record = layer.record.as_mut().expect("checked above");
417    let mut dirtied = 0;
418    match background {
419        Some(background) if background == record.background => {}
420        Some(background) => {
421            // Every tile is cleared with another colour: a new generation of
422            // the same content, all of it dirty.
423            record.background = background;
424            record.generation = generation;
425            record.dirty_tiles = all_tiles(&record.tile_hashes);
426            dirtied = record.dirty_tiles.len();
427        }
428        None => {
429            // The tiles cannot be cleared with what is under them now: the
430            // content is drawn into the frame, and painted afresh next time.
431            let record = layer.record.take().expect("checked above");
432            crate::fast::layers::policy::defer_unbaked(window, id);
433            draw_into_frame(window, record.content.operations(), translation);
434            let viewports = viewports(window);
435            insert_overlay(
436                &mut window.next_frame.scene,
437                &record.overlay,
438                translation,
439                viewports,
440            );
441            return;
442        }
443    }
444    insert_layer(window, id, translation, dirtied);
445}
446
447/// Composites the layer of the container `id` into the frame at
448/// `translation`, `dirtied` of its tiles new this frame: its tile quads
449/// over the viewport, the current content mask, and its [`LayerFrame`].
450/// Content whose overlay cannot be drawn over its tiles
451/// ([`LayerRecord::has_paths`]) is drawn into the frame instead.
452pub(crate) fn insert_layer(
453    window: &mut Window,
454    id: &GlobalElementId,
455    translation: Point<ScaledPixels>,
456    dirtied: usize,
457) {
458    let viewport = window.snapped_content_mask().bounds;
459    let Some(layer) = window.fast_layers.layers.get(id) else {
460        return;
461    };
462    let Some(record) = layer.record.as_ref() else {
463        return;
464    };
465    if layer.rows.list {
466        let content = record.content.clone();
467        let viewport = viewports(window).snapped;
468        let in_content = Bounds {
469            origin: viewport.origin - translation,
470            size: viewport.size,
471        };
472        draw_into_frame(window, content.operations_over(in_content), translation);
473        let stats = &mut window.layout_engine.as_mut().unwrap().retention.stats;
474        stats.layer_frames_composited += 1;
475        policy::note_work(window, id, 0.);
476        return;
477    }
478    if record.has_paths {
479        let content = record.content.clone();
480        draw_into_frame(window, content.operations(), translation);
481        return;
482    }
483    let viewports = viewports(window);
484    insert_tile_quads(&mut window.next_frame.scene, layer, viewport, translation);
485    insert_overlay(
486        &mut window.next_frame.scene,
487        &record.overlay,
488        translation,
489        viewports,
490    );
491    let stats = &mut window.layout_engine.as_mut().unwrap().retention.stats;
492    stats.layer_frames_composited += 1;
493    stats.tiles_dirtied += dirtied as u64;
494    policy::note_work(window, id, 0.);
495}
496
497/// Inserts into `scene` the quads of the tiles of `layer` that show in
498/// `viewport` with its content moved by `translation`, all at one draw
499/// order, and the layer's [`LayerFrame`] they are rasterized from (spec
500/// §5.1).
501pub(crate) fn insert_tile_quads(
502    scene: &mut Scene,
503    layer: &Layer,
504    viewport: Bounds<ScaledPixels>,
505    translation: Point<ScaledPixels>,
506) {
507    let Some(record) = layer.record.as_ref() else {
508        return;
509    };
510    if viewport.is_empty() {
511        return;
512    }
513    let frame = LayerFrame {
514        key: layer.key,
515        generation: record.generation,
516        background: record.background,
517        tile_size: TILE_SIZE,
518        content: record.content.clone(),
519        dirty_tiles: record.dirty_tiles.clone(),
520    };
521    let size = TILE_SIZE as f32;
522    let content_viewport = Bounds {
523        origin: viewport.origin - translation,
524        size: viewport.size,
525    };
526    let min = content_viewport.origin;
527    let max = content_viewport.bottom_right();
528    let (x0, y0) = (
529        (min.x.0 / size).floor() as i32,
530        (min.y.0 / size).floor() as i32,
531    );
532    let (x1, y1) = (
533        (max.x.0 / size).ceil() as i32,
534        (max.y.0 / size).ceil() as i32,
535    );
536    scene.push_layer(viewport);
537    let texture_id = layer_tile_texture_id(layer.key);
538    for y in y0..y1 {
539        for x in x0..x1 {
540            let coord = TileCoord { x, y };
541            let tile = frame.tile_bounds(coord);
542            scene.insert_primitive(PolychromeSprite {
543                order: 0,
544                pad: 0,
545                grayscale: false.into(),
546                opacity: 1.,
547                bounds: Bounds {
548                    origin: tile.origin + translation,
549                    size: tile.size,
550                },
551                content_mask: ContentMask { bounds: viewport },
552                corner_radii: Corners::default(),
553                tile: AtlasTile {
554                    texture_id,
555                    tile_id: layer_tile_id(coord),
556                    padding: 0,
557                    bounds: Bounds {
558                        origin: Point::default(),
559                        size: size2(
560                            DevicePixels(TILE_SIZE as i32),
561                            DevicePixels(TILE_SIZE as i32),
562                        ),
563                    },
564                },
565            });
566        }
567    }
568    scene.pop_layer();
569    scene.layers.frames.push(frame);
570}
571
572/// Inserts into `scene` the overlay a layer keeps apart from its tiles,
573/// moved by `translation` and clipped to `viewport`, after its tile quads,
574/// so that it is drawn over them (see `fast::layers::overlay`).
575fn insert_overlay(
576    scene: &mut Scene,
577    overlay: &[Primitive],
578    translation: Point<ScaledPixels>,
579    viewports: Viewports,
580) {
581    for primitive in overlay {
582        let mut primitive = translate_primitive(primitive, translation);
583        clip_primitive(&mut primitive, viewports);
584        scene.insert_primitive(primitive);
585    }
586}
587
588/// The viewport content drawn into the frame is clipped to: the current
589/// content mask, snapped to device pixels as the frame snaps every
590/// primitive's but a path's, and on [`snap_path`]'s grid, as
591/// `Window::paint_path` takes it, for paths.
592#[derive(Clone, Copy)]
593struct Viewports {
594    snapped: Bounds<ScaledPixels>,
595    exact: Bounds<ScaledPixels>,
596}
597
598fn viewports(window: &Window) -> Viewports {
599    Viewports {
600        snapped: window.snapped_content_mask().bounds,
601        exact: snap_bounds(window.content_mask().bounds.scale(window.scale_factor())),
602    }
603}
604
605/// How finely [`snap_path`] places path vertices: 256 steps a device pixel,
606/// as fine as a GPU rasterizer resolves a vertex's position.
607const PATH_GRID: f32 = 256.;
608
609/// `curve`, scaled to device pixels, with its end and control points on the
610/// grid of [`PATH_GRID`] steps a device pixel where layers are compiled.
611///
612/// A path painted into a layer is drawn moved by whole device pixels, while
613/// drawn without a layer it is painted where it is now: at a fractional
614/// scale factor the two differ by rounding error in the last bits of each
615/// position (a snapped scroll offset is not a whole number of logical
616/// pixels). On the grid they land on the same positions, as the curve's
617/// coefficients worked out from them again do.
618pub(crate) fn snap_curve(curve: crate::PathCurve) -> crate::PathCurve {
619    if !COMPILED {
620        return curve;
621    }
622    let snap_f32 = |p: Point<f32>| Point {
623        x: snap(ScaledPixels(p.x)).0,
624        y: snap(ScaledPixels(p.y)).0,
625    };
626    // `PathCurve::new`: a = p0 - 2·ctrl + p1, b = 2·(ctrl - p0).
627    let (p0, p1) = (snap_f32(curve.p0), snap_f32(curve.p1));
628    if curve.a.x == 0. && curve.a.y == 0. {
629        // A line stays one: its control point is halfway, off the grid.
630        return crate::PathCurve {
631            p0,
632            p1,
633            b: Point {
634                x: p1.x - p0.x,
635                y: p1.y - p0.y,
636            },
637            ..curve
638        };
639    }
640    let ctrl = snap_f32(Point {
641        x: curve.p0.x + curve.b.x / 2.,
642        y: curve.p0.y + curve.b.y / 2.,
643    });
644    crate::PathCurve {
645        p0,
646        p1,
647        a: Point {
648            x: p0.x - 2. * ctrl.x + p1.x,
649            y: p0.y - 2. * ctrl.y + p1.y,
650        },
651        b: Point {
652            x: 2. * (ctrl.x - p0.x),
653            y: 2. * (ctrl.y - p0.y),
654        },
655        ..curve
656    }
657}
658
659/// A path's content mask, in device pixels, on the grid of [`PATH_GRID`]
660/// steps a device pixel where layers are compiled.
661///
662/// A path painted into a layer is drawn moved by whole device pixels, while
663/// drawn without a layer it is painted where it is now: at a fractional
664/// scale factor the two masks differ by rounding error in the last bits (a
665/// snapped scroll offset is not a whole number of logical pixels), and a
666/// layer's overlay clips the path to the viewport where it is drawn, which
667/// must come out as the mask painted there. On the grid they agree.
668pub(crate) fn snap_mask(
669    mask: crate::ContentMask<ScaledPixels>,
670) -> crate::ContentMask<ScaledPixels> {
671    if !COMPILED {
672        return mask;
673    }
674    crate::ContentMask {
675        bounds: snap_bounds(mask.bounds),
676    }
677}
678
679/// `bounds`, the interior a quad's border is split around, shrunk to the
680/// grid of [`PATH_GRID`] steps a device pixel where layers are compiled.
681///
682/// The interior is worked out from the quad's position: a quad painted into
683/// a layer and moved by whole device pixels would otherwise split a rounding
684/// error away from the same quad painted where it is now. Shrinking keeps
685/// the interior inside the border; the strips around it still cover the rest.
686pub(crate) fn snap_inside(bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
687    if !COMPILED || bounds.is_empty() {
688        return bounds;
689    }
690    let on_grid = |value: ScaledPixels, round: fn(f32) -> f32| {
691        let steps = value.0 * PATH_GRID;
692        if steps.abs() < 4_194_304. {
693            ScaledPixels(round(steps) / PATH_GRID)
694        } else {
695            value
696        }
697    };
698    let origin = Point {
699        x: on_grid(bounds.origin.x, f32::ceil),
700        y: on_grid(bounds.origin.y, f32::ceil),
701    };
702    let corner = bounds.bottom_right();
703    let corner = Point {
704        x: on_grid(corner.x, f32::floor),
705        y: on_grid(corner.y, f32::floor),
706    };
707    Bounds::from_corners(origin, corner)
708}
709
710/// `value` on the grid of [`PATH_GRID`] steps a device pixel.
711fn snap(value: ScaledPixels) -> ScaledPixels {
712    // Adding and taking away 1.5 × 2^23 rounds an `f32` below 2^22 in
713    // magnitude to a whole number, ties to even, which a shift by whole
714    // pixels (a multiple of 256 steps) keeps; `floor` would call into libm.
715    const ROUNDER: f32 = 12_582_912.;
716    let steps = value.0 * PATH_GRID;
717    if steps.abs() < 4_194_304. {
718        ScaledPixels(((steps + ROUNDER) - ROUNDER) / PATH_GRID)
719    } else {
720        value
721    }
722}
723
724fn snap_point(point: Point<ScaledPixels>) -> Point<ScaledPixels> {
725    Point {
726        x: snap(point.x),
727        y: snap(point.y),
728    }
729}
730
731/// `bounds` with its corners on the grid of [`PATH_GRID`] steps a device
732/// pixel, as [`snap_path`] puts a path's.
733fn snap_bounds(bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
734    Bounds::from_corners(snap_point(bounds.origin), snap_point(bounds.bottom_right()))
735}
736
737/// Carries into `scene` the [`LayerFrame`]s of the tile quads that
738/// `scene.replay` copies from the operations `range` of `previous`, so
739/// that a retained subtree holding a layer composites it when it is reused.
740pub(crate) fn replay_layers(scene: &mut Scene, range: Range<usize>, previous: &Scene) {
741    if previous.layers.frames.is_empty() {
742        return;
743    }
744    for operation in &previous.paint_operations[range] {
745        let PaintOperation::Primitive(Primitive::PolychromeSprite(sprite)) = operation else {
746            continue;
747        };
748        let Some((key, _)) = decode_layer_tile(sprite.tile.texture_id, sprite.tile.tile_id) else {
749            continue;
750        };
751        if scene.layers.frames.iter().any(|frame| frame.key == key) {
752            continue;
753        }
754        if let Some(frame) = previous.layers.frames.iter().find(|frame| frame.key == key) {
755            scene.layers.frames.push(frame.clone());
756        }
757    }
758}
759
760/// Draws the primitives of `content`, moved by `delta` into window space,
761/// straight into the frame, clipped to the viewport, the current content
762/// mask: what painting the content into the frame would have drawn.
763pub(crate) fn draw_into_frame<'a>(
764    window: &mut Window,
765    operations: impl IntoIterator<Item = &'a PaintOperation>,
766    delta: Point<ScaledPixels>,
767) {
768    let viewports = viewports(window);
769    let viewport = viewports.snapped;
770    let scene = &mut window.next_frame.scene;
771    // A split quad's pieces are inserted together, as they were painted.
772    let mut quads = crate::fast::scene::QuadRun::default();
773    for operation in operations {
774        if let PaintOperation::Primitive(primitive @ Primitive::Quad(_)) = operation {
775            let mut primitive = translate_primitive(primitive, delta);
776            clip_primitive(&mut primitive, viewports);
777            if let Primitive::Quad(quad) = primitive {
778                quads.push(scene, quad);
779            }
780            continue;
781        }
782        quads.flush(scene);
783        match operation {
784            PaintOperation::Primitive(primitive) => {
785                let mut primitive = translate_primitive(primitive, delta);
786                clip_primitive(&mut primitive, viewports);
787                scene.insert_primitive(primitive);
788            }
789            PaintOperation::StartLayer(bounds) => {
790                let bounds = Bounds {
791                    origin: bounds.origin + delta,
792                    size: bounds.size,
793                };
794                scene.push_layer(bounds.intersect(&viewport));
795            }
796            PaintOperation::EndLayer => scene.pop_layer(),
797            PaintOperation::FastRoundedClip(clip) => {
798                crate::fast::rounded_clip::record(scene, clip.translated(delta))
799            }
800        }
801    }
802    quads.flush(scene);
803}
804
805/// Narrows every content mask `primitive` carries to `viewports`.
806fn clip_primitive(primitive: &mut Primitive, viewports: Viewports) {
807    let mask = match primitive {
808        Primitive::Path(_) => &viewports.exact,
809        _ => &viewports.snapped,
810    };
811    let clip = |content_mask: &mut ContentMask<ScaledPixels>| {
812        content_mask.bounds = content_mask.bounds.intersect(mask);
813    };
814    match primitive {
815        Primitive::Shadow(p) => clip(&mut p.content_mask),
816        Primitive::Quad(p) => clip(&mut p.content_mask),
817        Primitive::Path(p) => p.clip_content_mask(mask),
818        Primitive::Underline(p) => clip(&mut p.content_mask),
819        Primitive::MonochromeSprite(p) => clip(&mut p.content_mask),
820        Primitive::SubpixelSprite(p) => clip(&mut p.content_mask),
821        Primitive::PolychromeSprite(p) => clip(&mut p.content_mask),
822        Primitive::Surface(p) => clip(&mut p.content_mask),
823        Primitive::NativeView(p) => clip(&mut p.content_mask),
824    }
825}
826
827/// Every tile of `hashes`, sorted.
828pub(crate) fn all_tiles(hashes: &FxHashMap<TileCoord, u64>) -> Vec<TileCoord> {
829    let mut all: Vec<_> = hashes.keys().copied().collect();
830    all.sort();
831    all
832}
833
834/// Paints the content into the layer's scene and records it.
835fn repaint(
836    window: &mut Window,
837    cx: &mut App,
838    mut painting: Painting,
839    background: Rgba,
840    f: impl FnOnce(&mut Window, &mut App),
841) {
842    window.content_mask_stack.push(ContentMask {
843        bounds: painting.painted_region,
844    });
845    mem::swap(&mut window.next_frame.scene, &mut painting.scene);
846    let paint_start = window.paint_index();
847    window.take_hover_reads();
848    let hovers_start = window.retained_state.hover_dependencies.len();
849    let recording = cx.begin_recording_dependencies();
850    window.fast_layers.painting = Some(painting);
851
852    f(window, cx);
853
854    let mut painting = window
855        .fast_layers
856        .painting
857        .take()
858        .expect("the layer being painted");
859    let paint_dependencies = cx.finish_recording_dependencies(recording).all;
860    window.take_hover_reads();
861    let hovers: Rc<[_]> = window.retained_state.hover_dependencies[hovers_start..].into();
862    let paint_end = window.paint_index();
863    mem::swap(&mut window.next_frame.scene, &mut painting.scene);
864    window.content_mask_stack.pop();
865
866    let scale_factor = window.scale_factor();
867    let translation = painting.translation;
868    let to_content = point(
869        ScaledPixels(-translation.x.0),
870        ScaledPixels(-translation.y.0),
871    );
872    let content = translated_scene(&painting.scene, to_content);
873    let region = painting.painted_region.scale(scale_factor);
874    let region = Bounds {
875        origin: region.origin + to_content,
876        size: region.size,
877    };
878    let (content, overlay) = crate::fast::layers::overlay::lift(content);
879    let has_paths = content
880        .paint_operations
881        .iter()
882        .any(|operation| matches!(operation, PaintOperation::Primitive(Primitive::Path(_))));
883    let mut visible = painting.viewport.scale(scale_factor);
884    visible.origin += to_content;
885    let mut rendered_work = 0;
886    let mut visible_work = 0;
887    for operation in &content.paint_operations {
888        if let PaintOperation::Primitive(primitive) = operation {
889            rendered_work += 1;
890            visible_work += usize::from(visible_bounds(primitive).intersects(&visible));
891        }
892    }
893    policy::note_work(
894        window,
895        &painting.id,
896        rendered_work as f32 / visible_work.max(1) as f32 * crate::fast::layers::work::REPAINT_COST,
897    );
898    let hashes = tile_hashes(&content, TILE_SIZE, region);
899
900    let views = crate::fast::layers::invalidate::content_views(window, &painting.prepaint_range);
901    let layer = layer_mut(window, &painting.id);
902    let generation = layer.next_generation();
903    let dirty = match &layer.record {
904        Some(old) if old.background == background => dirty_tiles(&old.tile_hashes, &hashes),
905        _ => all_tiles(&hashes),
906    };
907    layer.record = Some(LayerRecord {
908        content: LayerContent::from(content),
909        generation,
910        painted_region: painting.painted_region,
911        viewport: painting.viewport,
912        scroll_offset: painting.scroll_offset,
913        translation,
914        prepaint_range: painting.prepaint_range,
915        paint_range: paint_start..paint_end,
916        tile_hashes: hashes,
917        dirty_tiles: dirty,
918        background,
919        hovers,
920        dependencies: painting.dependencies.union(&paint_dependencies),
921        views,
922        has_paths,
923        overlay,
924        view_layouts: Rc::new(mem::take(&mut painting.view_layouts)),
925        a11y: painting.a11y.take(),
926    });
927    let dirtied = layer
928        .record
929        .as_ref()
930        .map_or(0, |record| record.dirty_tiles.len());
931    crate::fast::layers::input::painted(window, &painting.id, painting.input);
932    window
933        .layout_engine
934        .as_mut()
935        .unwrap()
936        .retention
937        .stats
938        .layer_frames_repainted += 1;
939    insert_layer(window, &painting.id, translation, dirtied);
940}
941
942/// Ends the layers' part of the frame being drawn, before it becomes the
943/// rendered frame.
944pub(crate) fn finish_frame(window: &mut Window) {
945    debug_assert!(window.fast_layers.painting.is_none());
946    for layer in window.fast_layers.layers.values_mut() {
947        layer.prepainted = None;
948        layer.rows.finish_frame();
949    }
950}
951
952/// The layer of the container `id`, made if it has none.
953pub(crate) fn layer_mut<'a>(window: &'a mut Window, id: &GlobalElementId) -> &'a mut Layer {
954    let layers = &mut window.fast_layers;
955    if !layers.layers.contains_key(id) {
956        let key = LayerKey(layers.next_key % crate::fast::layers::scene::LAYER_KEY_LIMIT);
957        layers.next_key = (layers.next_key + 1) % crate::fast::layers::scene::LAYER_KEY_LIMIT;
958        layers.layers.insert(
959            id.clone(),
960            Layer {
961                key,
962                generation: 0,
963                record: None,
964                policy: Default::default(),
965                input: Default::default(),
966                rows: Default::default(),
967                last_composited_frame: layers.frame,
968                prepainted: None,
969            },
970        );
971    }
972    layers.layers.get_mut(id).unwrap()
973}
974
975/// Whether `style` scrolls on some axis.
976fn scrolls(style: &Style) -> bool {
977    style.overflow.x == Overflow::Scroll || style.overflow.y == Overflow::Scroll
978}
979
980/// The part of the content a layer paints: the viewport, and one viewport's
981/// extent on each side along the scrolled axes as far as the content goes.
982/// How far past the viewport a layer paints on each scrolled side, in
983/// viewport extents. Measured on `gpui_perf`'s scroll scenarios: 2 cut the
984/// mean frame of scroll-child-view by 44 % and of scroll-same-view by 21 %
985/// against 1, at the cost of repaint frames about 1.7 times as long (one per
986/// two viewports scrolled); 0.5 more than doubled the mean.
987pub(crate) const OVERSCAN_VIEWPORTS: f32 = 2.;
988
989pub(crate) fn painted_region(
990    viewport: Bounds<Pixels>,
991    content: Bounds<Pixels>,
992    overflow: Point<Overflow>,
993) -> Bounds<Pixels> {
994    fn extend(
995        min: Pixels,
996        extent: Pixels,
997        content_min: Pixels,
998        content_extent: Pixels,
999    ) -> (Pixels, Pixels) {
1000        let max = min + extent;
1001        let over = extent * OVERSCAN_VIEWPORTS;
1002        let low = (min - over).max(content_min).min(min);
1003        let high = (max + over).min(content_min + content_extent).max(max);
1004        (low, high - low)
1005    }
1006    let mut region = viewport;
1007    if overflow.x == Overflow::Scroll {
1008        (region.origin.x, region.size.width) = extend(
1009            viewport.origin.x,
1010            viewport.size.width,
1011            content.origin.x,
1012            content.size.width,
1013        );
1014    }
1015    if overflow.y == Overflow::Scroll {
1016        (region.origin.y, region.size.height) = extend(
1017            viewport.origin.y,
1018            viewport.size.height,
1019            content.origin.y,
1020            content.size.height,
1021        );
1022    }
1023    region
1024}
1025
1026/// A layer's translation at `scroll_offset`: the offset in whole device
1027/// pixels.
1028pub(crate) fn translation(window: &Window, scroll_offset: Point<Pixels>) -> Point<ScaledPixels> {
1029    let scale_factor = window.scale_factor();
1030    point(
1031        ScaledPixels((scroll_offset.x.0 * scale_factor).round()),
1032        ScaledPixels((scroll_offset.y.0 * scale_factor).round()),
1033    )
1034}
1035
1036/// `scene` moved by `delta`, finished.
1037fn translated_scene(scene: &Scene, delta: Point<ScaledPixels>) -> Scene {
1038    let mut translated = Scene::default();
1039    for operation in &scene.paint_operations {
1040        match operation {
1041            PaintOperation::Primitive(primitive) => {
1042                translated.insert_primitive(translate_primitive(primitive, delta))
1043            }
1044            PaintOperation::StartLayer(bounds) => translated.push_layer(Bounds {
1045                origin: bounds.origin + delta,
1046                size: bounds.size,
1047            }),
1048            PaintOperation::EndLayer => translated.pop_layer(),
1049            PaintOperation::FastRoundedClip(clip) => {
1050                crate::fast::rounded_clip::record(&mut translated, clip.translated(delta))
1051            }
1052        }
1053    }
1054    translated.finish();
1055    translated
1056}
1057
1058/// `offset`, a scroll offset about to be applied, moved to whole device
1059/// pixels where layers are compiled, with or without a layer, so that a
1060/// layer's content and content drawn without one land on the same pixels
1061/// (spec §5.3).
1062pub(crate) fn snap_scroll_offset(window: &Window, offset: Point<Pixels>) -> Point<Pixels> {
1063    snap_offset(offset, window.scale_factor(), COMPILED)
1064}
1065
1066/// [`snap_scroll_offset`] at `scale_factor`, snapping only when `compiled`,
1067/// rounding as [`Window::pixel_snap`] does.
1068pub(crate) fn snap_offset(
1069    offset: Point<Pixels>,
1070    scale_factor: f32,
1071    compiled: bool,
1072) -> Point<Pixels> {
1073    if !compiled {
1074        return offset;
1075    }
1076    offset.map(|value| {
1077        crate::px(crate::util::round_half_toward_zero(value.0 * scale_factor) / scale_factor)
1078    })
1079}