Truly independent web browser
LibCompositing+Compositor: Keep the visual context tree out of painters
Aliaksandr Kalenika56f8805307f
diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cppindex 5fa04a7efad..f45c1ef20b5 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp@@ -95,15 +95,10 @@ bool DisplayList::requires_direct_replay_without_nested_lists(AccumulatedVisualCreturn RustFFI::display_list_storage_requires_direct_replay_without_nested_lists(m_storage, visual_context_tree.rust_handle());}-void DisplayList::replay(AccumulatedVisualContextTree const& visual_context_tree, RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const+void DisplayList::replay(AccumulatedVisualContextTree const& visual_context_tree, RustFFI::FfiRasterPainter const& painter, i64 time_nanoseconds) const{VERIFY(m_compatible_visual_context_tree_structural_epoch == visual_context_tree.structural_epoch());- RustFFI::display_list_replay(visual_context_tree.rust_handle(), m_storage, m_root_group_color, &callbacks);-}--void DisplayList::replay_records(ReadonlyBytes records, RustFFI::FfiDisplayListReplayCallbacks const& callbacks)-{- RustFFI::display_list_replay_records(records.data(), records.size(), &callbacks);+ RustFFI::display_list_replay(visual_context_tree.rust_handle(), m_storage, m_root_group_color, time_nanoseconds, &painter);}u64 DisplayList::tape_size() constdiff --git a/Libraries/LibCompositing/DisplayList/DisplayList.h b/Libraries/LibCompositing/DisplayList/DisplayList.hindex b4a3ec7a9f0..82b23228dcf 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.h+++ b/Libraries/LibCompositing/DisplayList/DisplayList.h@@ -28,7 +28,7 @@ namespace Compositing {namespace RustFFI {struct FfiDisplayList;-struct FfiDisplayListReplayCallbacks;+struct FfiRasterPainter;}@@ -109,11 +109,9 @@ public:// display lists it nests.bool requires_direct_replay_without_nested_lists(AccumulatedVisualContextTree const&) const;- // Replays the list through a player's callbacks, against the visual context tree it was made for, with nothing- // scrolled.- void replay(AccumulatedVisualContextTree const&, RustFFI::FfiDisplayListReplayCallbacks const&) const;- // Replays a stream of records that a command of a list being replayed nests, with nothing scrolled.- static void replay_records(ReadonlyBytes records, RustFFI::FfiDisplayListReplayCallbacks const&);+ // Replays the list through a painter, against the visual context tree it was made for, with nothing scrolled and+ // a blinking caret as it shows at the time given.+ void replay(AccumulatedVisualContextTree const&, RustFFI::FfiRasterPainter const&, i64 time_nanoseconds) const;private:// Takes over the storage of a tape that came from another process and passed its checks.diff --git a/Libraries/LibCompositing/DisplayList/DisplayListCommand.h b/Libraries/LibCompositing/DisplayList/DisplayListCommand.hindex c162ddc5c5c..aff1b9e205b 100644--- a/Libraries/LibCompositing/DisplayList/DisplayListCommand.h+++ b/Libraries/LibCompositing/DisplayList/DisplayListCommand.h@@ -15,17 +15,6 @@namespace Compositing {-constexpr i64 caret_blink_interval_ns = 500'000'000;-inline bool caret_is_visible_at_time(PaintCaret const& caret, i64 monotonic_time_ns)-{- if (!caret.should_blink)- return true;- auto elapsed_ns = monotonic_time_ns > caret.blink_cycle_start_time_ns- ? monotonic_time_ns - caret.blink_cycle_start_time_ns- : 0;- return (elapsed_ns / caret_blink_interval_ns) % 2 == 0;-}-template<typename Command>concept DisplayListCommand = requires {Command::command_type;diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rsindex ad5db3d3d6c..ca5d6449397 100644--- a/Libraries/LibCompositing/Rust/build.rs+++ b/Libraries/LibCompositing/Rust/build.rs@@ -406,7 +406,7 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiVisualAnimationTransformOperationKind","FfiCompositorAnimationPublishOutcome","FfiVisualAnimationSummary",- "FfiDisplayListReplayCallbacks",+ "FfiRasterPainter","RecordSpan","FfiReplaySelection","FfiDisplayList",@@ -603,12 +603,35 @@ fn main() -> Result<(), Box<dyn Error>> {// The commands of the canvas 2D stream go into a list of their own, as only the canvas player plays them.let variants = display_list_command_type_variants(&commands_source)?;let mut after_includes = String::new();- for (macro_name, canvas_2d) in [- ("ENUMERATE_DISPLAY_LIST_COMMANDS", false),- ("ENUMERATE_CANVAS_2D_COMMANDS", true),+ // The replay resolves these commands for the frame and hands the painter what they draw, or plays them itself.+ let commands_the_replay_resolves = [+ "FillRect",+ "FillRectWithRoundedCorners",+ "PaintScrollBar",+ "DrawCompositedContext",+ "DeclareMaskContent",+ "DrawIsolatedGroup",+ "PaintNestedDisplayList",+ ];+ let belongs_to_list = |macro_name: &str, name: &str| {+ let is_canvas_2d_command = name.starts_with("Canvas2D");+ match macro_name {+ "ENUMERATE_CANVAS_2D_COMMANDS" => is_canvas_2d_command,+ "ENUMERATE_DISPLAY_LIST_COMMANDS_PLAYED_AS_RECORDED" => {+ !is_canvas_2d_command+ && !name.starts_with("Compositor")+ && !commands_the_replay_resolves.contains(&name)+ }+ _ => !is_canvas_2d_command,+ }+ };+ for macro_name in [+ "ENUMERATE_DISPLAY_LIST_COMMANDS",+ "ENUMERATE_DISPLAY_LIST_COMMANDS_PLAYED_AS_RECORDED",+ "ENUMERATE_CANVAS_2D_COMMANDS",] {after_includes.push_str(&format!("\n#define {macro_name}(V)"));- for name in variants.iter().filter(|name| name.starts_with("Canvas2D") == canvas_2d) {+ for name in variants.iter().filter(|name| belongs_to_list(macro_name, name)) {after_includes.push_str(&format!(" \\\n V({name})"));}after_includes.push('\n');diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rsindex 4bc9d7fda0e..1bc87a92cf1 100644--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs@@ -255,7 +255,8 @@ pub struct ReplayLayer {/// Where a blur() in the backdrop filter mirrors: the region as the clips around the box leave it, in the/// effect's space. None when the filter holds no such blur.pub backdrop_blur_edge: OptionalFloatRect,- pub effect: EffectNodeIndex,+ /// The same for as long as the effect's filters are, which lets a painter keep what it builds from them.+ pub filter_cache_key: u64,/// Bounds of everything replay draws into the layer, in the effect's space, when known.pub content_bounds: OptionalFloatRect,}diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rsindex bebc20ab4ae..85b04ec7f60 100644--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs@@ -8,15 +8,21 @@ use crate::display_list::builder::{for_each_command, has_inline_clip_in_its_own_space, inline_clips_of, inline_transform_of, read_command,};use crate::display_list::commands::{- ClipMode, ClipNodeIndex, DisplayListCommandHeader, DisplayListCommandRun, DisplayListCommandType, EffectNodeIndex,- InlineClipKind, OptionalFloatRect, PaintScrollBar, ReplayClip, ReplayLayer, ReplayMask, SpatialNodeIndex,+ ClipMode, ClipNodeIndex, DeclareMaskContent, DisplayListCommandHeader, DisplayListCommandRun,+ DisplayListCommandType, DisplayListPaintStyleType, DrawCompositedContext, DrawIsolatedGroup, DrawRepeatedTile,+ EffectNodeIndex, FillPath, FillRect, FillRectWithRoundedCorners, InlineClipKind, OptionalFloatRect, PaintCaret,+ PaintNestedDisplayList, PaintScrollBar, PathPaintKind, ReplayClip, ReplayLayer, ReplayMask, SpatialNodeIndex,+ StrokePath,};use crate::display_list::depth_sorted_plan::{DepthSortedReplayStepKind, build_depth_sorted_replay_plan};use crate::display_list::effect_clip_plan::EffectClipPlan;use crate::display_list::effect_geometry::{EffectGeometry, Extent, compute_effect_geometry};-use crate::display_list::ffi_bytes::FfiBytes;use crate::display_list::nested_records::span_bytes;-use crate::host::RecordSpan;+use crate::display_list::storage::DisplayListStorage;+use crate::host::{+ CompositedContextDraw, IsolatedGroup, NestedDisplayListPlacement, NestedDisplayListReplay, PresentedScrollbar,+ RecordSpan, ResolvedFillRect, ResolvedFillRectWithRoundedCorners, TileRaster,+};use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{ClipNodeData, ContextRef, EffectNodeData, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,@@ -25,11 +31,15 @@ use crate::visual_context::{use libgfx_rust::filter::Filter;use libgfx_rust::path::Path;use libgfx_rust::{- AffineTransform, Color, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, FloatVector3, IntRect, WindingRule,- enclosing_int_rect, multiply_affine,+ AffineTransform, Color, CornerRadii, FloatMatrix4x4, FloatPoint, FloatRect, FloatVector3, IntRect, IntSize,+ MaskKind, WindingRule, enclosing_int_rect, multiply_affine,};use std::cell::RefCell;+use std::collections::HashMap;+use std::hash::Hasher;+/// The raster primitives a replay draws through. Everything a painter is handed is resolved for the frame: it never+/// sees the visual context tree, the scroll offsets or the scrollbars of the frame.pub trait ReplayPainter {fn canvas_matrix(&mut self) -> FloatMatrix4x4;fn set_matrix(&mut self, matrix: &FloatMatrix4x4);@@ -39,26 +49,143 @@ pub trait ReplayPainter {fn push_layer(&mut self, layer: &ReplayLayer);// `backdrop`, when given, carries the backdrop filter the mask's layer starts with.fn push_mask(&mut self, mask: &ReplayMask, backdrop: Option<&ReplayLayer>);- fn pop_mask(&mut self, mask: &ReplayMask, effect: EffectNodeIndex);+ // Starts the content that masks the layer `push_mask` opened. `pop_mask` closes both.+ fn begin_mask_content(&mut self, mask: &ReplayMask);+ fn pop_mask(&mut self);fn pop(&mut self);fn push_device_space_plane_clip(&mut self, vertices: &[FloatVector3]);fn push_transform(&mut self, transform: &AffineTransform);fn push_clip_path_bytes(&mut self, path_bytes: &[u8], winding_rule: WindingRule, mode: ClipMode);- // Plays one command. `command` holds the command struct, which can differ from the one at the start of- // `payload`; the command's spans point into `payload`.+ // Plays one command as it was recorded. `command` holds the command struct, which can differ from the one at the+ // start of `payload`; the command's spans point into `payload`.fn play_command(&mut self, command_type: DisplayListCommandType, command: &[u8], payload: &[u8]);-- fn execute_run(+ fn fill_rect(&mut self, fill: &ResolvedFillRect);+ fn fill_rect_with_rounded_corners(&mut self, fill: &ResolvedFillRectWithRoundedCorners);+ fn paint_scrollbar(&mut self, scrollbar: &PresentedScrollbar);+ fn draw_composited_context(&mut self, draw: &CompositedContextDraw);+ fn begin_isolated_group(&mut self, group: &IsolatedGroup);+ fn begin_isolated_group_mask(&mut self, kind: MaskKind);+ fn end_isolated_group_mask(&mut self);+ fn end_isolated_group(&mut self);+ // Answers whether the tile records are to be replayed into the raster, which `end_tile_raster` then finishes.+ fn begin_tile_raster(&mut self, tile: &TileRaster) -> bool;+ fn end_tile_raster(&mut self);+ // Unless the painter skips the list, the replay of the list is followed by `end_nested_display_list`.+ fn begin_nested_display_list(&mut self,- _run_index: usize,- records: &[u8],- scroll_offsets: &[FloatPoint],- clip_space_matrix: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,- ) {- replay_records(records, scroll_offsets, clip_space_matrix, self);+ placement: &NestedDisplayListPlacement,+ requires_direct_replay: bool,+ ) -> NestedDisplayListReplay;+ fn end_nested_display_list(&mut self);++ fn execute_run<'t>(&mut self, _run_index: usize, records: &'t [u8], context: &RecordsContext<'_, 't>) {+ replay_records(records, context, self);+ }+}++/// A scrollbar of the page as the frame presents it, which replaces the geometry its display list recorded.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ScrollbarShownByFrame {+ pub scroll_node_index: SpatialNodeIndex,+ pub vertical: bool,+ pub gutter_rect: FloatRect,+ pub thumb_rect: FloatRect,+ // How far the scrollbar has grown from its thin geometry into its expanded one.+ pub expansion: f32,+ pub opacity: f32,+}++/// A display list nested in another: its tape, the tree it was recorded against, the color of its root group, and+/// whether a raster of it can differ from replaying it.+#[derive(Clone, Copy)]+pub struct NestedDisplayList<'a> {+ pub storage: &'a DisplayListStorage,+ pub tree: &'a VisualContextTree,+ pub root_group_color: Color,+ pub requires_direct_replay: bool,+}++/// Where a replay finds the display lists that the lists it plays nest, by their resource ids.+pub trait NestedDisplayLists {+ fn nested_display_list(&self, display_list_id: u64) -> Option<NestedDisplayList<'_>>;+}++/// The resources of a replay that nests no display list.+pub struct NoNestedDisplayLists;++impl NestedDisplayLists for NoNestedDisplayLists {+ fn nested_display_list(&self, _display_list_id: u64) -> Option<NestedDisplayList<'_>> {+ None+ }+}++/// What a replay paints a display list with besides the list: where the frame presents the scroll containers and the+/// scrollbars, the time it shows a blinking caret at, and the display lists the list nests.+#[derive(Clone, Copy)]+pub struct ReplayFrame<'a> {+ pub scroll_offsets: &'a [FloatPoint],+ pub scrollbars: &'a [ScrollbarShownByFrame],+ pub time_ns: i64,+ pub nested_display_lists: &'a dyn NestedDisplayLists,+}++impl<'a> ReplayFrame<'a> {+ /// A frame that scrolls nothing and presents no scrollbar of its own.+ pub fn unscrolled(time_ns: i64, nested_display_lists: &'a dyn NestedDisplayLists) -> Self {+ Self {+ scroll_offsets: &[],+ scrollbars: &[],+ time_ns,+ nested_display_lists,+ }+ }++ // Tile records paint into a raster of their own, where nothing scrolls.+ fn for_tile_records(&self) -> Self {+ Self {+ scroll_offsets: &[],+ ..*self+ }+ }++ // A nested display list scrolls nothing, and the scrollbars of the frame do not belong to its scroll nodes.+ fn for_nested_display_list(&self) -> Self {+ Self::unscrolled(self.time_ns, self.nested_display_lists)+ }+}++/// What one display list holds for the streams of records it plays: the tree it was recorded against, and the+/// content that each of its masks declared.+pub struct ListReplay<'t> {+ pub tree: &'t VisualContextTree,+ declared_mask_contents: RefCell<HashMap<EffectNodeIndex, &'t [u8]>>,+}++impl<'t> ListReplay<'t> {+ pub fn new(tree: &'t VisualContextTree) -> Self {+ Self {+ tree,+ declared_mask_contents: RefCell::new(HashMap::new()),+ }+ }++ fn declare_mask_content(&self, effect: EffectNodeIndex, content: &'t [u8]) {+ self.declared_mask_contents.borrow_mut().insert(effect, content);+ }++ fn declared_mask_content(&self, effect: EffectNodeIndex) -> Option<&'t [u8]> {+ self.declared_mask_contents.borrow().get(&effect).copied()}}+/// What playing a stream of records needs besides the records: the list they belong to, the frame, and the to-root+/// matrix of the space an inline clip of its own space is applied in.+pub struct RecordsContext<'c, 't> {+ pub list: &'c ListReplay<'t>,+ pub frame: &'c ReplayFrame<'c>,+ pub clip_space_matrix: &'c dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+}+/// How far the inline clips of a command that apply in spaces of their own let it draw.#[derive(Clone, Copy, Debug, PartialEq)]pub(crate) enum OwnSpaceClipExtent {@@ -101,17 +228,317 @@ pub(crate) fn own_space_clip_extent(extent}+const CARET_BLINK_INTERVAL_NS: i64 = 500_000_000;++fn caret_is_visible_at_time(caret: &PaintCaret, time_ns: i64) -> bool {+ if !caret.should_blink {+ return true;+ }+ let elapsed_ns = time_ns.saturating_sub(caret.blink_cycle_start_time_ns).max(0);+ (elapsed_ns / CARET_BLINK_INTERVAL_NS) % 2 == 0+}++/// A scroll offset outside the scroll range moves the thumb past an end of its track, where it is cut short instead.+pub fn thumb_rect_kept_inside_track(mut thumb_rect: IntRect, track_rect: IntRect, vertical: bool) -> IntRect {+ if vertical {+ let top = thumb_rect.y.max(track_rect.y);+ let bottom = thumb_rect.bottom().min(track_rect.bottom());+ thumb_rect.y = top;+ thumb_rect.height = 0.max(bottom - top);+ } else {+ let left = thumb_rect.x.max(track_rect.x);+ let right = thumb_rect.right().min(track_rect.right());+ thumb_rect.x = left;+ thumb_rect.width = 0.max(right - left);+ }+ thumb_rect+}++/// A scrollbar at the geometry the frame presents it with, in the colors given.+pub fn presented_scrollbar_with_colors(+ gutter_rect: FloatRect,+ thumb_rect: FloatRect,+ expansion: f32,+ opacity: f32,+ thumb_color: Color,+ thumb_outline_color: Color,+ track_color: Color,+) -> PresentedScrollbar {+ // The gutter of a thin scrollbar is not painted, so the gutter grows out of the thin track as it fades in.+ let track_alpha = (f32::from(track_color.alpha()) * expansion).round();+ PresentedScrollbar {+ gutter_rect,+ thumb_rect,+ thumb_color,+ thumb_outline_color,+ track_color: track_color.with_alpha(track_alpha as u8),+ opacity,+ }+}++fn tile_raster_key(tile_records: &[u8], tile_size: IntSize) -> u64 {+ let mut hasher = crate::fast_hash::fast_hasher();+ hasher.write(tile_records);+ hasher.write_i32(tile_size.width);+ hasher.write_i32(tile_size.height);+ hasher.finish()+}++// The records a pattern paint style tiles are replayed into its raster before the path command that paints with it.+fn rasterize_pattern_tile_of<'t, Painter: ReplayPainter + ?Sized>(+ paint_kind: PathPaintKind,+ paint_style: &crate::display_list::commands::DisplayListPaintStyle,+ payload: &'t [u8],+ context: &RecordsContext<'_, 't>,+ painter: &mut Painter,+) {+ if paint_kind != PathPaintKind::PaintStyle || paint_style.paint_style_type != DisplayListPaintStyleType::Pattern {+ return;+ }+ let tile_rect = paint_style.pattern_tile_rect;+ let content_scale = paint_style.pattern_content_scale;+ let tile_size = IntSize {+ width: (tile_rect.width * content_scale.width).ceil() as i32,+ height: (tile_rect.height * content_scale.height).ceil() as i32,+ };+ if tile_size.is_empty() {+ return;+ }+ let tile = TileRaster {+ key: 0,+ size: tile_size,+ cacheable: false,+ };+ if painter.begin_tile_raster(&tile) {+ let tile_frame = context.frame.for_tile_records();+ replay_records(+ span_bytes(payload, paint_style.pattern_tile),+ &RecordsContext {+ list: context.list,+ frame: &tile_frame,+ clip_space_matrix: &|_| None,+ },+ painter,+ );+ painter.end_tile_raster();+ }+}++// Plays one record, inside its inline clips and transform, resolving what the frame decides about it.+fn play_record<'t, Painter: ReplayPainter + ?Sized>(+ header: &DisplayListCommandHeader,+ payload: &'t [u8],+ context: &RecordsContext<'_, 't>,+ painter: &mut Painter,+) {+ let tree = context.list.tree;+ match header.command_type {+ DisplayListCommandType::FillRect => {+ let command = read_command::<FillRect>(payload);+ let color = if command.background_color_animation_effect == EffectNodeIndex::NONE {+ command.color+ } else {+ tree.sampled_background_color(command.background_color_animation_effect)+ .unwrap_or(command.color)+ };+ painter.fill_rect(&ResolvedFillRect {+ rect: command.rect,+ color,+ compositing_and_blending_operator: command.compositing_and_blending_operator,+ });+ }+ DisplayListCommandType::FillRectWithRoundedCorners => {+ let command = read_command::<FillRectWithRoundedCorners>(payload);+ let color = if command.background_color_animation_effect == EffectNodeIndex::NONE {+ command.color+ } else {+ tree.sampled_background_color(command.background_color_animation_effect)+ .unwrap_or(command.color)+ };+ painter.fill_rect_with_rounded_corners(&ResolvedFillRectWithRoundedCorners {+ rect: command.rect,+ color,+ corner_radii: command.corner_radii,+ });+ }+ DisplayListCommandType::PaintCaret => {+ let command = read_command::<PaintCaret>(payload);+ if caret_is_visible_at_time(&command, context.frame.time_ns) {+ painter.play_command(header.command_type, payload, payload);+ }+ }+ DisplayListCommandType::PaintScrollBar => {+ let mut command = read_command::<PaintScrollBar>(payload);+ // A scrollbar command of the display list with no scrollbar of the frame is painted as the command gives+ // it. The colors are the ones the display list resolved for the page, which it may have darkened.+ let shown_by_frame = context.frame.scrollbars.iter().find(|scrollbar| {+ scrollbar.scroll_node_index == command.scroll_node_index && scrollbar.vertical == command.vertical+ });+ let scrollbar = match shown_by_frame {+ Some(scrollbar) => presented_scrollbar_with_colors(+ scrollbar.gutter_rect,+ scrollbar.thumb_rect,+ scrollbar.expansion,+ scrollbar.opacity,+ command.thumb_color,+ command.thumb_outline_color,+ command.track_color,+ ),+ None => {+ let device_offset =+ device_offset_for_index(context.frame.scroll_offsets, command.scroll_node_index);+ if command.vertical {+ let shift = (-f64::from(device_offset.y) * command.scroll_size) as i32;+ command.thumb_rect.y = command.thumb_rect.y.saturating_add(shift);+ } else {+ let shift = (-f64::from(device_offset.x) * command.scroll_size) as i32;+ command.thumb_rect.x = command.thumb_rect.x.saturating_add(shift);+ }+ PresentedScrollbar {+ gutter_rect: command.gutter_rect.to_float(),+ thumb_rect: thumb_rect_kept_inside_track(+ command.thumb_rect,+ command.track_rect,+ command.vertical,+ )+ .to_float(),+ thumb_color: command.thumb_color,+ thumb_outline_color: command.thumb_outline_color,+ track_color: command.track_color,+ opacity: 1.0,+ }+ }+ };+ painter.paint_scrollbar(&scrollbar);+ }+ DisplayListCommandType::DrawCompositedContext => {+ let command = read_command::<DrawCompositedContext>(payload);+ let mut dst_rect = command.dst_rect;+ // Snap iframe origins to device pixels for browser compatibility when transforms are absent or identity.+ // Preserve fractional placement under other transforms to retain the raster phase of surrounding content.+ if command.snap_origin_if_untransformed+ && tree.translations_snap_to_device_pixels(command.spatial_node_index)+ {+ dst_rect.x = dst_rect.x.round();+ dst_rect.y = dst_rect.y.round();+ }+ painter.draw_composited_context(&CompositedContextDraw {+ child_context_id: command.child_context_id.0,+ dst_rect,+ scaling_mode: command.scaling_mode,+ });+ }+ DisplayListCommandType::DeclareMaskContent => {+ let command = read_command::<DeclareMaskContent>(payload);+ context+ .list+ .declare_mask_content(command.effect, span_bytes(payload, command.content));+ }+ DisplayListCommandType::DrawIsolatedGroup => {+ let command = read_command::<DrawIsolatedGroup>(payload);+ let filter = span_bytes(payload, command.filter);+ painter.begin_isolated_group(&IsolatedGroup {+ clip_rect: command.clip_rect,+ opacity: command.opacity,+ compositing_and_blending_operator: command.compositing_and_blending_operator,+ filter_bytes: filter.as_ptr(),+ filter_bytes_size: filter.len(),+ });+ let nested_records_context = RecordsContext {+ list: context.list,+ frame: context.frame,+ clip_space_matrix: &|_| None,+ };+ replay_records(span_bytes(payload, command.content), &nested_records_context, painter);+ if command.mask.size != 0 {+ painter.begin_isolated_group_mask(command.mask_kind);+ replay_records(span_bytes(payload, command.mask), &nested_records_context, painter);+ painter.end_isolated_group_mask();+ }+ painter.end_isolated_group();+ }+ DisplayListCommandType::DrawRepeatedTile => {+ let command = read_command::<DrawRepeatedTile>(payload);+ if command.tile_size.is_empty() || command.dst_rect.is_empty() || command.tile_step.is_empty() {+ return;+ }+ let tile_records = span_bytes(payload, command.tile);+ let tile = TileRaster {+ key: tile_raster_key(tile_records, command.tile_size),+ size: command.tile_size,+ cacheable: true,+ };+ if painter.begin_tile_raster(&tile) {+ let tile_frame = context.frame.for_tile_records();+ replay_records(+ tile_records,+ &RecordsContext {+ list: context.list,+ frame: &tile_frame,+ clip_space_matrix: &|_| None,+ },+ painter,+ );+ painter.end_tile_raster();+ }+ painter.play_command(header.command_type, payload, payload);+ }+ DisplayListCommandType::FillPath => {+ let command = read_command::<FillPath>(payload);+ rasterize_pattern_tile_of(command.paint_kind, &command.paint_style, payload, context, painter);+ painter.play_command(header.command_type, payload, payload);+ }+ DisplayListCommandType::StrokePath => {+ let command = read_command::<StrokePath>(payload);+ rasterize_pattern_tile_of(command.paint_kind, &command.paint_style, payload, context, painter);+ painter.play_command(header.command_type, payload, payload);+ }+ DisplayListCommandType::PaintNestedDisplayList => {+ let command = read_command::<PaintNestedDisplayList>(payload);+ let Some(nested) = context+ .frame+ .nested_display_lists+ .nested_display_list(command.display_list_id.0)+ else {+ return;+ };+ let placement = NestedDisplayListPlacement {+ display_list_id: command.display_list_id.0,+ rect: command.rect,+ list_size: command.list_size,+ };+ if painter.begin_nested_display_list(&placement, nested.requires_direct_replay)+ == NestedDisplayListReplay::Skipped+ {+ return;+ }+ let nested_frame = context.frame.for_nested_display_list();+ replay_display_list(+ nested.tree,+ nested.storage.bytes(),+ nested.storage.command_runs(),+ nested.storage.effect_clip_plan(nested.tree),+ nested.root_group_color,+ &nested_frame,+ ReplaySelection::default(),+ painter,+ );+ painter.end_nested_display_list();+ }+ _ => painter.play_command(header.command_type, payload, payload),+ }+}+/// Plays one stream of records: the records of a run, or the records nested in a command. Compositor/// metadata is skipped, a command whose bounds are empty or clipped away is culled, and each command plays-/// inside its inline clips and transform. A scroll bar's thumb moves by the offset of its scroll node.-/// `clip_space_matrix` gives the to-root matrix of the space an inline clip of its own space is applied in;-/// a clip whose space it does not know applies in the space of its command.-pub fn replay_records<Painter: ReplayPainter + ?Sized>(- records: &[u8],- scroll_offsets: &[FloatPoint],- clip_space_matrix: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+/// inside its inline clips and transform. A clip whose space the context does not know applies in the space of its+/// command.+pub fn replay_records<'t, Painter: ReplayPainter + ?Sized>(+ records: &'t [u8],+ context: &RecordsContext<'_, 't>,painter: &mut Painter,) {+ let clip_space_matrix = context.clip_space_matrix;for_each_command(records, |header, _, payload| {if header.command_type.is_compositor_metadata() {return;@@ -166,22 +593,7 @@ pub fn replay_records<Painter: ReplayPainter + ?Sized>(if let Some(transform) = &inline_transform {painter.push_transform(transform);}- if header.command_type == DisplayListCommandType::PaintScrollBar {- let mut command = read_command::<PaintScrollBar>(payload);- let device_offset = device_offset_for_index(scroll_offsets, command.scroll_node_index);- if command.vertical {- let shift = (-f64::from(device_offset.y) * command.scroll_size) as i32;- command.thumb_rect.y = command.thumb_rect.y.saturating_add(shift);- } else {- let shift = (-f64::from(device_offset.x) * command.scroll_size) as i32;- command.thumb_rect.x = command.thumb_rect.x.saturating_add(shift);- }- let mut command_bytes = [0u8; std::mem::size_of::<PaintScrollBar>()];- command.write_ffi_bytes(&mut command_bytes);- painter.play_command(header.command_type, &command_bytes, payload);- } else {- painter.play_command(header.command_type, payload, payload);- }+ play_record(header, payload, context, painter);if inline_transform.is_some() {painter.pop();}@@ -255,11 +667,12 @@ enum SwitchResult {CulledByEffect,}-struct ReplayDriver<'a, Painter: ReplayPainter> {+struct ReplayDriver<'a, Painter: ReplayPainter + ?Sized> {tree: &'a VisualContextTree,tape: &'a [u8],command_runs: &'a [DisplayListCommandRun],- scroll_offsets: &'a [FloatPoint],+ list: ListReplay<'a>,+ frame: &'a ReplayFrame<'a>,effect_clips: &'a EffectClipPlan,root_group_color: Color,selection: ReplaySelection<'a>,@@ -293,9 +706,18 @@ fn replay_clip_of(clip: &crate::visual_context::ClipData) -> ReplayClip {}}+// An effect keeps its filters for as long as the tree keeps its structure, so a painter can key what it builds from+// them on the two.+fn layer_filter_cache_key(tree: &VisualContextTree, effect: EffectNodeIndex) -> u64 {+ let mut hasher = crate::fast_hash::fast_hasher();+ hasher.write_u64(tree.structural_epoch);+ hasher.write_u32(effect.0);+ hasher.finish()+}+fn replay_layer_of(effects: &crate::visual_context::EffectsData,- effect: EffectNodeIndex,+ filter_cache_key: u64,content_bounds: Option<FloatRect>,) -> ReplayLayer {let (filter_bytes, filter_bytes_size) = match &effects.filter {@@ -323,7 +745,7 @@ fn replay_layer_of(backdrop_corner_radii,backdrop_base_color: Color::TRANSPARENT,backdrop_blur_edge: OptionalFloatRect::none(),- effect,+ filter_cache_key,content_bounds: OptionalFloatRect::from(content_bounds),}}@@ -359,7 +781,7 @@ fn int_rect_enclosing(rect: FloatRect) -> Option<IntRect> {.then(|| enclosing_int_rect(rect))}-impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {+impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {fn effect_layer_is_pushed(&self, effect: EffectNodeIndex) -> bool {self.tree.effect_pushes_layer_at_replay(effect)&& !(self.selection.skip_root_isolation_layer && self.tree.root_isolation_effect == Some(effect))@@ -436,7 +858,7 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {};match &tree.effect_nodes[effect.0 as usize].data {EffectNodeData::Effects(effects) if backdrop_is_drawn_by_masks(tree, effect) => {- let mut layer = replay_layer_of(effects, effect, None);+ let mut layer = replay_layer_of(effects, layer_filter_cache_key(tree, effect), None);layer.backdrop_base_color = self.backdrop_base_color(mask_effect);layer.backdrop_blur_edge = self.backdrop_blur_edge(effect);Some(layer)@@ -582,7 +1004,16 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {}EffectNodeData::Mask(mask) => {self.ensure_ctm_space(node.spatial);- self.painter.pop_mask(&replay_mask_of(mask), effect);+ self.painter.begin_mask_content(&replay_mask_of(mask));+ if let Some(content) = self.list.declared_mask_content(effect) {+ let records_context = RecordsContext {+ list: &self.list,+ frame: self.frame,+ clip_space_matrix: &|_| None,+ };+ replay_records(content, &records_context, &mut *self.painter);+ }+ self.painter.pop_mask();self.current_ctm_space = None;}// A marker touches no canvas state.@@ -662,7 +1093,8 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {if self.effect_layer_is_pushed(effect) {self.ensure_ctm_space(node.spatial);let content_bounds = self.layer_content_bounds(effect, node.spatial);- let mut layer = replay_layer_of(effects, effect, content_bounds);+ let mut layer =+ replay_layer_of(effects, layer_filter_cache_key(tree, effect), content_bounds);if backdrop_is_drawn_by_masks(tree, effect) {// NB: The outermost mask layer draws the backdrop, and applies the opacity and// blend mode to it and the masked content together.@@ -739,8 +1171,12 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {let records = &self.tape[begin_offset as usize..end_offset as usize];let world = &self.world;let clip_space_matrix = |space: SpatialNodeIndex| world.draw_matrix_if_known(space);- self.painter- .execute_run(run_index, records, self.scroll_offsets, &clip_space_matrix);+ let records_context = RecordsContext {+ list: &self.list,+ frame: self.frame,+ clip_space_matrix: &clip_space_matrix,+ };+ self.painter.execute_run(run_index, records, &records_context);}fn execute(&mut self) {@@ -821,15 +1257,15 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {}#[allow(clippy::too_many_arguments)]-pub fn replay_display_list(+pub fn replay_display_list<Painter: ReplayPainter + ?Sized>(tree: &VisualContextTree,tape: &[u8],command_runs: &[DisplayListCommandRun],effect_clips: &EffectClipPlan,root_group_color: Color,- scroll_offsets: &[FloatPoint],+ frame: &ReplayFrame<'_>,selection: ReplaySelection<'_>,- painter: &mut impl ReplayPainter,+ painter: &mut Painter,) {let replay_base_matrix = painter.canvas_matrix();let mut scratch = take_replay_scratch_storage();@@ -838,7 +1274,8 @@ pub fn replay_display_list(tree,tape,command_runs,- scroll_offsets,+ list: ListReplay::new(tree),+ frame,effect_clips,root_group_color,selection,@@ -860,7 +1297,7 @@ pub fn replay_display_list(driver.world.fill(tree,&driver.spatial_dependency_order,- scroll_offsets,+ frame.scroll_offsets,Some(replay_base_matrix),);driver.execute();@@ -981,7 +1418,7 @@ mod tests {PushClip(FloatRect),PushLayer(f32),PushMask(IntRect),- PopMask(EffectNodeIndex),+ PopMask,Pop,PushPlaneClip(usize),Run(usize),@@ -1035,8 +1472,9 @@ mod tests {fn push_mask(&mut self, mask: &ReplayMask, _backdrop: Option<&ReplayLayer>) {self.events.push(PainterEvent::PushMask(mask.rect));}- fn pop_mask(&mut self, _mask: &ReplayMask, effect: EffectNodeIndex) {- self.events.push(PainterEvent::PopMask(effect));+ fn begin_mask_content(&mut self, _mask: &ReplayMask) {}+ fn pop_mask(&mut self) {+ self.events.push(PainterEvent::PopMask);}fn pop(&mut self) {self.events.push(PainterEvent::Pop);@@ -1049,14 +1487,28 @@ mod tests {fn push_clip_path_bytes(&mut self, _path_bytes: &[u8], _winding_rule: WindingRule, _mode: ClipMode) {}fn play_command(&mut self, _command_type: DisplayListCommandType, _command: &[u8], _payload: &[u8]) {}-- fn execute_run(+ fn fill_rect(&mut self, _fill: &ResolvedFillRect) {}+ fn fill_rect_with_rounded_corners(&mut self, _fill: &ResolvedFillRectWithRoundedCorners) {}+ fn paint_scrollbar(&mut self, _scrollbar: &PresentedScrollbar) {}+ fn draw_composited_context(&mut self, _draw: &CompositedContextDraw) {}+ fn begin_isolated_group(&mut self, _group: &IsolatedGroup) {}+ fn begin_isolated_group_mask(&mut self, _kind: MaskKind) {}+ fn end_isolated_group_mask(&mut self) {}+ fn end_isolated_group(&mut self) {}+ fn begin_tile_raster(&mut self, _tile: &TileRaster) -> bool {+ false+ }+ fn end_tile_raster(&mut self) {}+ fn begin_nested_display_list(&mut self,- run_index: usize,- records: &[u8],- _scroll_offsets: &[FloatPoint],- _clip_space_matrix: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,- ) {+ _placement: &NestedDisplayListPlacement,+ _requires_direct_replay: bool,+ ) -> NestedDisplayListReplay {+ NestedDisplayListReplay::Skipped+ }+ fn end_nested_display_list(&mut self) {}++ fn execute_run<'t>(&mut self, run_index: usize, records: &'t [u8], _context: &RecordsContext<'_, 't>) {self.events.push(PainterEvent::Run(run_index));self.run_record_sizes.push(records.len());}@@ -1148,6 +1600,25 @@ mod tests {IntRect::new(0, 0, 10, 10)}+ fn replay_test_records(+ records: &[u8],+ clip_space_matrix: &dyn Fn(SpatialNodeIndex) -> Option<FloatMatrix4x4>,+ painter: &mut RecordingPainter,+ ) {+ let tree = identity_tree();+ let list = ListReplay::new(&tree);+ let frame = ReplayFrame::unscrolled(0, &NoNestedDisplayLists);+ replay_records(+ records,+ &RecordsContext {+ list: &list,+ frame: &frame,+ clip_space_matrix,+ },+ painter,+ );+ }+fn replay(tree: &VisualContextTree, runs: &[DisplayListCommandRun], painter: &mut RecordingPainter) {replay_display_list(tree,@@ -1155,7 +1626,7 @@ mod tests {runs,&EffectClipPlan::new(tree, runs).unwrap(),Color::TRANSPARENT,- &[],+ &ReplayFrame::unscrolled(0, &NoNestedDisplayLists),ReplaySelection::default(),painter,);@@ -1179,7 +1650,7 @@ mod tests {runs,&EffectClipPlan::new(tree, runs).unwrap(),Color::TRANSPARENT,- &[],+ &ReplayFrame::unscrolled(0, &NoNestedDisplayLists),selection,&mut painter,);@@ -1319,9 +1790,8 @@ mod tests {let clip_space_matrix = translation_matrix(102.0, 203.0, 0.0);let mut painter = RecordingPainter::new();let command_space_matrix = painter.base_matrix;- replay_records(+ replay_test_records(builder.bytes(),- &[],&|space| (space == clip_space).then_some(clip_space_matrix),&mut painter,);@@ -1361,9 +1831,8 @@ mod tests {);let clip_space_matrix = translation_matrix(0.0, -50.0, 0.0);let mut painter = RecordingPainter::new();- replay_records(+ replay_test_records(builder.bytes(),- &[],&|space| (space == clip_space).then_some(clip_space_matrix),&mut painter,);@@ -1390,7 +1859,7 @@ mod tests {],);let mut painter = RecordingPainter::new();- replay_records(builder.bytes(), &[], &|_| None, &mut painter);+ replay_test_records(builder.bytes(), &|_| None, &mut painter);assert_eq!(painter.events,vec![@@ -1693,7 +2162,7 @@ mod tests {PainterEvent::SetMatrix(base),PainterEvent::PushMask(IntRect::new(0, 0, 20, 20)),PainterEvent::Run(0),- PainterEvent::PopMask(mask_effect),+ PainterEvent::PopMask,PainterEvent::SetMatrix(base),]);@@ -1980,7 +2449,7 @@ mod tests {PainterEvent::Pop,PainterEvent::SetMatrix(base),PainterEvent::Run(2),- PainterEvent::PopMask(mask_effect),+ PainterEvent::PopMask,PainterEvent::SetMatrix(base),PainterEvent::PushClip(overflow),PainterEvent::Run(3),@@ -2007,18 +2476,18 @@ mod tests {corner_radii: radii,}),};- let layer = replay_layer_of(&with_backdrop, EffectNodeIndex(3), None);+ let layer = replay_layer_of(&with_backdrop, 3, None);assert_eq!(layer.opacity, 0.5);assert_eq!(layer.backdrop_filter_bytes, filter.as_ptr());assert_eq!(layer.backdrop_filter_bytes_size, 3);assert_eq!(layer.backdrop_region, region);assert_eq!(layer.backdrop_corner_radii, radii);- assert_eq!(layer.effect, EffectNodeIndex(3));+ assert_eq!(layer.filter_cache_key, 3);let EffectNodeData::Effects(without_backdrop) = effects(0.5) else {unreachable!()};- let layer = replay_layer_of(&without_backdrop, EffectNodeIndex(4), None);+ let layer = replay_layer_of(&without_backdrop, 4, None);assert!(layer.backdrop_filter_bytes.is_null());assert_eq!(layer.backdrop_filter_bytes_size, 0);assert_eq!(layer.backdrop_region, IntRect::default());@@ -2064,7 +2533,7 @@ mod tests {&runs,&EffectClipPlan::new(&tree, &runs).unwrap(),white,- &[],+ &ReplayFrame::unscrolled(0, &NoNestedDisplayLists),ReplaySelection::default(),&mut painter,);@@ -2191,7 +2660,10 @@ mod tests {&runs,&EffectClipPlan::new(&tree, &runs).unwrap(),Color::TRANSPARENT,- &scroll_offsets,+ &ReplayFrame {+ scroll_offsets: &scroll_offsets,+ ..ReplayFrame::unscrolled(0, &NoNestedDisplayLists)+ },ReplaySelection::default(),&mut painter,);@@ -2280,7 +2752,7 @@ mod tests {depth += 1;}PainterEvent::PushClip(_) | PainterEvent::PushLayer(_) | PainterEvent::PushMask(_) => depth += 1,- PainterEvent::Pop | PainterEvent::PopMask(_) => depth -= 1,+ PainterEvent::Pop | PainterEvent::PopMask => depth -= 1,_ => {}}}diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex f9d20dc773b..8cadfabd133 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -48,97 +48,67 @@ pub unsafe extern "C" fn ladybird_web_force_dark_should_filter_image(crate::force_dark::should_filter(&features)}-/// Replays the list `storage` holds against `tree`, with the scroll containers at `scroll_offsets`.+/// Replays the list `storage` holds against `tree`, as `frame` presents it.////// # Safety///-/// `storage` must be a live storage handle of a list recorded against the structural epoch of `tree`, and `callbacks`-/// must be live. The painter callbacks run synchronously and may re-enter a replay for a nested display list.+/// `storage` must be a live storage handle of a list recorded against the structural epoch of `tree`, and `painter`+/// must be live. The painter callbacks run synchronously.pub unsafe fn replay_display_list_storage(tree: &crate::visual_context::VisualContextTree,storage: *const c_void,root_group_color: libgfx_rust::Color,- scroll_offsets: &[FloatPoint],+ frame: &crate::display_list::replay::ReplayFrame<'_>,selection: crate::display_list::replay::ReplaySelection<'_>,- callbacks: *const crate::host::FfiDisplayListReplayCallbacks,+ painter: *const crate::host::FfiRasterPainter,) {// SAFETY: The caller guarantees a live handle for the duration of the call.let storage = unsafe { storage_from_handle(storage) };- // SAFETY: The caller guarantees `callbacks` is live for the call.- let mut painter = unsafe { *callbacks };+ // SAFETY: The caller guarantees `painter` is live for the call.+ let mut painter = unsafe { *painter };crate::display_list::replay::replay_display_list(tree,storage.bytes(),storage.command_runs(),storage.effect_clip_plan(tree),root_group_color,- scroll_offsets,+ frame,selection,&mut painter,);}-/// Plays a stream of records that a command nests, outside of any run, with the scroll containers at `scroll_offsets`.-///-/// # Safety-///-/// `records` must be a tape that is valid, and `callbacks` must be live. The painter callbacks run synchronously and-/// may re-enter a replay.-pub unsafe fn replay_nested_records(- records: &[u8],- scroll_offsets: &[FloatPoint],- callbacks: *const crate::host::FfiDisplayListReplayCallbacks,-) {- // SAFETY: The caller guarantees `callbacks` is live for the call.- let mut painter = unsafe { *callbacks };- // NB: Nested records share the context of the command they are nested in, and none of their inline clips has a- // space of its own.- crate::display_list::replay::replay_records(records, scroll_offsets, &|_| None, &mut painter);-}--/// Replays a list with nothing scrolled, as a list nested in another is.+/// Replays a list with nothing scrolled, showing a blinking caret as it is at `time_nanoseconds`. The display lists it+/// nests are looked up through the painter.////// # Safety////// `tree` must be a live retained tree handle of the structural epoch the storage was recorded-/// against, `storage` a live storage handle, and `callbacks` must be live. The painter callbacks run-/// synchronously and may re-enter this function for a nested display list.+/// against, `storage` a live storage handle, and `painter` must be live. The painter callbacks run synchronously.#[unsafe(no_mangle)]pub unsafe extern "C" fn display_list_replay(tree: *const c_void,storage: *const c_void,root_group_color: libgfx_rust::Color,- callbacks: *const crate::host::FfiDisplayListReplayCallbacks,+ time_nanoseconds: i64,+ painter: *const crate::host::FfiRasterPainter,) {- // SAFETY: The caller guarantees live handles and callbacks for the duration of the call.+ // SAFETY: The caller guarantees `painter` is live for the call.+ let nested_display_lists = unsafe { (*painter).nested_display_lists() };+ let frame = crate::display_list::replay::ReplayFrame::unscrolled(time_nanoseconds, &nested_display_lists);+ // SAFETY: The caller guarantees live handles and a live painter for the duration of the call.unsafe {replay_display_list_storage(tree_from_handle(tree),storage,root_group_color,- &[],+ &frame,Default::default(),- callbacks,+ painter,);};}-/// Plays a stream of records that a command nests, outside of any run, with nothing scrolled.-///-/// # Safety-///-/// `records` must address `records_size` bytes of a tape that is valid for the call; `callbacks` must be-/// live. The painter callbacks run synchronously and may re-enter this function.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn display_list_replay_records(- records: *const u8,- records_size: usize,- callbacks: *const crate::host::FfiDisplayListReplayCallbacks,-) {- // SAFETY: The caller guarantees the slice addresses the stated number of bytes, and live callbacks.- unsafe { replay_nested_records(ak::slice_from_raw_parts(records, records_size), &[], callbacks) };-}-/// # Safety////// `tree` must be a retained tree handle (from `layout_arena_main_visual_context_tree_retain`,diff --git a/Libraries/LibCompositing/Rust/src/host/replay.rs b/Libraries/LibCompositing/Rust/src/host/replay.rsindex 841842c225b..4919ec9f3f3 100644--- a/Libraries/LibCompositing/Rust/src/host/replay.rs+++ b/Libraries/LibCompositing/Rust/src/host/replay.rs@@ -4,13 +4,14 @@* SPDX-License-Identifier: BSD-2-Clause*/-use crate::display_list::commands::{- ClipMode, DisplayListCommandType, EffectNodeIndex, ReplayClip, ReplayLayer, ReplayMask,-};-use crate::display_list::replay::{ReplayPainter, ReplaySelection};+use crate::display_list::commands::{ClipMode, DisplayListCommandType, ReplayClip, ReplayLayer, ReplayMask};+use crate::display_list::replay::{NestedDisplayList, NestedDisplayLists, ReplayPainter, ReplaySelection};use libgfx_rust::path::Path;use libgfx_rust::path::ffi::PathGeometryData;-use libgfx_rust::{AffineTransform, FloatMatrix4x4, FloatVector3, IntRect, WindingRule};+use libgfx_rust::{+ AffineTransform, Color, CompositingAndBlendingOperator, CornerRadii, FloatMatrix4x4, FloatRect, FloatVector3,+ IntRect, IntSize, MaskKind, ScalingMode, WindingRule,+};use std::ffi::c_void;#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]@@ -45,9 +46,116 @@ impl FfiReplaySelection {}}+/// A rect fill whose color the replay resolved for the frame.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct ResolvedFillRect {+ pub rect: IntRect,+ pub color: Color,+ pub compositing_and_blending_operator: CompositingAndBlendingOperator,+}++/// A rounded rect fill whose color the replay resolved for the frame.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct ResolvedFillRectWithRoundedCorners {+ pub rect: IntRect,+ pub color: Color,+ pub corner_radii: CornerRadii,+}++/// A scrollbar as it is painted, somewhere between its thin and its expanded geometry.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct PresentedScrollbar {+ pub gutter_rect: FloatRect,+ pub thumb_rect: FloatRect,+ pub thumb_color: Color,+ pub thumb_outline_color: Color,+ pub track_color: Color,+ pub opacity: f32,+}++impl Default for PresentedScrollbar {+ fn default() -> Self {+ Self {+ gutter_rect: Default::default(),+ thumb_rect: Default::default(),+ thumb_color: Default::default(),+ thumb_outline_color: Default::default(),+ track_color: Default::default(),+ opacity: 1.0,+ }+ }+}++/// Where the frame of another context is drawn, with its origin already snapped where it lands on whole pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct CompositedContextDraw {+ pub child_context_id: u64,+ pub dst_rect: FloatRect,+ pub scaling_mode: ScalingMode,+}++/// A group of records that is composited as one: inside `clip_rect`, with the opacity, the blend mode and the filter.+#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct IsolatedGroup {+ pub clip_rect: FloatRect,+ pub opacity: f32,+ pub compositing_and_blending_operator: CompositingAndBlendingOperator,+ pub filter_bytes: *const u8,+ pub filter_bytes_size: usize,+}++/// A raster of tile records that a command repeats, or that a pattern paints with. A cacheable raster stays the same+/// for as long as its key does.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(C)]+pub struct TileRaster {+ pub key: u64,+ pub size: IntSize,+ pub cacheable: bool,+}++/// Where a display list nested in another is painted, and the size it was recorded at.+#[derive(Clone, Copy, Debug, PartialEq)]+#[repr(C)]+pub struct NestedDisplayListPlacement {+ pub display_list_id: u64,+ pub rect: FloatRect,+ pub list_size: IntSize,+}++/// How the painter takes a nested display list.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum NestedDisplayListReplay {+ /// The painter drew the list from a raster it keeps, or it draws nothing of it.+ Skipped,+ /// The list is replayed into a raster the painter keeps, which it draws once the replay ends.+ IntoRaster,+ /// The list is replayed in place.+ Directly,+}++/// A display list nested in another, as the painter's resources hold it: the storage of its tape, the tree it was+/// recorded against, and whether a raster of it can differ from replaying it.+#[derive(Clone, Copy)]+#[repr(C)]+pub struct FfiNestedDisplayList {+ pub storage: *const c_void,+ pub visual_context_tree: *const c_void,+ pub root_group_color: Color,+ pub requires_direct_replay: bool,+}++/// The raster primitives the replay drives a C++ painter through. The painter knows nothing of the visual context+/// tree, of scroll offsets or of the frame: every value it gets is resolved for what it draws.#[derive(Clone, Copy)]#[repr(C)]-pub struct FfiDisplayListReplayCallbacks {+pub struct FfiRasterPainter {pub context: *mut c_void,pub canvas_matrix: unsafe extern "C" fn(*mut c_void) -> FloatMatrix4x4,pub set_matrix: unsafe extern "C" fn(*mut c_void, *const FloatMatrix4x4),@@ -58,16 +166,81 @@ pub struct FfiDisplayListReplayCallbacks {pub push_layer: unsafe extern "C" fn(*mut c_void, *const ReplayLayer),// Arguments: the mask, and the layer whose backdrop filter the mask's layer starts with, or null.pub push_mask: unsafe extern "C" fn(*mut c_void, *const ReplayMask, *const ReplayLayer),- pub pop_mask: unsafe extern "C" fn(*mut c_void, *const ReplayMask, EffectNodeIndex),+ /// Starts the content that masks the layer `push_mask` opened; `pop_mask` closes both.+ pub begin_mask_content: unsafe extern "C" fn(*mut c_void, *const ReplayMask),+ pub pop_mask: unsafe extern "C" fn(*mut c_void),pub pop: unsafe extern "C" fn(*mut c_void),pub push_device_space_plane_clip: unsafe extern "C" fn(*mut c_void, *const FloatVector3, usize),pub push_transform: unsafe extern "C" fn(*mut c_void, *const AffineTransform),pub push_clip_path_bytes: unsafe extern "C" fn(*mut c_void, *const u8, usize, WindingRule, ClipMode),// Arguments: the command type, the command struct, and the payload its spans point into, with its size.pub play_command: unsafe extern "C" fn(*mut c_void, DisplayListCommandType, *const u8, *const u8, usize),+ pub fill_rect: unsafe extern "C" fn(*mut c_void, *const ResolvedFillRect),+ pub fill_rect_with_rounded_corners: unsafe extern "C" fn(*mut c_void, *const ResolvedFillRectWithRoundedCorners),+ pub paint_scrollbar: unsafe extern "C" fn(*mut c_void, *const PresentedScrollbar),+ pub draw_composited_context: unsafe extern "C" fn(*mut c_void, *const CompositedContextDraw),+ pub begin_isolated_group: unsafe extern "C" fn(*mut c_void, *const IsolatedGroup),+ pub begin_isolated_group_mask: unsafe extern "C" fn(*mut c_void, MaskKind),+ pub end_isolated_group_mask: unsafe extern "C" fn(*mut c_void),+ pub end_isolated_group: unsafe extern "C" fn(*mut c_void),+ /// Answers whether the tile records are to be replayed into the raster, which `end_tile_raster` then finishes.+ /// The command that draws the tiles comes next.+ pub begin_tile_raster: unsafe extern "C" fn(*mut c_void, *const TileRaster) -> bool,+ pub end_tile_raster: unsafe extern "C" fn(*mut c_void),+ /// Arguments: the placement, and whether a raster of the list can differ from replaying it. Unless the list is+ /// skipped, its replay is followed by `end_nested_display_list`.+ pub begin_nested_display_list:+ unsafe extern "C" fn(*mut c_void, *const NestedDisplayListPlacement, bool) -> NestedDisplayListReplay,+ pub end_nested_display_list: unsafe extern "C" fn(*mut c_void),+ /// Looks a nested display list up by its resource id, answering false where the resources hold none.+ pub nested_display_list: unsafe extern "C" fn(*mut c_void, u64, *mut FfiNestedDisplayList) -> bool,+}++impl FfiRasterPainter {+ /// The nested display lists that the resources of this painter hold.+ pub fn nested_display_lists(&self) -> FfiNestedDisplayLists {+ FfiNestedDisplayLists {+ context: self.context,+ nested_display_list: self.nested_display_list,+ }+ }}-impl ReplayPainter for FfiDisplayListReplayCallbacks {+/// The nested display lists of a C++ painter's resources, looked up through the painter.+pub struct FfiNestedDisplayLists {+ context: *mut c_void,+ nested_display_list: unsafe extern "C" fn(*mut c_void, u64, *mut FfiNestedDisplayList) -> bool,+}++impl NestedDisplayLists for FfiNestedDisplayLists {+ fn nested_display_list(&self, display_list_id: u64) -> Option<NestedDisplayList<'_>> {+ let mut nested = FfiNestedDisplayList {+ storage: std::ptr::null(),+ visual_context_tree: std::ptr::null(),+ root_group_color: Color::TRANSPARENT,+ requires_direct_replay: true,+ };+ // SAFETY: The C++ painter answers synchronously.+ if !unsafe { (self.nested_display_list)(self.context, display_list_id, &raw mut nested) } {+ return None;+ }+ // SAFETY: The painter's resources keep the storage and the tree alive for as long as the replay runs.+ let (storage, tree) = unsafe {+ (+ crate::display_list::storage::storage_from_handle(nested.storage),+ crate::ffi::tree_from_handle(nested.visual_context_tree),+ )+ };+ Some(NestedDisplayList {+ storage,+ tree,+ root_group_color: nested.root_group_color,+ requires_direct_replay: nested.requires_direct_replay,+ })+ }+}++impl ReplayPainter for FfiRasterPainter {fn canvas_matrix(&mut self) -> FloatMatrix4x4 {// SAFETY: The C++ painter answers synchronously.unsafe { (self.canvas_matrix)(self.context) }@@ -106,9 +279,14 @@ impl ReplayPainter for FfiDisplayListReplayCallbacks {unsafe { (self.push_mask)(self.context, mask, backdrop) };}- fn pop_mask(&mut self, mask: &ReplayMask, effect: EffectNodeIndex) {+ fn begin_mask_content(&mut self, mask: &ReplayMask) {// SAFETY: The C++ painter reads the mask synchronously.- unsafe { (self.pop_mask)(self.context, mask, effect) };+ unsafe { (self.begin_mask_content)(self.context, mask) };+ }++ fn pop_mask(&mut self) {+ // SAFETY: The C++ painter pops synchronously.+ unsafe { (self.pop_mask)(self.context) };}fn pop(&mut self) {@@ -143,4 +321,68 @@ impl ReplayPainter for FfiDisplayListReplayCallbacks {);}}++ fn fill_rect(&mut self, fill: &ResolvedFillRect) {+ // SAFETY: The C++ painter reads the fill synchronously.+ unsafe { (self.fill_rect)(self.context, fill) };+ }++ fn fill_rect_with_rounded_corners(&mut self, fill: &ResolvedFillRectWithRoundedCorners) {+ // SAFETY: The C++ painter reads the fill synchronously.+ unsafe { (self.fill_rect_with_rounded_corners)(self.context, fill) };+ }++ fn paint_scrollbar(&mut self, scrollbar: &PresentedScrollbar) {+ // SAFETY: The C++ painter reads the scrollbar synchronously.+ unsafe { (self.paint_scrollbar)(self.context, scrollbar) };+ }++ fn draw_composited_context(&mut self, draw: &CompositedContextDraw) {+ // SAFETY: The C++ painter reads the draw synchronously.+ unsafe { (self.draw_composited_context)(self.context, draw) };+ }++ fn begin_isolated_group(&mut self, group: &IsolatedGroup) {+ // SAFETY: The C++ painter reads the group and its filter bytes synchronously; the tape keeps them alive.+ unsafe { (self.begin_isolated_group)(self.context, group) };+ }++ fn begin_isolated_group_mask(&mut self, kind: MaskKind) {+ // SAFETY: The C++ painter starts the mask synchronously.+ unsafe { (self.begin_isolated_group_mask)(self.context, kind) };+ }++ fn end_isolated_group_mask(&mut self) {+ // SAFETY: The C++ painter ends the mask synchronously.+ unsafe { (self.end_isolated_group_mask)(self.context) };+ }++ fn end_isolated_group(&mut self) {+ // SAFETY: The C++ painter ends the group synchronously.+ unsafe { (self.end_isolated_group)(self.context) };+ }++ fn begin_tile_raster(&mut self, tile: &TileRaster) -> bool {+ // SAFETY: The C++ painter answers synchronously.+ unsafe { (self.begin_tile_raster)(self.context, tile) }+ }++ fn end_tile_raster(&mut self) {+ // SAFETY: The C++ painter finishes the raster synchronously.+ unsafe { (self.end_tile_raster)(self.context) };+ }++ fn begin_nested_display_list(+ &mut self,+ placement: &NestedDisplayListPlacement,+ requires_direct_replay: bool,+ ) -> NestedDisplayListReplay {+ // SAFETY: The C++ painter answers synchronously.+ unsafe { (self.begin_nested_display_list)(self.context, placement, requires_direct_replay) }+ }++ fn end_nested_display_list(&mut self) {+ // SAFETY: The C++ painter finishes the list synchronously.+ unsafe { (self.end_nested_display_list)(self.context) };+ }}diff --git a/Libraries/LibGfx/Rust/src/geometry.rs b/Libraries/LibGfx/Rust/src/geometry.rsindex 9f71e7c160c..74d7fcef1a5 100644--- a/Libraries/LibGfx/Rust/src/geometry.rs+++ b/Libraries/LibGfx/Rust/src/geometry.rs@@ -35,6 +35,12 @@ pub struct IntSize {pub height: i32,}+impl IntSize {+ pub fn is_empty(self) -> bool {+ self.width <= 0 || self.height <= 0+ }+}+#[derive(Clone, Copy, Debug, Default, PartialEq)]#[repr(C)]pub struct FloatSize {diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 90097ac43ae..35818f2d71e 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -9,7 +9,6 @@ set(SOURCESCompositorState.cppContextLayers.cppContextPresenter.cpp- DisplayListPlayer.cppDisplayListPlayerSkia.cppDisplayListRasterCache.cppFontSkia.cppdiff --git a/Services/Compositor/ContextPresenter.cpp b/Services/Compositor/ContextPresenter.cppindex ed6b2ef1897..58edc831a9c 100644--- a/Services/Compositor/ContextPresenter.cpp+++ b/Services/Compositor/ContextPresenter.cpp@@ -763,7 +763,7 @@ Optional<u64> ContextPresenter::current_video_frame_id(Compositing::VideoSinkResvoid ContextPresenter::paint_compositor_overlays(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& target_surface, FrameInputs const& frame_inputs, PaintUIOverlay paint_ui_overlay){- display_list_player.paint_scrollbars_painted_by_compositor(target_surface, frame_inputs.scrollbars());+ display_list_player.paint_scrollbars_into(target_surface, frame_inputs.scrollbars_painted_by_compositor());if (paint_ui_overlay == PaintUIOverlay::No)return;@@ -799,7 +799,7 @@ bool ContextPresenter::paint_layered_frame(DisplayListPlayerSkia& display_list_pauto layers = plan.layers();auto skia_backend_context = surface.skia_backend_context();auto surface_clear_color = Gfx::to_skia_color(m_display_list->surface_clear_color().value_or(Gfx::Color::Transparent));- m_raster_cache.drop_clip_paths_not_used_since_last_frame();+ m_raster_cache.drop_what_was_not_used_since_last_frame();m_layer_surfaces.resize(layers.size());for (size_t index = 0; index < layers.size(); ++index) {@@ -827,7 +827,7 @@ bool ContextPresenter::paint_layered_frame(DisplayListPlayerSkia& display_list_player_canvas.translate(-layer_surface.rect.x(), -layer_surface.rect.y());layer_canvas.clipIRect(SkIRect::MakeXYWH(repaint_rect.x(), repaint_rect.y(), repaint_rect.width(), repaint_rect.height()));layer_canvas.clear(layer.kind == LayerKind::Base ? surface_clear_color : SK_ColorTRANSPARENT);- display_list_player.execute(*m_display_list, frame_inputs.visual_context_tree(), m_resource_storage, m_raster_cache, &frame_inputs, *layer_surface.surface, &m_canvas_surfaces, composited_context_resolver, replaying_only(layer.record_spans));+ replay_display_list(display_list_player, *layer_surface.surface, frame_inputs, composited_context_resolver, replaying_only(layer.record_spans));layer_canvas.restore();layer_surface.content_version = ++m_last_layer_content_version;}@@ -865,7 +865,7 @@ void ContextPresenter::composite_layers_above_base(DisplayListPlayerSkia& displaauto const& layer = layers[index];if (layer.kind == LayerKind::Media) {if (layer.rect.intersects(damage_rect))- display_list_player.execute(*m_display_list, frame_inputs.visual_context_tree(), m_resource_storage, m_raster_cache, &frame_inputs, surface, &m_canvas_surfaces, composited_context_resolver, replaying_only(layer.record_spans, true));+ replay_display_list(display_list_player, surface, frame_inputs, composited_context_resolver, replaying_only(layer.record_spans, true));continue;}if (index >= m_layer_surfaces.size())@@ -1048,20 +1048,20 @@ Vector<RemoteSublayer> ContextPresenter::sublayers_shown_by_window_server()return sublayers;}+void ContextPresenter::replay_display_list(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver, ReplaySelection const& selection)+{+ auto painter = display_list_player.begin_painting(surface, m_resource_storage, m_raster_cache, &m_canvas_surfaces, composited_context_resolver);+ frame_inputs.replay(*m_display_list, painter, selection);+ display_list_player.end_painting();+}+void ContextPresenter::paint_current_display_list(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver, Optional<Gfx::IntRect> damage_rect, PaintUIOverlay paint_ui_overlay, bool apply_raster_transform){VERIFY(m_display_list);auto surface_clear_color = Gfx::to_skia_color(m_display_list->surface_clear_color().value_or(Gfx::Color::Transparent));auto paint_display_list = [&](Gfx::PaintingSurface& target_surface) {- display_list_player.execute(- *m_display_list,- frame_inputs.visual_context_tree(),- m_resource_storage,- m_raster_cache,- &frame_inputs,- target_surface,- &m_canvas_surfaces,- composited_context_resolver);+ m_raster_cache.drop_what_was_not_used_since_last_frame();+ replay_display_list(display_list_player, target_surface, frame_inputs, composited_context_resolver);paint_compositor_overlays(display_list_player, target_surface, frame_inputs, paint_ui_overlay);};diff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.hindex 4429f9ae0ed..e7d96677bf2 100644--- a/Services/Compositor/ContextPresenter.h+++ b/Services/Compositor/ContextPresenter.h@@ -191,6 +191,7 @@ private:// Returns the rect it painted, which grows to the whole frame when the frame has to hold media that the window// server was to show.[[nodiscard]] Gfx::IntRect paint_frame(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, CompositedContextResolver const*, Gfx::IntRect damage_rect, LayerUpdate&);+ void replay_display_list(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, CompositedContextResolver const*, ReplaySelection const& = replaying_everything());void paint_current_display_list(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, CompositedContextResolver const*, Optional<Gfx::IntRect> damage_rect = {}, PaintUIOverlay = PaintUIOverlay::Yes, bool apply_raster_transform = true);bool paint_layered_frame(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, CompositedContextResolver const*, Gfx::IntRect damage_rect, LayerUpdate const&);void composite_layers_above_base(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, CompositedContextResolver const*, LayerPlan const&, Gfx::IntRect damage_rect);diff --git a/Services/Compositor/DisplayListPlayer.cpp b/Services/Compositor/DisplayListPlayer.cppdeleted file mode 100644index d8ea7b836bb..00000000000--- a/Services/Compositor/DisplayListPlayer.cpp+++ /dev/null@@ -1,148 +0,0 @@-/*- * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/TemporaryChange.h>-#include <Compositor/DisplayListPlayer.h>-#include <Compositor/PaintingSurface.h>-#include <LibCompositing/RustFFI.h>-#include <LibGfx/PathData.h>--namespace Compositor {--using namespace Compositing;--void DisplayListPlayer::execute(- DisplayList const& display_list,- AccumulatedVisualContextTree const& visual_context_tree,- DisplayListResourceStorage const& resource_storage,- FrameInputs const* frame_inputs,- RefPtr<Gfx::PaintingSurface> surface,- OwnedCanvasSurfaces const* canvas_surfaces,- ReplaySelection const& selection)-{- VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());- VERIFY(frame_inputs || !selection.replays_only_record_spans);- TemporaryChange replay_selection_change { m_replay_selection, selection };- m_surface = surface;- m_active_display_list = &display_list;- m_active_visual_context_tree = &visual_context_tree;- m_resource_storage = &resource_storage;- m_canvas_surfaces = canvas_surfaces;- execute_impl(display_list, frame_inputs);- m_canvas_surfaces = nullptr;- m_resource_storage = nullptr;- m_active_visual_context_tree = nullptr;- m_active_display_list = nullptr;- m_surface = nullptr;-}--void DisplayListPlayer::execute_display_list_into_surface(DisplayList const& display_list, AccumulatedVisualContextTree const& visual_context_tree, Gfx::PaintingSurface& target_surface)-{- VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());- TemporaryChange surface_change { m_surface, RefPtr<Gfx::PaintingSurface> { target_surface } };- TemporaryChange display_list_change { m_active_display_list, &display_list };- TemporaryChange visual_context_tree_change { m_active_visual_context_tree, &visual_context_tree };- VERIFY(m_resource_storage);- execute_impl(display_list, nullptr);-}--void DisplayListPlayer::execute_nested_display_list(- DisplayList const& display_list,- AccumulatedVisualContextTree const& visual_context_tree)-{- VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());- TemporaryChange display_list_change { m_active_display_list, &display_list };- TemporaryChange visual_context_tree_change { m_active_visual_context_tree, &visual_context_tree };- VERIFY(m_resource_storage);- execute_impl(display_list, nullptr);-}--// Builds the callbacks the Rust replay drives a player through.-struct DisplayListPlayer::ReplayCallbacks {- static Compositing::RustFFI::FfiDisplayListReplayCallbacks for_player(DisplayListPlayer& player)- {- return {- .context = &player,- .canvas_matrix = [](void* context) -> Gfx::FloatMatrix4x4 { return static_cast<DisplayListPlayer*>(context)->canvas_matrix(); },- .set_matrix = [](void* context, Gfx::FloatMatrix4x4 const* matrix) { static_cast<DisplayListPlayer*>(context)->set_matrix(*matrix); },- .would_be_fully_clipped_by_painter = [](void* context, Gfx::IntRect rect) -> bool {- return static_cast<DisplayListPlayer*>(context)->would_be_fully_clipped_by_painter(rect);- },- .push_clip = [](void* context, ReplayClip const* clip) { static_cast<DisplayListPlayer*>(context)->push_clip(*clip); },- .push_clip_path = [](void* context, Gfx::FFI::PathGeometryData const* path, u64 path_identity, Gfx::WindingRule winding_rule) { static_cast<DisplayListPlayer*>(context)->push_clip_path(Gfx::PathData::from_ffi(*path), path_identity, winding_rule); },- .push_layer = [](void* context, ReplayLayer const* layer) { static_cast<DisplayListPlayer*>(context)->push_layer(*layer); },- .push_mask = [](void* context, ReplayMask const* mask, ReplayLayer const* backdrop) { static_cast<DisplayListPlayer*>(context)->push_mask(*mask, backdrop); },- .pop_mask = [](void* context, ReplayMask const* mask, EffectNodeIndex effect) { static_cast<DisplayListPlayer*>(context)->pop_mask(*mask, effect); },- .pop = [](void* context) { static_cast<DisplayListPlayer*>(context)->pop(); },- .push_device_space_plane_clip = [](void* context, Gfx::FloatVector3 const* vertices, size_t vertex_count) { static_cast<DisplayListPlayer*>(context)->push_device_space_plane_clip({ vertices, vertex_count }); },- .push_transform = [](void* context, Gfx::AffineTransform const* transform) { static_cast<DisplayListPlayer*>(context)->push_transform(*transform); },- .push_clip_path_bytes = [](void* context, u8 const* path_bytes, size_t path_bytes_size, Gfx::WindingRule winding_rule, Compositing::ClipMode mode) { static_cast<DisplayListPlayer*>(context)->push_clip_path_bytes({ path_bytes, path_bytes_size }, winding_rule, mode); },- .play_command = [](void* context, DisplayListCommandType command_type, u8 const* command, u8 const* payload, size_t payload_size) { static_cast<DisplayListPlayer*>(context)->play_command_bytes(command_type, command, { payload, payload_size }); },- };- }-};--void DisplayListPlayer::play_command_bytes(DisplayListCommandType command_type, u8 const* command, ReadonlyBytes payload)-{- TemporaryChange current_command_payload_change { m_current_command_payload, payload };- switch (command_type) {-#define PLAY_DISPLAY_LIST_COMMAND(command_type) \- case DisplayListCommandType::command_type: \- play_command(read_display_list_object<command_type>({ command, sizeof(command_type) })); \- break;- ENUMERATE_DISPLAY_LIST_COMMANDS(PLAY_DISPLAY_LIST_COMMAND)-#undef PLAY_DISPLAY_LIST_COMMAND-#define REJECT_CANVAS_2D_COMMAND(command_type) case DisplayListCommandType::command_type:- ENUMERATE_CANVAS_2D_COMMANDS(REJECT_CANVAS_2D_COMMAND)-#undef REJECT_CANVAS_2D_COMMAND- // NB: The display list of a page never holds a command of the canvas 2D stream; validation rejects one.- VERIFY_NOT_REACHED();- }-}--void DisplayListPlayer::execute_command_bytes(ReadonlyBytes command_bytes)-{- auto callbacks = ReplayCallbacks::for_player(*this);- if (m_active_frame_inputs)- m_active_frame_inputs->replay_records(command_bytes, callbacks);- else- DisplayList::replay_records(command_bytes, callbacks);-}--void DisplayListPlayer::execute_command_bytes_into_surface(ReadonlyBytes command_bytes, Gfx::PaintingSurface& target_surface)-{- TemporaryChange surface_change { m_surface, RefPtr<Gfx::PaintingSurface> { target_surface } };- DisplayList::replay_records(command_bytes, ReplayCallbacks::for_player(*this));-}--void DisplayListPlayer::declare_mask_content(EffectNodeIndex effect, ReadonlyBytes content)-{- m_declared_mask_contents.set(effect.value(), content);-}--Optional<ReadonlyBytes> DisplayListPlayer::declared_mask_content(EffectNodeIndex effect) const-{- return m_declared_mask_contents.get(effect.value());-}--void DisplayListPlayer::execute_impl(DisplayList const& display_list, FrameInputs const* frame_inputs)-{- TemporaryChange active_frame_inputs_change { m_active_frame_inputs, frame_inputs };- TemporaryChange declared_mask_contents_change { m_declared_mask_contents, HashMap<u32, ReadonlyBytes> {} };- auto const& visual_context_tree = active_visual_context_tree();- VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == visual_context_tree.structural_epoch());- VERIFY(m_surface);-- auto callbacks = ReplayCallbacks::for_player(*this);- if (frame_inputs) {- VERIFY(frame_inputs->visual_context_tree().rust_handle() == visual_context_tree.rust_handle());- frame_inputs->replay(display_list, callbacks, exchange(m_replay_selection, replaying_everything()));- } else {- display_list.replay(visual_context_tree, callbacks);- }-}--}diff --git a/Services/Compositor/DisplayListPlayer.h b/Services/Compositor/DisplayListPlayer.hdeleted file mode 100644index 822ef9715ca..00000000000--- a/Services/Compositor/DisplayListPlayer.h+++ /dev/null@@ -1,95 +0,0 @@-/*- * Copyright (c) 2024-2026, Aliaksandr Kalenik <[email protected]>- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/RefPtr.h>-#include <AK/Span.h>-#include <Compositor/Forward.h>-#include <Compositor/FrameInputs.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListCommand.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Forward.h>-#include <LibGfx/Forward.h>--namespace Compositor {--class DisplayListPlayer {-public:- virtual ~DisplayListPlayer() = default;-- // The frame inputs say where the frame presents what scrolls. Without them, nothing is scrolled.- void execute(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Compositing::DisplayListResourceStorage const&, FrameInputs const*, RefPtr<Gfx::PaintingSurface>, OwnedCanvasSurfaces const* = nullptr, ReplaySelection const& = replaying_everything());- virtual void flush(Gfx::PaintingSurface&) = 0;--protected:- Gfx::PaintingSurface& surface() const { return *m_surface; }- Compositing::DisplayList const& active_display_list() const { return *m_active_display_list; }- Compositing::AccumulatedVisualContextTree const& active_visual_context_tree() const { return *m_active_visual_context_tree; }- Compositing::DisplayListResourceStorage const& resource_storage() const { return *m_resource_storage; }- OwnedCanvasSurfaces const* canvas_surfaces() const { return m_canvas_surfaces; }- ReadonlyBytes inline_data(Compositing::DisplayListDataSpan span) const- {- VERIFY(static_cast<size_t>(span.offset) + span.size <= m_current_command_payload.size());- return m_current_command_payload.slice(span.offset, span.size);- }- template<typename T>- ReadonlySpan<T> inline_objects(Compositing::DisplayListDataSpan span) const- {- static_assert(alignof(T) <= Compositing::display_list_payload_alignment);- auto bytes = inline_data(span);- VERIFY(bytes.size() % sizeof(T) == 0);- VERIFY(reinterpret_cast<FlatPtr>(bytes.data()) % alignof(T) == 0);- return { reinterpret_cast<T const*>(bytes.data()), bytes.size() / sizeof(T) };- }- void execute_impl(Compositing::DisplayList const&, FrameInputs const*);- // Plays records that a command of the list being played nests, scrolled as that list is.- void execute_command_bytes(ReadonlyBytes);- void execute_display_list_into_surface(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&, Gfx::PaintingSurface&);- void execute_command_bytes_into_surface(ReadonlyBytes, Gfx::PaintingSurface&);- void declare_mask_content(Compositing::EffectNodeIndex, ReadonlyBytes content);- Optional<ReadonlyBytes> declared_mask_content(Compositing::EffectNodeIndex) const;- void execute_nested_display_list(Compositing::DisplayList const&, Compositing::AccumulatedVisualContextTree const&);--private:- struct ReplayCallbacks;- void play_command_bytes(Compositing::DisplayListCommandType, u8 const* command, ReadonlyBytes payload);--#define DECLARE_PLAY_COMMAND(command_type) \- virtual void play_command(Compositing::command_type const&) = 0;- ENUMERATE_DISPLAY_LIST_COMMANDS(DECLARE_PLAY_COMMAND)-#undef DECLARE_PLAY_COMMAND- virtual void set_matrix(Gfx::FloatMatrix4x4 const&) = 0;- virtual Gfx::FloatMatrix4x4 canvas_matrix() const = 0;- virtual bool would_be_fully_clipped_by_painter(Gfx::IntRect) const = 0;-- virtual void push_clip(Compositing::ReplayClip const&) = 0;- // A path stays the same for as long as it has its identity.- virtual void push_clip_path(Gfx::PathData const&, u64 path_identity, Gfx::WindingRule) = 0;- virtual void push_clip_path_bytes(ReadonlyBytes, Gfx::WindingRule, Compositing::ClipMode) = 0;- virtual void push_transform(Gfx::AffineTransform const&) = 0;- virtual void push_layer(Compositing::ReplayLayer const&) = 0;- virtual void push_mask(Compositing::ReplayMask const&, Compositing::ReplayLayer const* backdrop) = 0;- virtual void pop_mask(Compositing::ReplayMask const&, Compositing::EffectNodeIndex) = 0;- virtual void pop() = 0;- virtual void push_device_space_plane_clip(ReadonlySpan<Gfx::FloatVector3> polygon_vertices) = 0;-- Compositing::DisplayList const* m_active_display_list { nullptr };- Compositing::AccumulatedVisualContextTree const* m_active_visual_context_tree { nullptr };- Compositing::DisplayListResourceStorage const* m_resource_storage { nullptr };- OwnedCanvasSurfaces const* m_canvas_surfaces { nullptr };- RefPtr<Gfx::PaintingSurface> m_surface;- ReadonlyBytes m_current_command_payload;- FrameInputs const* m_active_frame_inputs { nullptr };- ReplaySelection m_replay_selection { replaying_everything() };- HashMap<u32, ReadonlyBytes> m_declared_mask_contents;-};--}diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 7f68f8703d1..1de3bea3585 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -39,6 +39,7 @@#include <Compositor/DisplayListRasterCache.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/SkiaUtils.h>+#include <LibCompositing/DisplayList/DisplayList.h>#include <LibGfx/Bitmap.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/DecodedImageFrame.h>@@ -48,6 +49,29 @@ namespace Compositor {using namespace Compositing;+struct DisplayListPlayerSkia::RasterState {+ AK_ALLOC_WITH_KMALLOC;++ struct TileRaster {+ RustFFI::TileRaster tile;+ RefPtr<Gfx::PaintingSurface> surface;+ };+ Vector<TileRaster, 2> tile_rasters_in_progress;+ // The raster of the tile records that the next command draws with.+ sk_sp<SkImage> tile_raster_for_next_command;++ struct NestedDisplayList {+ RustFFI::NestedDisplayListReplay replay { RustFFI::NestedDisplayListReplay::Skipped };+ // For a list replayed into a raster:+ DisplayListResourceId display_list_id {};+ Gfx::IntRect raster_rect_in_list_space {};+ Gfx::IntRect visible_rect_in_list_space {};+ SkMatrix placement {};+ bool draws_pixel_exact { false };+ };+ Vector<NestedDisplayList, 2> nested_display_lists_in_progress;+};+DisplayListPlayerSkia::DisplayListPlayerSkia(): DisplayListPlayerSkia(Gfx::SkiaBackendContext::the_main_thread_context()){@@ -55,37 +79,108 @@ DisplayListPlayerSkia::DisplayListPlayerSkia()DisplayListPlayerSkia::DisplayListPlayerSkia(RefPtr<Gfx::SkiaBackendContext> skia_backend_context): m_skia_backend_context(move(skia_backend_context))+ , m_raster_state(make<RasterState>())+{+}++DisplayListPlayerSkia::~DisplayListPlayerSkia() = default;++Gfx::PaintingSurface& DisplayListPlayerSkia::surface() const+{+ return *m_surfaces.last();+}++// The C++ ends of the raster painter the Rust replay drives.+struct DisplayListPlayerSkia::PainterCallbacks {+ static DisplayListPlayerSkia& player(void* context) { return *static_cast<DisplayListPlayerSkia*>(context); }++ static RustFFI::FfiRasterPainter for_player(DisplayListPlayerSkia& player)+ {+ return {+ .context = &player,+ .canvas_matrix = [](void* context) -> Gfx::FloatMatrix4x4 { return PainterCallbacks::player(context).canvas_matrix(); },+ .set_matrix = [](void* context, Gfx::FloatMatrix4x4 const* matrix) { PainterCallbacks::player(context).set_matrix(*matrix); },+ .would_be_fully_clipped_by_painter = [](void* context, Gfx::IntRect rect) -> bool { return PainterCallbacks::player(context).would_be_fully_clipped_by_painter(rect); },+ .push_clip = [](void* context, ReplayClip const* clip) { PainterCallbacks::player(context).push_clip(*clip); },+ .push_clip_path = [](void* context, Gfx::FFI::PathGeometryData const* path, u64 path_identity, Gfx::WindingRule winding_rule) { PainterCallbacks::player(context).push_clip_path(Gfx::PathData::from_ffi(*path), path_identity, winding_rule); },+ .push_layer = [](void* context, ReplayLayer const* layer) { PainterCallbacks::player(context).push_layer(*layer); },+ .push_mask = [](void* context, ReplayMask const* mask, ReplayLayer const* backdrop) { PainterCallbacks::player(context).push_mask(*mask, backdrop); },+ .begin_mask_content = [](void* context, ReplayMask const* mask) { PainterCallbacks::player(context).begin_mask_content(*mask); },+ .pop_mask = [](void* context) { PainterCallbacks::player(context).pop_mask(); },+ .pop = [](void* context) { PainterCallbacks::player(context).pop(); },+ .push_device_space_plane_clip = [](void* context, Gfx::FloatVector3 const* vertices, size_t vertex_count) { PainterCallbacks::player(context).push_device_space_plane_clip({ vertices, vertex_count }); },+ .push_transform = [](void* context, Gfx::AffineTransform const* transform) { PainterCallbacks::player(context).push_transform(*transform); },+ .push_clip_path_bytes = [](void* context, u8 const* path_bytes, size_t path_bytes_size, Gfx::WindingRule winding_rule, Compositing::ClipMode mode) { PainterCallbacks::player(context).push_clip_path_bytes({ path_bytes, path_bytes_size }, winding_rule, mode); },+ .play_command = [](void* context, DisplayListCommandType command_type, u8 const* command, u8 const* payload, size_t payload_size) { PainterCallbacks::player(context).play_command_bytes(command_type, command, { payload, payload_size }); },+ .fill_rect = [](void* context, RustFFI::ResolvedFillRect const* fill) { PainterCallbacks::player(context).fill_rect(*fill); },+ .fill_rect_with_rounded_corners = [](void* context, RustFFI::ResolvedFillRectWithRoundedCorners const* fill) { PainterCallbacks::player(context).fill_rect_with_rounded_corners(*fill); },+ .paint_scrollbar = [](void* context, PresentedScrollbar const* scrollbar) { PainterCallbacks::player(context).paint_scrollbar(*scrollbar); },+ .draw_composited_context = [](void* context, RustFFI::CompositedContextDraw const* draw) { PainterCallbacks::player(context).draw_composited_context(*draw); },+ .begin_isolated_group = [](void* context, RustFFI::IsolatedGroup const* group) { PainterCallbacks::player(context).begin_isolated_group(*group); },+ .begin_isolated_group_mask = [](void* context, Gfx::MaskKind kind) { PainterCallbacks::player(context).begin_isolated_group_mask(kind); },+ .end_isolated_group_mask = [](void* context) { PainterCallbacks::player(context).end_isolated_group_mask(); },+ .end_isolated_group = [](void* context) { PainterCallbacks::player(context).end_isolated_group(); },+ .begin_tile_raster = [](void* context, RustFFI::TileRaster const* tile) -> bool { return PainterCallbacks::player(context).begin_tile_raster(*tile); },+ .end_tile_raster = [](void* context) { PainterCallbacks::player(context).end_tile_raster(); },+ .begin_nested_display_list = [](void* context, RustFFI::NestedDisplayListPlacement const* placement, bool requires_direct_replay) { return PainterCallbacks::player(context).begin_nested_display_list(*placement, requires_direct_replay); },+ .end_nested_display_list = [](void* context) { PainterCallbacks::player(context).end_nested_display_list(); },+ .nested_display_list = [](void* context, u64 display_list_id, RustFFI::FfiNestedDisplayList* nested_display_list) -> bool { return PainterCallbacks::player(context).nested_display_list(display_list_id, *nested_display_list); },+ };+ }+};++RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSurface& surface, DisplayListResourceStorage const& resource_storage, DisplayListRasterCache& raster_cache, OwnedCanvasSurfaces const* canvas_surfaces, CompositedContextResolver const* composited_context_resolver){+ VERIFY(m_surfaces.is_empty());+ m_surfaces.append(surface);+ m_resource_storage = &resource_storage;+ m_raster_cache = &raster_cache;+ m_canvas_surfaces = canvas_surfaces;+ m_composited_context_resolver = composited_context_resolver;+ return PainterCallbacks::for_player(*this);}-DisplayListPlayerSkia::~DisplayListPlayerSkia()+void DisplayListPlayerSkia::end_painting(){+ VERIFY(m_surfaces.size() == 1);+ VERIFY(m_raster_state->tile_rasters_in_progress.is_empty());+ VERIFY(m_raster_state->nested_display_lists_in_progress.is_empty());+ m_raster_state->tile_raster_for_next_command = nullptr;+ m_surfaces.clear();+ m_resource_storage = nullptr;+ m_raster_cache = nullptr;+ m_canvas_surfaces = nullptr;+ m_composited_context_resolver = nullptr;+}++void DisplayListPlayerSkia::play_command_bytes(DisplayListCommandType command_type, u8 const* command, ReadonlyBytes payload)+{+ TemporaryChange current_command_payload_change { m_current_command_payload, payload };+ switch (command_type) {+#define PLAY_DISPLAY_LIST_COMMAND(command_type) \+ case DisplayListCommandType::command_type: \+ play_command(read_display_list_object<command_type>({ command, sizeof(command_type) })); \+ break;+ ENUMERATE_DISPLAY_LIST_COMMANDS_PLAYED_AS_RECORDED(PLAY_DISPLAY_LIST_COMMAND)+#undef PLAY_DISPLAY_LIST_COMMAND+ default:+ // NB: The replay resolves every other command of a display list itself, and validation rejects a command of+ // the canvas 2D stream in one.+ VERIFY_NOT_REACHED();+ }}-void DisplayListPlayerSkia::execute(- DisplayList const& display_list,- AccumulatedVisualContextTree const& visual_context_tree,- DisplayListResourceStorage const& resource_storage,- DisplayListRasterCache& raster_cache,- FrameInputs const* frame_inputs,- RefPtr<Gfx::PaintingSurface> surface,- OwnedCanvasSurfaces const* canvas_surfaces,- CompositedContextResolver const* composited_context_resolver,- ReplaySelection const& selection)+bool DisplayListPlayerSkia::nested_display_list(u64 display_list_id, RustFFI::FfiNestedDisplayList& nested_display_list) const{- TemporaryChange composited_context_resolver_change { m_composited_context_resolver, composited_context_resolver };- TemporaryChange scrollbars_of_frame_change { m_scrollbars_of_frame, frame_inputs ? frame_inputs->scrollbars() : ReadonlySpan<ScrollbarOfFrame> {} };- if (!selection.replays_only_record_spans)- raster_cache.drop_clip_paths_not_used_since_last_frame();- TemporaryChange raster_cache_change { m_raster_cache, &raster_cache };- DisplayListPlayer::execute(- display_list,- visual_context_tree,- resource_storage,- frame_inputs,- move(surface),- canvas_surfaces,- selection);+ DisplayListResourceId id { display_list_id };+ if (!resource_storage().has_display_list(id))+ return false;+ auto const& resource = resource_storage().display_list_resource(id);+ nested_display_list.storage = resource.display_list->rust_handle();+ nested_display_list.visual_context_tree = resource.visual_context_tree.rust_handle();+ nested_display_list.root_group_color = resource.display_list->root_group_color();+ nested_display_list.requires_direct_replay = resource_storage().display_list_requires_direct_replay(id);+ return true;}static SkRRect to_skia_rrect(auto const& rect, Gfx::CornerRadii const& corner_radii)@@ -200,13 +295,15 @@ static void paint_scrollbar_into_surface(Gfx::PaintingSurface& surface, Presentecanvas.drawRRect(thumb_rrect, stroke_paint);}-void DisplayListPlayerSkia::paint_scrollbars_painted_by_compositor(Gfx::PaintingSurface& surface, ReadonlySpan<ScrollbarOfFrame> scrollbars_of_frame)+void DisplayListPlayerSkia::paint_scrollbars_into(Gfx::PaintingSurface& surface, ReadonlySpan<PresentedScrollbar> scrollbars){- for (auto const& scrollbar : scrollbars_of_frame) {- if (!scrollbar.is_painted_by_compositor)- continue;- paint_scrollbar_into_surface(surface, presented_scrollbar_with_colors(scrollbar, scrollbar.thumb_color, scrollbar.thumb_outline_color, scrollbar.track_color));- }+ for (auto const& scrollbar : scrollbars)+ paint_scrollbar_into_surface(surface, scrollbar);+}++void DisplayListPlayerSkia::paint_scrollbar(PresentedScrollbar const& scrollbar)+{+ paint_scrollbar_into_surface(surface(), scrollbar);}static SkMatrix vertical_glyph_run_rotation(Gfx::IntRect const& rect)@@ -267,25 +364,18 @@ static void apply_compositing_and_blending_operator(SkPaint& paint, Gfx::Composipaint.setBlender(Gfx::to_skia_blender(compositing_and_blending_operator));}-void DisplayListPlayerSkia::play_command(FillRect const& command)+void DisplayListPlayerSkia::fill_rect(RustFFI::ResolvedFillRect const& fill){- auto const& rect = command.rect;auto& canvas = surface().canvas();SkPaint paint;paint.setAntiAlias(true);- auto color = command.background_color_animation_effect == NO_EFFECT_NODE- ? command.color- : active_visual_context_tree().sampled_background_color(command.background_color_animation_effect).value_or(command.color);- paint.setColor(to_skia_color(color));- apply_compositing_and_blending_operator(paint, command.compositing_and_blending_operator);- canvas.drawRect(to_skia_rect(rect), paint);+ paint.setColor(to_skia_color(fill.color));+ apply_compositing_and_blending_operator(paint, fill.compositing_and_blending_operator);+ canvas.drawRect(to_skia_rect(fill.rect), paint);}void DisplayListPlayerSkia::play_command(PaintCaret const& command){- if (!caret_is_visible_at_time(command, MonotonicTime::now().nanoseconds()))- return;-auto& canvas = surface().canvas();SkPaint paint;paint.setAntiAlias(true);@@ -293,21 +383,13 @@ void DisplayListPlayerSkia::play_command(PaintCaret const& command)canvas.drawRect(to_skia_rect(command.rect), paint);}-void DisplayListPlayerSkia::play_command(DrawCompositedContext const& command)+void DisplayListPlayerSkia::draw_composited_context(RustFFI::CompositedContextDraw const& command){if (!m_composited_context_resolver)return;auto destination_rect = command.dst_rect;-- // Snap iframe origins to device pixels for browser compatibility when transforms are absent or identity.- // Preserve fractional placement under other transforms to retain the raster phase of surrounding content.- if (command.snap_origin_if_untransformed && active_visual_context_tree().translations_snap_to_device_pixels(command.spatial_node_index)) {- destination_rect.set_x(roundf(destination_rect.x()));- destination_rect.set_y(roundf(destination_rect.y()));- }-- auto composited_context = (*m_composited_context_resolver)(command.child_context_id, destination_rect, canvas_matrix());+ auto composited_context = (*m_composited_context_resolver)(Web::CompositorContextId { command.child_context_id }, destination_rect, canvas_matrix());if (!composited_context.surface || composited_context.content_rect.is_empty())return;@@ -616,44 +698,44 @@ void DisplayListPlayerSkia::play_command(DrawTiledDecodedImageFrame const& commacanvas.drawRect(to_skia_rect(pattern_rect), paint);}-static u64 repeated_tile_raster_key(ReadonlyBytes tile_records, Gfx::IntSize tile_size)-{- auto const* characters = reinterpret_cast<char const*>(tile_records.data());- u64 high = string_hash(characters, tile_records.size(), 0x9e3779b9u);- u64 low = string_hash(characters, tile_records.size(), static_cast<u32>(tile_size.width() * 31 + tile_size.height()));- return (high << 32) | low;-}-void DisplayListPlayerSkia::play_command(DrawRepeatedTile const& command){- auto tile_size = command.tile_size;- if (tile_size.is_empty() || command.dst_rect.is_empty() || command.tile_step.is_empty())+ auto image = exchange(m_raster_state->tile_raster_for_next_command, nullptr);+ if (!image)return;-- auto tile_records = inline_data(command.tile);- auto raster_key = repeated_tile_raster_key(tile_records, tile_size);- auto image = raster_cache().repeated_tile_raster(raster_key, tile_size, m_skia_backend_context);- if (!image) {- image = rasterize_records_into_tile(tile_records, Gfx::IntRect { {}, tile_size });- if (!image)- return;- raster_cache().add_repeated_tile_raster(raster_key, tile_size, m_skia_backend_context, image);- }paint_repeated_image(surface().canvas(), *image, command.dst_rect, command.tile_step, command.scaling_mode, command.compositing_and_blending_operator, command.repeat.x, command.repeat.y);}-sk_sp<SkImage> DisplayListPlayerSkia::rasterize_records_into_tile(ReadonlyBytes tile_records, Gfx::IntRect tile_rect)+bool DisplayListPlayerSkia::begin_tile_raster(RustFFI::TileRaster const& tile){+ m_raster_state->tile_raster_for_next_command = nullptr;+ if (tile.cacheable) {+ if (auto image = raster_cache().repeated_tile_raster(tile.key, tile.size, m_skia_backend_context)) {+ m_raster_state->tile_raster_for_next_command = move(image);+ return false;+ }+ }// NB: A tile can be larger than any surface, e.g. a background tile far wider than a bitmap can be.- auto tile_surface_or_error = Gfx::PaintingSurface::try_create_with_size(tile_rect.size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, m_skia_backend_context);+ auto tile_surface_or_error = Gfx::PaintingSurface::try_create_with_size(tile.size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, m_skia_backend_context);if (tile_surface_or_error.is_error())- return nullptr;+ return false;auto tile_surface = tile_surface_or_error.release_value();tile_surface->canvas().clear(SK_ColorTRANSPARENT);- tile_surface->canvas().translate(-tile_rect.x(), -tile_rect.y());- execute_command_bytes_into_surface(tile_records, *tile_surface);- tile_surface->canvas().resetMatrix();- return tile_surface->sk_surface().makeImageSnapshot();+ m_raster_state->tile_rasters_in_progress.append({ tile, tile_surface });+ m_surfaces.append(tile_surface);+ return true;+}++void DisplayListPlayerSkia::end_tile_raster()+{+ auto raster = m_raster_state->tile_rasters_in_progress.take_last();+ VERIFY(m_surfaces.last().ptr() == raster.surface.ptr());+ (void)m_surfaces.take_last();+ raster.surface->canvas().resetMatrix();+ auto image = raster.surface->sk_surface().makeImageSnapshot();+ if (image && raster.tile.cacheable)+ raster_cache().add_repeated_tile_raster(raster.tile.key, raster.tile.size, m_skia_backend_context, image);+ m_raster_state->tile_raster_for_next_command = move(image);}static SkGradient::Interpolation to_skia_interpolation(Gfx::GradientInterpolationMethod interpolation_method)@@ -925,19 +1007,14 @@ void DisplayListPlayerSkia::play_command(PaintTextShadow const& command)}}-void DisplayListPlayerSkia::play_command(FillRectWithRoundedCorners const& command)+void DisplayListPlayerSkia::fill_rect_with_rounded_corners(RustFFI::ResolvedFillRectWithRoundedCorners const& fill){- auto const& rect = command.rect;-auto& canvas = surface().canvas();SkPaint paint;- auto color = command.background_color_animation_effect == NO_EFFECT_NODE- ? command.color- : active_visual_context_tree().sampled_background_color(command.background_color_animation_effect).value_or(command.color);- paint.setColor(to_skia_color(color));+ paint.setColor(to_skia_color(fill.color));paint.setAntiAlias(true);- auto rounded_rect = to_skia_rrect(rect, command.corner_radii);+ auto rounded_rect = to_skia_rrect(fill.rect, fill.corner_radii);canvas.drawRRect(rounded_rect, paint);}@@ -1102,7 +1179,8 @@ SkPaint DisplayListPlayerSkia::paint_style_to_skia_paint(DisplayListPaintStyle cif (tile_size.is_empty())return {};- auto image = rasterize_records_into_tile(inline_data(paint_style.pattern_tile), Gfx::IntRect { {}, tile_size });+ // The replay rasterized the pattern's tile records just before this command.+ auto image = exchange(m_raster_state->tile_raster_for_next_command, nullptr);if (!image)return {};@@ -1303,53 +1381,54 @@ void DisplayListPlayerSkia::play_command(PaintConicGradient const& command)surface().canvas().drawRect(to_skia_rect(rect), paint);}-void DisplayListPlayerSkia::play_command(DrawIsolatedGroup const& command)+void DisplayListPlayerSkia::begin_isolated_group(RustFFI::IsolatedGroup const& group){auto& canvas = surface().canvas();canvas.save();- canvas.clipRect(to_skia_rect(command.clip_rect), true);+ canvas.clipRect(to_skia_rect(group.clip_rect), true);SkPaint group_paint;- if (command.opacity < 1.0f)- group_paint.setAlphaf(command.opacity);- if (command.compositing_and_blending_operator != Gfx::CompositingAndBlendingOperator::Normal)- group_paint.setBlender(Gfx::to_skia_blender(command.compositing_and_blending_operator));- if (command.filter.size != 0)- group_paint.setImageFilter(image_filter_from_bytes(inline_data(command.filter)));+ if (group.opacity < 1.0f)+ group_paint.setAlphaf(group.opacity);+ if (group.compositing_and_blending_operator != Gfx::CompositingAndBlendingOperator::Normal)+ group_paint.setBlender(Gfx::to_skia_blender(group.compositing_and_blending_operator));+ if (group.filter_bytes_size != 0)+ group_paint.setImageFilter(image_filter_from_bytes({ group.filter_bytes, group.filter_bytes_size }));canvas.saveLayer(nullptr, &group_paint);- execute_command_bytes(inline_data(command.content));- if (command.mask.size != 0) {- SkPaint mask_paint;- mask_paint.setBlender(Gfx::to_skia_blender(Gfx::CompositingAndBlendingOperator::DestinationIn));- if (command.mask_kind == Gfx::MaskKind::Luminance)- mask_paint.setColorFilter(SkLumaColorFilter::Make());- canvas.saveLayer(nullptr, &mask_paint);- execute_command_bytes(inline_data(command.mask));- canvas.restore();- }- canvas.restore();- canvas.restore();}-void DisplayListPlayerSkia::play_command(DeclareMaskContent const& command)+void DisplayListPlayerSkia::begin_isolated_group_mask(Gfx::MaskKind mask_kind)+{+ SkPaint mask_paint;+ mask_paint.setBlender(Gfx::to_skia_blender(Gfx::CompositingAndBlendingOperator::DestinationIn));+ if (mask_kind == Gfx::MaskKind::Luminance)+ mask_paint.setColorFilter(SkLumaColorFilter::Make());+ surface().canvas().saveLayer(nullptr, &mask_paint);+}++void DisplayListPlayerSkia::end_isolated_group_mask(){- declare_mask_content(command.effect, inline_data(command.content));+ surface().canvas().restore();+}++void DisplayListPlayerSkia::end_isolated_group()+{+ auto& canvas = surface().canvas();+ canvas.restore();+ canvas.restore();}-void DisplayListPlayerSkia::play_command(PaintNestedDisplayList const& command)+// Rasterize immutable nested lists (SVG images and masks) at list resolution and reuse their snapshots.+// The first paint of a list rasterizes only the visible portion, so lists replaced every frame do not paint+// clipped content. Later cache misses rasterize small lists whole, so scrolled or sliced lists hit one raster.+// NB: Use this path from the first paint. Direct replay and a cached raster can produce different pixels,+// especially when a screenshot targets a CPU bitmap while the cached raster is rendered on the GPU.+// The number of previous paints must not change how the list is rendered.+// Lists with destination-reading blends or live content, or under rotated/skewed/mirrored transforms,+// replay directly. Near-integer placements at list resolution avoid filtering; other placements resample.+RustFFI::NestedDisplayListReplay DisplayListPlayerSkia::begin_nested_display_list(RustFFI::NestedDisplayListPlacement const& command, bool requires_direct_replay){auto& canvas = surface().canvas();- auto const& nested_display_list = resource_storage().display_list_resource(command.display_list_id);- // The scrollbars of this context do not belong to the scroll nodes of a nested display list.- TemporaryChange<ReadonlySpan<ScrollbarOfFrame>> scrollbars_of_frame_change { m_scrollbars_of_frame, {} };-- // Rasterize immutable nested lists (SVG images and masks) at list resolution and reuse their snapshots.- // The first paint of a list rasterizes only the visible portion, so lists replaced every frame do not paint- // clipped content. Later cache misses rasterize small lists whole, so scrolled or sliced lists hit one raster.- // NB: Use this path from the first paint. Direct replay and a cached raster can produce different pixels,- // especially when a screenshot targets a CPU bitmap while the cached raster is rendered on the GPU.- // The number of previous paints must not change how the list is rendered.- // Lists with destination-reading blends or live content, or under rotated/skewed/mirrored transforms,- // replay directly. Near-integer placements at list resolution avoid filtering; other placements resample.+ DisplayListResourceId display_list_id { command.display_list_id };auto total_matrix = canvas.getTotalMatrix();auto list_bounds = Gfx::IntRect { {}, command.list_size };if (m_skia_backend_context && total_matrix.isScaleTranslate() && total_matrix.getScaleX() > 0 && total_matrix.getScaleY() > 0@@ -1369,55 +1448,63 @@ void DisplayListPlayerSkia::play_command(PaintNestedDisplayList const& command)if (!placement_device_rect.isEmpty() && placement.invert(&inverse_placement)) {auto visible_device_rect = SkRect::Make(canvas.getDeviceClipBounds());if (!visible_device_rect.intersect(placement_device_rect))- return;+ return RustFFI::NestedDisplayListReplay::Skipped;auto visible_in_list_space = inverse_placement.mapRect(visible_device_rect);auto visible_rect_in_list_space = Gfx::enclosing_int_rect(Gfx::FloatRect { visible_in_list_space.left(), visible_in_list_space.top(), visible_in_list_space.width(), visible_in_list_space.height() }).intersected(list_bounds);if (visible_rect_in_list_space.is_empty())- return;+ return RustFFI::NestedDisplayListReplay::Skipped;++ auto draw_raster = [&](SkImage& image, Gfx::IntRect raster_rect) {+ auto source_rect = visible_rect_in_list_space.translated(-raster_rect.location());+ auto destination_rect = placement.mapRect(to_skia_rect(visible_rect_in_list_space));+ auto sampling = draws_pixel_exact ? SkSamplingOptions() : SkSamplingOptions(SkFilterMode::kLinear);+ canvas.save();+ canvas.setMatrix(SkMatrix::I());+ canvas.drawImageRect(&image, to_skia_rect(source_rect), destination_rect, sampling, nullptr, SkCanvas::kStrict_SrcRectConstraint);+ canvas.restore();+ };Gfx::IntRect raster_rect;- auto cached_image = raster_cache().nested_display_list_raster(command.display_list_id, m_skia_backend_context, visible_rect_in_list_space, raster_rect);- if (!cached_image && !resource_storage().display_list_requires_direct_replay(command.display_list_id)) {+ if (auto cached_image = raster_cache().nested_display_list_raster(display_list_id, m_skia_backend_context, visible_rect_in_list_space, raster_rect)) {+ draw_raster(*cached_image, raster_rect);+ return RustFFI::NestedDisplayListReplay::Skipped;+ }+ if (!requires_direct_replay) {constexpr size_t max_full_list_raster_bytes = 16 * MiB;constexpr int max_full_list_raster_dimension = 16384;constexpr size_t max_raster_bytes = 128 * MiB;auto byte_size = [](Gfx::IntRect const& rect) { return static_cast<size_t>(rect.width()) * rect.height() * 4; };- bool rasterize_whole_list = raster_cache().has_rasterized_nested_display_list(command.display_list_id)+ bool rasterize_whole_list = raster_cache().has_rasterized_nested_display_list(display_list_id)&& byte_size(list_bounds) <= max_full_list_raster_bytes&& list_bounds.width() <= max_full_list_raster_dimension&& list_bounds.height() <= max_full_list_raster_dimension;auto raster_candidate_rect = rasterize_whole_list ? list_bounds : visible_rect_in_list_space;- if (byte_size(raster_candidate_rect) <= max_raster_bytes) {- cached_image = raster_cache().create_nested_display_list_raster(command.display_list_id, m_skia_backend_context, raster_candidate_rect, [&] {- // NB: When the raster can't be allocated, the nested list is replayed directly instead.- auto offscreen_surface_or_error = Gfx::PaintingSurface::try_create_with_size(- raster_candidate_rect.size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, m_skia_backend_context);- if (offscreen_surface_or_error.is_error())- return sk_sp<SkImage> {};+ if (byte_size(raster_candidate_rect) <= max_raster_bytes+ && raster_cache().reserve_nested_display_list_raster(display_list_id, m_skia_backend_context, raster_candidate_rect)) {+ // NB: When the raster can't be allocated, the nested list is replayed directly instead.+ auto offscreen_surface_or_error = Gfx::PaintingSurface::try_create_with_size(+ raster_candidate_rect.size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, m_skia_backend_context);+ if (offscreen_surface_or_error.is_error()) {+ raster_cache().finish_nested_display_list_raster(display_list_id, m_skia_backend_context, raster_candidate_rect, nullptr);+ } else {auto offscreen_surface = offscreen_surface_or_error.release_value();offscreen_surface->canvas().clear(SK_ColorTRANSPARENT);offscreen_surface->canvas().translate(-raster_candidate_rect.x(), -raster_candidate_rect.y());- execute_display_list_into_surface(- *nested_display_list.display_list, nested_display_list.visual_context_tree, *offscreen_surface);- offscreen_surface->canvas().resetMatrix();- return offscreen_surface->sk_surface().makeImageSnapshot();- });- raster_rect = raster_candidate_rect;+ m_surfaces.append(offscreen_surface);+ m_raster_state->nested_display_lists_in_progress.append({+ .replay = RustFFI::NestedDisplayListReplay::IntoRaster,+ .display_list_id = display_list_id,+ .raster_rect_in_list_space = raster_candidate_rect,+ .visible_rect_in_list_space = visible_rect_in_list_space,+ .placement = placement,+ .draws_pixel_exact = draws_pixel_exact,+ });+ return RustFFI::NestedDisplayListReplay::IntoRaster;+ }}}- if (cached_image) {- auto source_rect = visible_rect_in_list_space.translated(-raster_rect.location());- auto destination_rect = placement.mapRect(to_skia_rect(visible_rect_in_list_space));- auto sampling = draws_pixel_exact ? SkSamplingOptions() : SkSamplingOptions(SkFilterMode::kLinear);- canvas.save();- canvas.setMatrix(SkMatrix::I());- canvas.drawImageRect(cached_image.get(), to_skia_rect(source_rect), destination_rect,- sampling, nullptr, SkCanvas::kStrict_SrcRectConstraint);- canvas.restore();- return;- }}}@@ -1439,52 +1526,31 @@ void DisplayListPlayerSkia::play_command(PaintNestedDisplayList const& command)if (!list_bounds.is_empty() && !command.rect.is_empty())canvas.scale(command.rect.width() / command.list_size.width(), command.rect.height() / command.list_size.height());}- execute_nested_display_list(*nested_display_list.display_list, nested_display_list.visual_context_tree);- canvas.restore();-}--void DisplayListPlayerSkia::play_command(CompositorWheelHitTestTarget const&)-{-}--void DisplayListPlayerSkia::play_command(CompositorWheelHitTestTargetWithCornerRadii const&)-{-}--void DisplayListPlayerSkia::play_command(CompositorMainThreadWheelEventRegion const&)-{+ m_raster_state->nested_display_lists_in_progress.append({ .replay = RustFFI::NestedDisplayListReplay::Directly });+ return RustFFI::NestedDisplayListReplay::Directly;}-void DisplayListPlayerSkia::play_command(CompositorScrollbar const&)+void DisplayListPlayerSkia::end_nested_display_list(){-}--void DisplayListPlayerSkia::play_command(CompositorBlockingWheelEventRegion const&)-{-}--void DisplayListPlayerSkia::play_command(CompositorNestedContextWheelRegion const&)-{-}--void DisplayListPlayerSkia::play_command(PaintScrollBar const& command)-{- // A scrollbar command of the display list with no scrollbar of the frame is painted as the command gives it. The- // colors are the ones the display list resolved for the page, which it may have darkened.- for (auto const& scrollbar_of_frame : m_scrollbars_of_frame) {- if (!scrollbar_of_frame.is_painted_by_compositor && scrollbar_of_frame.scroll_node_index == command.scroll_node_index && scrollbar_of_frame.vertical == command.vertical) {- paint_scrollbar_into_surface(surface(), presented_scrollbar_with_colors(scrollbar_of_frame, command.thumb_color, command.thumb_outline_color, command.track_color));- return;- }+ auto nested = m_raster_state->nested_display_lists_in_progress.take_last();+ if (nested.replay == RustFFI::NestedDisplayListReplay::Directly) {+ surface().canvas().restore();+ return;}- PresentedScrollbar scrollbar {- .gutter_rect = command.gutter_rect.to_type<float>(),- .thumb_rect = thumb_rect_kept_inside_track(command.thumb_rect, command.track_rect, command.vertical).to_type<float>(),- .thumb_color = command.thumb_color,- .thumb_outline_color = command.thumb_outline_color,- .track_color = command.track_color,- };- paint_scrollbar_into_surface(surface(), scrollbar);+ VERIFY(nested.replay == RustFFI::NestedDisplayListReplay::IntoRaster);+ auto offscreen_surface = m_surfaces.take_last();+ offscreen_surface->canvas().resetMatrix();+ auto image = raster_cache().finish_nested_display_list_raster(nested.display_list_id, m_skia_backend_context, nested.raster_rect_in_list_space, offscreen_surface->sk_surface().makeImageSnapshot());+ if (!image)+ return;+ auto& canvas = surface().canvas();+ auto source_rect = nested.visible_rect_in_list_space.translated(-nested.raster_rect_in_list_space.location());+ auto destination_rect = nested.placement.mapRect(to_skia_rect(nested.visible_rect_in_list_space));+ auto sampling = nested.draws_pixel_exact ? SkSamplingOptions() : SkSamplingOptions(SkFilterMode::kLinear);+ canvas.save();+ canvas.setMatrix(SkMatrix::I());+ canvas.drawImageRect(image.get(), to_skia_rect(source_rect), destination_rect, sampling, nullptr, SkCanvas::kStrict_SrcRectConstraint);+ canvas.restore();}void DisplayListPlayerSkia::push_clip(ReplayClip const& clip)@@ -1602,7 +1668,7 @@ sk_sp<SkImageFilter> DisplayListPlayerSkia::backdrop_image_filter(ReplayLayer coOptional<Gfx::FloatRect> blur_edge;if (layer.backdrop_blur_edge.has_value())blur_edge = backdrop_blur_edge_on_surface(surface().canvas(), *layer.backdrop_blur_edge);- return raster_cache().backdrop_image_filter(active_visual_context_tree().structural_epoch(), layer, blur_edge, limited_to_region, [&] {+ return raster_cache().backdrop_image_filter(layer, blur_edge, limited_to_region, [&] {auto image_filter = image_filter_from_bytes(filter_bytes, blur_edge);if (layer.backdrop_base_color.alpha() != 0) {auto base = SkImageFilters::Shader(SkShaders::Color(to_skia_color(layer.backdrop_base_color)));@@ -1628,7 +1694,7 @@ sk_sp<SkImageFilter> DisplayListPlayerSkia::backdrop_image_filter(ReplayLayer cosk_sp<SkImageFilter> DisplayListPlayerSkia::layer_image_filter(ReplayLayer const& layer){ReadonlyBytes filter_bytes { layer.filter_bytes, layer.filter_bytes_size };- return raster_cache().layer_image_filter(active_visual_context_tree().structural_epoch(), layer, [&] {+ return raster_cache().layer_image_filter(layer, [&] {return image_filter_from_bytes(filter_bytes);});}@@ -1658,7 +1724,7 @@ void DisplayListPlayerSkia::push_mask(ReplayMask const& mask, ReplayLayer const*canvas.saveLayer(nullptr, nullptr);}-void DisplayListPlayerSkia::pop_mask(ReplayMask const& mask, EffectNodeIndex effect)+void DisplayListPlayerSkia::begin_mask_content(ReplayMask const& mask){auto& canvas = surface().canvas();SkPaint paint;@@ -1666,12 +1732,14 @@ void DisplayListPlayerSkia::pop_mask(ReplayMask const& mask, EffectNodeIndex effif (mask.kind == Gfx::MaskKind::Luminance)paint.setColorFilter(SkLumaColorFilter::Make());canvas.saveLayer(nullptr, &paint);- if (auto content = declared_mask_content(effect); content.has_value()) {- canvas.save();- canvas.clipRect(to_skia_rect(mask.rect.to_type<float>()));- execute_command_bytes(*content);- canvas.restore();- }+ canvas.save();+ canvas.clipRect(to_skia_rect(mask.rect.to_type<float>()));+}++void DisplayListPlayerSkia::pop_mask()+{+ auto& canvas = surface().canvas();+ canvas.restore();canvas.restore();canvas.restore();canvas.restore();diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.hindex 3e9c4c23b2a..27dc266a962 100644--- a/Services/Compositor/DisplayListPlayerSkia.h+++ b/Services/Compositor/DisplayListPlayerSkia.h@@ -11,12 +11,12 @@#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <AK/RefPtr.h>+#include <AK/Vector.h>#include <Compositor/CompositedContext.h>-#include <Compositor/DisplayListPlayer.h>#include <Compositor/Forward.h>-#include <Compositor/FrameInputs.h>-#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>+#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>+#include <LibCompositing/RustFFI.h>#include <LibGfx/Forward.h>#include <LibGfx/Rect.h>@@ -35,7 +35,11 @@ namespace Compositor {// take — as a Skia runtime effect. Exposed so a benchmark can time the shipped effect, rather than a copy of it.sk_sp<SkColorFilter> force_dark_image_color_filter();-class DisplayListPlayerSkia final : public DisplayListPlayer {+using PresentedScrollbar = Compositing::RustFFI::PresentedScrollbar;++// Paints with Skia whatever a Rust replay draws through the raster painter it is handed. It knows nothing of the+// visual context tree, scroll offsets or frames: every value it gets is resolved for what it draws.+class DisplayListPlayerSkia final {public:AK_ALLOC_WITH_KMALLOC;@@ -43,39 +47,70 @@ public:explicit DisplayListPlayerSkia(RefPtr<Gfx::SkiaBackendContext>);~DisplayListPlayerSkia();- void execute(- Compositing::DisplayList const&,- Compositing::AccumulatedVisualContextTree const&,- Compositing::DisplayListResourceStorage const&,- DisplayListRasterCache&,- FrameInputs const*,- RefPtr<Gfx::PaintingSurface>,- OwnedCanvasSurfaces const*,- CompositedContextResolver const*,- ReplaySelection const& = replaying_everything());-- void flush(Gfx::PaintingSurface&) override;+ // The painter paints into `surface`, with the resources of `resource_storage` and the caches of `raster_cache`,+ // until end_painting().+ Compositing::RustFFI::FfiRasterPainter begin_painting(Gfx::PaintingSurface&, Compositing::DisplayListResourceStorage const&, DisplayListRasterCache&, OwnedCanvasSurfaces const*, CompositedContextResolver const*);+ void end_painting();++ void flush(Gfx::PaintingSurface&);void flush_async(Gfx::PaintingSurface&, Function<void()>&&);- void paint_scrollbars_painted_by_compositor(Gfx::PaintingSurface&, ReadonlySpan<ScrollbarOfFrame>);+ void paint_scrollbars_into(Gfx::PaintingSurface&, ReadonlySpan<PresentedScrollbar>);private:+ struct PainterCallbacks;++ Gfx::PaintingSurface& surface() const;+ Compositing::DisplayListResourceStorage const& resource_storage() const { return *m_resource_storage; }+ OwnedCanvasSurfaces const* canvas_surfaces() const { return m_canvas_surfaces; }+ DisplayListRasterCache& raster_cache() const { return *m_raster_cache; }++ ReadonlyBytes inline_data(Compositing::DisplayListDataSpan span) const+ {+ VERIFY(static_cast<size_t>(span.offset) + span.size <= m_current_command_payload.size());+ return m_current_command_payload.slice(span.offset, span.size);+ }+ template<typename T>+ ReadonlySpan<T> inline_objects(Compositing::DisplayListDataSpan span) const+ {+ static_assert(alignof(T) <= Compositing::display_list_payload_alignment);+ auto bytes = inline_data(span);+ VERIFY(bytes.size() % sizeof(T) == 0);+ VERIFY(reinterpret_cast<FlatPtr>(bytes.data()) % alignof(T) == 0);+ return { reinterpret_cast<T const*>(bytes.data()), bytes.size() / sizeof(T) };+ }++ void play_command_bytes(Compositing::DisplayListCommandType, u8 const* command, ReadonlyBytes payload);#define DECLARE_PLAY_COMMAND(command_type) \- void play_command(Compositing::command_type const&) override;- ENUMERATE_DISPLAY_LIST_COMMANDS(DECLARE_PLAY_COMMAND)+ void play_command(Compositing::command_type const&);+ ENUMERATE_DISPLAY_LIST_COMMANDS_PLAYED_AS_RECORDED(DECLARE_PLAY_COMMAND)#undef DECLARE_PLAY_COMMAND- void set_matrix(Gfx::FloatMatrix4x4 const&) override;- Gfx::FloatMatrix4x4 canvas_matrix() const override;- bool would_be_fully_clipped_by_painter(Gfx::IntRect) const override;-- void push_clip(Compositing::ReplayClip const&) override;- void push_clip_path(Gfx::PathData const&, u64 path_identity, Gfx::WindingRule) override;- void push_clip_path_bytes(ReadonlyBytes, Gfx::WindingRule, Compositing::ClipMode) override;- void push_transform(Gfx::AffineTransform const&) override;- void push_layer(Compositing::ReplayLayer const&) override;- void push_mask(Compositing::ReplayMask const&, Compositing::ReplayLayer const* backdrop) override;- void pop_mask(Compositing::ReplayMask const&, Compositing::EffectNodeIndex) override;- void pop() override;- void push_device_space_plane_clip(ReadonlySpan<Gfx::FloatVector3> polygon_vertices) override;++ void set_matrix(Gfx::FloatMatrix4x4 const&);+ Gfx::FloatMatrix4x4 canvas_matrix() const;+ bool would_be_fully_clipped_by_painter(Gfx::IntRect) const;+ void push_clip(Compositing::ReplayClip const&);+ void push_clip_path(Gfx::PathData const&, u64 path_identity, Gfx::WindingRule);+ void push_clip_path_bytes(ReadonlyBytes, Gfx::WindingRule, Compositing::ClipMode);+ void push_transform(Gfx::AffineTransform const&);+ void push_layer(Compositing::ReplayLayer const&);+ void push_mask(Compositing::ReplayMask const&, Compositing::ReplayLayer const* backdrop);+ void begin_mask_content(Compositing::ReplayMask const&);+ void pop_mask();+ void pop();+ void push_device_space_plane_clip(ReadonlySpan<Gfx::FloatVector3> polygon_vertices);+ void fill_rect(Compositing::RustFFI::ResolvedFillRect const&);+ void fill_rect_with_rounded_corners(Compositing::RustFFI::ResolvedFillRectWithRoundedCorners const&);+ void paint_scrollbar(PresentedScrollbar const&);+ void draw_composited_context(Compositing::RustFFI::CompositedContextDraw const&);+ void begin_isolated_group(Compositing::RustFFI::IsolatedGroup const&);+ void begin_isolated_group_mask(Gfx::MaskKind);+ void end_isolated_group_mask();+ void end_isolated_group();+ bool begin_tile_raster(Compositing::RustFFI::TileRaster const&);+ void end_tile_raster();+ Compositing::RustFFI::NestedDisplayListReplay begin_nested_display_list(Compositing::RustFFI::NestedDisplayListPlacement const&, bool requires_direct_replay);+ void end_nested_display_list();+ bool nested_display_list(u64 display_list_id, Compositing::RustFFI::FfiNestedDisplayList&) const;void clip_path(SkPath, Gfx::WindingRule, bool anti_aliased);@@ -84,16 +119,22 @@ private:sk_sp<SkImageFilter> backdrop_image_filter(Compositing::ReplayLayer const&, bool limited_to_region);sk_sp<SkImageFilter> image_filter_from_bytes(ReadonlyBytes, Optional<Gfx::FloatRect> blur_edge = {});SkPath path_from_data(Compositing::DisplayListDataSpan) const;- sk_sp<SkImage> rasterize_records_into_tile(ReadonlyBytes tile_records, Gfx::IntRect tile_rect);ReadonlySpan<Color> gradient_colors(Compositing::DisplayListGradientColorStops) const;ReadonlySpan<float> gradient_positions(Compositing::DisplayListGradientColorStops) const;RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;- CompositedContextResolver const* m_composited_context_resolver { nullptr };- // Says how opaque the scrollbars that the display list paints are.- ReadonlySpan<ScrollbarOfFrame> m_scrollbars_of_frame;++ // The surface painted into last, which a tile or nested display list raster stacks on top of the target.+ Vector<NonnullRefPtr<Gfx::PaintingSurface>, 4> m_surfaces;+ Compositing::DisplayListResourceStorage const* m_resource_storage { nullptr };DisplayListRasterCache* m_raster_cache { nullptr };- DisplayListRasterCache& raster_cache() const { return *m_raster_cache; }+ OwnedCanvasSurfaces const* m_canvas_surfaces { nullptr };+ CompositedContextResolver const* m_composited_context_resolver { nullptr };+ ReadonlyBytes m_current_command_payload;++ // The tile and nested display list rasters the painter replays into, which hold Skia objects.+ struct RasterState;+ NonnullOwnPtr<RasterState> m_raster_state;};}diff --git a/Services/Compositor/DisplayListRasterCache.cpp b/Services/Compositor/DisplayListRasterCache.cppindex dec99be75a6..0b79f5a738e 100644--- a/Services/Compositor/DisplayListRasterCache.cpp+++ b/Services/Compositor/DisplayListRasterCache.cpp@@ -34,6 +34,8 @@ namespace Compositor {using namespace Compositing;+// The Skia filters of the layers drawn in this frame and the one before, keyed on what the replay says stays the same+// for as long as a layer's filters do. An entry is only reused for the same filter bytes.struct DisplayListRasterCache::LayerImageFilterCache {AK_ALLOC_WITH_KMALLOC;@@ -50,9 +52,30 @@ struct DisplayListRasterCache::LayerImageFilterCache {bool limited_to_region { false };sk_sp<SkImageFilter> image_filter;};- HashMap<u64, HashMap<u32, Entry>> entries_by_tree_structural_epoch_and_effect;- HashMap<u64, HashMap<u32, BackdropEntry>> backdrop_entries_by_tree_structural_epoch_and_effect;- u64 tree_structural_epoch { 0 };+ template<typename EntryType>+ struct Generations {+ HashMap<u64, EntryType> this_frame;+ HashMap<u64, EntryType> last_frame;++ EntryType* find(u64 key)+ {+ if (auto it = this_frame.find(key); it != this_frame.end())+ return &it->value;+ auto entry = last_frame.take(key);+ if (!entry.has_value())+ return nullptr;+ this_frame.set(key, entry.release_value());+ return &this_frame.find(key)->value;+ }++ void begin_frame()+ {+ swap(this_frame, last_frame);+ this_frame.clear_with_capacity();+ }+ };+ Generations<Entry> entries;+ Generations<BackdropEntry> backdrop_entries;};struct DisplayListRasterCache::ImageFrameImage {@@ -186,31 +209,29 @@ void DisplayListRasterCache::evict(DisplayListResourceSet const& removed_resourc}}-DisplayListRasterCache::LayerImageFilterCache& DisplayListRasterCache::ensure_layer_image_filter_cache(u64 tree_structural_epoch)+DisplayListRasterCache::LayerImageFilterCache& DisplayListRasterCache::ensure_layer_image_filter_cache(){- if (!m_layer_image_filter_cache || m_layer_image_filter_cache->tree_structural_epoch != tree_structural_epoch) {+ if (!m_layer_image_filter_cache)m_layer_image_filter_cache = make<LayerImageFilterCache>();- m_layer_image_filter_cache->tree_structural_epoch = tree_structural_epoch;- }return *m_layer_image_filter_cache;}-sk_sp<SkImageFilter> DisplayListRasterCache::layer_image_filter(u64 tree_structural_epoch, ReplayLayer const& layer, Function<sk_sp<SkImageFilter>()> const& create)+sk_sp<SkImageFilter> DisplayListRasterCache::layer_image_filter(ReplayLayer const& layer, Function<sk_sp<SkImageFilter>()> const& create){ReadonlyBytes filter_bytes { layer.filter_bytes, layer.filter_bytes_size };- auto& entries = ensure_layer_image_filter_cache(tree_structural_epoch).entries_by_tree_structural_epoch_and_effect.ensure(tree_structural_epoch);- if (auto cached = entries.get(layer.effect.value()); cached.has_value() && cached->filter_bytes.bytes() == filter_bytes)+ auto& entries = ensure_layer_image_filter_cache().entries;+ if (auto* cached = entries.find(layer.filter_cache_key); cached && cached->filter_bytes.bytes() == filter_bytes)return cached->image_filter;auto image_filter = create();- entries.set(layer.effect.value(), LayerImageFilterCache::Entry { MUST(ByteBuffer::copy(filter_bytes)), image_filter });+ entries.this_frame.set(layer.filter_cache_key, LayerImageFilterCache::Entry { MUST(ByteBuffer::copy(filter_bytes)), image_filter });return image_filter;}-sk_sp<SkImageFilter> DisplayListRasterCache::backdrop_image_filter(u64 tree_structural_epoch, ReplayLayer const& layer, Optional<Gfx::FloatRect> blur_edge, bool limited_to_region, Function<sk_sp<SkImageFilter>()> const& create)+sk_sp<SkImageFilter> DisplayListRasterCache::backdrop_image_filter(ReplayLayer const& layer, Optional<Gfx::FloatRect> blur_edge, bool limited_to_region, Function<sk_sp<SkImageFilter>()> const& create){ReadonlyBytes filter_bytes { layer.backdrop_filter_bytes, layer.backdrop_filter_bytes_size };- auto& entries = ensure_layer_image_filter_cache(tree_structural_epoch).backdrop_entries_by_tree_structural_epoch_and_effect.ensure(tree_structural_epoch);- if (auto cached = entries.get(layer.effect.value()); cached.has_value()+ auto& entries = ensure_layer_image_filter_cache().backdrop_entries;+ if (auto* cached = entries.find(layer.filter_cache_key); cached&& cached->filter_bytes.bytes() == filter_bytes&& cached->region == layer.backdrop_region&& cached->blur_edge == blur_edge@@ -219,7 +240,7 @@ sk_sp<SkImageFilter> DisplayListRasterCache::backdrop_image_filter(u64 tree_stru&& cached->limited_to_region == limited_to_region)return cached->image_filter;auto image_filter = create();- entries.set(layer.effect.value(), LayerImageFilterCache::BackdropEntry { MUST(ByteBuffer::copy(filter_bytes)), layer.backdrop_region, blur_edge, layer.backdrop_corner_radii, layer.backdrop_base_color, limited_to_region, image_filter });+ entries.this_frame.set(layer.filter_cache_key, LayerImageFilterCache::BackdropEntry { MUST(ByteBuffer::copy(filter_bytes)), layer.backdrop_region, blur_edge, layer.backdrop_corner_radii, layer.backdrop_base_color, limited_to_region, image_filter });return image_filter;}@@ -352,7 +373,7 @@ bool DisplayListRasterCache::has_rasterized_nested_display_list(DisplayListResoureturn m_nested_display_list_rasters.contains(id.value());}-sk_sp<SkImage> DisplayListRasterCache::create_nested_display_list_raster(DisplayListResourceId id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, Gfx::IntRect rect_in_list_space, Function<sk_sp<SkImage>()> const& rasterize)+bool DisplayListRasterCache::reserve_nested_display_list_raster(DisplayListResourceId id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, Gfx::IntRect rect_in_list_space){auto& rasters = *m_nested_display_list_rasters.ensure(id.value(), [&] {return make<NestedDisplayListRasters>(skia_backend_context);@@ -384,16 +405,28 @@ sk_sp<SkImage> DisplayListRasterCache::create_nested_display_list_raster(Display});}if (total_bytes > max_nested_raster_cache_bytes)- return {};+ return false;}// Reserve before rasterizing: a nested list can create other cached rasters while it is painted.m_nested_raster_cache_reserved_bytes += raster_bytes;- ScopeGuard release_reservation = [&] { m_nested_raster_cache_reserved_bytes -= raster_bytes; };- auto image = rasterize();+ return true;+}++sk_sp<SkImage> DisplayListRasterCache::finish_nested_display_list_raster(DisplayListResourceId id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, Gfx::IntRect rect_in_list_space, sk_sp<SkImage> image)+{+ auto raster_bytes = static_cast<size_t>(rect_in_list_space.width()) * rect_in_list_space.height() * 4;+ m_nested_raster_cache_reserved_bytes -= raster_bytes;if (!image)return {};+ auto& rasters = *m_nested_display_list_rasters.ensure(id.value(), [&] {+ return make<NestedDisplayListRasters>(skia_backend_context);+ });+ if (rasters.skia_backend_context.ptr() != skia_backend_context.ptr()) {+ rasters.rasters.clear();+ rasters.skia_backend_context = skia_backend_context;+ }if (rasters.rasters.size() == NestedDisplayListRasters::max_rasters)rasters.rasters.take_last();rasters.rasters.prepend({ rect_in_list_space, image });@@ -505,10 +538,14 @@ SkPath DisplayListRasterCache::clip_path(u64 path_identity, Gfx::PathData const&return skia_path;}-void DisplayListRasterCache::drop_clip_paths_not_used_since_last_frame()+void DisplayListRasterCache::drop_what_was_not_used_since_last_frame(){swap(m_clip_paths, m_clip_paths_from_last_frame);m_clip_paths.clear_with_capacity();+ if (m_layer_image_filter_cache) {+ m_layer_image_filter_cache->entries.begin_frame();+ m_layer_image_filter_cache->backdrop_entries.begin_frame();+ }}}diff --git a/Services/Compositor/DisplayListRasterCache.h b/Services/Compositor/DisplayListRasterCache.hindex b0f7ab7cec2..d8d5d3b7266 100644--- a/Services/Compositor/DisplayListRasterCache.h+++ b/Services/Compositor/DisplayListRasterCache.h@@ -82,17 +82,21 @@ public:void add_repeated_tile_raster(u64 tile_key, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&, sk_sp<SkImage>);sk_sp<SkImage> nested_display_list_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect visible_rect_in_list_space, Gfx::IntRect& raster_rect_in_list_space);bool has_rasterized_nested_display_list(Compositing::DisplayListResourceId) const;- sk_sp<SkImage> create_nested_display_list_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect rect_in_list_space, Function<sk_sp<SkImage>()> const& rasterize);+ // Makes room for a raster of the list, which then counts against the budget until it is finished, and answers false+ // where the rasters in use leave no room for it.+ bool reserve_nested_display_list_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect rect_in_list_space);+ // Keeps the raster that was reserved, unless it could not be made.+ sk_sp<SkImage> finish_nested_display_list_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect rect_in_list_space, sk_sp<SkImage>);sk_sp<SkTextBlob> text_blob(Compositing::DisplayListResourceStorage const&, Compositing::FontResourceId, float scale, ReadonlySpan<Compositing::DisplayListGlyph>, u8 font_smoothing);- sk_sp<SkImageFilter> layer_image_filter(u64 tree_structural_epoch, Compositing::ReplayLayer const&, Function<sk_sp<SkImageFilter>()> const& create);- sk_sp<SkImageFilter> backdrop_image_filter(u64 tree_structural_epoch, Compositing::ReplayLayer const&, Optional<Gfx::FloatRect> blur_edge, bool limited_to_region, Function<sk_sp<SkImageFilter>()> const& create);+ sk_sp<SkImageFilter> layer_image_filter(Compositing::ReplayLayer const&, Function<sk_sp<SkImageFilter>()> const& create);+ sk_sp<SkImageFilter> backdrop_image_filter(Compositing::ReplayLayer const&, Optional<Gfx::FloatRect> blur_edge, bool limited_to_region, Function<sk_sp<SkImageFilter>()> const& create);// The Skia path for a path that stays the same for as long as it has this identity. Keeping one Skia path lets// the caches that are keyed on it work.SkPath clip_path(u64 path_identity, Gfx::PathData const&);- // Drops the clip paths that were not used since the last call.- void drop_clip_paths_not_used_since_last_frame();+ // Drops the clip paths and layer filters that were not used since the last call.+ void drop_what_was_not_used_since_last_frame();private:struct ImageFrameImage;@@ -102,7 +106,7 @@ private:struct TextBlob;struct ClipPath;struct LayerImageFilterCache;- LayerImageFilterCache& ensure_layer_image_filter_cache(u64 tree_structural_epoch);+ LayerImageFilterCache& ensure_layer_image_filter_cache();OwnPtr<LayerImageFilterCache> m_layer_image_filter_cache;diff --git a/Services/Compositor/FrameInputs.cpp b/Services/Compositor/FrameInputs.cppindex bc9c01c490f..9221f10d490 100644--- a/Services/Compositor/FrameInputs.cpp+++ b/Services/Compositor/FrameInputs.cpp@@ -51,15 +51,30 @@ ReadonlySpan<ScrollbarOfFrame> FrameInputs::scrollbars() constreturn { scrollbars, count };}-void FrameInputs::replay(Compositing::DisplayList const& display_list, Compositing::RustFFI::FfiDisplayListReplayCallbacks const& callbacks, ReplaySelection const& selection) const+void FrameInputs::replay(Compositing::DisplayList const& display_list, Compositing::RustFFI::FfiRasterPainter const& painter, ReplaySelection const& selection) const{VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == m_visual_context_tree.structural_epoch());- RustFFI::compositor_frame_inputs_replay(m_frame_inputs, display_list.rust_handle(), display_list.root_group_color(), &selection, &callbacks);+ RustFFI::compositor_frame_inputs_replay(m_frame_inputs, display_list.rust_handle(), display_list.root_group_color(), &selection, &painter);}-void FrameInputs::replay_records(ReadonlyBytes records, Compositing::RustFFI::FfiDisplayListReplayCallbacks const& callbacks) const+Vector<PresentedScrollbar> FrameInputs::scrollbars_painted_by_compositor() const{- RustFFI::compositor_frame_inputs_replay_records(m_frame_inputs, records.data(), records.size(), &callbacks);+ Vector<PresentedScrollbar> presented_scrollbars;+ for (auto const& scrollbar : scrollbars()) {+ if (!scrollbar.is_painted_by_compositor)+ continue;+ // The gutter of a thin scrollbar is not painted, so the gutter grows out of the thin track as it fades in.+ auto track_alpha = roundf(static_cast<float>(scrollbar.track_color.alpha()) * scrollbar.expansion);+ presented_scrollbars.append({+ .gutter_rect = scrollbar.gutter_rect,+ .thumb_rect = scrollbar.thumb_rect,+ .thumb_color = scrollbar.thumb_color,+ .thumb_outline_color = scrollbar.thumb_outline_color,+ .track_color = scrollbar.track_color.with_alpha(static_cast<u8>(track_alpha)),+ .opacity = scrollbar.opacity,+ });+ }+ return presented_scrollbars;}RustFFI::ContextLayerPlan* FrameInputs::build_layer_plan(Compositing::DisplayList const& display_list, Gfx::IntRect viewport_rect, ReadonlySpan<RustFFI::FfiLiveMedia> active_media) constdiff --git a/Services/Compositor/FrameInputs.h b/Services/Compositor/FrameInputs.hindex 0f5f62acaf1..14d17662398 100644--- a/Services/Compositor/FrameInputs.h+++ b/Services/Compositor/FrameInputs.h@@ -9,6 +9,7 @@#include <AK/Noncopyable.h>#include <AK/Optional.h>#include <AK/Span.h>+#include <AK/Vector.h>#include <Compositor/CompositorCoreRustFFI.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>@@ -19,15 +20,7 @@namespace Compositor {-// A scrollbar as it is painted, somewhere between its thin and its expanded geometry.-struct PresentedScrollbar {- Gfx::FloatRect gutter_rect;- Gfx::FloatRect thumb_rect;- Color thumb_color;- Color thumb_outline_color;- Color track_color;- float opacity { 1 };-};+using PresentedScrollbar = Compositing::RustFFI::PresentedScrollbar;using ScrollbarOfFrame = RustFFI::ScrollbarOfFrame;using ReplaySelection = Compositing::RustFFI::FfiReplaySelection;@@ -42,37 +35,6 @@ inline ReplaySelection replaying_only(ReadonlySpan<Compositing::RustFFI::RecordSreturn { record_spans.data(), record_spans.size(), true, skip_root_isolation_layer };}-// A scroll offset outside the scroll range moves the thumb past an end of its track, where it is cut short instead.-inline Gfx::IntRect thumb_rect_kept_inside_track(Gfx::IntRect thumb_rect, Gfx::IntRect const& track_rect, bool vertical)-{- if (vertical) {- auto top = max(thumb_rect.top(), track_rect.top());- auto bottom = min(thumb_rect.bottom(), track_rect.bottom());- thumb_rect.set_y(top);- thumb_rect.set_height(max(0, bottom - top));- } else {- auto left = max(thumb_rect.left(), track_rect.left());- auto right = min(thumb_rect.right(), track_rect.right());- thumb_rect.set_x(left);- thumb_rect.set_width(max(0, right - left));- }- return thumb_rect;-}--inline PresentedScrollbar presented_scrollbar_with_colors(ScrollbarOfFrame const& scrollbar, Color thumb_color, Color thumb_outline_color, Color track_color)-{- // The gutter of a thin scrollbar is not painted, so the gutter grows out of the thin track as it fades in.- auto track_alpha = roundf(static_cast<float>(track_color.alpha()) * scrollbar.expansion);- return PresentedScrollbar {- .gutter_rect = scrollbar.gutter_rect,- .thumb_rect = scrollbar.thumb_rect,- .thumb_color = thumb_color,- .thumb_outline_color = thumb_outline_color,- .track_color = track_color.with_alpha(static_cast<u8>(track_alpha)),- .opacity = scrollbar.opacity,- };-}-// The canvases, video sinks and image frames whose pixels changed since a display list was rasterized. The list draws// them with commands that stay the same, so comparing lists cannot see the change.struct LiveContentChanges {@@ -105,10 +67,10 @@ public:Compositing::AccumulatedVisualContextTree const& visual_context_tree() const { return m_visual_context_tree; }ReadonlySpan<ScrollbarOfFrame> scrollbars() const;- // Replays the list through a player's callbacks as the frame shows it.- void replay(Compositing::DisplayList const&, Compositing::RustFFI::FfiDisplayListReplayCallbacks const&, ReplaySelection const& = replaying_everything()) const;- // Replays a stream of records that a command of the list being replayed nests.- void replay_records(ReadonlyBytes records, Compositing::RustFFI::FfiDisplayListReplayCallbacks const&) const;+ // Replays the list through a painter as the frame shows it.+ void replay(Compositing::DisplayList const&, Compositing::RustFFI::FfiRasterPainter const&, ReplaySelection const& = replaying_everything()) const;+ // The scrollbars the compositor paints over the page, as the frame shows them.+ Vector<PresentedScrollbar> scrollbars_painted_by_compositor() const;RustFFI::ContextLayerPlan* build_layer_plan(Compositing::DisplayList const&, Gfx::IntRect viewport_rect, ReadonlySpan<RustFFI::FfiLiveMedia> active_media) const;bool places_content_like(FrameInputs const&) const;diff --git a/Services/Compositor/RasterizeDisplayList.cpp b/Services/Compositor/RasterizeDisplayList.cppindex 09f3f0b3636..aed72856899 100644--- a/Services/Compositor/RasterizeDisplayList.cpp+++ b/Services/Compositor/RasterizeDisplayList.cpp@@ -35,7 +35,9 @@ ErrorOr<void> rasterize_display_list(Compositing::DisplayList const& display_lis// Raster on the CPU, so the pixels match a raster of the same list in any other process.DisplayListPlayerSkia display_list_player { RefPtr<Gfx::SkiaBackendContext> {} };DisplayListRasterCache raster_cache;- display_list_player.execute(display_list, visual_context_tree, resource_storage, raster_cache, {}, surface, nullptr, nullptr);+ auto painter = display_list_player.begin_painting(*surface, resource_storage, raster_cache, nullptr, nullptr);+ display_list.replay(visual_context_tree, painter, MonotonicTime::now().nanoseconds());+ display_list_player.end_painting();display_list_player.flush(*surface);return {};}diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex 87cba5ad099..ddc4b081f7c 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -31,10 +31,7 @@ fn main() -> Result<(), Box<dyn Error>> {("RawMessage", "IPC::FfiRawMessage"),("EncodedValue", "AK::ReadonlyBytes"),("FfiDisplayList", "Compositing::RustFFI::FfiDisplayList"),- (- "FfiDisplayListReplayCallbacks",- "Compositing::RustFFI::FfiDisplayListReplayCallbacks",- ),+ ("FfiRasterPainter", "Compositing::RustFFI::FfiRasterPainter"),("FfiReplaySelection", "Compositing::RustFFI::FfiReplaySelection"),("RecordSpan", "Compositing::RustFFI::RecordSpan"),("CanvasId", "Compositing::CanvasId"),diff --git a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rsindex 55cd9bcd8ad..d7113079942 100644--- a/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs+++ b/Services/Compositor/Rust/src/context_state/frames_and_viewport.rs@@ -254,7 +254,7 @@ impl ContextState {scroll_offsets}- fn frame_inputs_as_presented_now(&mut self) -> FrameInputs {+ fn frame_inputs_as_presented_now(&mut self, now: MonotonicTime) -> FrameInputs {let stretched_scroll_state_snapshot = self.scroll_state_snapshot_stretched_by_elastic_overscrolls();let presented_scroll_state_snapshot =stretched_scroll_state_snapshot.unwrap_or_else(|| self.scroll_state_snapshot.clone());@@ -266,6 +266,7 @@ impl ContextState {presented_scroll_state_snapshot,scrollbars,viewport_scroll_node_index: self.async_scroll_tree.viewport_scroll_node_index(),+ painted_at: now,}}@@ -329,7 +330,7 @@ impl ContextState {pub fn frame_inputs(&mut self, now: MonotonicTime) -> Option<FrameInputs> {self.update_scrollbar_visibility(now);self.scene.display_list().as_ref()?;- Some(self.frame_inputs_as_presented_now())+ Some(self.frame_inputs_as_presented_now(now))}pub fn frame_inputs_for_screenshot(&mut self, now: MonotonicTime) -> ScreenshotInputs {@@ -341,7 +342,7 @@ impl ContextState {self.update_scrollbar_visibility(now);let scrollbar_fade_damage_rect = self.advance_scrollbar_fades_and_return_damage_rect(capture_time);ScreenshotInputs {- frame_inputs: self.frame_inputs_as_presented_now(),+ frame_inputs: self.frame_inputs_as_presented_now(capture_time),scrollbar_fade_damage_rect,}}diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex 6897aa8aa70..9d2e1f60436 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -19,11 +19,10 @@ use libcompositing_rust::display_list::commands::{CanvasId, CompositorContextId, ImageFrameResourceId, VideoSinkResourceId,};use libcompositing_rust::display_list::damage::{LayerPlans, LiveContentChanges};+use libcompositing_rust::display_list::replay::ReplayFrame;use libcompositing_rust::display_list::storage::storage_from_handle;-use libcompositing_rust::ffi::{- FfiDisplayList, replay_display_list_storage, replay_nested_records, tree_sharing_handle,-};-use libcompositing_rust::host::{FfiDisplayListReplayCallbacks, FfiReplaySelection};+use libcompositing_rust::ffi::{FfiDisplayList, replay_display_list_storage, tree_sharing_handle};+use libcompositing_rust::host::{FfiRasterPainter, FfiReplaySelection};use libcompositing_rust::ipc_types::{Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,};@@ -332,53 +331,39 @@ pub extern "C" fn compositor_frame_inputs_scrollbars(frame_inputs.scrollbars.as_ptr()}-/// Replays the list `display_list_storage` holds as the frame shows it, scrolled where the frame presents it.+/// Replays the list `display_list_storage` holds as the frame shows it: scrolled where the frame presents it, with the+/// frame's scrollbars and caret. The display lists it nests are looked up through the painter.////// # Safety////// `display_list_storage` must be a live storage handle of the list the context holds, `selection` must hold live-/// spans when it selects any, and `callbacks` must be live. The painter callbacks run synchronously and may re-enter a-/// replay.+/// spans when it selects any, and `painter` must be live. The painter callbacks run synchronously.#[unsafe(no_mangle)]pub unsafe extern "C" fn compositor_frame_inputs_replay(frame_inputs: &FrameInputs,display_list_storage: *const c_void,root_group_color: Color,selection: &FfiReplaySelection,- callbacks: *const FfiDisplayListReplayCallbacks,+ painter: *const FfiRasterPainter,) {- // SAFETY: The caller lends a live storage handle, live spans and live callbacks.+ // SAFETY: The caller lends a live painter.+ let nested_display_lists = unsafe { (*painter).nested_display_lists() };+ let scrollbars = frame_inputs.scrollbars_shown_for_the_page();+ let frame = ReplayFrame {+ scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ scrollbars: &scrollbars,+ time_ns: frame_inputs.painted_at.nanoseconds(),+ nested_display_lists: &nested_display_lists,+ };+ // SAFETY: The caller lends a live storage handle, live spans and a live painter.unsafe {replay_display_list_storage(frame_inputs.visual_context_tree.as_arc(),display_list_storage,root_group_color,- frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ &frame,selection.as_selection(),- callbacks,- );- }-}--/// Plays a stream of records that a command of the list being replayed nests, scrolled where the frame presents it.-///-/// # Safety-///-/// `records` must address `records_size` bytes of a tape that is valid for the call, and `callbacks` must be live.-/// The painter callbacks run synchronously and may re-enter a replay.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_frame_inputs_replay_records(- frame_inputs: &FrameInputs,- records: *const u8,- records_size: usize,- callbacks: *const FfiDisplayListReplayCallbacks,-) {- // SAFETY: The caller lends the stated number of bytes and live callbacks.- unsafe {- replay_nested_records(- ak::slice_from_raw_parts(records, records_size),- frame_inputs.presented_scroll_state_snapshot.device_offsets(),- callbacks,+ painter,);}}diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rsindex f4a51032c37..8c4756018b5 100644--- a/Services/Compositor/Rust/src/frame_inputs.rs+++ b/Services/Compositor/Rust/src/frame_inputs.rs@@ -9,35 +9,12 @@use libcompositing_rust::display_list::damage::{DisplayListDamage, DisplayListFrame, LayerPlans, LiveContentChanges, compute_display_list_damage,};+use libcompositing_rust::display_list::replay::ScrollbarShownByFrame;use libcompositing_rust::display_list::storage::DisplayListStorage;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, ScrollStateSnapshot, SpatialNodeIndex};+use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{Color, FloatRect, IntRect};-// A scrollbar as it is painted, somewhere between its thin and its expanded geometry.-#[derive(Clone, Copy)]-#[repr(C)]-pub struct PresentedScrollbar {- pub gutter_rect: FloatRect,- pub thumb_rect: FloatRect,- pub thumb_color: Color,- pub thumb_outline_color: Color,- pub track_color: Color,- pub opacity: f32,-}--impl Default for PresentedScrollbar {- fn default() -> Self {- Self {- gutter_rect: Default::default(),- thumb_rect: Default::default(),- thumb_color: Default::default(),- thumb_outline_color: Default::default(),- track_color: Default::default(),- opacity: 1.0,- }- }-}-#[derive(Clone, Copy)]#[repr(C)]pub struct ScrollbarOfFrame {@@ -72,21 +49,7 @@ impl Default for ScrollbarOfFrame {}}-// A scroll offset outside the scroll range moves the thumb past an end of its track, where it is cut short instead.-pub fn thumb_rect_kept_inside_track(mut thumb_rect: IntRect, track_rect: IntRect, vertical: bool) -> IntRect {- if vertical {- let top = thumb_rect.y.max(track_rect.y);- let bottom = thumb_rect.bottom().min(track_rect.bottom());- thumb_rect.y = top;- thumb_rect.height = 0.max(bottom - top);- } else {- let left = thumb_rect.x.max(track_rect.x);- let right = thumb_rect.right().min(track_rect.right());- thumb_rect.x = left;- thumb_rect.width = 0.max(right - left);- }- thumb_rect-}+pub use libcompositing_rust::display_list::replay::thumb_rect_kept_inside_track;// What a frame is painted with besides the display list and its resources.pub struct FrameInputs {@@ -94,9 +57,28 @@ pub struct FrameInputs {pub presented_scroll_state_snapshot: ScrollStateSnapshot,pub scrollbars: Vec<ScrollbarOfFrame>,pub viewport_scroll_node_index: Option<SpatialNodeIndex>,+ // When the frame is painted, which is the time a blinking caret shows as of.+ pub painted_at: MonotonicTime,}impl FrameInputs {+ // The scrollbars of the page that the frame presents, which replace the geometry the display list recorded for+ // them.+ pub fn scrollbars_shown_for_the_page(&self) -> Vec<ScrollbarShownByFrame> {+ self.scrollbars+ .iter()+ .filter(|scrollbar| !scrollbar.is_painted_by_compositor)+ .map(|scrollbar| ScrollbarShownByFrame {+ scroll_node_index: scrollbar.scroll_node_index,+ vertical: scrollbar.vertical,+ gutter_rect: scrollbar.gutter_rect,+ thumb_rect: scrollbar.thumb_rect,+ expansion: scrollbar.expansion,+ opacity: scrollbar.opacity,+ })+ .collect()+ }+// What a frame painted with these inputs repaints of the frame `last_frame_inputs` painted `last_display_list`// with, none where that has no bounds, and given the frames' layer plans, what it repaints of each layer.pub fn damage_since(diff --git a/Tests/Compositor/TestDisplayListImageFilters.cpp b/Tests/Compositor/TestDisplayListImageFilters.cppindex a1395e8c55d..d621aebf998 100644--- a/Tests/Compositor/TestDisplayListImageFilters.cpp+++ b/Tests/Compositor/TestDisplayListImageFilters.cpp@@ -7,6 +7,7 @@#include <Compositor/DisplayListPlayerSkia.h>#include <Compositor/DisplayListRasterCache.h>#include <Compositor/PaintingSurface.h>+#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>#include <LibCompositing/DisplayList/VisualContextTreeTestBuilder.h>#include <LibGfx/Bitmap.h>@@ -30,7 +31,9 @@ static Gfx::Color render(Compositor::DisplayListPlayerSkia& player, Compositing:{auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, rect.size()));auto surface = Gfx::PaintingSurface::wrap_bitmap(*bitmap);- player.execute(list, tree, storage, cache, {}, surface, nullptr, nullptr);+ auto painter = player.begin_painting(*surface, storage, cache, nullptr, nullptr);+ list.replay(tree, painter, 0);+ player.end_painting();player.flush(*surface);return bitmap->get_pixel(0, 0);}diff --git a/Tests/Compositor/TestPaintingSurface.cpp b/Tests/Compositor/TestPaintingSurface.cppindex c411e074019..50a9a0a3c41 100644--- a/Tests/Compositor/TestPaintingSurface.cpp+++ b/Tests/Compositor/TestPaintingSurface.cpp@@ -9,6 +9,7 @@#include <Compositor/PaintingSurface.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/SkiaUtils.h>+#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/DisplayList/VisualContextTreeTestBuilder.h>#include <LibGfx/Bitmap.h>#include <LibTest/TestCase.h>@@ -50,7 +51,9 @@ TEST_CASE(zero_width_border_sides_do_not_paint_on_gpu_surface).color = Gfx::Color::Black,};auto list = Compositing::VisualContextTreeTestBuilder::rounded_rect_ring_display_list(tree, {}, ring);- player.execute(*list, tree, storage, cache, {}, surface, nullptr, nullptr);+ auto painter = player.begin_painting(*surface, storage, cache, nullptr, nullptr);+ list->replay(tree, painter, 0);+ player.end_painting();surface->read_into_bitmap(*bitmap);EXPECT_EQ(bitmap->get_pixel(0, 4), Gfx::Color::White); // Left border.