Truly independent web browser
LibCompositing+Compositor: Decide which frames are presented in Rust
Aliaksandr Kalenikb1132ea96f2b
diff --git a/Libraries/LibCompositing/DisplayList/DisplayList.cpp b/Libraries/LibCompositing/DisplayList/DisplayList.cppindex f45c1ef20b5..b77197039b7 100644--- a/Libraries/LibCompositing/DisplayList/DisplayList.cpp+++ b/Libraries/LibCompositing/DisplayList/DisplayList.cpp@@ -154,6 +154,9 @@ RustFFI::FfiDisplayList DisplayList::for_scroll_logic(ReadonlyBytes encoded_asyn.id = m_id,.compatible_visual_context_tree_structural_epoch = m_compatible_visual_context_tree_structural_epoch,.async_scrolling_metadata = encoded_async_scrolling_metadata,+ .has_surface_clear_color = m_surface_clear_color.has_value(),+ .surface_clear_color = m_surface_clear_color.value_or(Gfx::Color::Transparent),+ .root_group_color = m_root_group_color,};}diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rsindex 85b04ec7f60..5203292e6a6 100644--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs@@ -110,6 +110,39 @@ pub trait NestedDisplayLists {fn nested_display_list(&self, display_list_id: u64) -> Option<NestedDisplayList<'_>>;}+/// The surface that shows the frame of a context drawn into another, and the part of it the frame is in.+#[derive(Clone, Copy, Debug)]+pub struct ResolvedCompositedContext {+ pub surface: *mut std::ffi::c_void,+ pub content_rect: FloatRect,+}++/// Where a replay finds the frames of the contexts the list draws.+pub trait CompositedContexts {+ // The frame of the child context as it is drawn into `destination_rect` under `canvas_matrix`, none where the+ // context shows nothing there.+ fn resolve(+ &self,+ child_context_id: u64,+ destination_rect: FloatRect,+ canvas_matrix: &FloatMatrix4x4,+ ) -> Option<ResolvedCompositedContext>;+}++/// The contexts of a replay that draws no other context.+pub struct NoCompositedContexts;++impl CompositedContexts for NoCompositedContexts {+ fn resolve(+ &self,+ _child_context_id: u64,+ _destination_rect: FloatRect,+ _canvas_matrix: &FloatMatrix4x4,+ ) -> Option<ResolvedCompositedContext> {+ None+ }+}+/// The resources of a replay that nests no display list.pub struct NoNestedDisplayLists;@@ -120,23 +153,26 @@ impl NestedDisplayLists for NoNestedDisplayLists {}/// 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.+/// scrollbars, the time it shows a blinking caret at, the display lists the list nests, and the frames of the contexts+/// it draws.#[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,+ pub composited_contexts: &'a dyn CompositedContexts,}impl<'a> ReplayFrame<'a> {- /// A frame that scrolls nothing and presents no scrollbar of its own.+ /// A frame that scrolls nothing, presents no scrollbar of its own, and draws no other context.pub fn unscrolled(time_ns: i64, nested_display_lists: &'a dyn NestedDisplayLists) -> Self {Self {scroll_offsets: &[],scrollbars: &[],time_ns,nested_display_lists,+ composited_contexts: &NoCompositedContexts,}}@@ -150,7 +186,11 @@ impl<'a> ReplayFrame<'a> {// 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)+ Self {+ scroll_offsets: &[],+ scrollbars: &[],+ ..*self+ }}}@@ -422,8 +462,21 @@ fn play_record<'t, Painter: ReplayPainter + ?Sized>(dst_rect.x = dst_rect.x.round();dst_rect.y = dst_rect.y.round();}+ let canvas_matrix = painter.canvas_matrix();+ let Some(resolved) =+ context+ .frame+ .composited_contexts+ .resolve(command.child_context_id.0, dst_rect, &canvas_matrix)+ else {+ return;+ };+ if resolved.surface.is_null() || resolved.content_rect.is_empty() {+ return;+ }painter.draw_composited_context(&CompositedContextDraw {- child_context_id: command.child_context_id.0,+ surface: resolved.surface,+ src_rect: resolved.content_rect,dst_rect,scaling_mode: command.scaling_mode,});diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rsindex 8cadfabd133..06fb5679ae9 100644--- a/Libraries/LibCompositing/Rust/src/ffi.rs+++ b/Libraries/LibCompositing/Rust/src/ffi.rs@@ -383,6 +383,9 @@ pub struct FfiDisplayList<'a> {pub compatible_visual_context_tree_structural_epoch: u64,/// A `Compositing::DisplayList::AsyncScrollingMetadata`, or none.pub async_scrolling_metadata: EncodedValue<'a>,+ pub has_surface_clear_color: bool,+ pub surface_clear_color: libgfx_rust::Color,+ pub root_group_color: libgfx_rust::Color,}impl FfiDisplayList<'_> {@@ -402,6 +405,8 @@ impl FfiDisplayList<'_> {self.id,self.compatible_visual_context_tree_structural_epoch,async_scrolling_metadata,+ self.has_surface_clear_color.then_some(self.surface_clear_color),+ self.root_group_color,))}}diff --git a/Libraries/LibCompositing/Rust/src/host/replay.rs b/Libraries/LibCompositing/Rust/src/host/replay.rsindex 4919ec9f3f3..0285fe3b2aa 100644--- a/Libraries/LibCompositing/Rust/src/host/replay.rs+++ b/Libraries/LibCompositing/Rust/src/host/replay.rs@@ -89,11 +89,13 @@ impl Default for PresentedScrollbar {}}-/// Where the frame of another context is drawn, with its origin already snapped where it lands on whole pixels.+/// The frame of another context drawn from the surface that holds it: the part of the surface the frame is in, and+/// where it goes, 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 surface: *mut c_void,+ pub src_rect: FloatRect,pub dst_rect: FloatRect,pub scaling_mode: ScalingMode,}diff --git a/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rsindex 002de60637b..940bbab4e21 100644--- a/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs+++ b/Libraries/LibCompositing/Rust/src/scrolling/display_list.rs@@ -11,7 +11,7 @@ use crate::display_list::builder::read_command;use crate::display_list::commands::{DisplayListCommandType, PaintCaret};use crate::display_list::storage::DisplayListStorage;use crate::display_list::summary::{for_each_compositor_metadata, for_each_indexed_record};-use libgfx_rust::IntRect;+use libgfx_rust::{Color, IntRect};use std::sync::Arc;pub use crate::ipc_types::Compositing_DisplayList_AsyncScrollingMetadata as AsyncScrollingMetadata;@@ -22,6 +22,8 @@ pub struct DisplayList {id: u64,compatible_visual_context_tree_structural_epoch: u64,async_scrolling_metadata: Option<AsyncScrollingMetadata>,+ surface_clear_color: Option<Color>,+ root_group_color: Color,}impl DisplayList {@@ -30,15 +32,33 @@ impl DisplayList {id: u64,compatible_visual_context_tree_structural_epoch: u64,async_scrolling_metadata: Option<AsyncScrollingMetadata>,+ surface_clear_color: Option<Color>,+ root_group_color: Color,) -> Self {Self {storage,id,compatible_visual_context_tree_structural_epoch,async_scrolling_metadata,+ surface_clear_color,+ root_group_color,}}+ pub fn storage(&self) -> &Arc<DisplayListStorage> {+ &self.storage+ }++ // What the surface a frame of the list is painted into is cleared to first, none for transparent.+ pub fn surface_clear_color(&self) -> Option<Color> {+ self.surface_clear_color+ }++ // What the backdrop of an effect directly under the root group reads, outside every layer.+ pub fn root_group_color(&self) -> Color {+ self.root_group_color+ }+pub fn compatible_visual_context_tree_structural_epoch(&self) -> u64 {self.compatible_visual_context_tree_structural_epoch}diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cppindex f67c6c9bd85..241e796f090 100644--- a/Services/Compositor/BackingStoreManager.cpp+++ b/Services/Compositor/BackingStoreManager.cpp@@ -183,7 +183,6 @@ ErrorOr<Optional<BackingStoreManager::Publication>> BackingStoreManager::allocat.window_server_surface = nullptr,.bitmap_id = allocation.bitmap_ids[i],.state = BufferState::Available,- .accumulated_damage = { {}, allocation.size },});}return Optional<Publication> {};@@ -232,7 +231,6 @@ ErrorOr<Optional<BackingStoreManager::Publication>> BackingStoreManager::allocat.window_server_surface = nullptr,.bitmap_id = allocation.bitmap_ids[i],.state = initial_buffer_state(i),- .accumulated_damage = { {}, allocation.size },});shared_images.append(move(store.shared_image));}@@ -271,7 +269,6 @@ BackingStoreManager::BackingStore BackingStoreManager::create_shareable_backing_.window_server_surface = nullptr,.bitmap_id = bitmap_id,.state = state,- .accumulated_damage = { {}, size },};}@@ -285,7 +282,6 @@ ErrorOr<BackingStoreManager::BackingStore> BackingStoreManager::create_backing_s.window_server_surface = move(surface),.bitmap_id = bitmap_id,.state = BufferState::Available,- .accumulated_damage = { {}, size },};}@@ -391,11 +387,9 @@ bool BackingStoreManager::has_available_buffer() constreturn any_of(m_backing_stores, [](auto const& store) { return store_can_be_rendered_into(store); });}-Optional<BackingStoreManager::RenderTarget> BackingStoreManager::acquire_render_target(Gfx::IntRect frame_damage)+Optional<BackingStoreManager::RenderTarget> BackingStoreManager::acquire_render_target(){VERIFY(!m_rendering_store_index.has_value());- for (auto& store : m_backing_stores)- store.accumulated_damage.unite(frame_damage);for (size_t i = 0; i < m_backing_stores.size(); ++i) {auto& store = m_backing_stores[i];@@ -405,9 +399,7 @@ Optional<BackingStoreManager::RenderTarget> BackingStoreManager::acquire_render_store.state = BufferState::Rendering;store.was_rendered_into_since_last_retirement_check = true;m_rendering_store_index = i;- auto damage_rect = store.accumulated_damage;- store.accumulated_damage = {};- return RenderTarget { *store.surface, store.bitmap_id, damage_rect };+ return RenderTarget { *store.surface, store.bitmap_id };}return {};}diff --git a/Services/Compositor/BackingStoreManager.h b/Services/Compositor/BackingStoreManager.hindex a1db5061767..eab6bd25bf8 100644--- a/Services/Compositor/BackingStoreManager.h+++ b/Services/Compositor/BackingStoreManager.h@@ -40,7 +40,6 @@ public:struct RenderTarget {Gfx::PaintingSurface& surface;i32 bitmap_id { -1 };- Gfx::IntRect damage_rect;};enum class PublicationMode {@@ -71,7 +70,7 @@ public:bool is_valid() const;bool is_rendering() const { return m_rendering_store_index.has_value(); }bool has_available_buffer() const;- Optional<RenderTarget> acquire_render_target(Gfx::IntRect frame_damage);+ Optional<RenderTarget> acquire_render_target();void complete_rendering(i32 bitmap_id);bool release_buffer(i32 bitmap_id);void release_all_presented_buffers();@@ -96,7 +95,6 @@ private:RefPtr<PresentableSurface> window_server_surface;i32 bitmap_id { -1 };BufferState state { BufferState::Available };- Gfx::IntRect accumulated_damage;bool was_shown_on_screen { false };bool was_rendered_into_since_last_retirement_check { false };};diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 8b43366d354..a99e7cb7024 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -7,16 +7,13 @@ set(SOURCESColorSpaceSkia.cppCompositorCore.cppCompositorState.cpp- ContextLayers.cpp- ContextPresenter.cpp+ ContextRasterTargets.cppDisplayListPlayerSkia.cppDisplayListRasterCache.cppFontSkia.cpp- FrameInputs.cppConnectionFromClient.cppConnectionFromPresentation.cppConnectionFromWebContent.cpp- FramePacer.cppHostWebGLContext.cppOpenGLContext.cppPaintingSurface.cppdiff --git a/Services/Compositor/CompositedContext.h b/Services/Compositor/CompositedContext.hdeleted file mode 100644index 2b78314f49d..00000000000--- a/Services/Compositor/CompositedContext.h+++ /dev/null@@ -1,26 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Function.h>-#include <AK/RefPtr.h>-#include <Compositor/PaintingSurface.h>-#include <LibCompositing/Types.h>-#include <LibGfx/Matrix4x4.h>-#include <LibGfx/Rect.h>--namespace Compositor {--struct CompositedContextSurface {- RefPtr<Gfx::PaintingSurface> surface;- // The viewport's pixels, excluding padding needed for fractional raster placement.- Gfx::FloatRect content_rect;-};--using CompositedContextResolver = Function<CompositedContextSurface(Web::CompositorContextId, Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform)>;--}diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex 245de6a17d6..ea522c0f292 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -18,7 +18,6 @@ static_assert(IsTriviallyCopyable<Gfx::IntSize>);static_assert(IsTriviallyCopyable<Gfx::FloatPoint>);static_assert(IsTriviallyCopyable<Gfx::FloatRect>);static_assert(IsTriviallyCopyable<Gfx::Color>);-static_assert(IsTriviallyCopyable<Compositing::SpatialNodeIndex>);static_assert(IsTriviallyCopyable<ReadonlyBytes>);static void post_message_to_web_content(void* host, u64 client_id, ReadonlyBytes bytes, ReadonlySpan<IPC::RawAttachment> attachments)@@ -39,11 +38,6 @@ static void post_message_to_presentation(void* host, u64 presentation_id, Readonstatic_cast<CompositorCoreHost*>(host)->post_message_to_presentation(PresentationId { presentation_id }, buffer);}-static void request_display_ticks(void* host, u64 context_id)-{- static_cast<CompositorCoreHost*>(host)->request_display_ticks(Web::CompositorContextId { context_id });-}-static void set_timer(void* host, u64 context_id, ContextTimer timer, i64 delay_nanoseconds){static_cast<CompositorCoreHost*>(host)->set_timer(Web::CompositorContextId { context_id }, timer, AK::Duration::from_nanoseconds(delay_nanoseconds));@@ -74,19 +68,23 @@ static void shape_overlay_label(void* host, u64 context_id, bool has_font_familyreceive(receiver, &ffi_label);}-CompositorCore::CompositorCore(CompositorCoreHost& host, bool scrollbars_always_shown)+static MonotonicTime now()+{+ return MonotonicTime::now();+}++CompositorCore::CompositorCore(CompositorCoreHost& host, RustFFI::FfiRasterHost raster_host, bool scrollbars_always_shown, RustFFI::GpuBackend gpu){RustFFI::FfiCompositorCoreHost ffi_host {.host = &host,.post_message_to_web_content = Compositor::post_message_to_web_content,.post_message_to_render_clock_of_web_content = Compositor::post_message_to_render_clock_of_web_content,.post_message_to_presentation = Compositor::post_message_to_presentation,- .request_display_ticks = Compositor::request_display_ticks,.set_timer = Compositor::set_timer,.cancel_timer = Compositor::cancel_timer,.shape_overlay_label = Compositor::shape_overlay_label,};- m_core = RustFFI::compositor_core_create(ffi_host, scrollbars_always_shown);+ m_core = RustFFI::compositor_core_create(ffi_host, raster_host, scrollbars_always_shown, gpu);}CompositorCore::~CompositorCore()@@ -96,12 +94,12 @@ CompositorCore::~CompositorCore()void CompositorCore::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, WebContentClientId web_content_client_id){- RustFFI::compositor_core_create_context(m_core, context_id.value(), page_id.has_value(), page_id.value_or(0), web_content_client_id.value());+ RustFFI::compositor_core_create_context(m_core, context_id.value(), page_id.has_value(), page_id.value_or(0), web_content_client_id.value(), now().nanoseconds());}void CompositorCore::destroy_context(Web::CompositorContextId context_id){- RustFFI::compositor_core_destroy_context(m_core, context_id.value());+ RustFFI::compositor_core_destroy_context(m_core, context_id.value(), now().nanoseconds());}CompositorCore::ContextOwnerCheckResult CompositorCore::check_context_owner(Web::CompositorContextId context_id, WebContentClientId client) const@@ -109,27 +107,58 @@ CompositorCore::ContextOwnerCheckResult CompositorCore::check_context_owner(Web:return RustFFI::compositor_core_check_context_owner(m_core, context_id.value(), client.value());}+bool CompositorCore::context_can_be_nested_in(Web::CompositorContextId context_id, Web::CompositorContextId parent_context_id) const+{+ return RustFFI::compositor_core_context_can_be_nested_in(m_core, context_id.value(), parent_context_id.value());+}++bool CompositorCore::presents_to_client(Web::CompositorContextId context_id) const+{+ return RustFFI::compositor_core_presents_to_client(m_core, context_id.value());+}++bool CompositorCore::context_is_effectively_visible(Web::CompositorContextId context_id) const+{+ return RustFFI::compositor_core_context_is_effectively_visible(m_core, context_id.value());+}++Optional<Web::CompositorContextId> CompositorCore::parent_context(Web::CompositorContextId context_id) const+{+ u64 parent_context_id = 0;+ if (!RustFFI::compositor_core_parent_context(m_core, context_id.value(), &parent_context_id))+ return {};+ return Web::CompositorContextId { parent_context_id };+}++Optional<PresentationId> CompositorCore::bound_presentation(Web::CompositorContextId context_id) const+{+ u64 presentation_id = 0;+ if (!RustFFI::compositor_core_bound_presentation(m_core, context_id.value(), &presentation_id))+ return {};+ return PresentationId { presentation_id };+}+void CompositorCore::set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id){- RustFFI::compositor_core_set_parent_context(m_core, context_id.value(), parent_context_id.has_value(), parent_context_id.value_or({}).value());+ RustFFI::compositor_core_set_parent_context(m_core, context_id.value(), parent_context_id.has_value(), parent_context_id.value_or({}).value(), now().nanoseconds());}void CompositorCore::stop_presenting_to_client(Web::CompositorContextId context_id){- RustFFI::compositor_core_stop_presenting_to_client(m_core, context_id.value());+ RustFFI::compositor_core_stop_presenting_to_client(m_core, context_id.value(), now().nanoseconds());}-void CompositorCore::set_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility, MonotonicTime now)+bool CompositorCore::set_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility){- RustFFI::compositor_core_set_visibility(m_core, context_id.value(), visibility == Compositing::ContextVisibility::Visible, now.nanoseconds());+ return RustFFI::compositor_core_set_visibility(m_core, context_id.value(), visibility == Compositing::ContextVisibility::Visible, now().nanoseconds());}-void CompositorCore::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio)+void CompositorCore::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress){- RustFFI::compositor_core_viewport_size_updated(m_core, context_id.value(), viewport_size, device_pixel_ratio);+ RustFFI::compositor_core_viewport_size_updated(m_core, context_id.value(), viewport_size, device_pixel_ratio, window_resize_in_progress == Compositing::WindowResizingInProgress::Yes, now().nanoseconds());}-void CompositorCore::set_ui_overlays(Web::CompositorContextId context_id, Compositing::UIOverlays const& overlays, MonotonicTime now)+void CompositorCore::set_ui_overlays(Web::CompositorContextId context_id, Compositing::UIOverlays const& overlays){auto const& paused_debugger = overlays.paused_debugger;auto const& picture_in_picture_controls = overlays.picture_in_picture_controls;@@ -145,93 +174,145 @@ void CompositorCore::set_ui_overlays(Web::CompositorContextId context_id, Compos.picture_in_picture_controls_has_hovered_control = picture_in_picture_controls.has_value() && picture_in_picture_controls->hovered_control.has_value(),.picture_in_picture_controls_hovered_control = picture_in_picture_controls.has_value() && picture_in_picture_controls->hovered_control.has_value() ? to_underlying(*picture_in_picture_controls->hovered_control) : u8 { 0 },};- RustFFI::compositor_core_set_ui_overlays(m_core, context_id.value(), &ffi_overlays, now.nanoseconds());+ RustFFI::compositor_core_set_ui_overlays(m_core, context_id.value(), &ffi_overlays, now().nanoseconds());}-void CompositorCore::set_bound_presentation(Web::CompositorContextId context_id, Optional<PresentationId> presentation_id)+void CompositorCore::register_presentation(PresentationId presentation_id, PresentationCapabilities const& capabilities){- RustFFI::compositor_core_set_bound_presentation(m_core, context_id.value(), presentation_id.has_value(), presentation_id.value_or({}).value());+ RustFFI::compositor_core_register_presentation(m_core, presentation_id.value(), &capabilities);}-void CompositorCore::set_scroll_capabilities(Web::CompositorContextId context_id, ScrollCapabilities const& capabilities)+void CompositorCore::unregister_presentation(PresentationId presentation_id){- RustFFI::compositor_core_set_scroll_capabilities(m_core, context_id.value(), capabilities);+ RustFFI::compositor_core_unregister_presentation(m_core, presentation_id.value(), now().nanoseconds());}-bool CompositorCore::install_display_list_update(Web::CompositorContextId context_id, Compositing::DisplayList const& display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, MonotonicTime now)+void CompositorCore::set_presentation_gpu_capability(PresentationId presentation_id, bool supported, u64 adapter_luid){- auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());- return RustFFI::compositor_core_install_display_list_update(m_core, context_id.value(), &display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state, now.nanoseconds());+ RustFFI::compositor_core_set_presentation_gpu_capability(m_core, presentation_id.value(), supported, adapter_luid, now().nanoseconds());}-CompositorCore::VisualContextTreeUpdateResult CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const& keyboard_scroll_state, MonotonicTime now)+void CompositorCore::set_scrollbar_track_press_jumps(PresentationId presentation_id, bool jumps){- return RustFFI::compositor_core_update_visual_context_tree(m_core, context_id.value(), visual_context_tree.rust_handle(), encoded_scroll_state, keyboard_scroll_state.bytes(), now.nanoseconds());+ RustFFI::compositor_core_set_scrollbar_track_press_jumps(m_core, presentation_id.value(), jumps);}-bool CompositorCore::needs_animation_frames(Web::CompositorContextId context_id, MonotonicTime now)+void CompositorCore::bind_presentation(Web::CompositorContextId context_id, PresentationId presentation_id){- return RustFFI::compositor_core_needs_animation_frames(m_core, context_id.value(), now.nanoseconds());+ RustFFI::compositor_core_bind_presentation(m_core, context_id.value(), presentation_id.value(), now().nanoseconds());}-Optional<FrameInputs> CompositorCore::frame_inputs(Web::CompositorContextId context_id, MonotonicTime now)+void CompositorCore::set_shown_in_remote_layer(Web::CompositorContextId context_id, bool shown){- auto* frame_inputs = RustFFI::compositor_core_frame_inputs(m_core, context_id.value(), now.nanoseconds());- if (!frame_inputs)- return {};- return FrameInputs::adopt(frame_inputs);+ RustFFI::compositor_core_set_shown_in_remote_layer(m_core, context_id.value(), shown, now().nanoseconds());+}++void CompositorCore::set_display_metadata(Web::CompositorContextId context_id, Optional<u64> display_id, double refresh_rate)+{+ RustFFI::compositor_core_set_display_metadata(m_core, context_id.value(), display_id.has_value(), display_id.value_or(0), refresh_rate, now().nanoseconds());+}++void CompositorCore::set_window_server_may_show_high_dynamic_range(bool may_show)+{+ RustFFI::compositor_core_set_window_server_may_show_high_dynamic_range(m_core, may_show, now().nanoseconds());+}++void CompositorCore::set_presents_from_cpu_memory(Web::CompositorContextId context_id, bool presents_from_cpu_memory)+{+ RustFFI::compositor_core_set_presents_from_cpu_memory(m_core, context_id.value(), presents_from_cpu_memory, now().nanoseconds());}-CompositorCore::ScreenshotInputs CompositorCore::frame_inputs_for_screenshot(Web::CompositorContextId context_id, MonotonicTime now)+void CompositorCore::request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second){- Gfx::IntRect scrollbar_fade_damage_rect;- auto* frame_inputs = RustFFI::compositor_core_frame_inputs_for_screenshot(m_core, context_id.value(), now.nanoseconds(), &scrollbar_fade_damage_rect);- return { .frame_inputs = FrameInputs::adopt(frame_inputs), .scrollbar_fade_damage_rect = scrollbar_fade_damage_rect };+ RustFFI::compositor_core_request_rendering_opportunity(m_core, context_id.value(), maximum_frames_per_second, now().nanoseconds());}-DisplayTickResult CompositorCore::display_tick(Web::CompositorContextId context_id, MonotonicTime frame_time, MonotonicTime now, DisplayTickInputs const& inputs)+void CompositorCore::request_clock_tick(Web::CompositorContextId context_id, double maximum_frames_per_second){- return RustFFI::compositor_core_display_tick(- m_core, context_id.value(), frame_time.nanoseconds(), now.nanoseconds(),- {- .context_is_on_tick_display = inputs.context_is_on_tick_display,- .present_is_scheduled_on_tick_display = inputs.present_is_scheduled_on_tick_display,- .clock_tick_is_due = inputs.clock_tick_interval_in_milliseconds.has_value(),- .clock_tick_interval_in_milliseconds = inputs.clock_tick_interval_in_milliseconds.value_or(0),- });+ RustFFI::compositor_core_request_clock_tick(m_core, context_id.value(), maximum_frames_per_second);}-void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer, MonotonicTime now)+void CompositorCore::hurry_rendering_opportunity(Web::CompositorContextId context_id){- RustFFI::compositor_core_timer_fired(m_core, context_id.value(), timer, now.nanoseconds());+ RustFFI::compositor_core_hurry_rendering_opportunity(m_core, context_id.value(), now().nanoseconds());+}++void CompositorCore::present_frame_of_page(Web::CompositorContextId context_id, Gfx::IntRect viewport_rect)+{+ RustFFI::compositor_core_present_frame_of_page(m_core, context_id.value(), viewport_rect, now().nanoseconds());+}++void CompositorCore::presented_store_released(Web::CompositorContextId context_id, i32 bitmap_id)+{+ RustFFI::compositor_core_presented_store_released(m_core, context_id.value(), bitmap_id, now().nanoseconds());+}++void CompositorCore::vsync(Optional<u64> display_id, MonotonicTime frame_time)+{+ RustFFI::compositor_core_vsync(m_core, display_id.has_value(), display_id.value_or(0), frame_time.nanoseconds(), now().nanoseconds());+}++void CompositorCore::gpu_work_finished(u64 token)+{+ RustFFI::compositor_core_gpu_work_finished(m_core, token, now().nanoseconds());+}++void CompositorCore::frame_ready_for_hand_off(u64 token)+{+ RustFFI::compositor_core_frame_ready_for_hand_off(m_core, token, now().nanoseconds());+}++void CompositorCore::context_content_changed(Web::CompositorContextId context_id)+{+ RustFFI::compositor_core_context_content_changed(m_core, context_id.value(), now().nanoseconds());+}++void CompositorCore::canvas_content_changed(WebContentClientId client, Compositing::CanvasId canvas_id)+{+ RustFFI::compositor_core_canvas_content_changed(m_core, client.value(), canvas_id.value(), now().nanoseconds());+}++bool CompositorCore::paint_screenshot(Web::CompositorContextId context_id, Gfx::PaintingSurface& surface)+{+ return RustFFI::compositor_core_paint_screenshot(m_core, context_id.value(), &surface, now().nanoseconds());+}++Optional<CompositorCore::PresentedFrame> CompositorCore::presented_frame_for_snapshot(Web::CompositorContextId context_id)+{+ void* surface = nullptr;+ Gfx::IntSize frame_size;+ if (!RustFFI::compositor_core_presented_frame_for_snapshot(m_core, context_id.value(), now().nanoseconds(), &surface, &frame_size))+ return {};+ return PresentedFrame { adopt_ref(*static_cast<Gfx::PaintingSurface*>(surface)), frame_size };+}++bool CompositorCore::install_display_list_update(Web::CompositorContextId context_id, Compositing::DisplayList const& display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state)+{+ auto display_list_for_scroll_logic = display_list.for_scroll_logic(async_scrolling_metadata.bytes());+ return RustFFI::compositor_core_install_display_list_update(m_core, context_id.value(), &display_list_for_scroll_logic, visual_context_tree.rust_handle(), encoded_scroll_state, now().nanoseconds());}-static void receive_present_request(void* receiver, RustFFI::FfiPresentRequest request)+CompositorCore::VisualContextTreeUpdateResult CompositorCore::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree const& visual_context_tree, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const& keyboard_scroll_state){- Optional<Gfx::IntRect> viewport_rect;- if (request.has_viewport_rect)- viewport_rect = request.viewport_rect;- static_cast<Vector<PresentRequest>*>(receiver)->append({ Web::CompositorContextId { request.context_id }, viewport_rect, request.forced_damage_rect, request.scheduling });+ return RustFFI::compositor_core_update_visual_context_tree(m_core, context_id.value(), visual_context_tree.rust_handle(), encoded_scroll_state, keyboard_scroll_state.bytes(), now().nanoseconds());}-Vector<PresentRequest> CompositorCore::take_present_requests()+void CompositorCore::timer_fired(Web::CompositorContextId context_id, ContextTimer timer){- Vector<PresentRequest> requests;- RustFFI::compositor_core_take_present_requests(m_core, &requests, receive_present_request);- return requests;+ RustFFI::compositor_core_timer_fired(m_core, context_id.value(), timer, now().nanoseconds());}-IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message, MonotonicTime now)+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message){return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {- RustFFI::compositor_core_handle_web_content_message(m_core, client_id.value(), raw_message, now.nanoseconds());+ RustFFI::compositor_core_handle_web_content_message(m_core, client_id.value(), raw_message, now().nanoseconds());});}-IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message, MonotonicTime now)+IPC::RawMessage::OutcomeInRust CompositorCore::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message){return message.hand_to_rust([&](IPC::FfiRawMessage raw_message) {- RustFFI::compositor_core_handle_presentation_message(m_core, presentation_id.value(), raw_message, now.nanoseconds());+ RustFFI::compositor_core_handle_presentation_message(m_core, presentation_id.value(), raw_message, now().nanoseconds());});}diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex e1fe5abb063..8c20ce31ac6 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -7,10 +7,10 @@#pragma once#include <AK/Noncopyable.h>+#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>-#include <AK/Vector.h>#include <Compositor/CompositorCoreHost.h>-#include <Compositor/FrameInputs.h>+#include <Compositor/PaintingSurface.h>#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>#include <LibCompositing/DisplayList/DisplayList.h>#include <LibCompositing/Types.h>@@ -21,60 +21,81 @@namespace Compositor {-// The scroll and input logic of the contexts and the routing of input between them, which is Rust (compositor_core).-// It talks to the process through its host, hands the frames it wants presented back as requests, and is never-// entered while one of its own calls runs.+// The logic of the compositor, which is Rust (compositor_core): the contexts, their scrolling and input, and when and+// what of their frames is painted and presented. It talks to the process through its hosts, which paint and present as+// it asks, and it is never entered while one of its own calls runs.class CompositorCore {AK_MAKE_NONCOPYABLE(CompositorCore);AK_MAKE_NONMOVABLE(CompositorCore);public:- CompositorCore(CompositorCoreHost&, bool scrollbars_always_shown);+ CompositorCore(CompositorCoreHost&, RustFFI::FfiRasterHost, bool scrollbars_always_shown, RustFFI::GpuBackend);~CompositorCore();using ContextOwnerCheckResult = RustFFI::ContextOwnerCheckResult;using VisualContextTreeUpdateResult = RustFFI::VisualContextTreeUpdateResult;- // What the presentation a context is shown through makes of the user's scrolling.- using ScrollCapabilities = RustFFI::FfiScrollCapabilities;+ using PresentationCapabilities = RustFFI::FfiPresentationCapabilities;void create_context(Web::CompositorContextId, Optional<u64> page_id, WebContentClientId);// Also leaves the contexts nested in it without a parent.void destroy_context(Web::CompositorContextId);ContextOwnerCheckResult check_context_owner(Web::CompositorContextId, WebContentClientId) const;+ bool context_can_be_nested_in(Web::CompositorContextId, Web::CompositorContextId parent_context_id) const;+ bool presents_to_client(Web::CompositorContextId) const;+ bool context_is_effectively_visible(Web::CompositorContextId) const;+ Optional<Web::CompositorContextId> parent_context(Web::CompositorContextId) const;+ Optional<PresentationId> bound_presentation(Web::CompositorContextId) const;void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>);void stop_presenting_to_client(Web::CompositorContextId);- // Ends the fling of a context that is hidden, whether or not it was visible.- void set_visibility(Web::CompositorContextId, Compositing::ContextVisibility, MonotonicTime now);- void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio);- void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays const&, MonotonicTime now);- void set_bound_presentation(Web::CompositorContextId, Optional<PresentationId>);- void set_scroll_capabilities(Web::CompositorContextId, ScrollCapabilities const&);+ // Ends the fling of a context that is hidden, whether or not it was visible. Answers whether the context became+ // visible.+ bool set_visibility(Web::CompositorContextId, Compositing::ContextVisibility);+ void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress);+ void set_ui_overlays(Web::CompositorContextId, Compositing::UIOverlays const&);++ void register_presentation(PresentationId, PresentationCapabilities const&);+ // Leaves every context bound to the presentation unbound.+ void unregister_presentation(PresentationId);+ void set_presentation_gpu_capability(PresentationId, bool supported, u64 adapter_luid);+ void set_scrollbar_track_press_jumps(PresentationId, bool jumps);+ void bind_presentation(Web::CompositorContextId, PresentationId);+ void set_shown_in_remote_layer(Web::CompositorContextId, bool shown);+ void set_display_metadata(Web::CompositorContextId, Optional<u64> display_id, double refresh_rate);+ void set_window_server_may_show_high_dynamic_range(bool);+ void set_presents_from_cpu_memory(Web::CompositorContextId, bool);++ void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second);+ void request_clock_tick(Web::CompositorContextId, double maximum_frames_per_second);+ void hurry_rendering_opportunity(Web::CompositorContextId);+ void present_frame_of_page(Web::CompositorContextId, Gfx::IntRect viewport_rect);+ void presented_store_released(Web::CompositorContextId, i32 bitmap_id);+ void vsync(Optional<u64> display_id, MonotonicTime frame_time);+ void gpu_work_finished(u64 token);+ void frame_ready_for_hand_off(u64 token);+ // A video sink or an image frame that the context draws has new pixels.+ void context_content_changed(Web::CompositorContextId);+ void canvas_content_changed(WebContentClientId, Compositing::CanvasId);++ // Answers false for a context with nothing to paint yet.+ bool paint_screenshot(Web::CompositorContextId, Gfx::PaintingSurface&);+ struct PresentedFrame {+ NonnullRefPtr<Gfx::PaintingSurface> surface;+ Gfx::IntSize frame_size;+ };+ // The surface that holds the frame on screen as a whole, and the size of the frame in it.+ Optional<PresentedFrame> presented_frame_for_snapshot(Web::CompositorContextId);// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode.- bool install_display_list_update(Web::CompositorContextId, Compositing::DisplayList const&, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, MonotonicTime now);+ bool install_display_list_update(Web::CompositorContextId, Compositing::DisplayList const&, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const&, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state);// Changes nothing for a scroll state or keyboard scroll state that do not decode. Of a tree that does not fit the// installed display list, only the scroll state is taken.- VisualContextTreeUpdateResult update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const&, MonotonicTime now);-- bool needs_animation_frames(Web::CompositorContextId, MonotonicTime now);- // Each frame shows the scrollbars as of when it is painted, so this updates which of them are shown. Empty until a- // display list is installed.- Optional<FrameInputs> frame_inputs(Web::CompositorContextId, MonotonicTime now);- struct ScreenshotInputs {- FrameInputs frame_inputs;- // The scrollbar fade damage that the screenshot does not present on screen.- Gfx::IntRect scrollbar_fade_damage_rect;- };- ScreenshotInputs frame_inputs_for_screenshot(Web::CompositorContextId, MonotonicTime now);- DisplayTickResult display_tick(Web::CompositorContextId, MonotonicTime frame_time, MonotonicTime now, DisplayTickInputs const&);- void timer_fired(Web::CompositorContextId, ContextTimer, MonotonicTime now);+ VisualContextTreeUpdateResult update_visual_context_tree(Web::CompositorContextId, Compositing::AccumulatedVisualContextTree const&, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const&);- // The frames asked for since the last call, in the order they were asked for.- Vector<PresentRequest> take_present_requests();+ void timer_fired(Web::CompositorContextId, ContextTimer);// The messages of CompositorWebContentServer and CompositorPresentationServer that are marked [RustReceiver].- IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&, MonotonicTime now);- IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&, MonotonicTime now);+ IPC::RawMessage::OutcomeInRust handle_message_from_web_content(WebContentClientId, IPC::RawMessage&);+ IPC::RawMessage::OutcomeInRust handle_message_from_presentation(PresentationId, IPC::RawMessage&);private:RustFFI::CompositorCore* m_core { nullptr };diff --git a/Services/Compositor/CompositorCoreHost.h b/Services/Compositor/CompositorCoreHost.hindex f634c683589..68490761660 100644--- a/Services/Compositor/CompositorCoreHost.h+++ b/Services/Compositor/CompositorCoreHost.h@@ -12,7 +12,6 @@#include <AK/Time.h>#include <AK/Vector.h>#include <Compositor/CompositorCoreRustFFI.h>-#include <LibGfx/Rect.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Page/CompositorContextId.h>@@ -21,36 +20,6 @@ namespace Compositor {AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, WebContentClientId);AK_TYPEDEF_DISTINCT_ORDERED_ID(u64, PresentationId);-struct PendingFrame {- Gfx::IntRect viewport_rect;- Gfx::IntRect forced_damage_rect;-- static PendingFrame repainting_everything(Gfx::IntRect viewport_rect) { return { viewport_rect, { {}, viewport_rect.size() } }; }- static PendingFrame repainting_changes(Gfx::IntRect viewport_rect) { return { viewport_rect, {} }; }-};--using PresentScheduling = RustFFI::PresentScheduling;--// A frame that the scroll and input logic of a context wants presented. The compositor schedules it once the call that-// asked for it has returned.-struct PresentRequest {- Web::CompositorContextId context_id;- // Empty for a frame at the viewport rect the context is presented at.- Optional<Gfx::IntRect> viewport_rect;- Gfx::IntRect forced_damage_rect;- PresentScheduling scheduling { PresentScheduling::OnNextDisplayTick };-};--// What the presentation knows of a context as a tick of a display begins.-struct DisplayTickInputs {- bool context_is_on_tick_display { false };- bool present_is_scheduled_on_tick_display { false };- // Set when the render clock of the context is due a tick now.- Optional<double> clock_tick_interval_in_milliseconds;-};--using DisplayTickResult = RustFFI::DisplayTickResult;-using ContextTimer = RustFFI::ContextTimer;// A label of an overlay, shaped in a font that the overlays' resources of its context hold: the glyphs, where each goes@@ -79,8 +48,6 @@ public:virtual void post_message_to_render_clock_of_web_content(WebContentClientId, IPC::MessageBuffer&) = 0;// A message for a presentation that is gone is dropped.virtual void post_message_to_presentation(PresentationId, IPC::MessageBuffer&) = 0;- // Display ticks reach a context whose scroll and input logic says it needs animation frames, while it is visible.- virtual void request_display_ticks(Web::CompositorContextId) = 0;// Each timer of a context fires once after the delay, and setting it again replaces the delay.virtual void set_timer(Web::CompositorContextId, ContextTimer, AK::Duration delay) = 0;virtual void cancel_timer(Web::CompositorContextId, ContextTimer) = 0;diff --git a/Services/Compositor/CompositorPresentationClient.ipc b/Services/Compositor/CompositorPresentationClient.ipcindex 2f50bac710e..cd3aacc1cb1 100644--- a/Services/Compositor/CompositorPresentationClient.ipc+++ b/Services/Compositor/CompositorPresentationClient.ipc@@ -8,8 +8,8 @@ endpoint CompositorPresentationClientdid_allocate_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_add_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_retire_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids) =|- did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) =|- did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) =|+ [RustSender] did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) =|+ [RustSender] did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) =|did_take_frame_snapshot(u64 request_id, Optional<Gfx::ShareableBitmap> snapshot) =|did_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) =|did_commit_synchronized_resize(u64 remote_layer_id, u64 token) =|diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 95847d45ce9..0a7d980b932 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -7,12 +7,18 @@#include <AK/Math.h>#include <AK/Random.h>#include <AK/StdLibExtras.h>+#include <AK/TemporaryChange.h>#include <Compositor/CanvasHost.h>#include <Compositor/CompositorState.h>+#include <Compositor/SkiaUtils.h>#include <LibCore/EventLoop.h>#include <LibCore/StatsLog.h>#include <LibCore/Timer.h>+#include <LibGfx/Bitmap.h>#include <LibMedia/Sinks/DisplayingVideoSink.h>+#include <LibMediaCodecs/VideoSurface.h>+#include <core/SkCanvas.h>+#include <core/SkImage.h>namespace Compositor {@@ -25,29 +31,38 @@ NonnullRefPtr<CompositorState> CompositorState::create(RefPtr<Gfx::SkiaBackendCoCompositorState::CompositorState(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, bool scrollbars_always_shown): m_skia_backend_context(move(skia_backend_context))- , m_display_list_player(make<DisplayListPlayerSkia>(m_skia_backend_context))- , m_core(*this, scrollbars_always_shown)+ , m_core(*this, raster_host(*this), scrollbars_always_shown, gpu_backend(m_skia_backend_context)){}+RustFFI::GpuBackend CompositorState::gpu_backend([[maybe_unused]] RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)+{+ RustFFI::GpuBackend backend {+ .has_gpu = skia_backend_context != nullptr,+ .shared_stores_need_the_same_adapter = false,+ .adapter_luid = 0,+ };+#ifdef USE_DIRECTX+ backend.shared_stores_need_the_same_adapter = true;+ if (skia_backend_context)+ backend.adapter_luid = skia_backend_context->direct3d_context().adapter_luid();+#endif+ return backend;+}+IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_web_content(WebContentClientId client_id, IPC::RawMessage& message){- auto outcome = m_core.handle_message_from_web_content(client_id, message, MonotonicTime::now());- schedule_requested_presents();- return outcome;+ return m_core.handle_message_from_web_content(client_id, message);}IPC::RawMessage::OutcomeInRust CompositorState::handle_message_from_presentation(PresentationId presentation_id, IPC::RawMessage& message){- auto outcome = m_core.handle_message_from_presentation(presentation_id, message, MonotonicTime::now());- schedule_requested_presents();- return outcome;+ return m_core.handle_message_from_presentation(presentation_id, message);}-CompositorState::PresentedContext::PresentedContext(Optional<u64> page_id, CompositorStateWebContentClient& web_content_client, OwnedCanvasSurfaces canvas_surfaces)- : page_id(page_id)- , web_content_client(web_content_client)- , presenter(canvas_surfaces, page_id.has_value())+CompositorState::PresentedContext::PresentedContext(CompositorStateWebContentClient& web_content_client, OwnedCanvasSurfaces canvas_surfaces)+ : web_content_client(web_content_client)+ , raster_targets(canvas_surfaces){}@@ -85,14 +100,13 @@ void CompositorState::post_message_to_render_clock_of_web_content(WebContentClievoid CompositorState::post_message_to_presentation(PresentationId presentation_id, IPC::MessageBuffer& buffer){- if (auto* presentation = m_presentations_by_id.get(presentation_id).value_or(nullptr))+ if (auto* presentation = presentation_if_present(presentation_id))presentation->post_message_to_presentation(buffer);}-void CompositorState::request_display_ticks(Web::CompositorContextId context_id)+CompositorStateClient* CompositorState::presentation_if_present(PresentationId presentation_id) const{- if (auto* context = presented_context_if_present(context_id); context && context_is_effectively_visible(*context))- vsync_scheduler_for_display(display_id_for_context(*context)).schedule(display_refresh_rate_for_context(*context));+ return m_presentations_by_id.get(presentation_id).value_or(nullptr);}void CompositorState::set_timer(Web::CompositorContextId context_id, ContextTimer timer, AK::Duration delay)@@ -118,17 +132,24 @@ void CompositorState::context_timer_fired(Web::CompositorContextId context_id, C{if (!presented_context_if_present(context_id))return;- m_core.timer_fired(context_id, timer, MonotonicTime::now());- schedule_requested_presents();+ m_core.timer_fired(context_id, timer);}PresentationId CompositorState::register_presentation(CompositorStateClient& presentation, PresentationCapabilities capabilities){PresentationId presentation_id { m_next_presentation_id++ };- m_presentations.set(&presentation, capabilities);m_presentations_by_id.set(presentation_id, &presentation);if (auto window_server = WindowServer::try_create_for_presentation())m_window_servers.set(&presentation, window_server.release_nonnull());+ m_core.register_presentation(presentation_id,+ {+ .synthesizes_scroll_momentum = capabilities.synthesizes_scroll_momentum,+ .scrolls_elastically = capabilities.scrolls_elastically,+ .scrollbar_track_press_jumps = capabilities.scrollbar_track_press_jumps,+ .has_gpu_presentation_adapter = capabilities.gpu_presentation_adapter_luid.has_value(),+ .gpu_presentation_adapter_luid = capabilities.gpu_presentation_adapter_luid.value_or(0),+ .cannot_present_gpu_images = capabilities.cannot_present_gpu_images,+ });return presentation_id;}@@ -146,62 +167,21 @@ void CompositorState::unregister_presentation(CompositorStateClient& presentatio(*window_server)->release_changes_held_off_screen();}- Vector<Web::CompositorContextId> bound_context_ids;- for (auto const& [context_id, bound_presentation] : m_context_presentations) {- if (bound_presentation == &presentation)- bound_context_ids.append(context_id);- }- for (auto context_id : bound_context_ids)- unbind_presentation(context_id);- m_presentations.remove(&presentation);+ m_core.unregister_presentation(presentation.presentation_id());m_presentations_by_id.remove(presentation.presentation_id());}void CompositorState::bind_presentation(Web::CompositorContextId context_id, CompositorStateClient& presentation){- VERIFY(m_presentations.contains(&presentation));- auto* context = presented_context_if_present(context_id);- if (!context || !context->presenter.presents_to_client()) {- dbgln("Compositor: Ignoring presentation binding for context {}, which is not a root context", context_id);- return;- }- if (presentation_for_context(context_id) == &presentation)- return;-- unbind_presentation(context_id);- m_context_presentations.set(context_id, &presentation);- m_core.set_bound_presentation(context_id, presentation.presentation_id());- update_scroll_capabilities();-- // The new presentation has seen none of the context's buffers, so it gets buffers of its own.- context->presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(context_id, *context);-}--void CompositorState::unbind_presentation(Web::CompositorContextId context_id)-{- if (!m_context_presentations.remove(context_id))+ VERIFY(presentation_if_present(presentation.presentation_id()) == &presentation);+ if (!presented_context_if_present(context_id))return;- auto* context = presented_context_if_present(context_id);- VERIFY(context);- m_core.set_bound_presentation(context_id, {});-- for (auto& pending_present : m_pending_async_presents) {- if (pending_present.context_id == context_id)- pending_present.publish_to_presentation = false;- }- // Nobody is left to release the buffers the presentation was showing.- context->presenter.acknowledge_all_presented_bitmaps();- update_scroll_capabilities();-- context->presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(context_id, *context);- schedule_pending_present_frame_if_unblocked(context_id, *context);+ m_core.bind_presentation(context_id, presentation.presentation_id());}Compositing::RemoteLayerHostHandle CompositorState::create_remote_layer(CompositorStateClient& presentation, u64 remote_layer_id){- VERIFY(m_presentations.contains(&presentation));+ VERIFY(presentation_if_present(presentation.presentation_id()) == &presentation);if (auto existing = m_remote_layers.find(remote_layer_id); existing != m_remote_layers.end()) {dbgln("Compositor: Ignoring creation of remote layer {}, which already exists", remote_layer_id);return {};@@ -237,14 +217,16 @@ void CompositorState::show_context_in_remote_layer(u64 remote_layer_id, Optionalremote_layer->value.size_of_shown_frame_laid_out_by_page = {};if (auto shown_context_id = exchange(remote_layer->value.shown_context_id, {}); shown_context_id.has_value()) {- if (auto* shown_context = presented_context_if_present(*shown_context_id))- stop_showing_context_in_remote_layer(*shown_context_id, *shown_context);+ if (auto* shown_context = presented_context_if_present(*shown_context_id)) {+ shown_context->remote_layer_id = {};+ m_core.set_shown_in_remote_layer(*shown_context_id, false);+ }}if (!context_id.has_value())return;auto* context = presented_context_if_present(*context_id);- if (!context || !context->presenter.presents_to_client()) {+ if (!context || !m_core.presents_to_client(*context_id)) {dbgln("Compositor: Ignoring context {} for remote layer {}, as it is not a root context", *context_id, remote_layer_id);return;}@@ -257,12 +239,7 @@ void CompositorState::show_context_in_remote_layer(u64 remote_layer_id, Optionalremote_layer->value.shown_context_id = context_id;context->remote_layer_id = remote_layer_id;- stop_delivering_in_flight_frames_to_their_viewer(*context_id);- // The presentation no longer shows the stores it was given, so none of them is waiting to be released by it.- context->presenter.acknowledge_all_presented_bitmaps();- context->presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(*context_id, *context);- schedule_pending_present_frame_if_unblocked(*context_id, *context);+ m_core.set_shown_in_remote_layer(*context_id, true);}void CompositorState::set_remote_layer_fit(u64 remote_layer_id, Optional<Gfx::IntSize> fit_within)@@ -342,29 +319,12 @@ void CompositorState::release_synchronized_resize_hold()window_server->release_changes_held_off_screen();}-void CompositorState::stop_showing_context_in_remote_layer(Web::CompositorContextId context_id, PresentedContext& context)-{- context.remote_layer_id = {};- stop_delivering_in_flight_frames_to_their_viewer(context_id);- context.presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(context_id, context);- schedule_pending_present_frame_if_unblocked(context_id, context);-}--// The frames were drawn into stores of the way the context was shown before, so they are released without being shown.-void CompositorState::stop_delivering_in_flight_frames_to_their_viewer(Web::CompositorContextId context_id)-{- for (auto& pending_present : m_pending_async_presents) {- if (pending_present.context_id != context_id)- continue;- pending_present.publish_to_presentation = false;- pending_present.shows_in_remote_layer = false;- }-}-CompositorStateClient* CompositorState::presentation_for_context(Web::CompositorContextId context_id) const{- return m_context_presentations.get(context_id).value_or(nullptr);+ auto presentation_id = m_core.bound_presentation(context_id);+ if (!presentation_id.has_value())+ return nullptr;+ return presentation_if_present(*presentation_id);}CompositorState::ContextOwnerCheckResult CompositorState::check_context_owner(Web::CompositorContextId context_id, WebContentClientId client)@@ -454,7 +414,7 @@ void CompositorState::commit_placeholder_canvas(Compositing::CanvasId canvas_id,placeholder.surface = nullptr;m_canvas_surface_registry.remove_canvas_surface(canvas_id);}- present_contexts_drawing_canvas(*placeholder.owner, canvas_id);+ m_core.canvas_content_changed(placeholder.owner->web_content_client_id(), canvas_id);if (placeholder.size == size && placeholder.origin_clean == origin_clean)return;@@ -476,33 +436,19 @@ CompositorState::PlaceholderCanvasPixels CompositorState::read_placeholder_canvavoid CompositorState::create_context(Web::CompositorContextId context_id, Optional<u64> page_id, CompositorStateWebContentClient& web_content_client){- m_core.create_context(context_id, page_id, web_content_client.web_content_client_id());- auto& context = *m_presented_contexts.ensure(context_id, [&] {- return make<PresentedContext>(page_id, web_content_client, OwnedCanvasSurfaces { m_canvas_surface_registry, web_content_client.canvas_surface_owner_id() });+ m_presented_contexts.ensure(context_id, [&] {+ return make<PresentedContext>(web_content_client, OwnedCanvasSurfaces { m_canvas_surface_registry, web_content_client.canvas_surface_owner_id() });});- context.presenter.set_window_server_may_show_high_dynamic_range(m_window_server_may_show_high_dynamic_range);- resize_backing_stores_if_needed(context_id, context);+ m_core.create_context(context_id, page_id, web_content_client.web_content_client_id());}void CompositorState::destroy_context(Web::CompositorContextId context_id){- auto* context = presented_context_if_present(context_id);- VERIFY(context);-- cancel_pending_async_presents_for_context(context_id);- clear_parent_context(context_id, *context);- for (auto& context_entry : m_presented_contexts) {- if (context_entry.key == context_id)- continue;- auto& possible_child_context = *context_entry.value;- auto parent_context_id = possible_child_context.parent_context_id;- if (parent_context_id.has_value() && *parent_context_id == context_id)- possible_child_context.parent_context_id = {};- }- m_context_presentations.remove(context_id);- if (context->remote_layer_id.has_value()) {+ auto& context = presented_context(context_id);+ m_core.destroy_context(context_id);+ if (context.remote_layer_id.has_value()) {// The layer keeps the context's last frame until another context is shown in it.- if (auto remote_layer = m_remote_layers.find(*context->remote_layer_id); remote_layer != m_remote_layers.end())+ if (auto remote_layer = m_remote_layers.find(*context.remote_layer_id); remote_layer != m_remote_layers.end())remote_layer->value.shown_context_id = {};}if (auto timers = m_context_timers.find(context_id); timers != m_context_timers.end()) {@@ -512,72 +458,31 @@ void CompositorState::destroy_context(Web::CompositorContextId context_id)}m_context_timers.remove(timers);}- m_core.destroy_context(context_id);m_presented_contexts.remove(context_id);- update_scroll_capabilities();update_unpainted_video_update_scheduling();}-// What a client shows is rooted at the context presented to it, and no context is nested in itself.bool CompositorState::context_can_be_nested_in(Web::CompositorContextId context_id, Web::CompositorContextId parent_context_id) const{- auto const* context = presented_context_if_present(context_id);- VERIFY(context);- return !context->presenter.presents_to_client() && parent_context_id != context_id;+ VERIFY(presented_context_if_present(context_id));+ return m_core.context_can_be_nested_in(context_id, parent_context_id);}void CompositorState::set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id){- auto* context = presented_context_if_present(context_id);- VERIFY(context);-- if (parent_context_id.has_value()) {- VERIFY(!context->presenter.presents_to_client());- VERIFY(*parent_context_id != context_id);- // The parent's context belongs to the process hosting the parent, which can destroy it before this context's- // process hears that the parent is gone. The context is left without a parent then, as destroying the parent- // would have left it.- // NB: The UI process creates a context here before it hands the context's ID out, so a parent this doesn't know- // has been destroyed.- if (!presented_context_if_present(*parent_context_id))- parent_context_id = {};- }-- auto current_parent_context_id = context->parent_context_id;- if (current_parent_context_id.has_value() == parent_context_id.has_value()- && (!current_parent_context_id.has_value() || *current_parent_context_id == *parent_context_id))- return;-- clear_parent_context(context_id, *context);- context->parent_context_id = parent_context_id;+ VERIFY(presented_context_if_present(context_id));m_core.set_parent_context(context_id, parent_context_id);- update_scroll_capabilities();-- if (!parent_context_id.has_value())- return;-- if (!context->presenter.latest_rendered_surface() && !context->presenter.needs_rasterization())- return;-- auto* parent_context = presented_context_if_present(*parent_context_id);- VERIFY(parent_context);- present_current_frame(*parent_context_id, *parent_context);}void CompositorState::stop_presenting_to_client(Web::CompositorContextId context_id){- auto* context = presented_context_if_present(context_id);- VERIFY(context);- unbind_presentation(context_id);+ VERIFY(presented_context_if_present(context_id));m_core.stop_presenting_to_client(context_id);- context->presenter.stop_presenting_to_client();}bool CompositorState::update_display_list(Web::CompositorContextId context_id, NonnullRefPtr<Compositing::DisplayList> display_list, IPC::Encoded<Optional<Compositing::DisplayList::AsyncScrollingMetadata>> const& async_scrolling_metadata, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, ReadonlyBytes encoded_scroll_state){- auto now = MonotonicTime::now();- auto* context = presented_context_if_present(context_id);- VERIFY(context);+ auto& context = presented_context(context_id);if (display_list->compatible_visual_context_tree_structural_epoch() != visual_context_tree.structural_epoch()) {dbgln("Compositor: Dropping inconsistent display list update (display list epoch {}, tree epoch {})",@@ -590,41 +495,36 @@ bool CompositorState::update_display_list(Web::CompositorContextId context_id, Nreturn true;}- if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, encoded_scroll_state, now))+ if (!m_core.install_display_list_update(context_id, *display_list, async_scrolling_metadata, visual_context_tree, encoded_scroll_state))return false;- context->presenter.apply_resource_transaction(move(resource_transaction));- context->presenter.set_display_list(display_list);- resolve_video_sinks(*context);- show_animated_image_frames_in(*context);-+ context.raster_targets.apply_resource_transaction(move(resource_transaction));+ resolve_video_sinks(context);+ show_animated_image_frames_in(context);update_unpainted_video_update_scheduling();return true;}void CompositorState::update_display_list_resources(Web::CompositorContextId context_id, Compositing::DisplayListResourceTransaction&& resource_transaction){- auto* context = presented_context_if_present(context_id);- VERIFY(context);- context->presenter.apply_resource_transaction(move(resource_transaction));- show_animated_image_frames_in(*context);+ auto& context = presented_context(context_id);+ context.raster_targets.apply_resource_transaction(move(resource_transaction));+ show_animated_image_frames_in(context);}bool CompositorState::update_visual_context_tree(Web::CompositorContextId context_id, Compositing::AccumulatedVisualContextTree visual_context_tree, Compositing::DisplayListResourceTransaction&& resource_transaction, ReadonlyBytes encoded_scroll_state, IPC::Encoded<Compositing::KeyboardScrollState> const& keyboard_scroll_state){- auto now = MonotonicTime::now();- auto* context = presented_context_if_present(context_id);- VERIFY(context);+ auto& context = presented_context(context_id);- switch (m_core.update_visual_context_tree(context_id, visual_context_tree, encoded_scroll_state, keyboard_scroll_state, now)) {+ switch (m_core.update_visual_context_tree(context_id, visual_context_tree, encoded_scroll_state, keyboard_scroll_state)) {case CompositorCore::VisualContextTreeUpdateResult::TreeReplaced:- context->presenter.apply_resource_transaction(move(resource_transaction));+ context.raster_targets.apply_resource_transaction(move(resource_transaction));break;case CompositorCore::VisualContextTreeUpdateResult::TreeDropped:break;case CompositorCore::VisualContextTreeUpdateResult::InvalidScrollState:return false;}- show_animated_image_frames_in(*context);+ show_animated_image_frames_in(context);return true;}@@ -698,9 +598,9 @@ void CompositorState::on_video_sink_ready(CompositorStateWebContentClient& clienpresent_contexts_drawing_video_sink(client, handle);update_unpainted_video_update_scheduling();});- for (auto& context_entry : m_presented_contexts) {- if (context_entry.value->web_content_client.web_content_client_id() == client.web_content_client_id())- resolve_video_sinks(*context_entry.value);+ for (auto& [_, context] : m_presented_contexts) {+ if (context->web_content_client.web_content_client_id() == client.web_content_client_id())+ resolve_video_sinks(*context);}present_contexts_drawing_video_sink(client, handle);update_unpainted_video_update_scheduling();@@ -795,9 +695,8 @@ void CompositorState::animated_image_decoder_lost(CompositorStateWebContentClienbool CompositorState::animated_image_is_drawn(CompositorStateWebContentClient* client, Compositing::ImageFrameResourceId id){- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (context.web_content_client.web_content_client_id() == client->web_content_client_id() && context_is_effectively_visible(context) && context.presenter.resource_storage().has_image_frame(id))+ for (auto& [context_id, context] : m_presented_contexts) {+ if (context->web_content_client.web_content_client_id() == client->web_content_client_id() && context->raster_targets.resource_storage().has_image_frame(id) && m_core.context_is_effectively_visible(context_id))return true;}return false;@@ -805,15 +704,12 @@ bool CompositorState::animated_image_is_drawn(CompositorStateWebContentClient* cvoid CompositorState::show_animated_image_frame(CompositorStateWebContentClient* client, Compositing::ImageFrameResourceId id, Gfx::DecodedImageFrame const& frame){- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (context.web_content_client.web_content_client_id() != client->web_content_client_id() || !context.presenter.resource_storage().has_image_frame(id))- continue;- context.presenter.resource_storage().replace_image_frame_pixels(id, frame);- if (!context_is_effectively_visible(context))+ for (auto& [context_id, context] : m_presented_contexts) {+ auto& resource_storage = context->raster_targets.resource_storage();+ if (context->web_content_client.web_content_client_id() != client->web_content_client_id() || !resource_storage.has_image_frame(id))continue;- if (auto rect = context.presenter.self_present_rect(); rect.has_value())- schedule_present_frame(context_entry.key, context, PendingFrame::repainting_changes(*rect));+ resource_storage.replace_image_frame_pixels(id, frame);+ m_core.context_content_changed(context_id);}}@@ -825,8 +721,8 @@ void CompositorState::show_animated_image_frames_in(PresentedContext& context)for (auto& image_entry : images->value) {Compositing::ImageFrameResourceId id { image_entry.key };auto const& frame = image_entry.value->shown_frame();- if (frame.has_value() && context.presenter.resource_storage().has_image_frame(id) && !context.presenter.resource_storage().image_frame(id).has_same_pixels_as(*frame))- context.presenter.resource_storage().replace_image_frame_pixels(id, *frame);+ if (frame.has_value() && context.raster_targets.resource_storage().has_image_frame(id) && !context.raster_targets.resource_storage().image_frame(id).has_same_pixels_as(*frame))+ context.raster_targets.resource_storage().replace_image_frame_pixels(id, *frame);}// An image that nothing drew has been waiting for a context to draw it.if (!images->value.is_empty())@@ -878,64 +774,48 @@ void CompositorState::schedule_animated_image_update(AK::Duration delay)void CompositorState::present_contexts_drawing_video_sink(CompositorStateWebContentClient& client, Media::VideoSinkHandle handle){- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (context.web_content_client.web_content_client_id() != client.web_content_client_id())- continue;- if (!context_is_effectively_visible(context))- continue;- for (auto const& resource_entry : context.presenter.resource_storage().video_sink_handles()) {- if (resource_entry.value == handle) {- if (auto rect = context.presenter.self_present_rect(); rect.has_value())- schedule_present_frame(context_entry.key, context, PendingFrame::repainting_changes(*rect));- break;- }- }- }-}--void CompositorState::present_contexts_drawing_canvas(CompositorStateWebContentClient& client, Compositing::CanvasId canvas_id)-{- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (context.web_content_client.web_content_client_id() != client.web_content_client_id())- continue;- if (!context_is_effectively_visible(context) || !context.presenter.draws_canvas(canvas_id))+ for (auto& [context_id, context] : m_presented_contexts) {+ if (context->web_content_client.web_content_client_id() != client.web_content_client_id() || !context->raster_targets.draws_video_sink(handle))continue;- if (auto rect = context.presenter.self_present_rect(); rect.has_value())- schedule_present_frame(context_entry.key, context, PendingFrame::repainting_changes(*rect));+ // NB: While the video sinks are updated for a display tick, the tick presents the contexts it is told about.+ if (m_contexts_with_new_video_frames)+ m_contexts_with_new_video_frames->append(context_id.value());+ else+ m_core.context_content_changed(context_id);}}void CompositorState::resolve_video_sinks(PresentedContext& context){auto& client = context.web_content_client;- for (auto const& resource_entry : context.presenter.resource_storage().video_sink_handles()) {- auto* sink_state = video_sink_state(client, resource_entry.value);- context.presenter.resource_storage().set_video_sink(Compositing::VideoSinkResourceId { resource_entry.key }, sink_state ? sink_state->sink : nullptr);+ auto& resource_storage = context.raster_targets.resource_storage();+ for (auto const& [id, handle] : resource_storage.video_sink_handles()) {+ auto* sink_state = video_sink_state(client, handle);+ resource_storage.set_video_sink(Compositing::VideoSinkResourceId { id }, sink_state ? sink_state->sink : nullptr);}}bool CompositorState::video_sink_is_painted_by_any_context(CompositorStateWebContentClient* client, Media::VideoSinkHandle handle) const{- for (auto const& context_entry : m_presented_contexts) {- auto const& context = *context_entry.value;- if (context.web_content_client.web_content_client_id() != client->web_content_client_id())- continue;- for (auto const& resource_entry : context.presenter.resource_storage().video_sink_handles()) {- if (resource_entry.value == handle)- return true;- }+ for (auto const& [_, context] : m_presented_contexts) {+ if (context->web_content_client.web_content_client_id() == client->web_content_client_id() && context->raster_targets.draws_video_sink(handle))+ return true;}return false;}int CompositorState::unpainted_video_update_interval_ms() const{- auto max_refresh_rate = 60.0;- for (auto const& context_entry : m_presented_contexts)- max_refresh_rate = max(max_refresh_rate, context_entry.value->display_refresh_rate);- return max(1, static_cast<int>(1000.0 / max_refresh_rate));+ return max(1, static_cast<int>(1000.0 / m_maximum_display_refresh_rate));+}++void CompositorState::set_maximum_display_refresh_rate(double refresh_rate)+{+ if (m_maximum_display_refresh_rate == refresh_rate)+ return;+ m_maximum_display_refresh_rate = refresh_rate;+ if (m_unpainted_video_update_timer)+ m_unpainted_video_update_timer->set_interval(AK::Duration::from_milliseconds(unpainted_video_update_interval_ms()));}void CompositorState::schedule_unpainted_video_updates()@@ -977,103 +857,23 @@ CompositorState::VideoSinkUpdateResult CompositorState::update_all_video_sinks()return result;}-void CompositorState::update_video_sinks_for_display(Optional<u64> display_id)-{- update_all_video_sinks();-- // Keep this display's vsync ticking while any sink painted on it may require updates.- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (display_id_for_context(context) != display_id)- continue;- if (!context_is_effectively_visible(context))- continue;- for (auto const& resource_entry : context.presenter.resource_storage().video_sink_handles()) {- auto* sink_state = video_sink_state(context.web_content_client, resource_entry.value);- if (sink_state != nullptr && sink_state->requires_updates) {- vsync_scheduler_for_display(display_id).schedule(display_refresh_rate_for_context(context));- break;- }- }- }-}--Optional<u64> CompositorState::display_id_for_context(PresentedContext const& context) const-{- auto current_context = &context;- while (current_context) {- if (current_context->display_id.has_value())- return current_context->display_id;- auto parent_context_id = current_context->parent_context_id;- if (!parent_context_id.has_value())- break;- current_context = presented_context_if_present(*parent_context_id);- }- return {};-}--CompositorState::PresentedContext const* CompositorState::root_context_of(PresentedContext const& context) const-{- auto const* current_context = &context;- while (true) {- auto parent_context_id = current_context->parent_context_id;- if (!parent_context_id.has_value())- return current_context;- auto const* parent_context = presented_context_if_present(*parent_context_id);- if (!parent_context)- return current_context;- current_context = parent_context;- }-}--Web::CompositorContextId CompositorState::root_context_id_of(Web::CompositorContextId context_id) const-{- auto const* current_context = presented_context_if_present(context_id);- VERIFY(current_context);- while (true) {- auto parent_context_id = current_context->parent_context_id;- if (!parent_context_id.has_value())- return context_id;- auto const* parent_context = presented_context_if_present(*parent_context_id);- if (!parent_context)- return context_id;- context_id = *parent_context_id;- current_context = parent_context;- }-}--bool CompositorState::context_is_effectively_visible(PresentedContext const& context) const-{- return root_context_of(context)->visibility == Compositing::ContextVisibility::Visible;-}--double CompositorState::display_refresh_rate_for_context(PresentedContext const& context) const+bool CompositorState::context_video_sinks_require_updates(Web::CompositorContextId context_id){- auto current_context = &context;- while (current_context) {- if (current_context->display_id.has_value())- return current_context->display_refresh_rate;- auto parent_context_id = current_context->parent_context_id;- if (!parent_context_id.has_value())- break;- current_context = presented_context_if_present(*parent_context_id);+ auto* context = presented_context_if_present(context_id);+ if (!context)+ return false;+ for (auto const& [_, handle] : context->raster_targets.resource_storage().video_sink_handles()) {+ if (auto* sink_state = video_sink_state(context->web_content_client, handle); sink_state && sink_state->requires_updates)+ return true;}- return context.display_refresh_rate;+ return false;}void CompositorState::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress){- auto* context = presented_context_if_present(context_id);- if (!context)+ if (!presented_context_if_present(context_id))return;-- m_core.viewport_size_updated(context_id, viewport_size, device_pixel_ratio);- auto is_page_presentation_context = context->page_id.has_value() && !context->parent_context_id.has_value();- context->presenter.set_viewport_size(viewport_size, device_pixel_ratio, is_page_presentation_context ? window_resize_in_progress : Compositing::WindowResizingInProgress::No);- resize_backing_stores_if_needed(context_id, *context);- schedule_requested_presents();- if (context->presenter.should_shrink_backing_stores_after_resize())- schedule_backing_store_shrink(context_id, *context);+ m_core.viewport_size_updated(context_id, viewport_size, device_pixel_ratio, window_resize_in_progress);}Optional<OverlayLabel> CompositorState::shape_overlay_label(Web::CompositorContextId context_id, Optional<StringView> font_family, double device_pixel_ratio, StringView text)@@ -1081,488 +881,144 @@ Optional<OverlayLabel> CompositorState::shape_overlay_label(Web::CompositorConteauto* context = presented_context_if_present(context_id);if (!context)return {};- return context->presenter.shape_overlay_label(font_family, device_pixel_ratio, text);+ return context->raster_targets.shape_overlay_label(font_family, device_pixel_ratio, text);}void CompositorState::set_ui_overlays(Web::CompositorContextId context_id, Compositing::UIOverlays overlays){if (!presented_context_if_present(context_id))return;- m_core.set_ui_overlays(context_id, overlays, MonotonicTime::now());- schedule_requested_presents();+ m_core.set_ui_overlays(context_id, overlays);}void CompositorState::set_display_metadata(Web::CompositorContextId context_id, Optional<u64> display_id, double refresh_rate){- auto* context = presented_context_if_present(context_id);- if (!context)+ if (!presented_context_if_present(context_id))return;VERIFY(refresh_rate == refresh_rate);VERIFY(refresh_rate > 0);VERIFY(refresh_rate < AK::Infinity<double>);-- context->display_id = display_id;- context->display_refresh_rate = refresh_rate;- if (context->presenter.pending_present_frame_scheduled()) {- schedule_pending_present_frame(context_id, *context);- if (m_unpainted_video_update_timer)- m_unpainted_video_update_timer->set_interval(AK::Duration::from_milliseconds(unpainted_video_update_interval_ms()));- }-- if ((context->rendering_opportunity_request.is_requested() || context->clock_tick_request.is_requested()) && context_is_effectively_visible(*context))- vsync_scheduler_for_display(display_id_for_context(*context)).schedule(display_refresh_rate_for_context(*context));+ m_core.set_display_metadata(context_id, display_id, refresh_rate);}void CompositorState::set_context_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility){- auto now = MonotonicTime::now();- auto* context = presented_context_if_present(context_id);- if (!context)- return;- m_core.set_visibility(context_id, visibility, now);- schedule_requested_presents();- if (context->visibility == visibility)+ if (!presented_context_if_present(context_id))return;- context->visibility = visibility;-- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} became {}", context_id, visibility == Compositing::ContextVisibility::Visible ? "visible" : "hidden");-- if (visibility == Compositing::ContextVisibility::Visible)- resume_presentation_after_becoming_visible(context_id, *context);+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} is {}", context_id, visibility == Compositing::ContextVisibility::Visible ? "visible" : "hidden");+ // An image that was hidden finds its place by the clock again.+ if (m_core.set_visibility(context_id, visibility))+ schedule_animated_image_update({});}void CompositorState::set_window_server_may_show_high_dynamic_range(bool may_show){- if (m_window_server_may_show_high_dynamic_range == may_show)- return;- m_window_server_may_show_high_dynamic_range = may_show;- for (auto& context_entry : m_presented_contexts) {- context_entry.value->presenter.set_window_server_may_show_high_dynamic_range(may_show);- present_current_frame(context_entry.key, *context_entry.value);- }+ m_core.set_window_server_may_show_high_dynamic_range(may_show);}void CompositorState::set_context_presents_from_cpu_memory(Web::CompositorContextId context_id, bool presents_from_cpu_memory){- auto* context = presented_context_if_present(context_id);- if (!context || context->presents_from_cpu_memory == presents_from_cpu_memory)- return;- auto previous_gpu_sharing = gpu_sharing_for_context(context_id);- context->presents_from_cpu_memory = presents_from_cpu_memory;- // NB: Without a GPU, the backing stores are in CPU memory either way.- if (!m_skia_backend_context || gpu_sharing_for_context(context_id) == previous_gpu_sharing)+ if (!presented_context_if_present(context_id))return;-- // NB: Otherwise, the presentation would read every frame back from GPU memory on its main thread.- context->presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(context_id, *context);-}--void CompositorState::resume_presentation_after_becoming_visible(Web::CompositorContextId root_context_id, PresentedContext& root_context)-{- schedule_animated_image_update({});-- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (root_context_of(context) != &root_context)- continue;- schedule_animation_frames_if_needed(context_entry.key, context);- if ((context.rendering_opportunity_request.is_requested() || context.clock_tick_request.is_requested()))- vsync_scheduler_for_display(display_id_for_context(context)).schedule(display_refresh_rate_for_context(context));- }-- if (auto frame_rect_to_present = root_context.presenter.frame_rect_to_repaint(); frame_rect_to_present.has_value())- schedule_present_frame(root_context_id, root_context, *frame_rect_to_present);+ m_core.set_presents_from_cpu_memory(context_id, presents_from_cpu_memory);}void CompositorState::request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second){- auto* context = presented_context_if_present(context_id);- VERIFY(context);-- if (!context->rendering_opportunity_request.request(maximum_frames_per_second))- return;- if (!context_is_effectively_visible(*context))- return;-- auto display_id = display_id_for_context(*context);- auto display_refresh_rate = display_refresh_rate_for_context(*context);- auto& scheduler = vsync_scheduler_for_display(display_id);- // INTEROP: Like Chromium's missed BeginFrame delivery, reuse a recent display tick when a context requests its- // next opportunity after the tick has already happened. This keeps heavy frames from waiting an extra tick.- if (auto frame_time = scheduler.most_recent_tick_time(MonotonicTime::now(), display_refresh_rate);- frame_time.has_value() && context->rendering_opportunity_request.is_due(*frame_time, display_refresh_rate)) {- auto frame_interval = context->rendering_opportunity_request.frame_interval(display_refresh_rate);- context->rendering_opportunity_request.did_deliver(*frame_time);- context->web_content_client.rendering_opportunity(context_id, frame_time->nanoseconds(), frame_interval);- return;- }-- scheduler.schedule(display_refresh_rate);+ VERIFY(presented_context_if_present(context_id));+ m_core.request_rendering_opportunity(context_id, maximum_frames_per_second);}void CompositorState::request_clock_tick(Web::CompositorContextId context_id, double maximum_frames_per_second){- auto* context = presented_context_if_present(context_id);- if (!context || !context->clock_tick_request.request(maximum_frames_per_second) || !context_is_effectively_visible(*context))+ if (!presented_context_if_present(context_id))return;- vsync_scheduler_for_display(display_id_for_context(*context)).schedule(display_refresh_rate_for_context(*context));+ m_core.request_clock_tick(context_id, maximum_frames_per_second);}void CompositorState::hurry_rendering_opportunity(Web::CompositorContextId context_id){- auto* context = presented_context_if_present(context_id);- if (!context || !context->rendering_opportunity_request.is_requested() || !context_is_effectively_visible(*context))+ if (!presented_context_if_present(context_id))return;- auto display_refresh_rate = display_refresh_rate_for_context(*context);- auto frame_interval = context->rendering_opportunity_request.frame_interval(display_refresh_rate);- auto frame_time = MonotonicTime::now();- context->rendering_opportunity_request.did_deliver(frame_time);- context->web_content_client.rendering_opportunity(context_id, frame_time.nanoseconds(), frame_interval);+ m_core.hurry_rendering_opportunity(context_id);}void CompositorState::present_frame(Web::CompositorContextId context_id, Gfx::IntRect viewport_rect){- auto* context = presented_context_if_present(context_id);- VERIFY(context);- context->size_laid_out_by_page = viewport_rect.size();- // The frame joins whatever is queued, so a frame queued earlier cannot be presented after it.- context->presenter.queue_present_frame({ viewport_rect, {} });- if (try_present_frame_during_resize(context_id, *context))- return;- schedule_pending_present_frame(context_id, *context);+ VERIFY(presented_context_if_present(context_id));+ m_core.present_frame_of_page(context_id, viewport_rect);}-void CompositorState::present_frame(Web::CompositorContextId context_id, PresentedContext& context, PendingFrame pending_frame)+bool CompositorState::request_screenshot(Web::CompositorContextId context_id, Gfx::ShareableBitmap& target_bitmap){- auto composited_context_resolver = resolver_for(context_id);- auto prepared_frame = context.presenter.prepare_frame(*m_display_list_player, pending_frame, m_core.frame_inputs(context_id, MonotonicTime::now()), &composited_context_resolver);- if (!prepared_frame.has_value())- return;-- m_pending_async_presents.append(context_id, pending_frame.viewport_rect, prepared_frame->damage_rect, prepared_frame->bitmap_id, prepared_frame->device_pixel_ratio);- auto* pending_present = &m_pending_async_presents.last();- pending_present->shows_in_remote_layer = context.presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::ShownInRemoteLayer;- pending_present->publish_to_presentation = !pending_present->shows_in_remote_layer && presentation_for_context(context_id) != nullptr;- pending_present->keeps_shown_store = !prepared_frame->rendered_surface;- pending_present->sublayers = move(prepared_frame->sublayers);-- auto& event_loop = Core::EventLoop::current();- auto self = NonnullRefPtr { *this };- auto did_finish = [self = move(self), &event_loop, pending_present] {- event_loop.deferred_invoke([self = move(self), pending_present] {- self->did_finish_async_present(*pending_present);- });- };- // A frame without a store still waits for what was drawn into the surfaces that the window server shows above the- // store, such as a canvas that presented.- if (prepared_frame->rendered_surface)- m_display_list_player->flush_async(*prepared_frame->rendered_surface, move(did_finish));- else- m_skia_backend_context->flush_and_submit_async(move(did_finish));- context.presenter.did_submit_prepared_frame(pending_frame.viewport_rect);- // Handing the frame to the client before its GPU work finishes keeps it ahead of the window server's deadline for- // the next refresh. A client that reads frames from CPU memory does not wait for that work, so it gets each frame- // once it is done.- if (context.presenter.presents_to_client() && m_skia_backend_context && !context.presents_from_cpu_memory && frame_hand_off_for(context) == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled)- hand_off_frame_once_gpu_work_is_scheduled(*pending_present);- schedule_gpu_completion_check();+ VERIFY(presented_context_if_present(context_id));+ if (!target_bitmap.is_valid() || !target_bitmap.bitmap())+ return false;+ auto target_surface = Gfx::PaintingSurface::wrap_bitmap(*target_bitmap.bitmap());+ return m_core.paint_screenshot(context_id, *target_surface);}-WindowServer::FrameHandOff CompositorState::frame_hand_off_for(PresentedContext const& context) const-{- if (context.remote_layer_id.has_value()) {- if (auto remote_layer = m_remote_layers.find(*context.remote_layer_id); remote_layer != m_remote_layers.end())- return remote_layer->value.window_server->frame_hand_off();- }- return WindowServer::frame_hand_off_through_presentation();-}+// How long a screenshot waits for the processes that paint its context's descendants. One whose script never yields+// keeps its connection open without answering, and the screenshot then goes ahead with the frames it last handed over.+static constexpr auto SCREENSHOT_PREPARATION_LIMIT = AK::Duration::from_seconds(10);-void CompositorState::hand_off_frame_once_gpu_work_is_scheduled([[maybe_unused]] PendingAsyncPresent& pending_present)+void CompositorState::prepare_remote_descendants_for_screenshot(CompositorStateWebContentClient& requester, Web::CompositorContextId context_id, u64 request_id){-#if defined(AK_OS_MACOS) || (defined(AK_OS_WINDOWS) && defined(USE_DIRECTX))- auto& event_loop = Core::EventLoop::current();- auto deliver = [self = NonnullRefPtr { *this }, &event_loop, pending_present = &pending_present]() mutable {- event_loop.deferred_invoke([self = move(self), pending_present] {- for (auto& entry : self->m_pending_async_presents) {- if (&entry == pending_present) {- self->deliver_rendered_frame(entry);- return;- }- }- });- };-#endif-#ifdef AK_OS_MACOS- // The window server's reads of an IOSurface wait for GPU work that is already scheduled to write it.- m_skia_backend_context->metal_context().when_committed_work_is_scheduled(move(deliver));-#elif defined(AK_OS_WINDOWS) && defined(USE_DIRECTX)- deliver();-#else- VERIFY_NOT_REACHED();-#endif-}+ HashMap<Web::CompositorContextId, Vector<Web::CompositorContextId>> children;+ for (auto const& [child_id, _] : m_presented_contexts) {+ if (auto parent_context_id = m_core.parent_context(child_id); parent_context_id.has_value())+ children.ensure(*parent_context_id).append(child_id);+ }-void CompositorState::schedule_requested_presents()-{- auto requests = m_core.take_present_requests();- for (auto const& request : requests) {- auto* context = presented_context_if_present(request.context_id);- if (!context)+ // From the first context of a branch that another process owns on down, each process paints the contexts it owns+ // there, the requester's included. Above that point, the requester paints its own as it takes the screenshot.+ HashMap<WebContentClientId, Vector<Web::CompositorContextId>> contexts_by_painter;+ HashTable<Web::CompositorContextId> visited;+ Vector<Web::CompositorContextId> to_visit { context_id };+ HashTable<Web::CompositorContextId> below_another_process;+ while (!to_visit.is_empty()) {+ auto id = to_visit.take_last();+ if (visited.set(id) != HashSetResult::InsertedNewEntry)continue;- auto viewport_rect = request.viewport_rect;- if (!viewport_rect.has_value())- viewport_rect = context->presenter.viewport_rect_for_ui_overlay();- if (!viewport_rect.has_value())+ auto context = m_presented_contexts.get(id);+ if (!context.has_value())continue;- switch (request.scheduling) {- case PresentScheduling::OnNextDisplayTick:- schedule_present_frame(request.context_id, *context, PendingFrame { *viewport_rect, request.forced_damage_rect });- break;- case PresentScheduling::WithDisplayTickInProgress:- context->presenter.queue_present_frame(PendingFrame { *viewport_rect, request.forced_damage_rect });- break;+ auto owner = (*context)->web_content_client.web_content_client_id();+ bool painted_by_owner = below_another_process.contains(id) || owner != requester.web_content_client_id();+ if (painted_by_owner)+ contexts_by_painter.ensure(owner).append(id);+ auto child_ids = children.find(id);+ if (child_ids == children.end())+ continue;+ for (auto child_id : child_ids->value) {+ if (painted_by_owner)+ below_another_process.set(child_id);+ to_visit.append(child_id);}}-}--void CompositorState::schedule_present_frame(Web::CompositorContextId context_id, PresentedContext& context, PendingFrame pending_frame)-{- context.presenter.queue_present_frame(pending_frame);- schedule_pending_present_frame(context_id, context);-}--void CompositorState::schedule_present_frame(Web::CompositorContextId context_id, PresentedContext& context, Gfx::IntRect viewport_rect)-{- schedule_present_frame(context_id, context, PendingFrame::repainting_everything(viewport_rect));-}-void CompositorState::schedule_pending_present_frame(Web::CompositorContextId context_id, PresentedContext& context)-{- if (!context.presenter.presents_to_client()) {- schedule_containing_context_present(context);- // A nested context is presented through its containing context, but its- // own async animations still need a vsync source. The containing frame- // may already be up to date (and therefore not schedule a new present),- // so explicitly keep the effective display's scheduler ticking while- // a nested animation is active.- schedule_animation_frames_if_needed(context_id, context);+ if (contexts_by_painter.is_empty()) {+ requester.tell_remote_descendants_prepared_for_screenshot(request_id);return;}- schedule_pending_present_frame_on_vsync(context_id, context);+ auto preparation_id = m_next_screenshot_preparation_id++;+ ScreenshotPreparation preparation { requester.web_content_client_id(), request_id, {}, {} };+ for (auto const& [painter, _] : contexts_by_painter)+ preparation.awaited_painters.set(painter);+ preparation.deadline = Core::Timer::create_single_shot(SCREENSHOT_PREPARATION_LIMIT, [this, preparation_id] {+ finish_screenshot_preparation(preparation_id);+ });+ preparation.deadline->start();+ m_screenshot_preparations.set(preparation_id, move(preparation));+ for (auto const& [painter, context_ids] : contexts_by_painter) {+ if (auto* client = web_content_client_if_present(painter))+ client->ask_to_paint_contexts_for_screenshot(preparation_id, context_ids);+ }}-bool CompositorState::needs_animation_frames(Web::CompositorContextId context_id, PresentedContext const& context, MonotonicTime now)-{- (void)context;- return m_core.needs_animation_frames(context_id, now);-}--bool CompositorState::has_pending_present_frame_scheduled_on(PresentedContext const& context, Optional<u64> display_id)-{- return context.presenter.pending_present_frame_scheduled() && context.display_id == display_id;-}--void CompositorState::schedule_animation_frames_if_needed(Web::CompositorContextId context_id, PresentedContext const& context)-{- if (needs_animation_frames(context_id, context, MonotonicTime::now()) && context_is_effectively_visible(context))- vsync_scheduler_for_display(display_id_for_context(context)).schedule(display_refresh_rate_for_context(context));-}--void CompositorState::schedule_pending_present_frame_on_vsync(Web::CompositorContextId, PresentedContext& context)-{- if (!context_is_effectively_visible(context))- return;- context.presenter.mark_pending_present_frame_scheduled();- vsync_scheduler_for_display(context.display_id).schedule(context.display_refresh_rate);-}--void CompositorState::schedule_containing_context_present(PresentedContext& context)-{- auto parent_context_id = context.parent_context_id;- if (!parent_context_id.has_value())- return;-- auto* parent_context = presented_context_if_present(*parent_context_id);- VERIFY(parent_context);- present_current_frame(*parent_context_id, *parent_context);-}--void CompositorState::schedule_pending_present_frame_if_unblocked(Web::CompositorContextId context_id, PresentedContext& context)-{- if (!context.presenter.can_schedule_pending_present_frame_if_unblocked())- return;-- if (try_present_frame_during_resize(context_id, context))- return;- schedule_pending_present_frame(context_id, context);-}--bool CompositorState::try_present_frame_during_resize(Web::CompositorContextId context_id, PresentedContext& context)-{- if (!context.presenter.window_resize_in_progress() || !context.presenter.presents_to_client() || !context_is_effectively_visible(context))- return false;- auto pending_frame = context.presenter.take_pending_present_frame_if_unblocked();- if (!pending_frame.has_value())- return false;-- // Rasterize resize frames as soon as a backing store is available, so the previous size does not- // remain visible for another display tick. prepare_frame() owns requeuing any blocked frame.- present_frame(context_id, context, *pending_frame);- // The display tick does more than present frames, such as updating the video sinks that are painted.- vsync_scheduler_for_display(display_id_for_context(context)).schedule(display_refresh_rate_for_context(context));- return true;-}--VSyncScheduler& CompositorState::vsync_scheduler_for_display(Optional<u64> display_id)-{- return *m_vsync_schedulers_by_display.ensure(display_id, [this, display_id] {- return create_vsync_scheduler(display_id, [this, display_id](MonotonicTime frame_time) {- present_pending_frames_on_vsync(display_id, frame_time);- });- });-}--void CompositorState::present_pending_frames_on_vsync(Optional<u64> display_id, MonotonicTime frame_time)-{- update_video_sinks_for_display(display_id);-- for (auto& context_entry : m_presented_contexts) {- auto context_id = context_entry.key;- auto& context = *context_entry.value;- auto now = MonotonicTime::now();- if (!context_is_effectively_visible(context)) {- context.presenter.unschedule_pending_present_frame();- continue;- }-- if (context.rendering_opportunity_request.is_requested() && display_id_for_context(context) == display_id) {- auto display_refresh_rate = display_refresh_rate_for_context(context);- if (context.rendering_opportunity_request.is_due(frame_time, display_refresh_rate)) {- auto frame_interval = context.rendering_opportunity_request.frame_interval(display_refresh_rate);- context.rendering_opportunity_request.did_deliver(frame_time);- context.web_content_client.rendering_opportunity(context_id, frame_time.nanoseconds(), frame_interval);- } else {- vsync_scheduler_for_display(display_id).schedule(display_refresh_rate);- }- }-- auto context_is_on_tick_display = display_id_for_context(context) == display_id;- DisplayTickInputs inputs {- .context_is_on_tick_display = context_is_on_tick_display,- .present_is_scheduled_on_tick_display = has_pending_present_frame_scheduled_on(context, display_id),- .clock_tick_interval_in_milliseconds = {},- };- if (context.clock_tick_request.is_requested() && context_is_on_tick_display) {- auto display_refresh_rate = display_refresh_rate_for_context(context);- if (context.clock_tick_request.is_due(frame_time, display_refresh_rate)) {- inputs.clock_tick_interval_in_milliseconds = context.clock_tick_request.frame_interval(display_refresh_rate);- context.clock_tick_request.did_deliver(frame_time);- } else {- vsync_scheduler_for_display(display_id).schedule(display_refresh_rate);- }- }-- auto tick = m_core.display_tick(context_id, frame_time, now, inputs);- schedule_requested_presents();- if (!tick.presents_on_display)- continue;-- add_backing_store_for_pending_frame_if_needed(context_id, context);- auto needs_animation_frames = tick.needs_animation_frames;- auto pending_present_frame = context.presenter.take_pending_present_frame_if_unblocked();- if (!pending_present_frame.has_value()) {- if (has_pending_present_frame_scheduled_on(context, display_id) || (needs_animation_frames && context_is_on_tick_display))- vsync_scheduler_for_display(display_id).schedule(display_refresh_rate_for_context(context));- continue;- }- if (needs_animation_frames)- schedule_present_frame(context_id, context, PendingFrame::repainting_changes(pending_present_frame->viewport_rect));- present_frame(context_id, context, *pending_present_frame);- }-}--bool CompositorState::request_screenshot(Web::CompositorContextId context_id, Gfx::ShareableBitmap& target_bitmap)-{- auto now = MonotonicTime::now();- auto* context = presented_context_if_present(context_id);- VERIFY(context);-- if (!context->presenter.has_display_list() || !target_bitmap.is_valid() || !target_bitmap.bitmap())- return false;-- auto composited_context_resolver = resolver_for(context_id);- auto screenshot_inputs = m_core.frame_inputs_for_screenshot(context_id, now);- context->presenter.paint_screenshot(*m_display_list_player, target_bitmap, screenshot_inputs.frame_inputs, &composited_context_resolver);- if (!screenshot_inputs.scrollbar_fade_damage_rect.is_empty()) {- if (auto viewport_rect = context->presenter.viewport_rect_for_ui_overlay(); viewport_rect.has_value())- schedule_present_frame(context_id, *context, { *viewport_rect, screenshot_inputs.scrollbar_fade_damage_rect });- }- return true;-}--// How long a screenshot waits for the processes that paint its context's descendants. One whose script never yields-// keeps its connection open without answering, and the screenshot then goes ahead with the frames it last handed over.-static constexpr auto SCREENSHOT_PREPARATION_LIMIT = AK::Duration::from_seconds(10);--void CompositorState::prepare_remote_descendants_for_screenshot(CompositorStateWebContentClient& requester, Web::CompositorContextId context_id, u64 request_id)-{- HashMap<Web::CompositorContextId, Vector<Web::CompositorContextId>> children;- for (auto const& [child_id, child] : m_presented_contexts) {- if (child->parent_context_id.has_value())- children.ensure(*child->parent_context_id).append(child_id);- }-- // From the first context of a branch that another process owns on down, each process paints the contexts it owns- // there, the requester's included. Above that point, the requester paints its own as it takes the screenshot.- HashMap<WebContentClientId, Vector<Web::CompositorContextId>> contexts_by_painter;- HashTable<Web::CompositorContextId> visited;- Vector<Web::CompositorContextId> to_visit { context_id };- HashTable<Web::CompositorContextId> below_another_process;- while (!to_visit.is_empty()) {- auto id = to_visit.take_last();- if (visited.set(id) != HashSetResult::InsertedNewEntry)- continue;- auto context = m_presented_contexts.get(id);- if (!context.has_value())- continue;- auto owner = (*context)->web_content_client.web_content_client_id();- bool painted_by_owner = below_another_process.contains(id) || owner != requester.web_content_client_id();- if (painted_by_owner)- contexts_by_painter.ensure(owner).append(id);- auto child_ids = children.find(id);- if (child_ids == children.end())- continue;- for (auto child_id : child_ids->value) {- if (painted_by_owner)- below_another_process.set(child_id);- to_visit.append(child_id);- }- }-- if (contexts_by_painter.is_empty()) {- requester.tell_remote_descendants_prepared_for_screenshot(request_id);- return;- }-- auto preparation_id = m_next_screenshot_preparation_id++;- ScreenshotPreparation preparation { requester.web_content_client_id(), request_id, {}, {} };- for (auto const& [painter, _] : contexts_by_painter)- preparation.awaited_painters.set(painter);- preparation.deadline = Core::Timer::create_single_shot(SCREENSHOT_PREPARATION_LIMIT, [this, preparation_id] {- finish_screenshot_preparation(preparation_id);- });- preparation.deadline->start();- m_screenshot_preparations.set(preparation_id, move(preparation));- for (auto const& [painter, context_ids] : contexts_by_painter) {- if (auto* client = web_content_client_if_present(painter))- client->ask_to_paint_contexts_for_screenshot(preparation_id, context_ids);- }-}--void CompositorState::did_paint_contexts_for_screenshot(CompositorStateWebContentClient& painter, u64 preparation_id)+void CompositorState::did_paint_contexts_for_screenshot(CompositorStateWebContentClient& painter, u64 preparation_id){auto preparation = m_screenshot_preparations.get(preparation_id);if (!preparation.has_value() || !preparation->awaited_painters.remove(painter.web_content_client_id()))@@ -1589,381 +1045,630 @@ void CompositorState::finish_screenshot_preparation(u64 preparation_id)requester->tell_remote_descendants_prepared_for_screenshot(finished->request_id);}+static Gfx::IntSize size_fitting_within(Gfx::IntSize size, Gfx::IntSize maximum_size)+{+ if (size.width() <= maximum_size.width() && size.height() <= maximum_size.height())+ return size;+ auto scale = min(static_cast<double>(maximum_size.width()) / size.width(), static_cast<double>(maximum_size.height()) / size.height());+ return { max(1, static_cast<int>(round(size.width() * scale))), max(1, static_cast<int>(round(size.height() * scale))) };+}+Optional<Gfx::ShareableBitmap> CompositorState::take_frame_snapshot(Web::CompositorContextId context_id, Optional<Gfx::IntSize> maximum_size){- auto* context = presented_context_if_present(context_id);- if (!context || !context->presenter.presents_to_client())+ if (!presented_context_if_present(context_id))+ return {};+ auto presented_frame = m_core.presented_frame_for_snapshot(context_id);+ if (!presented_frame.has_value())+ return {};+ auto const& source = *presented_frame->surface;+ auto frame_size = presented_frame->frame_size;+ auto snapshot_size = frame_size;+ if (maximum_size.has_value() && !maximum_size->is_empty())+ snapshot_size = size_fitting_within(frame_size, *maximum_size);++ auto bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, snapshot_size);+ if (bitmap_or_error.is_error())+ return {};+ auto bitmap = bitmap_or_error.release_value();++ if (snapshot_size == frame_size) {+ source.read_into_bitmap(*bitmap);+ return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };+ }++ // A linear filter reads only the pixels around each one it writes, so a frame scaled down to a fraction of its size+ // in one step would skip most of them. Halving it first lets every pixel count.+ auto image = source.sk_image_snapshot<sk_sp<SkImage>>();+ auto image_size = frame_size;+ SkSamplingOptions const sampling { SkFilterMode::kLinear };+ auto draw_scaled = [&](Gfx::IntSize size) -> RefPtr<Gfx::PaintingSurface> {+ auto surface_or_error = Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, source.skia_backend_context());+ if (surface_or_error.is_error())+ return nullptr;+ auto surface = surface_or_error.release_value();+ surface->canvas().drawImageRect(image.get(), SkRect::MakeIWH(image_size.width(), image_size.height()), SkRect::MakeIWH(size.width(), size.height()), sampling, nullptr, SkCanvas::kStrict_SrcRectConstraint);+ return surface;+ };+ while (image_size.width() / 2 >= snapshot_size.width() && image_size.height() / 2 >= snapshot_size.height()) {+ Gfx::IntSize half_size { image_size.width() / 2, image_size.height() / 2 };+ auto half = draw_scaled(half_size);+ if (!half)+ return {};+ image = half->sk_image_snapshot<sk_sp<SkImage>>();+ image_size = half_size;+ }+ auto snapshot_surface = draw_scaled(snapshot_size);+ if (!snapshot_surface)return {};- return context->presenter.snapshot_of_presented_frame(*m_display_list_player, maximum_size);+ snapshot_surface->read_into_bitmap(*bitmap);+ return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };}void CompositorState::presented_bitmap_ready_to_paint(Web::CompositorContextId context_id, i32 bitmap_id){- auto* context = presented_context_if_present(context_id);- if (!context)- return;-- if (!context->presenter.acknowledge_presented_bitmap(bitmap_id))+ if (!presented_context_if_present(context_id))return;-- schedule_pending_present_frame_if_unblocked(context_id, *context);+ m_core.presented_store_released(context_id, bitmap_id);}-void CompositorState::did_finish_async_present(PendingAsyncPresent& pending_present)+void CompositorState::set_scrollbar_track_press_jumps(CompositorStateClient& presentation, bool jumps){- auto pending_present_iterator = m_pending_async_presents.begin();- for (; pending_present_iterator != m_pending_async_presents.end(); ++pending_present_iterator) {- if (&*pending_present_iterator == &pending_present)- break;- }- VERIFY(pending_present_iterator != m_pending_async_presents.end());+ m_core.set_scrollbar_track_press_jumps(presentation.presentation_id(), jumps);+}- auto finished_present = pending_present;- (void)m_pending_async_presents.remove(pending_present_iterator);- if (m_pending_async_presents.is_empty() && m_gpu_completion_timer)- m_gpu_completion_timer->stop();+void CompositorState::set_client_gpu_presentation_capability(CompositorStateClient& presentation, bool supported, u64 adapter_luid)+{+ m_core.set_presentation_gpu_capability(presentation.presentation_id(), supported, adapter_luid);+}- deliver_rendered_frame(finished_present);+CompositorState::PresentedContext* CompositorState::presented_context_if_present(Web::CompositorContextId context_id)+{+ auto it = m_presented_contexts.find(context_id);+ if (it == m_presented_contexts.end())+ return nullptr;+ return it->value.ptr();}-static void log_presented_frame(Optional<u64> page_id, Gfx::IntRect damage)+CompositorState::PresentedContext const* CompositorState::presented_context_if_present(Web::CompositorContextId context_id) const{- auto* log = Core::StatsLog::the();- if (!log || !page_id.has_value())- return;- JsonObject data;- data.set("page_id"sv, *page_id);- data.set("changed"sv, !damage.is_empty());- data.set("damage_x"sv, damage.x());- data.set("damage_y"sv, damage.y());- data.set("damage_width"sv, damage.width());- data.set("damage_height"sv, damage.height());- log->event("frame"sv, move(data));+ auto it = m_presented_contexts.find(context_id);+ if (it == m_presented_contexts.end())+ return nullptr;+ return it->value.ptr();}-void CompositorState::show_frame_in_remote_layer(Web::CompositorContextId context_id, PresentedContext& context, PendingAsyncPresent& pending_present)+CompositorState::PresentedContext& CompositorState::presented_context(Web::CompositorContextId context_id){- VERIFY(context.remote_layer_id.has_value());- auto remote_layer = m_remote_layers.find(*context.remote_layer_id);- VERIFY(remote_layer != m_remote_layers.end());- auto* store = pending_present.keeps_shown_store ? nullptr : context.presenter.window_server_surface_of_latest_rendered_store();- VERIFY(store || pending_present.keeps_shown_store);+ auto* context = presented_context_if_present(context_id);+ VERIFY(context);+ return *context;+}- auto frame_size = pending_present.viewport_rect.size();- auto shown = remote_layer->value.layer->show_frame({- .store = store ? Optional<PresentableSurface::Lease> { store->lease() } : OptionalNone {},- .painted_size = frame_size,- .device_pixel_ratio = pending_present.device_pixel_ratio,- .fit_within = remote_layer->value.fit_within,- .sublayers = move(pending_present.sublayers),- });- if (!shown) {- dbgln("Compositor: Remote layer {} failed to show a frame of context {}, which its presentation shows again", remote_layer->key, context_id);- show_context_in_remote_layer(remote_layer->key, {});- return;+Compositing::RustFFI::FfiRasterPainter CompositorState::begin_painting(Web::CompositorContextId context_id, Gfx::PaintingSurface& surface, RustFFI::PaintingResources resources)+{+ auto& raster_targets = presented_context(context_id).raster_targets;+ if (m_painting_depth == m_display_list_players.size())+ m_display_list_players.append(make<DisplayListPlayerSkia>(m_skia_backend_context));+ auto& player = *m_display_list_players[m_painting_depth++];+ switch (resources) {+ case RustFFI::PaintingResources::Page:+ return player.begin_painting(surface, raster_targets.resource_storage(), raster_targets.raster_cache(), &raster_targets.canvas_surfaces());+ case RustFFI::PaintingResources::Overlays:+ return player.begin_painting(surface, raster_targets.overlay_resource_storage(), raster_targets.overlay_raster_cache(), nullptr);}- remote_layer->value.size_of_shown_frame_laid_out_by_page = frame_size == context.size_laid_out_by_page ? Optional<Gfx::IntSize> { frame_size } : OptionalNone {};- report_held_synchronized_resize_frames(remote_layer->key);- remote_layer->value.presentation->did_present_frame_in_remote_layer(context_id, pending_present.viewport_rect, pending_present.damage_rect, pending_present.device_pixel_ratio);+ VERIFY_NOT_REACHED();}-void CompositorState::deliver_rendered_frame(PendingAsyncPresent& pending_present)+void CompositorState::end_painting(){- if (pending_present.was_cancelled && pending_present.keeps_shown_store && !pending_present.was_delivered) {- if (auto* context = presented_context_if_present(pending_present.context_id))- context->presenter.did_deliver_frame_without_store();+ VERIFY(m_painting_depth > 0);+ m_display_list_players[--m_painting_depth]->end_painting();+}++static BackingStoreManager::PublicationMode publication_mode_of(RustFFI::StorePublication publication)+{+ switch (publication) {+ case RustFFI::StorePublication::Unpublished:+ return BackingStoreManager::PublicationMode::Unpublished;+ case RustFFI::StorePublication::Published:+ return BackingStoreManager::PublicationMode::Published;+ case RustFFI::StorePublication::ShownInRemoteLayer:+ return BackingStoreManager::PublicationMode::ShownInRemoteLayer;}- if (pending_present.was_cancelled || exchange(pending_present.was_delivered, true))- return;+ VERIFY_NOT_REACHED();+}- auto context_id = pending_present.context_id;- auto* context = presented_context_if_present(context_id);- VERIFY(context);+RustFFI::StoreResizeOutcome CompositorState::resize_stores(Web::CompositorContextId context_id, RustFFI::FfiStoreResize const& resize)+{+ auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();+ auto publication_mode = publication_mode_of(resize.publication);+ auto window_resize_in_progress = resize.window_resize_in_progress ? Compositing::WindowResizingInProgress::Yes : Compositing::WindowResizingInProgress::No;+ auto allocation = backing_stores.resize_backing_stores_if_needed(resize.raster_size, window_resize_in_progress, publication_mode);+ if (!allocation.has_value())+ return RustFFI::StoreResizeOutcome::Unchanged;- if (pending_present.keeps_shown_store)- context->presenter.did_deliver_frame_without_store();- else- context->presenter.did_finish_gpu_present(pending_present.bitmap_id, pending_present.viewport_rect.size());- auto* presentation = pending_present.publish_to_presentation ? presentation_for_context(context_id) : nullptr;- if (pending_present.shows_in_remote_layer) {- log_presented_frame(context->page_id, pending_present.damage_rect);- show_frame_in_remote_layer(context_id, *context, pending_present);- } else if (context->presenter.presents_to_client() && !presentation) {- // Nobody shows the frame, so it is released here, on another turn, as a presentation would release it.- Core::deferred_invoke([self = NonnullRefPtr { *this }, context_id, bitmap_id = pending_present.bitmap_id] {- self->presented_bitmap_ready_to_paint(context_id, bitmap_id);- });- } else if (context->presenter.presents_to_client()) {- log_presented_frame(context->page_id, pending_present.damage_rect);- presentation->did_present_frame(context_id, pending_present.viewport_rect, pending_present.damage_rect, pending_present.bitmap_id, pending_present.device_pixel_ratio);+ RefPtr<WindowServer> window_server_showing_stores;+ if (publication_mode == BackingStoreManager::PublicationMode::ShownInRemoteLayer) {+ auto* remote_layer = remote_layer_showing(context_id);+ VERIFY(remote_layer);+ window_server_showing_stores = remote_layer->window_server;+ }+ auto gpu_sharing = resize.gpu_sharing_allowed ? BackingStoreManager::GpuSharing::Allowed : BackingStoreManager::GpuSharing::Disallowed;+ auto publication = backing_stores.allocate_backing_stores(*allocation, m_skia_backend_context, publication_mode, gpu_sharing, move(window_server_showing_stores));+ if (publication.is_error()) {+ dbgln("Compositor: Failed to allocate the stores of context {} that a remote layer shows, which its presentation shows again: {}", context_id, publication.error());+ return RustFFI::StoreResizeOutcome::Failed;}- resize_backing_stores_if_needed(context_id, *context);- if (auto parent_context_id = context->parent_context_id; parent_context_id.has_value()) {- auto* parent_context = presented_context_if_present(*parent_context_id);- VERIFY(parent_context);- present_current_frame(*parent_context_id, *parent_context);+ if (!publication.value().has_value())+ return RustFFI::StoreResizeOutcome::ReallocatedOffscreen;+ if (publication_mode == BackingStoreManager::PublicationMode::Published) {+ auto* presentation = resize.has_presentation ? presentation_if_present(PresentationId { resize.presentation_id }) : nullptr;+ VERIFY(presentation);+ auto stores = publication.release_value().release_value();+ presentation->did_allocate_backing_stores(context_id, move(stores.bitmap_ids), move(stores.shared_images));}+ return RustFFI::StoreResizeOutcome::ReallocatedForViewer;+}- schedule_pending_present_frame_if_unblocked(context_id, *context);+bool CompositorState::add_store_if_window_server_reads_every_released_store(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation)+{+ auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();+ auto publication = backing_stores.add_backing_store_if_window_server_still_reads_every_released_store(m_skia_backend_context);+ if (!publication.has_value())+ return false;+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} gained backing store {}, as the window server still reads every released one", context_id, publication->bitmap_ids);+ if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr)+ presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));+ return true;}-void CompositorState::cancel_pending_async_presents_for_context(Web::CompositorContextId context_id)+bool CompositorState::retire_idle_surplus_stores(Web::CompositorContextId context_id, Optional<PresentationId> publishing_presentation){- for (auto& pending_present : m_pending_async_presents) {- if (pending_present.context_id == context_id)- pending_present.was_cancelled = true;+ auto& backing_stores = presented_context(context_id).raster_targets.backing_stores();+ auto retired_bitmap_ids = backing_stores.retire_idle_surplus_backing_stores();+ if (auto* presentation = publishing_presentation.has_value() ? presentation_if_present(*publishing_presentation) : nullptr; presentation && !retired_bitmap_ids.is_empty()) {+ dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} retired idle backing stores {}", context_id, retired_bitmap_ids);+ presentation->did_retire_backing_stores(context_id, move(retired_bitmap_ids));}+ return backing_stores.has_surplus_backing_stores();}-void CompositorState::schedule_gpu_completion_check()+static bool video_frame_holds_high_dynamic_range(Media::VideoFrame const& frame){- if (!m_skia_backend_context)- return;- VERIFY(!m_pending_async_presents.is_empty());-- if (!m_gpu_completion_timer) {- m_gpu_completion_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(gpu_completion_check_interval_ms), [this] {- check_gpu_completions();- });- }- if (!m_gpu_completion_timer->is_active())- m_gpu_completion_timer->start();+ auto transfer_characteristics = frame.cicp().transfer_characteristics();+ return transfer_characteristics == Media::TransferCharacteristics::SMPTE2084 || transfer_characteristics == Media::TransferCharacteristics::HLG;}-void CompositorState::check_gpu_completions()+void CompositorState::report_live_content(Web::CompositorContextId context_id, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*)){- if (m_pending_async_presents.is_empty()) {- if (m_gpu_completion_timer)- m_gpu_completion_timer->stop();- return;- }+ auto& raster_targets = presented_context(context_id).raster_targets;+ auto const& resource_storage = raster_targets.resource_storage();- if (m_skia_backend_context)- m_skia_backend_context->check_async_work_completion();+ Vector<RustFFI::FfiCanvasContent> canvases;+ canvases.ensure_capacity(canvas_ids.size());+ for (auto id : canvas_ids) {+ Compositing::CanvasId canvas_id { id };+ canvases.unchecked_append({+ .id = id,+ .content_generation = raster_targets.canvas_surfaces().canvas_content_generation(canvas_id),+ .has_presentable_surface = raster_targets.canvas_surfaces().presentable_canvas_surface(canvas_id) != nullptr,+ });+ }+ Vector<RustFFI::FfiVideoSinkContent> video_sinks;+ video_sinks.ensure_capacity(resource_storage.video_sink_handles().size());+ for (auto const& [id, handle] : resource_storage.video_sink_handles()) {+ auto frame = raster_targets.current_video_frame(Compositing::VideoSinkResourceId { id });+ video_sinks.unchecked_append({+ .id = id,+ .has_frame = frame != nullptr,+ .frame_id = frame ? frame->id() : 0,+ .frame_holds_high_dynamic_range = frame && video_frame_holds_high_dynamic_range(*frame),+ .frame_has_surface = frame && frame->surface(),+ });+ }+ Vector<RustFFI::FfiImageFrameContent> image_frames;+ image_frames.ensure_capacity(resource_storage.image_frame_pixel_generations().size());+ for (auto const& [id, pixel_generation] : resource_storage.image_frame_pixel_generations())+ image_frames.unchecked_append({ .id = id, .pixel_generation = pixel_generation });- if (m_pending_async_presents.is_empty() && m_gpu_completion_timer)- m_gpu_completion_timer->stop();+ RustFFI::FfiLiveContent content {+ .canvases = canvases.span(),+ .video_sinks = video_sinks.span(),+ .image_frames = image_frames.span(),+ };+ receive(receiver, &content);}-CompositorState::PresentedContext* CompositorState::presented_context_if_present(Web::CompositorContextId context_id)+CompositorState::RemoteLayerState* CompositorState::remote_layer_showing(Web::CompositorContextId context_id){- auto it = m_presented_contexts.find(context_id);- if (it == m_presented_contexts.end())+ auto* context = presented_context_if_present(context_id);+ if (!context || !context->remote_layer_id.has_value())return nullptr;- return it->value.ptr();+ auto remote_layer = m_remote_layers.find(*context->remote_layer_id);+ if (remote_layer == m_remote_layers.end())+ return nullptr;+ return &remote_layer->value;}-CompositorState::PresentedContext const* CompositorState::presented_context_if_present(Web::CompositorContextId context_id) const+Optional<RemoteLayer::Content> CompositorState::remote_layer_content(PresentedContext& context, RustFFI::MediaKind kind, u64 media_id){- auto it = m_presented_contexts.find(context_id);- if (it == m_presented_contexts.end())- return nullptr;- return it->value.ptr();+ switch (kind) {+ case RustFFI::MediaKind::Canvas:+ if (auto surface = context.raster_targets.canvas_surfaces().presentable_canvas_surface(Compositing::CanvasId { media_id }))+ return RemoteLayer::Content { surface.release_nonnull() };+ return {};+ case RustFFI::MediaKind::Video:+ if (auto frame = context.raster_targets.current_video_frame(Compositing::VideoSinkResourceId { media_id }))+ return RemoteLayer::Content { frame.release_nonnull() };+ return {};+ }+ VERIFY_NOT_REACHED();}-void CompositorState::clear_parent_context(Web::CompositorContextId context_id, PresentedContext& context)+static Optional<RemoteSublayer::RoundedClip> rounded_clip_of(RustFFI::FfiSublayerPlacement const& placement){- auto parent_context_id = context.parent_context_id;- if (!parent_context_id.has_value())- return;+ if (!placement.has_rounded_clip)+ return {};+ return RemoteSublayer::RoundedClip {+ .rect = placement.rounded_clip_rect,+ .radius = placement.rounded_clip_radius,+ .rounds_top_left = placement.rounds_top_left,+ .rounds_top_right = placement.rounds_top_right,+ .rounds_bottom_right = placement.rounds_bottom_right,+ .rounds_bottom_left = placement.rounds_bottom_left,+ };+}- context.parent_context_id = {};- m_core.set_parent_context(context_id, {});- auto* parent_context = presented_context_if_present(*parent_context_id);- if (!parent_context)- return;- present_current_frame(*parent_context_id, *parent_context);+static Gfx::AffineTransform content_to_frame_of(RustFFI::FfiSublayerPlacement const& placement)+{+ auto const* transform = placement.content_to_frame;+ return { transform[0], transform[1], transform[2], transform[3], transform[4], transform[5] };}-CompositedContextResolver CompositorState::resolver_for(Web::CompositorContextId parent_context_id)+bool CompositorState::remote_layer_can_show(Web::CompositorContextId context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const& placement, double device_pixel_ratio){- return [this, parent_context_id](Web::CompositorContextId child_context_id, Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform) {- return resolve_composited_context(parent_context_id, child_context_id, destination_rect, canvas_transform);+ auto* remote_layer = remote_layer_showing(context_id);+ if (!remote_layer)+ return false;+ auto content = remote_layer_content(presented_context(context_id), kind, media_id);+ if (!content.has_value())+ return false;+ WindowServerPlacement window_server_placement {+ .content_rect = placement.content_rect,+ .content_to_viewport = content_to_frame_of(placement),+ .clip_rect = placement.clip_rect,+ .rounded_clip = rounded_clip_of(placement),+ .scaling_mode = placement.scaling_mode,};+ return remote_layer->layer->can_show(window_server_placement, *content, device_pixel_ratio);}-CompositedContextSurface CompositorState::resolve_composited_context(Web::CompositorContextId parent_context_id, Web::CompositorContextId child_context_id, Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform)+Vector<RemoteSublayer>* CompositorState::build_sublayers(Web::CompositorContextId context_id, ReadonlySpan<RustFFI::FfiSublayer> sublayers_to_build){- auto* child_context = presented_context_if_present(child_context_id);- if (!child_context)- return {};- auto child_parent_context_id = child_context->parent_context_id;- if (!child_parent_context_id.has_value() || *child_parent_context_id != parent_context_id)- return {};-- if (child_context->presenter.update_composited_raster_transform(destination_rect, canvas_transform)) {- auto publication = MUST(child_context->presenter.resize_backing_stores_if_needed(m_skia_backend_context, BackingStoreManager::GpuSharing::Disallowed, BackingStoreManager::PublicationMode::Unpublished));- VERIFY(!publication.has_value());- }-- if (child_context->presenter.needs_rasterization()) {- auto composited_context_resolver = resolver_for(child_context_id);- DisplayListPlayerSkia display_list_player { m_skia_backend_context };- child_context->presenter.present_synchronously(display_list_player, m_core.frame_inputs(child_context_id, MonotonicTime::now()), &composited_context_resolver);+ auto sublayers = make<Vector<RemoteSublayer>>();+ auto& raster_targets = presented_context(context_id).raster_targets;+ for (auto const& sublayer : sublayers_to_build) {+ Optional<Variant<NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease>> content;+ switch (sublayer.content_kind) {+ case RustFFI::SublayerContentKind::Canvas:+ if (auto surface = raster_targets.canvas_surfaces().presentable_canvas_surface(Compositing::CanvasId { sublayer.media_id }))+ content = surface->lease();+ break;+ case RustFFI::SublayerContentKind::Video:+ if (auto frame = raster_targets.current_video_frame(Compositing::VideoSinkResourceId { sublayer.media_id }); frame && frame->surface())+ content = frame.release_nonnull();+ break;+ case RustFFI::SublayerContentKind::PresentableSurface:+ content = static_cast<PresentableSurface*>(sublayer.presentable_surface)->lease();+ break;+ }+ if (!content.has_value())+ continue;+ auto const& placement = sublayer.placement;+ sublayers->append({+ .identity = sublayer.identity,+ .content = content.release_value(),+ .content_rect = placement.content_rect,+ .content_to_frame = content_to_frame_of(placement),+ .clip_rect = placement.clip_rect,+ .rounded_clip = rounded_clip_of(placement),+ .scaling_mode = placement.scaling_mode,+ });}+ return sublayers.leak_ptr();+}- return child_context->presenter.composited_surface();+WindowServer::FrameHandOff CompositorState::frame_hand_off(Web::CompositorContextId context_id)+{+ if (auto* remote_layer = remote_layer_showing(context_id))+ return remote_layer->window_server->frame_hand_off();+ return WindowServer::frame_hand_off_through_presentation();}-void CompositorState::resize_backing_stores_if_needed(Web::CompositorContextId context_id, PresentedContext& context)+u64 CompositorState::submit_frame(Gfx::PaintingSurface* surface){- auto publication_mode = BackingStoreManager::PublicationMode::Unpublished;- RemoteLayerState const* remote_layer_showing_context = nullptr;- if (context.remote_layer_id.has_value()) {- auto remote_layer = m_remote_layers.find(*context.remote_layer_id);- VERIFY(remote_layer != m_remote_layers.end());- remote_layer_showing_context = &remote_layer->value;- publication_mode = BackingStoreManager::PublicationMode::ShownInRemoteLayer;- } else if (presentation_for_context(context_id)) {- publication_mode = BackingStoreManager::PublicationMode::Published;- }+ auto token = m_next_gpu_work_token++;+ m_gpu_work_in_flight.set(token);+ auto& event_loop = Core::EventLoop::current();+ auto did_finish = [self = NonnullRefPtr { *this }, &event_loop, token] {+ event_loop.deferred_invoke([self, token] {+ self->gpu_work_finished(token);+ });+ };+ if (surface)+ DisplayListPlayerSkia::flush_async(*surface, move(did_finish));+ else if (m_skia_backend_context)+ m_skia_backend_context->flush_and_submit_async(move(did_finish));+ else+ did_finish();+ schedule_gpu_completion_check();+ return token;+}- // The window server reads what it shows above the store straight from GPU memory.- auto window_server_may_show_media = remote_layer_showing_context && m_skia_backend_context && !context.presents_from_cpu_memory;- context.presenter.set_remote_layer_that_may_show_media(window_server_may_show_media ? remote_layer_showing_context->layer.ptr() : nullptr);- auto window_server_showing_stores = remote_layer_showing_context ? RefPtr<WindowServer> { remote_layer_showing_context->window_server } : nullptr;- auto publication = context.presenter.resize_backing_stores_if_needed(m_skia_backend_context, gpu_sharing_for_context(context_id), publication_mode, move(window_server_showing_stores));- if (publication.is_error()) {- VERIFY(context.remote_layer_id.has_value());- dbgln("Compositor: Failed to allocate the stores of context {} that remote layer {} shows, which its presentation shows again: {}", context_id, *context.remote_layer_id, publication.error());- show_context_in_remote_layer(*context.remote_layer_id, {});- return;- }- if (publication.value().has_value()) {- if (publication_mode == BackingStoreManager::PublicationMode::Published)- publish_backing_stores(context_id, context, publication.release_value().release_value());- present_current_frame(context_id, context);- }+void CompositorState::gpu_work_finished(u64 token)+{+ m_gpu_work_in_flight.remove(token);+ if (m_gpu_work_in_flight.is_empty() && m_gpu_completion_timer)+ m_gpu_completion_timer->stop();+ m_core.gpu_work_finished(token);}-BackingStoreManager::GpuSharing CompositorState::gpu_sharing_for_context(Web::CompositorContextId context_id) const+void CompositorState::hand_off_once_gpu_work_is_scheduled([[maybe_unused]] u64 token){- if (auto const* context = presented_context_if_present(context_id); context && context->presents_from_cpu_memory)- return BackingStoreManager::GpuSharing::Disallowed;-#ifdef USE_DIRECTX- // Shared Direct3D textures can only be opened by the presentation if it presents on the same adapter.- auto* presentation = presentation_for_context(context_id);- if (!presentation || !m_skia_backend_context || m_presentations.get(presentation)->gpu_presentation_adapter_luid != m_skia_backend_context->direct3d_context().adapter_luid())- return BackingStoreManager::GpuSharing::Disallowed;+#if defined(AK_OS_MACOS) || (defined(AK_OS_WINDOWS) && defined(USE_DIRECTX))+ auto& event_loop = Core::EventLoop::current();+ auto deliver = [self = NonnullRefPtr { *this }, &event_loop, token] {+ event_loop.deferred_invoke([self, token] {+ self->m_core.frame_ready_for_hand_off(token);+ });+ };+#endif+#ifdef AK_OS_MACOS+ // The window server's reads of an IOSurface wait for GPU work that is already scheduled to write it.+ m_skia_backend_context->metal_context().when_committed_work_is_scheduled(move(deliver));+#elif defined(AK_OS_WINDOWS) && defined(USE_DIRECTX)+ deliver();#else- if (auto* presentation = presentation_for_context(context_id); presentation && m_presentations.get(presentation)->cannot_present_gpu_images)- return BackingStoreManager::GpuSharing::Disallowed;+ VERIFY_NOT_REACHED();#endif- return BackingStoreManager::GpuSharing::Allowed;}-// A context scrolls elastically, takes presses on scrollbar tracks, and ends touchpad gestures as the presentation of-// its root context does. A platform that reports the momentum of a flick reports when the fingers lift for it.-void CompositorState::update_scroll_capabilities()+Optional<PresentationId> CompositorState::show_frame_in_remote_layer(Web::CompositorContextId context_id, RustFFI::FfiRemoteLayerFrame const& frame, NonnullOwnPtr<Vector<RemoteSublayer>> sublayers){- for (auto& [context_id, context] : m_presented_contexts) {- CompositorCore::ScrollCapabilities capabilities {};- if (auto* presentation = presentation_for_context(root_context_id_of(context_id))) {- auto const& presentation_capabilities = *m_presentations.get(presentation);- capabilities.synthesizes_scroll_momentum = presentation_capabilities.synthesizes_scroll_momentum;- capabilities.scrolls_elastically = presentation_capabilities.scrolls_elastically;- capabilities.scrollbar_track_press_jumps = presentation_capabilities.scrollbar_track_press_jumps;- capabilities.touchpad_gestures_end_when_fingers_lift = !presentation_capabilities.synthesizes_scroll_momentum;- }- m_core.set_scroll_capabilities(context_id, capabilities);- }-}+ auto* remote_layer = remote_layer_showing(context_id);+ if (!remote_layer)+ return {};+ auto& context = presented_context(context_id);+ auto* store = frame.uses_store ? context.raster_targets.backing_stores().window_server_surface_of_latest_rendered_store() : nullptr;+ VERIFY(store || !frame.uses_store);-void CompositorState::set_scrollbar_track_press_jumps(CompositorStateClient& presentation, bool jumps)-{- m_presentations.get(&presentation)->scrollbar_track_press_jumps = jumps;- update_scroll_capabilities();+ auto remote_layer_id = *context.remote_layer_id;+ auto shown = remote_layer->layer->show_frame({+ .store = store ? Optional<PresentableSurface::Lease> { store->lease() } : OptionalNone {},+ .painted_size = frame.painted_size,+ .device_pixel_ratio = frame.device_pixel_ratio,+ .fit_within = remote_layer->fit_within,+ .sublayers = move(*sublayers),+ });+ if (!shown) {+ dbgln("Compositor: Remote layer {} failed to show a frame of context {}, which its presentation shows again", remote_layer_id, context_id);+ stop_showing_in_remote_layer(context_id);+ return {};+ }+ remote_layer->size_of_shown_frame_laid_out_by_page = frame.laid_out_by_page ? Optional<Gfx::IntSize> { frame.painted_size } : OptionalNone {};+ report_held_synchronized_resize_frames(remote_layer_id);+ return remote_layer->presentation->presentation_id();}-void CompositorState::set_client_gpu_presentation_capability(CompositorStateClient& presentation, bool supported, u64 adapter_luid)+void CompositorState::stop_showing_in_remote_layer(Web::CompositorContextId context_id){- Optional<u64> new_adapter_luid;- if (supported)- new_adapter_luid = adapter_luid;- auto& capabilities = *m_presentations.get(&presentation);- if (capabilities.gpu_presentation_adapter_luid == new_adapter_luid && capabilities.cannot_present_gpu_images == !supported)+ auto& context = presented_context(context_id);+ auto remote_layer_id = exchange(context.remote_layer_id, {});+ if (!remote_layer_id.has_value())return;- capabilities.gpu_presentation_adapter_luid = new_adapter_luid;- capabilities.cannot_present_gpu_images = !supported;-- // Reallocate the backing stores of the presentation's contexts so they match the new capability.- for (auto& context_entry : m_presented_contexts) {- auto& context = *context_entry.value;- if (presentation_for_context(context_entry.key) != &presentation)- continue;- context.presenter.invalidate_backing_stores();- resize_backing_stores_if_needed(context_entry.key, context);+ if (auto remote_layer = m_remote_layers.find(*remote_layer_id); remote_layer != m_remote_layers.end()) {+ remote_layer->value.shown_context_id = {};+ remote_layer->value.size_of_shown_frame_laid_out_by_page = {};}}-void CompositorState::schedule_backing_store_shrink(Web::CompositorContextId context_id, PresentedContext& context)+void CompositorState::release_store_later(Web::CompositorContextId context_id, i32 bitmap_id){- context.presenter.schedule_backing_store_shrink([this, context_id] {- shrink_backing_stores_after_resize(context_id);+ Core::deferred_invoke([self = NonnullRefPtr { *this }, context_id, bitmap_id] {+ self->presented_bitmap_ready_to_paint(context_id, bitmap_id);});}-void CompositorState::shrink_backing_stores_after_resize(Web::CompositorContextId context_id)+static void log_presented_frame(u64 page_id, Gfx::IntRect damage){- auto* context = presented_context_if_present(context_id);- if (!context)+ auto* log = Core::StatsLog::the();+ if (!log)return;-- context->presenter.finish_window_resize();- resize_backing_stores_if_needed(context_id, *context);+ JsonObject data;+ data.set("page_id"sv, page_id);+ data.set("changed"sv, !damage.is_empty());+ data.set("damage_x"sv, damage.x());+ data.set("damage_y"sv, damage.y());+ data.set("damage_width"sv, damage.width());+ data.set("damage_height"sv, damage.height());+ log->event("frame"sv, move(data));}-void CompositorState::add_backing_store_for_pending_frame_if_needed(Web::CompositorContextId context_id, PresentedContext& context)+void CompositorState::schedule_gpu_completion_check(){- auto* presentation = presentation_for_context(context_id);- if (!presentation && !context.remote_layer_id.has_value())+ if (!m_skia_backend_context || m_gpu_work_in_flight.is_empty())return;- auto publication = context.presenter.add_backing_store_for_pending_frame_if_needed(m_skia_backend_context);- if (!publication.has_value())+ if (!m_gpu_completion_timer) {+ m_gpu_completion_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(gpu_completion_check_interval_ms), [this] {+ check_gpu_completions();+ });+ }+ if (!m_gpu_completion_timer->is_active())+ m_gpu_completion_timer->start();+}++void CompositorState::check_gpu_completions()+{+ if (m_gpu_work_in_flight.is_empty()) {+ if (m_gpu_completion_timer)+ m_gpu_completion_timer->stop();return;+ }- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} gained backing store {}, as the window server still reads every released one", context_id, publication->bitmap_ids);- if (presentation && context.presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::Published)- presentation->did_add_backing_stores(context_id, move(publication->bitmap_ids), move(publication->shared_images));- schedule_surplus_backing_store_retirement(context_id, context);+ if (m_skia_backend_context)+ m_skia_backend_context->check_async_work_completion();++ if (m_gpu_work_in_flight.is_empty() && m_gpu_completion_timer)+ m_gpu_completion_timer->stop();}-void CompositorState::schedule_surplus_backing_store_retirement(Web::CompositorContextId context_id, PresentedContext& context)+VSyncScheduler& CompositorState::vsync_scheduler_for_display(Optional<u64> display_id){- context.presenter.schedule_surplus_backing_store_retirement([this, context_id] {- retire_idle_surplus_backing_stores(context_id);+ return *m_vsync_schedulers_by_display.ensure(display_id, [this, display_id] {+ return create_vsync_scheduler(display_id, [this, display_id](MonotonicTime frame_time) {+ m_core.vsync(display_id, frame_time);+ });});}-void CompositorState::retire_idle_surplus_backing_stores(Web::CompositorContextId context_id)+static CompositorState& state_of(void* host){- auto* context = presented_context_if_present(context_id);- if (!context)- return;+ return *static_cast<CompositorState*>(host);+}- auto retired_bitmap_ids = context->presenter.retire_idle_surplus_backing_stores();- auto shows_stores_to_presentation = context->presenter.backing_store_publication_mode() == BackingStoreManager::PublicationMode::Published;- if (auto* presentation = presentation_for_context(context_id); presentation && shows_stores_to_presentation && !retired_bitmap_ids.is_empty()) {- dbgln_if(COMPOSITOR_DEBUG, "[Compositor] Context {} retired idle backing stores {}", context_id, retired_bitmap_ids);- presentation->did_retire_backing_stores(context_id, move(retired_bitmap_ids));- }- if (context->presenter.has_surplus_backing_stores())- schedule_surplus_backing_store_retirement(context_id, *context);+static Gfx::PaintingSurface& painting_surface_of(void* surface)+{+ return *static_cast<Gfx::PaintingSurface*>(surface);}-void CompositorState::present_current_frame(Web::CompositorContextId context_id, PresentedContext& context)+static SkCanvas& canvas_of(void* surface){- if (auto frame_to_present = context.presenter.frame_rect_to_repaint(); frame_to_present.has_value())- schedule_present_frame(context_id, context, *frame_to_present);+ return painting_surface_of(surface).canvas();}-void CompositorState::publish_backing_stores(Web::CompositorContextId context_id, PresentedContext& context, BackingStoreManager::Publication&& publication)+static Optional<u64> display_of(bool has_display_id, u64 display_id){- auto* presentation = presentation_for_context(context_id);- VERIFY(presentation);- VERIFY(context.presenter.presents_to_client());+ if (!has_display_id)+ return {};+ return display_id;+}- presentation->did_allocate_backing_stores(context_id, move(publication.bitmap_ids), move(publication.shared_images));+static Optional<PresentationId> presentation_of(bool has_presentation, u64 presentation_id)+{+ if (!has_presentation)+ return {};+ return PresentationId { presentation_id };+}++static MonotonicTime time_of(i64 nanoseconds)+{+ return MonotonicTime {} + AK::Duration::from_nanoseconds(nanoseconds);+}++RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)+{+ using Context = Web::CompositorContextId;+ return {+ .host = &state,+ .surface_retain = [](void* surface) { painting_surface_of(surface).ref(); },+ .surface_release = [](void* surface) { painting_surface_of(surface).unref(); },+ .surface_size = [](void* surface, Gfx::IntSize* size) { *size = painting_surface_of(surface).size(); },+ .create_surface = [](void* host, Gfx::IntSize size, void* like) -> void* {+ auto skia_backend_context = like ? painting_surface_of(like).skia_backend_context() : state_of(host).m_skia_backend_context;+ auto surface = Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context);+ if (surface.is_error())+ return nullptr;+ return &surface.release_value().leak_ref();+ },+ .surfaces_share_backend = [](void* a, void* b) { return painting_surface_of(a).skia_backend_context() == painting_surface_of(b).skia_backend_context(); },+ .surface_uses_gpu = [](void* surface) { return painting_surface_of(surface).skia_backend_context() != nullptr; },+ .surface_save = [](void* surface) { return canvas_of(surface).save(); },+ .surface_restore_to_count = [](void* surface, i32 count) { canvas_of(surface).restoreToCount(count); },+ .surface_translate = [](void* surface, float x, float y) { canvas_of(surface).translate(x, y); },+ .surface_scale = [](void* surface, float x, float y) { canvas_of(surface).scale(x, y); },+ .surface_clip_rect = [](void* surface, Gfx::IntRect rect) { canvas_of(surface).clipIRect(SkIRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height())); },+ .surface_clear = [](void* surface, Gfx::Color color) { canvas_of(surface).clear(Gfx::to_skia_color(color)); },+ .surface_draw_surface = [](void* target, void* source, Gfx::IntRect source_rect, Gfx::IntRect target_rect, RustFFI::SurfaceBlend blend) {+ auto image = painting_surface_of(source).sk_image_snapshot<sk_sp<SkImage>>();+ SkPaint paint;+ paint.setBlendMode(blend == RustFFI::SurfaceBlend::Source ? SkBlendMode::kSrc : SkBlendMode::kSrcOver);+ canvas_of(target).drawImageRect(image.get(), Gfx::to_skia_rect(source_rect), Gfx::to_skia_rect(target_rect), SkSamplingOptions {}, &paint, SkCanvas::kStrict_SrcRectConstraint); },+ .flush_surface = [](void*, void* surface) { DisplayListPlayerSkia::flush(painting_surface_of(surface)); },+ .begin_painting = [](void* host, u64 context_id, void* surface, RustFFI::PaintingResources resources, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, painting_surface_of(surface), resources); },+ .end_painting = [](void* host) { state_of(host).end_painting(); },+ .start_raster_cache_frame = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.raster_cache().drop_what_was_not_used_since_last_frame(); },+ .store_state = [](void* host, u64 context_id) -> RustFFI::FfiStoreState {+ auto const& backing_stores = state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores();+ return { .is_valid = backing_stores.is_valid(), .is_rendering = backing_stores.is_rendering(), .has_available_store = backing_stores.has_available_buffer() };+ },+ .resize_stores = [](void* host, u64 context_id, RustFFI::FfiStoreResize const* resize) { return state_of(host).resize_stores(Context { context_id }, *resize); },+ .invalidate_stores = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().invalidate(); },+ .acquire_store = [](void* host, u64 context_id, RustFFI::FfiAcquiredStore* acquired) {+ auto render_target = state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().acquire_render_target();+ if (!render_target.has_value())+ return false;+ acquired->bitmap_id = render_target->bitmap_id;+ acquired->surface = &render_target->surface;+ return true; },+ .complete_rendering = [](void* host, u64 context_id, i32 bitmap_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().complete_rendering(bitmap_id); },+ .release_store = [](void* host, u64 context_id, i32 bitmap_id) { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_buffer(bitmap_id); },+ .release_all_presented_stores = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().release_all_presented_buffers(); },+ .latest_rendered_store_surface = [](void* host, u64 context_id) -> void* { return state_of(host).presented_context(Context { context_id }).raster_targets.backing_stores().latest_rendered_surface().ptr(); },+ .add_store_if_window_server_reads_every_released_store = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).add_store_if_window_server_reads_every_released_store(Context { context_id }, presentation_of(has_presentation, presentation_id)); },+ .retire_idle_surplus_stores = [](void* host, u64 context_id, bool has_presentation, u64 presentation_id) { return state_of(host).retire_idle_surplus_stores(Context { context_id }, presentation_of(has_presentation, presentation_id)); },+ .next_presentable_surface = [](void* host, u64 context_id, u32 pool, Gfx::IntSize size, void* like) -> void* {+ auto& state = state_of(host);+ auto skia_backend_context = like ? painting_surface_of(like).skia_backend_context() : state.m_skia_backend_context;+ auto surface = state.presented_context(Context { context_id }).raster_targets.next_presentable_surface(pool, size, skia_backend_context);+ if (!surface)+ return nullptr;+ return surface.leak_ref();+ },+ .drop_presentable_surface_pool = [](void* host, u64 context_id, u32 pool) { state_of(host).presented_context(Context { context_id }).raster_targets.drop_presentable_surface_pool(pool); },+ .presentable_surface_retain = [](void* surface) { static_cast<PresentableSurface*>(surface)->ref(); },+ .presentable_surface_release = [](void* surface) { static_cast<PresentableSurface*>(surface)->unref(); },+ .presentable_surface_painting_surface = [](void* surface) -> void* { return &static_cast<PresentableSurface*>(surface)->painting_surface(); },+ .live_content = [](void* host, u64 context_id, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*)) { state_of(host).report_live_content(Context { context_id }, canvas_ids, receiver, receive); },+ .remote_layer_can_show = [](void* host, u64 context_id, RustFFI::MediaKind kind, u64 media_id, RustFFI::FfiSublayerPlacement const* placement, double device_pixel_ratio) { return state_of(host).remote_layer_can_show(Context { context_id }, kind, media_id, *placement, device_pixel_ratio); },+ .remote_layer_can_show_high_dynamic_range = [](void* host, u64 context_id) {+ auto* remote_layer = state_of(host).remote_layer_showing(Context { context_id });+ return remote_layer && remote_layer->layer->can_show_high_dynamic_range(); },+ .build_sublayers = [](void* host, u64 context_id, ReadonlySpan<RustFFI::FfiSublayer> sublayers) -> void* {+ return state_of(host).build_sublayers(Context { context_id }, sublayers);+ },+ .destroy_sublayers = [](void* sublayers) { delete static_cast<Vector<RemoteSublayer>*>(sublayers); },+ .frame_hand_off = [](void* host, u64 context_id) { return state_of(host).frame_hand_off(Context { context_id }) == WindowServer::FrameHandOff::OnceGpuWorkIsScheduled+ ? RustFFI::FrameHandOff::OnceGpuWorkIsScheduled+ : RustFFI::FrameHandOff::OnceGpuWorkIsFinished; },+ .submit_frame = [](void* host, u64, void* surface) { return state_of(host).submit_frame(static_cast<Gfx::PaintingSurface*>(surface)); },+ .hand_off_once_gpu_work_is_scheduled = [](void* host, u64 token) { state_of(host).hand_off_once_gpu_work_is_scheduled(token); },+ .show_frame_in_remote_layer = [](void* host, u64 context_id, RustFFI::FfiRemoteLayerFrame const* frame, void* sublayers, u64* presentation_id) {+ auto shown_in = state_of(host).show_frame_in_remote_layer(Context { context_id }, *frame, adopt_own(*static_cast<Vector<RemoteSublayer>*>(sublayers)));+ if (!shown_in.has_value())+ return false;+ *presentation_id = shown_in->value();+ return true; },+ .stop_showing_in_remote_layer = [](void* host, u64 context_id) { state_of(host).stop_showing_in_remote_layer(Context { context_id }); },+ .log_presented_frame = [](void*, u64 page_id, Gfx::IntRect damage_rect) { log_presented_frame(page_id, damage_rect); },+ .release_store_later = [](void* host, u64 context_id, i32 bitmap_id) { state_of(host).release_store_later(Context { context_id }, bitmap_id); },+ .request_vsync = [](void* host, bool has_display_id, u64 display_id, double refresh_rate) { state_of(host).vsync_scheduler_for_display(display_of(has_display_id, display_id)).schedule(refresh_rate); },+ .most_recent_tick_time = [](void* host, bool has_display_id, u64 display_id, i64 now_nanoseconds, double refresh_rate, i64* tick_time_nanoseconds) {+ auto tick_time = state_of(host).vsync_scheduler_for_display(display_of(has_display_id, display_id)).most_recent_tick_time(time_of(now_nanoseconds), refresh_rate);+ if (!tick_time.has_value())+ return false;+ *tick_time_nanoseconds = tick_time->nanoseconds();+ return true; },+ .update_video_sinks = [](void* host, void* receiver, void (*receive)(void*, ReadonlySpan<u64>)) {+ auto& state = state_of(host);+ Vector<u64> contexts_with_new_video_frames;+ {+ TemporaryChange collecting { state.m_contexts_with_new_video_frames, &contexts_with_new_video_frames };+ (void)state.update_all_video_sinks();+ }+ receive(receiver, contexts_with_new_video_frames.span()); },+ .context_video_sinks_require_updates = [](void* host, u64 context_id) { return state_of(host).context_video_sinks_require_updates(Context { context_id }); },+ .set_maximum_display_refresh_rate = [](void* host, double refresh_rate) { state_of(host).set_maximum_display_refresh_rate(refresh_rate); },+ };}}diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex 954790dc3ea..032cbf59db8 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -6,9 +6,8 @@#pragma once-#include <AK/Array.h>-#include <AK/DoublyLinkedList.h>#include <AK/HashMap.h>+#include <AK/HashTable.h>#include <AK/NonnullRefPtr.h>#include <AK/Optional.h>#include <AK/OwnPtr.h>@@ -16,9 +15,9 @@#include <Compositor/AnimatedImage.h>#include <Compositor/CanvasSurfaceRegistry.h>#include <Compositor/CompositorCore.h>-#include <Compositor/ContextPresenter.h>+#include <Compositor/ContextRasterTargets.h>#include <Compositor/DisplayListPlayerSkia.h>-#include <Compositor/FramePacer.h>+#include <Compositor/RemoteLayer.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/VSyncScheduler.h>#include <Compositor/WindowServer.h>@@ -50,9 +49,6 @@ public:// The stores join the ones allocated last, and leave them again once retired.virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) = 0;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) = 0;- virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) = 0;- // The frame is on screen already, in the remote layer that shows the context.- virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) = 0;virtual void did_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) = 0;virtual void did_commit_synchronized_resize(u64 remote_layer_id, u64 token) = 0;};@@ -64,7 +60,6 @@ public:virtual WebContentClientId web_content_client_id() const = 0;virtual void post_message_to_web_content(IPC::MessageBuffer&) = 0;virtual void post_message_to_render_clock(IPC::MessageBuffer&) = 0;- virtual void rendering_opportunity(Web::CompositorContextId, i64 frame_time_nanoseconds, double frame_interval_milliseconds) = 0;virtual void create_video_edge(Media::VideoSinkHandle) = 0;virtual void release_video_edge(Media::VideoSinkHandle) = 0;virtual void video_sink_presented_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>, Media::DisplayingVideoSinkFrameCounts) { }@@ -202,13 +197,12 @@ private:virtual void post_message_to_web_content(WebContentClientId, IPC::MessageBuffer&) override;virtual void post_message_to_render_clock_of_web_content(WebContentClientId, IPC::MessageBuffer&) override;virtual void post_message_to_presentation(PresentationId, IPC::MessageBuffer&) override;- virtual void request_display_ticks(Web::CompositorContextId) override;virtual void set_timer(Web::CompositorContextId, ContextTimer, AK::Duration delay) override;virtual void cancel_timer(Web::CompositorContextId, ContextTimer) override;virtual Optional<OverlayLabel> shape_overlay_label(Web::CompositorContextId, Optional<StringView> font_family, double device_pixel_ratio, StringView text) override;void context_timer_fired(Web::CompositorContextId, ContextTimer);- // What the compositor keeps of a context to present it.+ // What the compositor keeps of a context to paint and present its frames.struct PresentedContext {AK_MAKE_NONCOPYABLE(PresentedContext);AK_MAKE_NONMOVABLE(PresentedContext);@@ -216,112 +210,54 @@ private:public:AK_ALLOC_WITH_KMALLOC;- PresentedContext(Optional<u64> page_id, CompositorStateWebContentClient&, OwnedCanvasSurfaces);+ PresentedContext(CompositorStateWebContentClient&, OwnedCanvasSurfaces);- Optional<u64> page_id;CompositorStateWebContentClient& web_content_client;- ContextPresenter presenter;- Optional<Web::CompositorContextId> parent_context_id;- Compositing::ContextVisibility visibility { Compositing::ContextVisibility::Visible };- Optional<u64> display_id;- double display_refresh_rate { 60.0 };- // Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.- bool presents_from_cpu_memory { false };+ ContextRasterTargets raster_targets;Optional<u64> remote_layer_id;- // The viewport size of the frame that the page presented last, which it laid out at.- Gfx::IntSize size_laid_out_by_page;- PacedTickRequest rendering_opportunity_request;- PacedTickRequest clock_tick_request;};- struct PendingAsyncPresent {- PendingAsyncPresent(Web::CompositorContextId context_id, Gfx::IntRect viewport_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio)- : context_id(context_id)- , viewport_rect(viewport_rect)- , damage_rect(damage_rect)- , bitmap_id(bitmap_id)- , device_pixel_ratio(device_pixel_ratio)- {- }-- Web::CompositorContextId context_id;- Gfx::IntRect viewport_rect;- Gfx::IntRect damage_rect;- i32 bitmap_id { 0 };- double device_pixel_ratio { 1.0 };- bool was_cancelled { false };- bool was_delivered { false };- // A frame that started rendering before its context was bound has no published buffer to present to.- bool publish_to_presentation { true };- bool shows_in_remote_layer { false };- // A frame that changes only what the window server shows above the frame on screen.- bool keeps_shown_store { false };- Vector<RemoteSublayer> sublayers;- };--public:- void present_pending_frames_for_testing() { present_pending_frames_on_vsync({}, MonotonicTime::now()); }- size_t pending_async_present_count_for_testing() const { return m_pending_async_presents.size(); }--private:PresentedContext* presented_context_if_present(Web::CompositorContextId);PresentedContext const* presented_context_if_present(Web::CompositorContextId) const;- Optional<u64> display_id_for_context(PresentedContext const&) const;- PresentedContext const* root_context_of(PresentedContext const&) const;- Web::CompositorContextId root_context_id_of(Web::CompositorContextId) const;- bool context_is_effectively_visible(PresentedContext const&) const;- void resume_presentation_after_becoming_visible(Web::CompositorContextId root_context_id, PresentedContext& root_context);- double display_refresh_rate_for_context(PresentedContext const&) const;- void clear_parent_context(Web::CompositorContextId, PresentedContext&);- CompositedContextResolver resolver_for(Web::CompositorContextId parent_context_id);- CompositedContextSurface resolve_composited_context(Web::CompositorContextId parent_context_id, Web::CompositorContextId child_context_id, Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform);- void schedule_backing_store_shrink(Web::CompositorContextId, PresentedContext&);- void shrink_backing_stores_after_resize(Web::CompositorContextId);- void resize_backing_stores_if_needed(Web::CompositorContextId, PresentedContext&);- void add_backing_store_for_pending_frame_if_needed(Web::CompositorContextId, PresentedContext&);- void schedule_surplus_backing_store_retirement(Web::CompositorContextId, PresentedContext&);- void retire_idle_surplus_backing_stores(Web::CompositorContextId);- void present_current_frame(Web::CompositorContextId, PresentedContext&);- void resolve_video_sinks(PresentedContext&);+ PresentedContext& presented_context(Web::CompositorContextId);+ CompositorStateClient* presentation_if_present(PresentationId) const;++ // The entry points of the raster host, which the logic in Rust paints and presents through. None of them calls back+ // into that logic.+ static RustFFI::FfiRasterHost raster_host(CompositorState&);+ static RustFFI::GpuBackend gpu_backend(RefPtr<Gfx::SkiaBackendContext> const&);+ Compositing::RustFFI::FfiRasterPainter begin_painting(Web::CompositorContextId, Gfx::PaintingSurface&, RustFFI::PaintingResources);+ void end_painting();+ RustFFI::StoreResizeOutcome resize_stores(Web::CompositorContextId, RustFFI::FfiStoreResize const&);+ bool add_store_if_window_server_reads_every_released_store(Web::CompositorContextId, Optional<PresentationId>);+ bool retire_idle_surplus_stores(Web::CompositorContextId, Optional<PresentationId>);+ void report_live_content(Web::CompositorContextId, ReadonlySpan<u64> canvas_ids, void* receiver, void (*receive)(void*, RustFFI::FfiLiveContent const*));+ Optional<RemoteLayer::Content> remote_layer_content(PresentedContext&, RustFFI::MediaKind, u64 media_id);+ bool remote_layer_can_show(Web::CompositorContextId, RustFFI::MediaKind, u64 media_id, RustFFI::FfiSublayerPlacement const&, double device_pixel_ratio);+ Vector<RemoteSublayer>* build_sublayers(Web::CompositorContextId, ReadonlySpan<RustFFI::FfiSublayer>);+ WindowServer::FrameHandOff frame_hand_off(Web::CompositorContextId);+ u64 submit_frame(Gfx::PaintingSurface*);+ void hand_off_once_gpu_work_is_scheduled(u64 token);+ Optional<PresentationId> show_frame_in_remote_layer(Web::CompositorContextId, RustFFI::FfiRemoteLayerFrame const&, NonnullOwnPtr<Vector<RemoteSublayer>>);+ void stop_showing_in_remote_layer(Web::CompositorContextId);+ void release_store_later(Web::CompositorContextId, i32 bitmap_id);+ void gpu_work_finished(u64 token);+ void schedule_gpu_completion_check();+ void check_gpu_completions();++ VSyncScheduler& vsync_scheduler_for_display(Optional<u64> display_id);+ void set_maximum_display_refresh_rate(double);+ void present_contexts_drawing_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);enum class VideoSinkUpdateResult : u8 {NoUnpaintedSinkRequiresUpdates,UnpaintedSinkRequiresUpdates,};VideoSinkUpdateResult update_all_video_sinks();- void update_video_sinks_for_display(Optional<u64> display_id);+ bool context_video_sinks_require_updates(Web::CompositorContextId);+ void resolve_video_sinks(PresentedContext&);void update_unpainted_video_sinks();void schedule_unpainted_video_updates();int unpainted_video_update_interval_ms() const;- void present_contexts_drawing_video_sink(CompositorStateWebContentClient&, Media::VideoSinkHandle);- void present_contexts_drawing_canvas(CompositorStateWebContentClient&, Compositing::CanvasId);- bool needs_animation_frames(Web::CompositorContextId, PresentedContext const&, MonotonicTime now);- static bool has_pending_present_frame_scheduled_on(PresentedContext const&, Optional<u64> display_id);- void schedule_animation_frames_if_needed(Web::CompositorContextId, PresentedContext const&);- void present_frame(Web::CompositorContextId, PresentedContext&, PendingFrame);- void schedule_requested_presents();- void schedule_present_frame(Web::CompositorContextId, PresentedContext&, PendingFrame);- void schedule_present_frame(Web::CompositorContextId, PresentedContext&, Gfx::IntRect viewport_rect);- void schedule_pending_present_frame(Web::CompositorContextId, PresentedContext&);- void schedule_pending_present_frame_on_vsync(Web::CompositorContextId, PresentedContext&);- void schedule_containing_context_present(PresentedContext&);- void schedule_pending_present_frame_if_unblocked(Web::CompositorContextId, PresentedContext&);- bool try_present_frame_during_resize(Web::CompositorContextId, PresentedContext&);- VSyncScheduler& vsync_scheduler_for_display(Optional<u64> display_id);- void present_pending_frames_on_vsync(Optional<u64> display_id, MonotonicTime frame_time);- void publish_backing_stores(Web::CompositorContextId, PresentedContext&, BackingStoreManager::Publication&&);- BackingStoreManager::GpuSharing gpu_sharing_for_context(Web::CompositorContextId) const;- void unbind_presentation(Web::CompositorContextId);- void stop_showing_context_in_remote_layer(Web::CompositorContextId, PresentedContext&);- void stop_delivering_in_flight_frames_to_their_viewer(Web::CompositorContextId);- WindowServer::FrameHandOff frame_hand_off_for(PresentedContext const&) const;- void hand_off_frame_once_gpu_work_is_scheduled(PendingAsyncPresent&);- void show_frame_in_remote_layer(Web::CompositorContextId, PresentedContext&, PendingAsyncPresent&);- void update_scroll_capabilities();- void did_finish_async_present(PendingAsyncPresent&);- void deliver_rendered_frame(PendingAsyncPresent&);- void cancel_pending_async_presents_for_context(Web::CompositorContextId);- void schedule_gpu_completion_check();- void check_gpu_completions();HashMap<Web::CompositorContextId, NonnullOwnPtr<PresentedContext>> m_presented_contexts;@@ -340,17 +276,21 @@ private:HashMap<WebContentClientId, CompositorStateWebContentClient*> m_web_content_clients;HashMap<Web::CompositorContextId, HashMap<ContextTimer, NonnullRefPtr<Core::Timer>>> m_context_timers;- DoublyLinkedList<PendingAsyncPresent> m_pending_async_presents;RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;CanvasSurfaceRegistry m_canvas_surface_registry;- OwnPtr<DisplayListPlayerSkia> m_display_list_player;+ // A context nested in another is painted while the frame of the other is, by a player of its own.+ Vector<NonnullOwnPtr<DisplayListPlayerSkia>> m_display_list_players;+ size_t m_painting_depth { 0 };HashMap<Optional<u64>, OwnPtr<VSyncScheduler>> m_vsync_schedulers_by_display;+ double m_maximum_display_refresh_rate { 60.0 };+ HashTable<u64> m_gpu_work_in_flight;+ u64 m_next_gpu_work_token { 1 };RefPtr<Core::Timer> m_gpu_completion_timer;+ // The contexts that draw a video sink with a new frame, while the video sinks are updated for a display tick.+ Vector<u64>* m_contexts_with_new_video_frames { nullptr };- HashMap<CompositorStateClient*, PresentationCapabilities> m_presentations;u64 m_next_presentation_id { 1 };HashMap<PresentationId, CompositorStateClient*> m_presentations_by_id;- HashMap<Web::CompositorContextId, CompositorStateClient*> m_context_presentations;HashMap<CompositorStateClient*, NonnullRefPtr<WindowServer>> m_window_servers;@@ -370,11 +310,11 @@ private:Optional<Gfx::IntSize> awaited_size;bool frame_is_held { false };};+ RemoteLayerState* remote_layer_showing(Web::CompositorContextId);void report_held_synchronized_resize_frames(u64 remote_layer_id);void release_synchronized_resize_hold();Vector<SynchronizedResize> m_synchronized_resizes;Vector<NonnullRefPtr<WindowServer>> m_window_servers_holding_changes;- bool m_window_server_may_show_high_dynamic_range { true };RefPtr<Core::Timer> m_synchronized_resize_hold_timeout;HashMap<u64, RemoteLayerState> m_remote_layers;diff --git a/Services/Compositor/CompositorWebContentClient.ipc b/Services/Compositor/CompositorWebContentClient.ipcindex d6efda1c6bb..fa4759bbe72 100644--- a/Services/Compositor/CompositorWebContentClient.ipc+++ b/Services/Compositor/CompositorWebContentClient.ipc@@ -9,7 +9,7 @@ endpoint CompositorWebContentClient[RustSender] key_event(u64 page_id, Web::KeyEvent event) =|[RustSender] pinch_event(u64 page_id, Web::PinchEvent event) =|[RustSender] request_rendering_update() =|- rendering_opportunity(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds) =|+ [RustSender] rendering_opportunity(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds) =|[RustSender] async_scroll_updates(Web::CompositorContextId context_id, Compositing::PendingAsyncScrollUpdates updates) =|// A frame of a transform animation the compositor runs moved content under the pointer at rest, or away from it,// as of the frame's time.diff --git a/Services/Compositor/ConnectionFromPresentation.cpp b/Services/Compositor/ConnectionFromPresentation.cppindex 0097b865ba8..770a27331c4 100644--- a/Services/Compositor/ConnectionFromPresentation.cpp+++ b/Services/Compositor/ConnectionFromPresentation.cpp@@ -49,16 +49,6 @@ void ConnectionFromPresentation::did_retire_backing_stores(Web::CompositorContexasync_did_retire_backing_stores(context_id, move(bitmap_ids));}-void ConnectionFromPresentation::did_present_frame(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio)-{- async_did_present_frame(context_id, content_rect, damage_rect, bitmap_id, device_pixel_ratio);-}--void ConnectionFromPresentation::did_present_frame_in_remote_layer(Web::CompositorContextId context_id, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio)-{- async_did_present_frame_in_remote_layer(context_id, content_rect, damage_rect, device_pixel_ratio);-}-void ConnectionFromPresentation::post_message_to_presentation(IPC::MessageBuffer& buffer){(void)post_message(buffer);diff --git a/Services/Compositor/ConnectionFromPresentation.h b/Services/Compositor/ConnectionFromPresentation.hindex 30afd662488..681d7d41211 100644--- a/Services/Compositor/ConnectionFromPresentation.h+++ b/Services/Compositor/ConnectionFromPresentation.h@@ -35,8 +35,6 @@ private:virtual void did_allocate_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) override;virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage>&& backing_stores) override;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) override;- virtual void did_present_frame(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, i32 bitmap_id, double device_pixel_ratio) override;- virtual void did_present_frame_in_remote_layer(Web::CompositorContextId, Gfx::IntRect content_rect, Gfx::IntRect damage_rect, double device_pixel_ratio) override;virtual void did_hold_synchronized_resize_frame(u64 remote_layer_id, u64 token) override { async_did_hold_synchronized_resize_frame(remote_layer_id, token); }virtual void did_commit_synchronized_resize(u64 remote_layer_id, u64 token) override { async_did_commit_synchronized_resize(remote_layer_id, token); }diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 156ebeabc15..fbbaf41fa65 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -208,11 +208,6 @@ void ConnectionFromWebContent::post_message_to_render_clock(IPC::MessageBuffer&(void)m_render_clock_connection->post_message(buffer);}-void ConnectionFromWebContent::rendering_opportunity(Web::CompositorContextId context_id, i64 frame_time_nanoseconds, double frame_interval_milliseconds)-{- async_rendering_opportunity(context_id, frame_time_nanoseconds, frame_interval_milliseconds);-}-ErrorOr<OwnPtr<IPC::MessageBuffer>> ConnectionFromWebContent::handle_raw(IPC::RawMessage& message){auto outcome = m_compositor_state->handle_message_from_web_content(web_content_client_id(), message);diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex ba996f322f1..f253b48d040 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -94,7 +94,6 @@ private:virtual WebContentClientId web_content_client_id() const override { return m_web_content_client_id; }virtual void post_message_to_web_content(IPC::MessageBuffer&) override;virtual void post_message_to_render_clock(IPC::MessageBuffer&) override;- virtual void rendering_opportunity(Web::CompositorContextId, i64 frame_time_nanoseconds, double frame_interval_milliseconds) override;virtual void create_video_edge(Media::VideoSinkHandle) override;virtual void release_video_edge(Media::VideoSinkHandle) override;virtual void request_animated_image_frames(AnimatedImage::FrameRequest const&) override;diff --git a/Services/Compositor/ContextLayers.cpp b/Services/Compositor/ContextLayers.cppdeleted file mode 100644index 1dcd740b20e..00000000000--- a/Services/Compositor/ContextLayers.cpp+++ /dev/null@@ -1,133 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/ContextLayers.h>--namespace Compositor {--bool same_media(ReadonlySpan<LiveMedia> a, ReadonlySpan<LiveMedia> b)-{- if (a.size() != b.size())- return false;- for (size_t index = 0; index < a.size(); ++index) {- if (a[index].kind != b[index].kind || a[index].id != b[index].id)- return false;- }- return true;-}--OwnPtr<LayerPlan> LayerPlan::build(FrameInputs const& frame_inputs, Compositing::DisplayList const& display_list, Gfx::IntRect viewport_rect, ReadonlySpan<LiveMedia> active_media)-{- auto* plan = frame_inputs.build_layer_plan(display_list, viewport_rect, active_media);- if (!plan)- return {};- return adopt_own(*new LayerPlan(plan));-}--LayerPlan::LayerPlan(RustFFI::ContextLayerPlan* plan)- : m_plan(plan)-{- auto layer_count = RustFFI::compositor_layer_plan_layer_count(m_plan);- m_layers.ensure_capacity(layer_count);- for (size_t index = 0; index < layer_count; ++index) {- RustFFI::FfiLayer layer {};- RustFFI::compositor_layer_plan_layer(m_plan, index, &layer);- Optional<WindowServerPlacement> window_server_placement;- if (layer.can_be_shown_by_window_server) {- auto const& placement = layer.window_server_placement;- auto const* transform = placement.content_to_viewport;- Optional<RemoteSublayer::RoundedClip> rounded_clip;- if (placement.has_rounded_clip) {- rounded_clip = RemoteSublayer::RoundedClip {- .rect = placement.rounded_clip_rect,- .radius = placement.rounded_clip_radius,- .rounds_top_left = placement.rounds_top_left,- .rounds_top_right = placement.rounds_top_right,- .rounds_bottom_right = placement.rounds_bottom_right,- .rounds_bottom_left = placement.rounds_bottom_left,- };- }- window_server_placement = WindowServerPlacement {- .content_rect = placement.content_rect,- .content_to_viewport = Gfx::AffineTransform { transform[0], transform[1], transform[2], transform[3], transform[4], transform[5] },- .clip_rect = placement.clip_rect,- .rounded_clip = rounded_clip,- .scaling_mode = placement.scaling_mode,- };- }- m_layers.unchecked_append({- .kind = layer.kind,- .media = layer.media,- .rect = layer.rect,- .record_spans = { layer.record_spans, layer.record_span_count },- .window_server_placement = move(window_server_placement),- });- if (layer.kind == LayerKind::Media)- m_media_record_offsets.append(layer.record_spans[0].begin_offset);- }-}--LayerPlan::~LayerPlan()-{- RustFFI::compositor_layer_plan_destroy(m_plan);-}--Gfx::IntRect LayerPlan::rect_of_media_layers_showing(ReadonlySpan<Compositing::CanvasId> canvases, ReadonlySpan<Compositing::VideoSinkResourceId> video_sinks) const-{- Gfx::IntRect rect;- for (auto const& layer : m_layers) {- if (layer.kind != LayerKind::Media)- continue;- auto shows_changed_media = layer.media.kind == RustFFI::FfiLiveMediaKind::Canvas- ? canvases.contains_slow(Compositing::CanvasId { layer.media.id })- : video_sinks.contains_slow(Compositing::VideoSinkResourceId { layer.media.id });- if (shows_changed_media)- rect.unite(layer.rect);- }- return rect;-}--bool LayerPlan::has_same_layers_as(LayerPlan const& other) const-{- return RustFFI::compositor_layer_plans_have_same_layers(m_plan, other.m_plan);-}--void MediaActivity::note_updates(ReadonlySpan<Update> updates, MonotonicTime now)-{- m_updates.remove_all_matching([&](auto const& media_updates) {- return now - media_updates.last_update > time_media_stays_active_after_an_update;- });- for (auto const& update : updates)- note_update(update, now);-}--void MediaActivity::note_update(Update const& update, MonotonicTime now)-{- for (auto& updates : m_updates) {- if (updates.media.kind != update.media.kind || updates.media.id != update.media.id)- continue;- if (updates.content_version == update.content_version)- return;- if (now - updates.last_update <= longest_time_between_updates_that_activate_media)- updates.active = true;- updates.content_version = update.content_version;- updates.last_update = now;- return;- }- m_updates.append({ .media = update.media, .content_version = update.content_version, .last_update = now });-}--Vector<LiveMedia> MediaActivity::active_media(MonotonicTime now) const-{- Vector<LiveMedia> media;- for (auto const& updates : m_updates) {- if (updates.active && now - updates.last_update <= time_media_stays_active_after_an_update)- media.append(updates.media);- }- return media;-}--}diff --git a/Services/Compositor/ContextLayers.h b/Services/Compositor/ContextLayers.hdeleted file mode 100644index 5c722ebf0f9..00000000000--- a/Services/Compositor/ContextLayers.h+++ /dev/null@@ -1,93 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Noncopyable.h>-#include <AK/Optional.h>-#include <AK/OwnPtr.h>-#include <AK/Span.h>-#include <AK/Time.h>-#include <AK/Vector.h>-#include <AK/kmalloc.h>-#include <Compositor/CompositorCoreRustFFI.h>-#include <Compositor/FrameInputs.h>-#include <Compositor/RemoteSublayer.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>-#include <LibGfx/Rect.h>--namespace Compositor {--using LiveMedia = RustFFI::FfiLiveMedia;-using LayerKind = RustFFI::FfiLayerKind;--bool same_media(ReadonlySpan<LiveMedia>, ReadonlySpan<LiveMedia>);--class LayerPlan {- AK_MAKE_NONCOPYABLE(LayerPlan);- AK_MAKE_NONMOVABLE(LayerPlan);--public:- AK_ALLOC_WITH_KMALLOC;-- static OwnPtr<LayerPlan> build(FrameInputs const&, Compositing::DisplayList const&, Gfx::IntRect viewport_rect, ReadonlySpan<LiveMedia> active_media);- ~LayerPlan();-- using WindowServerPlacement = Compositor::WindowServerPlacement;-- struct Layer {- LayerKind kind;- LiveMedia media;- Gfx::IntRect rect;- ReadonlySpan<Compositing::RustFFI::RecordSpan> record_spans;- Optional<WindowServerPlacement> window_server_placement;- };-- ReadonlySpan<Layer> layers() const { return m_layers; }- ReadonlySpan<u32> media_record_offsets() const { return m_media_record_offsets; }-- Gfx::IntRect rect_of_media_layers_showing(ReadonlySpan<Compositing::CanvasId>, ReadonlySpan<Compositing::VideoSinkResourceId>) const;-- bool has_same_layers_as(LayerPlan const&) const;-- RustFFI::ContextLayerPlan const* rust_plan() const { return m_plan; }--private:- explicit LayerPlan(RustFFI::ContextLayerPlan*);-- RustFFI::ContextLayerPlan* m_plan { nullptr };- Vector<Layer> m_layers;- Vector<u32> m_media_record_offsets;-};--class MediaActivity {-public:- static constexpr AK::Duration longest_time_between_updates_that_activate_media = AK::Duration::from_seconds(1);- static constexpr AK::Duration time_media_stays_active_after_an_update = AK::Duration::from_seconds(3);-- struct Update {- LiveMedia media;- u64 content_version { 0 };- };-- void note_updates(ReadonlySpan<Update>, MonotonicTime now);- Vector<LiveMedia> active_media(MonotonicTime now) const;--private:- struct Updates {- LiveMedia media;- u64 content_version { 0 };- MonotonicTime last_update;- bool active { false };- };-- void note_update(Update const&, MonotonicTime now);-- Vector<Updates> m_updates;-};--}diff --git a/Services/Compositor/ContextPresenter.cpp b/Services/Compositor/ContextPresenter.cppdeleted file mode 100644index e9f8fe41b42..00000000000--- a/Services/Compositor/ContextPresenter.cpp+++ /dev/null@@ -1,1100 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/AnyOf.h>-#include <AK/Math.h>-#include <Compositor/CanvasSurfaceRegistry.h>-#include <Compositor/ContextPresenter.h>-#include <Compositor/DisplayListPlayerSkia.h>-#include <Compositor/FontSkia.h>-#include <Compositor/SkiaUtils.h>-#include <LibCore/Timer.h>-#include <LibGfx/Bitmap.h>-#include <LibGfx/Font/Font.h>-#include <LibGfx/Font/FontDatabase.h>-#include <LibMedia/Sinks/VideoSink.h>-#include <LibMediaCodecs/VideoFrame.h>-#include <LibMediaCodecs/VideoSurface.h>-#include <core/SkCanvas.h>-#include <core/SkFont.h>-#include <core/SkFontMetrics.h>-#include <core/SkImage.h>-#include <math.h>--namespace Compositor {--static Gfx::FloatSize bounded_composited_raster_scale(Gfx::FloatSize scale, Gfx::IntSize viewport_size)-{- if (viewport_size.is_empty())- return { 1, 1 };-- scale = { clamp(scale.width(), 0.25f, 5.0f), clamp(scale.height(), 0.25f, 5.0f) };- // Reserve a pixel on each axis for fractional placement. The two backing stores together use at most- // 128 MiB, even when an embedding transform magnifies a large iframe.- constexpr float maximum_dimension = 16384;- constexpr float maximum_pixels = 16 * 1024 * 1024;- scale.set_width(min(scale.width(), (maximum_dimension - 1) / viewport_size.width()));- scale.set_height(min(scale.height(), (maximum_dimension - 1) / viewport_size.height()));- auto pixel_count = (viewport_size.width() * scale.width()) * (viewport_size.height() * scale.height());- constexpr float maximum_content_pixels = maximum_pixels - 2 * maximum_dimension - 1;- if (pixel_count > maximum_content_pixels)- scale.scale_by(sqrtf(maximum_content_pixels / pixel_count));- return scale;-}--static bool video_frame_holds_high_dynamic_range(Media::VideoFrame const& frame)-{- auto transfer_characteristics = frame.cicp().transfer_characteristics();- return transfer_characteristics == Media::TransferCharacteristics::SMPTE2084 || transfer_characteristics == Media::TransferCharacteristics::HLG;-}--ContextPresenter::ContextPresenter(OwnedCanvasSurfaces canvas_surfaces, bool presents_to_client)- : m_canvas_surfaces(canvas_surfaces)- , m_presents_to_client(presents_to_client)-{-}--ContextPresenter::~ContextPresenter()-{- stop_backing_store_shrink_timer();- stop_surplus_backing_store_retirement_timer();- stop_layer_drop_timer();-}--void ContextPresenter::set_display_list(NonnullRefPtr<Compositing::DisplayList const> display_list)-{- m_display_list = move(display_list);-}--void ContextPresenter::apply_resource_transaction(Compositing::DisplayListResourceTransaction&& resource_transaction)-{- m_raster_cache.evict(m_resource_storage.apply_transaction(move(resource_transaction)));-}--void ContextPresenter::set_viewport_size(Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress)-{- m_viewport_size = viewport_size;- m_device_pixel_ratio = device_pixel_ratio;- m_window_resize_in_progress = window_resize_in_progress;-}--bool ContextPresenter::should_shrink_backing_stores_after_resize() const-{- return m_window_resize_in_progress == Compositing::WindowResizingInProgress::Yes;-}--void ContextPresenter::schedule_backing_store_shrink(Function<void()> on_timeout)-{- if (!m_backing_store_shrink_timer)- m_backing_store_shrink_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(3000), move(on_timeout));- m_backing_store_shrink_timer->restart();-}--void ContextPresenter::finish_window_resize()-{- m_window_resize_in_progress = Compositing::WindowResizingInProgress::No;-}--Optional<OverlayLabel> ContextPresenter::shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text)-{- RefPtr<Gfx::Font> font;- if (font_family.has_value())- font = Gfx::FontDatabase::the().get(MUST(FlyString::from_utf8(*font_family)), 12, 400, Gfx::FontWidth::Normal, 0);- if (!font)- font = Gfx::FontDatabase::the().get("SerenitySans"_fly_string, 12, 400, Gfx::FontWidth::Normal, 0);- if (!font)- return {};- auto skia_font = Compositor::skia_font(*font, static_cast<float>(device_pixel_ratio));- if (!skia_font.has_value())- return {};-- OverlayLabel label;- auto glyph_count = skia_font->countText(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8);- Vector<SkGlyphID> glyphs;- glyphs.resize(glyph_count);- skia_font->textToGlyphs(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8, { glyphs.data(), glyphs.size() });- label.glyph_x_positions.resize(glyph_count);- skia_font->getXPos({ glyphs.data(), glyphs.size() }, { label.glyph_x_positions.data(), label.glyph_x_positions.size() });- label.glyph_ids.ensure_capacity(glyph_count);- for (auto glyph : glyphs)- label.glyph_ids.unchecked_append(glyph);- label.width = skia_font->measureText(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8);- SkFontMetrics font_metrics;- skia_font->getMetrics(&font_metrics);- label.ascent = font_metrics.fAscent;- label.descent = font_metrics.fDescent;- label.font_ascent = font->pixel_metrics().ascent;- label.font_id = m_overlay_resource_storage.add_font(*font).value();- return label;-}--Optional<Gfx::IntRect> ContextPresenter::viewport_rect_for_ui_overlay() const-{- if (m_viewport_size.is_empty())- return {};-- auto viewport_rect = m_pending_present_frame.has_value()- ? m_pending_present_frame->viewport_rect- : m_presented_frame.value_or(Gfx::IntRect {});- viewport_rect.set_size(m_viewport_size);- return viewport_rect;-}--ErrorOr<Optional<BackingStoreManager::Publication>> ContextPresenter::resize_backing_stores_if_needed(RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, BackingStoreManager::GpuSharing gpu_sharing, BackingStoreManager::PublicationMode publication_mode, RefPtr<WindowServer> window_server_showing_stores)-{- if (m_backing_store_manager.is_rendering())- return Optional<BackingStoreManager::Publication> {};- if (!presents_to_client()) {- // A resize can arrive before the parent's next replay supplies the new embedding transform.- // Bound the existing embedding's scale for the new viewport before allocating backing stores. Bounding the- // already bounded scale instead can round it differently, which would discard the raster on every replay.- auto scale = bounded_composited_raster_scale(m_unbounded_raster_scale_of_embedding, m_viewport_size);- if (m_raster_scale != scale) {- m_raster_scale = scale;- m_latest_rendered_surface = nullptr;- m_last_rasterized_frame.clear();- }- }- if (!presents_to_client())- publication_mode = BackingStoreManager::PublicationMode::Unpublished;- auto allocation = m_backing_store_manager.resize_backing_stores_if_needed(raster_size(), m_window_resize_in_progress, publication_mode);- if (!allocation.has_value())- return Optional<BackingStoreManager::Publication> {};- m_latest_rendered_surface = nullptr;- m_last_rasterized_frame.clear();- return m_backing_store_manager.allocate_backing_stores(*allocation, skia_backend_context, publication_mode, gpu_sharing, move(window_server_showing_stores));-}--void ContextPresenter::invalidate_backing_stores()-{- m_backing_store_manager.invalidate();- m_frame_without_store_in_flight = false;-}--Optional<BackingStoreManager::Publication> ContextPresenter::add_backing_store_for_pending_frame_if_needed(RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)-{- if (!presents_to_client() || !m_pending_present_frame.has_value() || !can_render_frame())- return {};- return m_backing_store_manager.add_backing_store_if_window_server_still_reads_every_released_store(skia_backend_context);-}--void ContextPresenter::schedule_surplus_backing_store_retirement(Function<void()> on_timeout)-{- if (!m_surplus_backing_store_retirement_timer)- m_surplus_backing_store_retirement_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(3000), move(on_timeout));- if (!m_surplus_backing_store_retirement_timer->is_active())- m_surplus_backing_store_retirement_timer->start();-}--bool ContextPresenter::acknowledge_presented_bitmap(i32 bitmap_id)-{- return m_backing_store_manager.release_buffer(bitmap_id);-}--void ContextPresenter::did_finish_gpu_present(i32 bitmap_id, Gfx::IntSize frame_size)-{- m_backing_store_manager.complete_rendering(bitmap_id);- m_latest_rendered_surface = m_backing_store_manager.latest_rendered_surface();- m_size_of_latest_rendered_frame = frame_size;-}--bool ContextPresenter::update_composited_raster_transform(Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& transform)-{- if (presents_to_client() || m_backing_store_manager.is_rendering() || m_viewport_size.is_empty() || destination_rect.is_empty())- return false;-- // Display list coordinates already include device scale and page zoom. Only the embedding transform and- // the viewport-to-destination mapping belong here; neither changes the child's layout or scroll geometry.- auto has_perspective = transform[3, 0] != 0 || transform[3, 1] != 0 || transform[3, 3] != 1;- float scale_x = 1;- float scale_y = 1;- if (!has_perspective) {- scale_x = AK::hypot<float>(transform[0, 0], transform[1, 0]) * destination_rect.width() / m_viewport_size.width();- scale_y = AK::hypot<float>(transform[0, 1], transform[1, 1]) * destination_rect.height() / m_viewport_size.height();- }- if (!isfinite(scale_x) || !isfinite(scale_y))- return false;- m_unbounded_raster_scale_of_embedding = { scale_x, scale_y };-- // Perspective keeps the native resolution until we can choose a scale from the visible projected region.- auto scale = bounded_composited_raster_scale(m_unbounded_raster_scale_of_embedding, m_viewport_size);-- Gfx::FloatPoint translation;- if (!has_perspective && transform[0, 1] == 0 && transform[1, 0] == 0 && scale.width() == scale_x && scale.height() == scale_y) {- auto x = transform[0, 0] * destination_rect.x() + transform[0, 3];- auto y = transform[1, 1] * destination_rect.y() + transform[1, 3];- if (!isfinite(x) || !isfinite(y))- return false;- // Mirrored placements need the opposite fractional phase so the remaining image transform still- // lands on integer device pixels.- if (transform[0, 0] < 0)- x = -x;- if (transform[1, 1] < 0)- y = -y;- translation = { x - floorf(x), y - floorf(y) };- }-- if (m_raster_scale == scale && m_raster_translation == translation)- return false;- m_raster_scale = scale;- m_raster_translation = translation;- m_latest_rendered_surface = nullptr;- m_last_rasterized_frame.clear();- return true;-}--CompositedContextSurface ContextPresenter::composited_surface() const-{- if (!m_latest_rendered_surface || !m_last_rasterized_frame.has_value())- return {};- auto size = m_last_rasterized_frame->viewport_size.to_type<float>();- size.scale_by(m_raster_scale.width(), m_raster_scale.height());- return { m_latest_rendered_surface, { m_raster_translation, size } };-}--void ContextPresenter::queue_present_frame(PendingFrame pending_frame)-{- if (!m_pending_present_frame.has_value()) {- m_pending_present_frame = pending_frame;- return;- }-- if (m_pending_present_frame->viewport_rect.size() != pending_frame.viewport_rect.size()) {- m_pending_present_frame = PendingFrame::repainting_everything(pending_frame.viewport_rect);- return;- }-- m_pending_present_frame->viewport_rect = pending_frame.viewport_rect;- m_pending_present_frame->forced_damage_rect.unite(pending_frame.forced_damage_rect);-}--void ContextPresenter::mark_pending_present_frame_scheduled()-{- m_pending_present_frame_scheduled = true;-}--bool ContextPresenter::can_schedule_pending_present_frame_if_unblocked() const-{- if (is_present_blocked())- return false;- if (!m_pending_present_frame.has_value())- return false;- if (m_pending_present_frame_scheduled)- return false;- return true;-}--Optional<PendingFrame> ContextPresenter::take_pending_present_frame_if_unblocked()-{- if (is_present_blocked())- return {};- m_pending_present_frame_scheduled = false;- if (!m_pending_present_frame.has_value())- return {};- return m_pending_present_frame.release_value();-}--bool ContextPresenter::needs_rasterization() const-{- return m_pending_present_frame.has_value()- || (!m_latest_rendered_surface && m_presented_frame.has_value());-}--Optional<Gfx::IntRect> ContextPresenter::frame_rect_to_repaint() const-{- if (m_pending_present_frame.has_value())- return m_pending_present_frame->viewport_rect;- return m_presented_frame;-}--Optional<Gfx::IntRect> ContextPresenter::self_present_rect() const-{- if (m_presented_frame.has_value())- return m_presented_frame;- if (!m_viewport_size.is_empty())- return Gfx::IntRect { {}, m_viewport_size };- return {};-}--bool ContextPresenter::draws_canvas(Compositing::CanvasId canvas_id) const-{- return m_last_rasterized_frame.has_value() && m_last_rasterized_frame->canvas_content_generations.contains(canvas_id);-}--Optional<PreparedFrame> ContextPresenter::prepare_frame(DisplayListPlayerSkia& display_list_player, PendingFrame pending_frame, Optional<FrameInputs>&& frame_inputs, CompositedContextResolver const* composited_context_resolver)-{- if (is_present_blocked()) {- queue_present_frame(pending_frame);- return {};- }-- if (!can_render_frame()) {- m_presented_frame = pending_frame.viewport_rect;- return {};- }- VERIFY(frame_inputs.has_value());-- auto frame_damage = frame_damage_for(pending_frame, *frame_inputs);- auto damage_rect = frame_damage.rect;- // NB: A changed content rect must still reach the client even if the pixels are identical.- if (damage_rect.is_empty() && m_presented_frame == pending_frame.viewport_rect) {- auto only_media_shown_by_window_server_changed = frame_damage.layers.shown_by_window_server && frame_damage.live_media_changed;- commit_layer_update(move(frame_damage.layers));- remember_rasterized_frame(pending_frame.viewport_rect.size(), frame_inputs.release_value());- if (!only_media_shown_by_window_server_changed)- return {};- m_frame_without_store_in_flight = true;- return PreparedFrame {- .rendered_surface = nullptr,- .bitmap_id = -1,- .damage_rect = {},- .device_pixel_ratio = m_device_pixel_ratio,- .sublayers = sublayers_shown_by_window_server(),- };- }- auto render_target = m_backing_store_manager.acquire_render_target(raster_damage_rect(damage_rect));- if (!render_target.has_value()) {- queue_present_frame(pending_frame);- return {};- }- auto& back_store = render_target->surface;- auto painted_rect = paint_frame(display_list_player, back_store, *frame_inputs, composited_context_resolver, render_target->damage_rect, frame_damage.layers);- if (painted_rect != render_target->damage_rect)- damage_rect = { {}, pending_frame.viewport_rect.size() };- commit_layer_update(move(frame_damage.layers));- remember_rasterized_frame(pending_frame.viewport_rect.size(), frame_inputs.release_value());-- return PreparedFrame {- .rendered_surface = &back_store,- .bitmap_id = render_target->bitmap_id,- .damage_rect = damage_rect,- .device_pixel_ratio = m_device_pixel_ratio,- .sublayers = sublayers_shown_by_window_server(),- };-}--void ContextPresenter::did_submit_prepared_frame(Gfx::IntRect viewport_rect)-{- m_presented_frame = viewport_rect;-}--bool ContextPresenter::present_synchronously(DisplayListPlayerSkia& display_list_player, Optional<FrameInputs>&& frame_inputs, CompositedContextResolver const* composited_context_resolver)-{- if (!can_render_frame())- return false;- VERIFY(frame_inputs.has_value());- // Don't race an async present already in flight for this context; its own completion will update the output.- if (is_present_blocked())- return false;-- Optional<PendingFrame> pending_frame = m_pending_present_frame;- if (!pending_frame.has_value() && m_presented_frame.has_value())- pending_frame = PendingFrame::repainting_everything(*m_presented_frame);- if (!pending_frame.has_value())- return false;-- auto frame_damage = frame_damage_for(*pending_frame, *frame_inputs);- auto render_target = m_backing_store_manager.acquire_render_target(raster_damage_rect(frame_damage.rect));- if (!render_target.has_value())- return false;- auto& back_store = render_target->surface;- (void)paint_frame(display_list_player, back_store, *frame_inputs, composited_context_resolver, render_target->damage_rect, frame_damage.layers);- commit_layer_update(move(frame_damage.layers));- remember_rasterized_frame(pending_frame->viewport_rect.size(), frame_inputs.release_value());- display_list_player.flush(back_store);- m_backing_store_manager.complete_rendering(render_target->bitmap_id);- m_latest_rendered_surface = m_backing_store_manager.latest_rendered_surface();- m_size_of_latest_rendered_frame = pending_frame->viewport_rect.size();- m_presented_frame = pending_frame->viewport_rect;- m_pending_present_frame.clear();- m_pending_present_frame_scheduled = false;- return true;-}--void ContextPresenter::paint_screenshot(DisplayListPlayerSkia& display_list_player, Gfx::ShareableBitmap& target_bitmap, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver)-{- auto target_surface = Gfx::PaintingSurface::wrap_bitmap(*target_bitmap.bitmap());- paint_current_display_list(display_list_player, *target_surface, frame_inputs, composited_context_resolver, {}, PaintUIOverlay::No, false);- display_list_player.flush(*target_surface);-}--static Gfx::IntSize size_fitting_within(Gfx::IntSize size, Gfx::IntSize maximum_size)-{- if (size.width() <= maximum_size.width() && size.height() <= maximum_size.height())- return size;- auto scale = min(static_cast<double>(maximum_size.width()) / size.width(), static_cast<double>(maximum_size.height()) / size.height());- return { max(1, static_cast<int>(round(size.width() * scale))), max(1, static_cast<int>(round(size.height() * scale))) };-}--Optional<Gfx::ShareableBitmap> ContextPresenter::snapshot_of_presented_frame(DisplayListPlayerSkia& display_list_player, Optional<Gfx::IntSize> maximum_size)-{- if (!m_latest_rendered_surface)- return {};- NonnullRefPtr<Gfx::PaintingSurface> source_surface = *m_latest_rendered_surface;- // The store then holds only what is under the canvases, videos and overlays that the window server shows above it.- if (m_window_server_shows_media && m_layer_plan && m_last_rasterized_frame.has_value()) {- auto composited_or_error = Gfx::PaintingSurface::try_create_with_size(source_surface->size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, source_surface->skia_backend_context());- if (composited_or_error.is_error())- return {};- auto composited = composited_or_error.release_value();- auto store_image = source_surface->sk_image_snapshot<sk_sp<SkImage>>();- SkPaint paint;- paint.setBlendMode(SkBlendMode::kSrc);- composited->canvas().drawImage(store_image.get(), 0, 0, SkSamplingOptions {}, &paint);- auto const& frame_inputs = m_last_rasterized_frame->frame_inputs;- composite_layers_above_base(display_list_player, *composited, frame_inputs, nullptr, *m_layer_plan, composited->rect());- paint_compositor_overlays(display_list_player, *composited, frame_inputs, PaintUIOverlay::Yes);- source_surface = composited;- }- auto const& source = *source_surface;- Gfx::IntSize frame_size { min(m_size_of_latest_rendered_frame.width(), source.size().width()), min(m_size_of_latest_rendered_frame.height(), source.size().height()) };- if (frame_size.is_empty())- return {};- auto snapshot_size = frame_size;- if (maximum_size.has_value() && !maximum_size->is_empty())- snapshot_size = size_fitting_within(frame_size, *maximum_size);-- auto bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, snapshot_size);- if (bitmap_or_error.is_error())- return {};- auto bitmap = bitmap_or_error.release_value();-- if (snapshot_size == frame_size) {- source.read_into_bitmap(*bitmap);- return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };- }-- // A linear filter reads only the pixels around each one it writes, so a frame scaled down to a fraction of its size- // in one step would skip most of them. Halving it first lets every pixel count.- auto image = source.sk_image_snapshot<sk_sp<SkImage>>();- auto image_size = frame_size;- SkSamplingOptions const sampling { SkFilterMode::kLinear };- auto draw_scaled = [&](Gfx::IntSize size) -> RefPtr<Gfx::PaintingSurface> {- auto surface_or_error = Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, source.skia_backend_context());- if (surface_or_error.is_error())- return nullptr;- auto surface = surface_or_error.release_value();- surface->canvas().drawImageRect(image.get(), SkRect::MakeIWH(image_size.width(), image_size.height()), SkRect::MakeIWH(size.width(), size.height()), sampling, nullptr, SkCanvas::kStrict_SrcRectConstraint);- return surface;- };- while (image_size.width() / 2 >= snapshot_size.width() && image_size.height() / 2 >= snapshot_size.height()) {- Gfx::IntSize half_size { image_size.width() / 2, image_size.height() / 2 };- auto half = draw_scaled(half_size);- if (!half)- return {};- image = half->sk_image_snapshot<sk_sp<SkImage>>();- image_size = half_size;- }- auto snapshot_surface = draw_scaled(snapshot_size);- if (!snapshot_surface)- return {};- snapshot_surface->read_into_bitmap(*bitmap);- return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };-}--void ContextPresenter::stop_backing_store_shrink_timer()-{- if (!m_backing_store_shrink_timer)- return;- m_backing_store_shrink_timer->on_timeout = {};- m_backing_store_shrink_timer->stop();-}--void ContextPresenter::stop_surplus_backing_store_retirement_timer()-{- if (!m_surplus_backing_store_retirement_timer)- return;- m_surplus_backing_store_retirement_timer->on_timeout = {};- m_surplus_backing_store_retirement_timer->stop();-}--void ContextPresenter::stop_layer_drop_timer()-{- if (!m_layer_drop_timer)- return;- m_layer_drop_timer->on_timeout = {};- m_layer_drop_timer->stop();-}--bool ContextPresenter::is_present_blocked() const-{- return m_backing_store_manager.is_rendering()- || m_frame_without_store_in_flight- || !m_backing_store_manager.has_available_buffer();-}--bool ContextPresenter::can_render_frame() const-{- return m_display_list && m_backing_store_manager.is_valid();-}--Gfx::IntSize ContextPresenter::raster_size() const-{- if (m_viewport_size.is_empty())- return {};- if (presents_to_client())- return m_viewport_size;- return {- static_cast<int>(ceilf(m_viewport_size.width() * m_raster_scale.width() + m_raster_translation.x())),- static_cast<int>(ceilf(m_viewport_size.height() * m_raster_scale.height() + m_raster_translation.y())),- };-}--Gfx::IntRect ContextPresenter::raster_damage_rect(Gfx::IntRect damage_rect) const-{- if (damage_rect.is_empty())- return {};- if (damage_rect.contains(Gfx::IntRect { {}, m_viewport_size }))- return { {}, raster_size() };- auto rect = damage_rect.to_type<float>();- rect.scale_by(m_raster_scale.width(), m_raster_scale.height());- rect.translate_by(m_raster_translation);- return Gfx::enclosing_int_rect(rect).intersected(Gfx::IntRect { {}, raster_size() });-}--ContextPresenter::FrameDamage ContextPresenter::frame_damage_for(PendingFrame const& pending_frame, FrameInputs const& frame_inputs)-{- Gfx::IntRect viewport_rect { {}, pending_frame.viewport_rect.size() };- auto forced_damage_rect = pending_frame.forced_damage_rect.intersected(viewport_rect);- auto changes = live_content_changes_since_last_raster(viewport_rect.size());- auto now = MonotonicTime::now();- m_media_activity.note_updates(changes.media_updates, now);-- auto layers = layer_update_for(frame_inputs, viewport_rect, now);- auto const* plan = layers.keeps_plan ? m_layer_plan.ptr() : layers.new_plan.ptr();- layers.shown_by_window_server = plan && window_server_can_show_media_layers_of(*plan);- auto layers_hold_last_frame = m_layer_plan && m_last_rasterized_frame.has_value();- auto keeps_layer_rasters = plan && layers_hold_last_frame && plan->has_same_layers_as(*m_layer_plan);- auto repaints_everything = changes.repaints_everything || forced_damage_rect.contains(viewport_rect);- auto damage = repaints_everything- ? DisplayListDamage {}- : damage_since_last_raster(viewport_rect.size(), frame_inputs, forced_damage_rect, changes,- plan ? plan->media_record_offsets() : ReadonlySpan<u32> {},- keeps_layer_rasters ? m_layer_plan.ptr() : nullptr,- keeps_layer_rasters ? plan : nullptr);- layers.painted_damage = damage.rect.value_or(viewport_rect).intersected(viewport_rect);-- if (!plan) {- layers.repaints_everything = layers_hold_last_frame || m_repaint_everything_after_dropping_layers;- } else if (!keeps_layer_rasters) {- layers.fully_repainted_layer_bits = NumericLimits<u32>::max();- layers.repaints_everything = true;- } else {- for (size_t index = 0; index < plan->layers().size(); ++index) {- auto layer_damage = damage.layer_rects.is_empty() ? Optional<Gfx::IntRect> { layers.painted_damage } : damage.layer_rects[index];- if (!layer_damage.has_value())- layers.fully_repainted_layer_bits |= 1u << index;- layers.damage_of_layers.append(layer_damage.value_or(viewport_rect).intersected(viewport_rect));- }- }-- // A frame holds the canvases and videos only while the window server does not show them, so a switch either way- // repaints all of it.- if (m_last_rasterized_frame.has_value() && layers.shown_by_window_server != m_window_server_shows_media) {- layers.repaints_everything = true;- layers.fully_repainted_layer_bits = NumericLimits<u32>::max();- }-- auto live_media_changed = !changes.canvases.is_empty() || !changes.video_sinks.is_empty();- if (layers.repaints_everything)- return { viewport_rect, move(layers), live_media_changed };- auto damage_rect = layers.painted_damage;- if (plan && !layers.shown_by_window_server)- damage_rect.unite(plan->rect_of_media_layers_showing(changes.canvases, changes.video_sinks).intersected(viewport_rect));- return { damage_rect, move(layers), live_media_changed };-}--ContextPresenter::LiveContentChangesSinceLastRaster ContextPresenter::live_content_changes_since_last_raster(Gfx::IntSize viewport_size)-{- LiveContentChangesSinceLastRaster changes;- if (!m_last_rasterized_frame.has_value()) {- changes.repaints_everything = true;- return changes;- }- auto const& last_frame = *m_last_rasterized_frame;- if (last_frame.viewport_size != viewport_size || last_frame.display_list->surface_clear_color() != m_display_list->surface_clear_color())- changes.repaints_everything = true;-- for (auto const& [canvas_id, content_generation] : last_frame.canvas_content_generations) {- auto current_content_generation = m_canvas_surfaces.canvas_content_generation(canvas_id);- if (current_content_generation == content_generation)- continue;- changes.canvases.append(canvas_id);- changes.media_updates.append({ { RustFFI::FfiLiveMediaKind::Canvas, canvas_id.value() }, current_content_generation });- }- auto video_sinks_drawn_by_list = m_display_list->referenced_resource_ids().video_sinks;- for (auto const& [video_sink_id, frame_id] : last_frame.video_frame_ids) {- auto current_frame_id = current_video_frame_id(video_sink_id);- if (current_frame_id == frame_id)- continue;- changes.media_updates.append({ { RustFFI::FfiLiveMediaKind::Video, video_sink_id.value() }, current_frame_id.value_or(0) });- // A video drawn only by a nested display list, such as an SVG image's, has no command in- // this list to damage.- if (!video_sinks_drawn_by_list.contains_slow(video_sink_id.value()))- changes.repaints_everything = true;- changes.video_sinks.append(video_sink_id);- }- auto image_frames_drawn_by_list = m_display_list->referenced_resource_ids().image_frames;- for (auto const& [image_frame_id, generation] : m_resource_storage.image_frame_pixel_generations()) {- if (last_frame.image_frame_pixel_generations.get(image_frame_id) == generation)- continue;- // An image drawn only by a nested display list, such as an SVG image's, has no command in this list to damage.- if (!image_frames_drawn_by_list.contains_slow(image_frame_id))- changes.repaints_everything = true;- changes.image_frames.append(Compositing::ImageFrameResourceId { image_frame_id });- }- return changes;-}--DisplayListDamage ContextPresenter::damage_since_last_raster(Gfx::IntSize viewport_size, FrameInputs const& frame_inputs, Gfx::IntRect forced_damage_rect, LiveContentChangesSinceLastRaster const& changes, ReadonlySpan<u32> offsets_of_records_composited_as_media_layers, LayerPlan const* last_layer_plan, LayerPlan const* layer_plan)-{- Gfx::IntRect viewport_rect { {}, viewport_size };- auto const& last_frame = *m_last_rasterized_frame;- auto damage = frame_inputs.damage_since(- *m_display_list,- last_frame.frame_inputs,- *last_frame.display_list,- viewport_rect,- { .canvases = changes.canvases, .video_sinks = changes.video_sinks, .image_frames = changes.image_frames, .forced_damage_rect = forced_damage_rect, .offsets_of_records_composited_as_media_layers = offsets_of_records_composited_as_media_layers },- last_layer_plan ? last_layer_plan->rust_plan() : nullptr,- layer_plan ? layer_plan->rust_plan() : nullptr);- if (damage.rect.has_value())- damage.rect = damage.rect->intersected(viewport_rect);- return damage;-}--ContextPresenter::LayerUpdate ContextPresenter::layer_update_for(FrameInputs const& frame_inputs, Gfx::IntRect viewport_rect, MonotonicTime now)-{- LayerUpdate layers;- if (!presents_to_client())- return layers;- layers.active_media = m_media_activity.active_media(now);- // An HDR video is a layer from its first frame for as long as it is drawn, even while paused, so that the window- // server keeps showing it brighter than SDR white instead of it going back into the frame, which holds SDR.- if (m_remote_layer_that_may_show_media && m_remote_layer_that_may_show_media->can_show_high_dynamic_range() && m_window_server_may_show_high_dynamic_range) {- for (auto id : m_display_list->referenced_resource_ids().video_sinks) {- LiveMedia media { RustFFI::FfiLiveMediaKind::Video, id };- auto is_active = any_of(layers.active_media, [&](auto const& active) { return active.kind == media.kind && active.id == media.id; });- if (is_active)- continue;- auto frame = current_video_frame(Compositing::VideoSinkResourceId { id });- if (frame && video_frame_holds_high_dynamic_range(*frame))- layers.active_media.append(media);- }- }- if (layers.active_media.is_empty())- return layers;- auto plan_holds_for_frame = m_layer_plan- && m_last_rasterized_frame.has_value()- && m_last_rasterized_frame->display_list.ptr() == m_display_list.ptr()- && m_last_rasterized_frame->viewport_size == viewport_rect.size()- && same_media(m_layer_plan_active_media, layers.active_media)- && frame_inputs.places_content_like(m_last_rasterized_frame->frame_inputs);- if (plan_holds_for_frame)- layers.keeps_plan = true;- else- layers.new_plan = LayerPlan::build(frame_inputs, *m_display_list, viewport_rect, layers.active_media);- return layers;-}--void ContextPresenter::commit_layer_update(LayerUpdate&& layers)-{- m_window_server_shows_media = layers.has_plan() && layers.shown_by_window_server;- if (layers.repaints_everything)- m_repaint_everything_after_dropping_layers = false;- if (!layers.has_plan()) {- drop_layers();- return;- }- if (layers.new_plan)- m_layer_plan = move(layers.new_plan);- m_layer_plan_active_media = move(layers.active_media);-- if (!m_layer_drop_timer) {- m_layer_drop_timer = Core::Timer::create_single_shot(MediaActivity::time_media_stays_active_after_an_update, [this] {- // While the window server shows the media, the layers cost nothing, and the frame on screen still needs- // their plan, as for a snapshot. The next frame without a plan puts the media back into the store.- if (!m_layer_plan || m_window_server_shows_media)- return;- drop_layers();- m_repaint_everything_after_dropping_layers = true;- });- }- m_layer_drop_timer->restart();-}--void ContextPresenter::drop_layers()-{- m_layer_plan = nullptr;- m_layer_plan_active_media.clear();- m_layer_surfaces.clear();- m_painted_layer_presentations.clear();- if (m_layer_drop_timer)- m_layer_drop_timer->stop();-}--void ContextPresenter::remember_rasterized_frame(Gfx::IntSize viewport_size, FrameInputs&& frame_inputs)-{- HashMap<Compositing::CanvasId, u64> canvas_content_generations;- for (auto id : m_display_list->referenced_resource_ids().canvases) {- Compositing::CanvasId canvas_id { id };- canvas_content_generations.set(canvas_id, m_canvas_surfaces.canvas_content_generation(canvas_id));- }- // Every video the context holds is drawn by the list or by a display list it nests.- HashMap<Compositing::VideoSinkResourceId, Optional<u64>> video_frame_ids;- for (auto const& [id, handle] : m_resource_storage.video_sink_handles()) {- Compositing::VideoSinkResourceId video_sink_id { id };- video_frame_ids.set(video_sink_id, current_video_frame_id(video_sink_id));- }- m_last_rasterized_frame = RasterizedFrame {- .display_list = NonnullRefPtr { *m_display_list },- .frame_inputs = move(frame_inputs),- .viewport_size = viewport_size,- .canvas_content_generations = move(canvas_content_generations),- .video_frame_ids = move(video_frame_ids),- .image_frame_pixel_generations = m_resource_storage.image_frame_pixel_generations(),- };-}--RefPtr<Media::VideoFrame> ContextPresenter::current_video_frame(Compositing::VideoSinkResourceId video_sink_id)-{- auto sink = m_resource_storage.video_sink(video_sink_id);- if (!sink)- return {};- return sink->current_frame();-}--Optional<u64> ContextPresenter::current_video_frame_id(Compositing::VideoSinkResourceId video_sink_id)-{- auto frame = current_video_frame(video_sink_id);- if (!frame)- return {};- return frame->id();-}--void ContextPresenter::paint_compositor_overlays(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& target_surface, FrameInputs const& frame_inputs, PaintUIOverlay paint_ui_overlay)-{- auto painter = display_list_player.begin_painting(target_surface, m_overlay_resource_storage, m_overlay_raster_cache, nullptr, nullptr);- frame_inputs.paint_overlays(painter, paint_ui_overlay == PaintUIOverlay::Yes);- display_list_player.end_painting();-}--Gfx::IntRect ContextPresenter::paint_frame(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver, Gfx::IntRect damage_rect, LayerUpdate& layers)-{- if (layers.has_plan()) {- if (paint_layered_frame(display_list_player, surface, frame_inputs, composited_context_resolver, damage_rect, layers))- return damage_rect;- // The sublayers that the window server was to show go away with this frame, so the store has to hold all- // that they showed.- if (layers.shown_by_window_server)- damage_rect = { {}, raster_size() };- layers.new_plan = nullptr;- layers.keeps_plan = false;- layers.shown_by_window_server = false;- drop_layers();- m_repaint_everything_after_dropping_layers = true;- }- paint_current_display_list(display_list_player, surface, frame_inputs, composited_context_resolver, damage_rect);- return damage_rect;-}--bool ContextPresenter::paint_layered_frame(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver, Gfx::IntRect damage_rect, LayerUpdate const& layer_update)-{- VERIFY(m_display_list);- auto const& plan = layer_update.keeps_plan ? *m_layer_plan : *layer_update.new_plan;- auto 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_what_was_not_used_since_last_frame();-- m_layer_surfaces.resize(layers.size());- for (size_t index = 0; index < layers.size(); ++index) {- auto const& layer = layers[index];- auto& layer_surface = m_layer_surfaces[index];- auto rect = layer.kind == LayerKind::Base ? Gfx::IntRect { {}, m_viewport_size } : layer.rect;- if (layer.kind == LayerKind::Media || rect.is_empty()) {- layer_surface = {};- continue;- }- auto repaints_whole_layer = (layer_update.fully_repainted_layer_bits & (1u << index)) != 0;- auto surface_fits = layer.kind == LayerKind::Base ? layer_surface.rect == rect : layer_surface.rect.contains(rect);- if (!layer_surface.surface || !surface_fits || layer_surface.surface->skia_backend_context() != skia_backend_context) {- auto new_surface = Gfx::PaintingSurface::try_create_with_size(rect.size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context);- if (new_surface.is_error())- return false;- layer_surface = { new_surface.release_value(), rect };- repaints_whole_layer = true;- }- auto repaint_rect = repaints_whole_layer ? layer_surface.rect : layer_update.damage_of_layers[index].intersected(layer_surface.rect);- if (repaint_rect.is_empty())- continue;- auto& layer_canvas = layer_surface.surface->canvas();- layer_canvas.save();- layer_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);- 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;- }-- auto& canvas = surface.canvas();- auto save_count = canvas.save();- canvas.clipIRect(SkIRect::MakeXYWH(damage_rect.x(), damage_rect.y(), damage_rect.width(), damage_rect.height()));- if (auto const& base_surface = m_layer_surfaces[0]; base_surface.surface && base_surface.rect.intersects(damage_rect)) {- auto image = base_surface.surface->sk_image_snapshot<sk_sp<SkImage>>();- SkPaint paint;- paint.setBlendMode(SkBlendMode::kSrc);- canvas.drawImage(image.get(), base_surface.rect.x(), base_surface.rect.y(), SkSamplingOptions {}, &paint);- }- if (!layer_update.shown_by_window_server) {- composite_layers_above_base(display_list_player, surface, frame_inputs, composited_context_resolver, plan, damage_rect);- paint_compositor_overlays(display_list_player, surface, frame_inputs, PaintUIOverlay::Yes);- }- canvas.restoreToCount(save_count);-- // The window server shows everything above the base layer from surfaces of its own.- if (layer_update.shown_by_window_server) {- if (!present_painted_layers_to_window_server(plan, skia_backend_context))- return false;- if (!present_compositor_overlays_to_window_server(display_list_player, frame_inputs, skia_backend_context))- return false;- }- return true;-}--void ContextPresenter::composite_layers_above_base(DisplayListPlayerSkia& display_list_player, Gfx::PaintingSurface& surface, FrameInputs const& frame_inputs, CompositedContextResolver const* composited_context_resolver, LayerPlan const& plan, Gfx::IntRect damage_rect)-{- auto layers = plan.layers();- auto& canvas = surface.canvas();- for (size_t index = 1; index < layers.size(); ++index) {- auto const& layer = layers[index];- if (layer.kind == LayerKind::Media) {- if (layer.rect.intersects(damage_rect))- 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())- continue;- auto const& layer_surface = m_layer_surfaces[index];- if (!layer_surface.surface || !layer_surface.rect.intersects(damage_rect))- continue;- auto image = layer_surface.surface->sk_image_snapshot<sk_sp<SkImage>>();- SkPaint paint;- paint.setBlendMode(SkBlendMode::kSrcOver);- canvas.drawImage(image.get(), layer_surface.rect.x(), layer_surface.rect.y(), SkSamplingOptions {}, &paint);- }-}--bool ContextPresenter::window_server_can_show_media_layers_of(LayerPlan const& plan)-{- if (!m_remote_layer_that_may_show_media)- return false;- for (auto const& layer : plan.layers()) {- if (layer.kind != LayerKind::Media)- continue;- if (!layer.window_server_placement.has_value())- return false;- Optional<RemoteLayer::Content> content;- if (layer.media.kind == RustFFI::FfiLiveMediaKind::Canvas) {- if (auto surface = m_canvas_surfaces.presentable_canvas_surface(Compositing::CanvasId { layer.media.id }))- content = surface.release_nonnull();- } else if (auto frame = current_video_frame(Compositing::VideoSinkResourceId { layer.media.id })) {- if (!m_window_server_may_show_high_dynamic_range && video_frame_holds_high_dynamic_range(*frame))- return false;- content = frame.release_nonnull();- }- if (!content.has_value() || !m_remote_layer_that_may_show_media->can_show(*layer.window_server_placement, *content, m_device_pixel_ratio))- return false;- }- return true;-}--// Each painted layer goes to the window server as its own surface, which is copied from its raster when the raster-// changes. The window server may still show the surface of the frame before, so the copy goes into another one.-bool ContextPresenter::present_painted_layers_to_window_server(LayerPlan const& plan, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)-{- auto layers = plan.layers();- m_painted_layer_presentations.resize(layers.size());- for (size_t index = 0; index < layers.size(); ++index) {- auto const& layer = layers[index];- auto& presentation = m_painted_layer_presentations[index];- auto const* layer_surface = index < m_layer_surfaces.size() ? &m_layer_surfaces[index] : nullptr;- if (layer.kind != LayerKind::Painted || layer.rect.is_empty() || !layer_surface || !layer_surface->surface) {- presentation.latest_surface = nullptr;- continue;- }- if (presentation.latest_surface && presentation.rect == layer.rect && presentation.content_version == layer_surface->content_version)- continue;- auto surface_or_error = presentation.surfaces.surface_for_next_content(layer.rect.size(), skia_backend_context);- if (surface_or_error.is_error())- return false;- auto surface = surface_or_error.release_value();- auto image = layer_surface->surface->sk_image_snapshot<sk_sp<SkImage>>();- auto source_rect = layer.rect.translated(-layer_surface->rect.location());- SkPaint paint;- paint.setBlendMode(SkBlendMode::kSrc);- surface->painting_surface().canvas().drawImageRect(image.get(), Gfx::to_skia_rect(source_rect), SkRect::MakeIWH(layer.rect.width(), layer.rect.height()), SkSamplingOptions {}, &paint, SkCanvas::kStrict_SrcRectConstraint);- presentation.latest_surface = move(surface);- presentation.rect = layer.rect;- presentation.content_version = layer_surface->content_version;- }- return true;-}--bool ContextPresenter::present_compositor_overlays_to_window_server(DisplayListPlayerSkia& display_list_player, FrameInputs const& frame_inputs, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)-{- auto bounds = frame_inputs.overlay_bounds();- m_compositor_overlay_rect = bounds;- if (bounds.is_empty()) {- m_latest_compositor_overlay_surface = nullptr;- return true;- }- auto surface_or_error = m_compositor_overlay_surfaces.surface_for_next_content(bounds.size(), skia_backend_context);- if (surface_or_error.is_error())- return false;- auto surface = surface_or_error.release_value();- auto& canvas = surface->painting_surface().canvas();- canvas.clear(SK_ColorTRANSPARENT);- auto save_count = canvas.save();- canvas.translate(-bounds.x(), -bounds.y());- paint_compositor_overlays(display_list_player, surface->painting_surface(), frame_inputs, PaintUIOverlay::Yes);- canvas.restoreToCount(save_count);- m_latest_compositor_overlay_surface = move(surface);- return true;-}--// Sublayers keep their identity from one frame to the next by what they show.-static constexpr u64 canvas_sublayer_identity_tag = u64 { 1 } << 60;-static constexpr u64 video_sublayer_identity_tag = u64 { 2 } << 60;-static constexpr u64 painted_layer_sublayer_identity_tag = u64 { 3 } << 60;-static constexpr u64 compositor_overlay_sublayer_identity = u64 { 4 } << 60;-// Canvas and video IDs count up from 1, and stay far below this.-static constexpr u64 media_drawing_index_shift = 44;--Vector<RemoteSublayer> ContextPresenter::sublayers_shown_by_window_server()-{- Vector<RemoteSublayer> sublayers;- if (!m_window_server_shows_media || !m_layer_plan)- return sublayers;- // The same canvas or video can be drawn by more than one record, and each drawing is a sublayer of its own.- HashMap<u64, u64> drawings_of_media;- auto layers = m_layer_plan->layers();- for (size_t index = 1; index < layers.size(); ++index) {- auto const& layer = layers[index];- if (layer.kind == LayerKind::Media) {- auto const& placement = *layer.window_server_placement;- Optional<Variant<NonnullRefPtr<Media::VideoFrame>, PresentableSurface::Lease>> content;- u64 identity = 0;- if (layer.media.kind == RustFFI::FfiLiveMediaKind::Canvas) {- if (auto surface = m_canvas_surfaces.presentable_canvas_surface(Compositing::CanvasId { layer.media.id }))- content = surface->lease();- identity = canvas_sublayer_identity_tag | layer.media.id;- } else {- if (auto frame = current_video_frame(Compositing::VideoSinkResourceId { layer.media.id }); frame && frame->surface())- content = frame.release_nonnull();- identity = video_sublayer_identity_tag | layer.media.id;- }- if (!content.has_value())- continue;- auto& earlier_drawings = drawings_of_media.ensure(identity, [] { return 0; });- identity |= earlier_drawings++ << media_drawing_index_shift;- sublayers.append({- .identity = identity,- .content = content.release_value(),- .content_rect = placement.content_rect,- .content_to_frame = placement.content_to_viewport,- .clip_rect = placement.clip_rect,- .rounded_clip = placement.rounded_clip,- .scaling_mode = placement.scaling_mode,- });- continue;- }- if (index >= m_painted_layer_presentations.size() || !m_painted_layer_presentations[index].latest_surface)- continue;- auto const& presentation = m_painted_layer_presentations[index];- sublayers.append({- .identity = painted_layer_sublayer_identity_tag | index,- .content = presentation.latest_surface->lease(),- .content_rect = presentation.rect,- .content_to_frame = {},- .clip_rect = presentation.rect.to_type<float>(),- .rounded_clip = {},- .scaling_mode = Gfx::ScalingMode::NearestNeighbor,- });- }- if (m_latest_compositor_overlay_surface) {- sublayers.append({- .identity = compositor_overlay_sublayer_identity,- .content = m_latest_compositor_overlay_surface->lease(),- .content_rect = m_compositor_overlay_rect,- .content_to_frame = {},- .clip_rect = m_compositor_overlay_rect.to_type<float>(),- .rounded_clip = {},- .scaling_mode = Gfx::ScalingMode::NearestNeighbor,- });- }- 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) {- 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);- };-- if (damage_rect.has_value() && !damage_rect->is_empty() && presents_to_client() && damage_rect->size() != surface.size() && surface.skia_backend_context()) {- if (!m_damage_surface || m_damage_surface->size() != damage_rect->size()) {- m_damage_surface = Gfx::PaintingSurface::create_with_size(- damage_rect->size(), Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, surface.skia_backend_context());- }-- auto& damage_canvas = m_damage_surface->canvas();- damage_canvas.clear(surface_clear_color);- damage_canvas.save();- damage_canvas.translate(-damage_rect->x(), -damage_rect->y());- paint_display_list(*m_damage_surface);- damage_canvas.restore();-- auto image = m_damage_surface->sk_image_snapshot<sk_sp<SkImage>>();- SkPaint paint;- paint.setBlendMode(SkBlendMode::kSrc);- surface.canvas().drawImageRect(- image.get(),- SkRect::MakeWH(damage_rect->width(), damage_rect->height()),- SkRect::MakeXYWH(damage_rect->x(), damage_rect->y(), damage_rect->width(), damage_rect->height()),- SkSamplingOptions {},- &paint,- SkCanvas::kStrict_SrcRectConstraint);- return;- }-- auto& canvas = surface.canvas();- auto save_count = canvas.save();- if (damage_rect.has_value()) {- canvas.clipIRect(SkIRect::MakeXYWH(damage_rect->x(), damage_rect->y(), damage_rect->width(), damage_rect->height()));- canvas.clear(surface_clear_color);- }- if (apply_raster_transform) {- canvas.translate(m_raster_translation.x(), m_raster_translation.y());- canvas.scale(m_raster_scale.width(), m_raster_scale.height());- }- paint_display_list(surface);- canvas.restoreToCount(save_count);-}--}diff --git a/Services/Compositor/ContextPresenter.h b/Services/Compositor/ContextPresenter.hdeleted file mode 100644index 414f3ee4728..00000000000--- a/Services/Compositor/ContextPresenter.h+++ /dev/null@@ -1,264 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Function.h>-#include <AK/HashMap.h>-#include <AK/Noncopyable.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/RefPtr.h>-#include <AK/Vector.h>-#include <Compositor/BackingStoreManager.h>-#include <Compositor/CanvasSurfaceRegistry.h>-#include <Compositor/CompositedContext.h>-#include <Compositor/CompositorCoreHost.h>-#include <Compositor/ContextLayers.h>-#include <Compositor/DisplayListRasterCache.h>-#include <Compositor/Forward.h>-#include <Compositor/FrameInputs.h>-#include <Compositor/PaintingSurface.h>-#include <Compositor/PresentableSurface.h>-#include <Compositor/RemoteLayer.h>-#include <LibCompositing/DisplayList/AccumulatedVisualContext.h>-#include <LibCompositing/DisplayList/DisplayList.h>-#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>-#include <LibCompositing/Forward.h>-#include <LibCompositing/Types.h>-#include <LibCore/Forward.h>-#include <LibGfx/Rect.h>-#include <LibGfx/ShareableBitmap.h>-#include <LibGfx/Size.h>-#include <LibMediaCodecs/VideoFrame.h>--namespace Gfx {--class SkiaBackendContext;--}--namespace Compositor {--struct PreparedFrame {- // Null for a frame that changes only what the window server shows above the frame.- Gfx::PaintingSurface* rendered_surface { nullptr };- i32 bitmap_id { 0 };- Gfx::IntRect damage_rect;- double device_pixel_ratio { 1.0 };- // What the window server shows above the frame, bottom to top.- Vector<RemoteSublayer> sublayers;-};--// Rasterizes the scene of a context into its backing stores and keeps track of the frames it presents.-class ContextPresenter {- AK_MAKE_NONCOPYABLE(ContextPresenter);- AK_MAKE_NONMOVABLE(ContextPresenter);--public:- ContextPresenter(OwnedCanvasSurfaces, bool presents_to_client);- ~ContextPresenter();-- bool has_display_list() const { return m_display_list; }- void set_display_list(NonnullRefPtr<Compositing::DisplayList const>);- Compositing::DisplayListResourceStorage& resource_storage() { return m_resource_storage; }- Compositing::DisplayListResourceStorage const& resource_storage() const { return m_resource_storage; }- void apply_resource_transaction(Compositing::DisplayListResourceTransaction&&);-- bool presents_to_client() const { return m_presents_to_client; }- void stop_presenting_to_client() { m_presents_to_client = false; }-- // The remote layer that may show the canvases and videos of the frames above them, instead of the frames holding- // them.- void set_remote_layer_that_may_show_media(RemoteLayer const* remote_layer) { m_remote_layer_that_may_show_media = remote_layer; }- // Otherwise, the frame draws HDR content tone-mapped to SDR.- void set_window_server_may_show_high_dynamic_range(bool may_show) { m_window_server_may_show_high_dynamic_range = may_show; }- void did_deliver_frame_without_store() { m_frame_without_store_in_flight = false; }-- Gfx::IntSize viewport_size() const { return m_viewport_size; }- double device_pixel_ratio() const { return m_device_pixel_ratio; }- void set_viewport_size(Gfx::IntSize, double device_pixel_ratio, Compositing::WindowResizingInProgress);- bool window_resize_in_progress() const { return m_window_resize_in_progress == Compositing::WindowResizingInProgress::Yes; }- bool should_shrink_backing_stores_after_resize() const;- void schedule_backing_store_shrink(Function<void()>);- void finish_window_resize();-- // The viewport rect of the next frame, or of the frame presented last.- Optional<Gfx::IntRect> viewport_rect_for_ui_overlay() const;- // Shapes a label of the overlays, in a font that the overlays' resources then hold.- Optional<OverlayLabel> shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text);-- ErrorOr<Optional<BackingStoreManager::Publication>> resize_backing_stores_if_needed(RefPtr<Gfx::SkiaBackendContext> const&, BackingStoreManager::GpuSharing, BackingStoreManager::PublicationMode, RefPtr<WindowServer> window_server_showing_stores = {});- void invalidate_backing_stores();- Optional<BackingStoreManager::Publication> add_backing_store_for_pending_frame_if_needed(RefPtr<Gfx::SkiaBackendContext> const&);- bool has_surplus_backing_stores() const { return m_backing_store_manager.has_surplus_backing_stores(); }- Vector<i32> retire_idle_surplus_backing_stores() { return m_backing_store_manager.retire_idle_surplus_backing_stores(); }- void schedule_surplus_backing_store_retirement(Function<void()>);- bool acknowledge_presented_bitmap(i32 bitmap_id);- void acknowledge_all_presented_bitmaps() { m_backing_store_manager.release_all_presented_buffers(); }- void did_finish_gpu_present(i32 bitmap_id, Gfx::IntSize frame_size);- RefPtr<Gfx::PaintingSurface> latest_rendered_surface() const { return m_latest_rendered_surface; }- PresentableSurface* window_server_surface_of_latest_rendered_store() const { return m_backing_store_manager.window_server_surface_of_latest_rendered_store(); }- BackingStoreManager::PublicationMode backing_store_publication_mode() const { return m_backing_store_manager.publication_mode(); }-- bool update_composited_raster_transform(Gfx::FloatRect destination_rect, Gfx::FloatMatrix4x4 const& canvas_transform);- CompositedContextSurface composited_surface() const;-- void queue_present_frame(PendingFrame);- void mark_pending_present_frame_scheduled();- void unschedule_pending_present_frame() { m_pending_present_frame_scheduled = false; }- bool pending_present_frame_scheduled() const { return m_pending_present_frame_scheduled; }- bool can_schedule_pending_present_frame_if_unblocked() const;- Optional<PendingFrame> take_pending_present_frame_if_unblocked();- bool needs_rasterization() const;- Optional<Gfx::IntRect> frame_rect_to_repaint() const;- Optional<Gfx::IntRect> self_present_rect() const;- bool draws_canvas(Compositing::CanvasId) const;-- // The inputs are empty for a context that has no display list yet.- Optional<PreparedFrame> prepare_frame(DisplayListPlayerSkia&, PendingFrame, Optional<FrameInputs>&&, CompositedContextResolver const*);- void did_submit_prepared_frame(Gfx::IntRect);- bool present_synchronously(DisplayListPlayerSkia&, Optional<FrameInputs>&&, CompositedContextResolver const*);- void paint_screenshot(DisplayListPlayerSkia&, Gfx::ShareableBitmap&, FrameInputs const&, CompositedContextResolver const*);- // The frame on screen, read back from the store that holds it, and scaled down to fit within the size given.- Optional<Gfx::ShareableBitmap> snapshot_of_presented_frame(DisplayListPlayerSkia&, Optional<Gfx::IntSize> maximum_size);--private:- struct RasterizedFrame {- NonnullRefPtr<Compositing::DisplayList const> display_list;- FrameInputs frame_inputs;- Gfx::IntSize viewport_size;- HashMap<Compositing::CanvasId, u64> canvas_content_generations;- HashMap<Compositing::VideoSinkResourceId, Optional<u64>> video_frame_ids;- HashMap<u64, u64> image_frame_pixel_generations;- };-- enum class PaintUIOverlay : u8 {- No,- Yes,- };-- struct LiveContentChangesSinceLastRaster {- Vector<Compositing::CanvasId> canvases;- Vector<Compositing::VideoSinkResourceId> video_sinks;- Vector<Compositing::ImageFrameResourceId> image_frames;- Vector<MediaActivity::Update> media_updates;- bool repaints_everything { false };- };-- struct LayerSurface {- RefPtr<Gfx::PaintingSurface> surface;- Gfx::IntRect rect;- // Changes whenever anything is drawn into the surface.- u64 content_version { 0 };- };-- // The surface that the window server shows a painted layer from.- struct PaintedLayerPresentation {- PresentableSurfacePool surfaces;- RefPtr<PresentableSurface> latest_surface;- Gfx::IntRect rect;- u64 content_version { 0 };- };-- struct LayerUpdate {- OwnPtr<LayerPlan> new_plan;- bool keeps_plan { false };- Vector<LiveMedia> active_media;- Gfx::IntRect painted_damage;- Vector<Gfx::IntRect> damage_of_layers;- u32 fully_repainted_layer_bits { 0 };- bool repaints_everything { false };- bool shown_by_window_server { false };-- bool has_plan() const { return new_plan || keeps_plan; }- };-- struct FrameDamage {- Gfx::IntRect rect;- LayerUpdate layers;- bool live_media_changed { false };- };-- bool is_present_blocked() const;- bool can_render_frame() const;- // 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);- bool window_server_can_show_media_layers_of(LayerPlan const&);- bool present_painted_layers_to_window_server(LayerPlan const&, RefPtr<Gfx::SkiaBackendContext> const&);- bool present_compositor_overlays_to_window_server(DisplayListPlayerSkia&, FrameInputs const&, RefPtr<Gfx::SkiaBackendContext> const&);- Vector<RemoteSublayer> sublayers_shown_by_window_server();- RefPtr<Media::VideoFrame> current_video_frame(Compositing::VideoSinkResourceId);- void paint_compositor_overlays(DisplayListPlayerSkia&, Gfx::PaintingSurface&, FrameInputs const&, PaintUIOverlay);- Gfx::IntSize raster_size() const;- Gfx::IntRect raster_damage_rect(Gfx::IntRect) const;- FrameDamage frame_damage_for(PendingFrame const&, FrameInputs const&);- LiveContentChangesSinceLastRaster live_content_changes_since_last_raster(Gfx::IntSize viewport_size);- DisplayListDamage damage_since_last_raster(Gfx::IntSize viewport_size, FrameInputs const&, Gfx::IntRect forced_damage_rect, LiveContentChangesSinceLastRaster const&, ReadonlySpan<u32> offsets_of_records_composited_as_media_layers, LayerPlan const* last_layer_plan, LayerPlan const* layer_plan);- LayerUpdate layer_update_for(FrameInputs const&, Gfx::IntRect viewport_rect, MonotonicTime now);- void commit_layer_update(LayerUpdate&&);- void drop_layers();- void remember_rasterized_frame(Gfx::IntSize viewport_size, FrameInputs&&);- Optional<u64> current_video_frame_id(Compositing::VideoSinkResourceId);- void stop_backing_store_shrink_timer();- void stop_surplus_backing_store_retirement_timer();- void stop_layer_drop_timer();-- RefPtr<Compositing::DisplayList const> m_display_list;- Compositing::DisplayListResourceStorage m_resource_storage;- DisplayListRasterCache m_raster_cache;- OwnedCanvasSurfaces m_canvas_surfaces;- bool m_presents_to_client { false };-- Gfx::IntSize m_viewport_size;- double m_device_pixel_ratio { 1.0 };- Compositing::WindowResizingInProgress m_window_resize_in_progress { Compositing::WindowResizingInProgress::No };- // The resources that the overlays draw with, apart from those of the page.- Compositing::DisplayListResourceStorage m_overlay_resource_storage;- DisplayListRasterCache m_overlay_raster_cache;-- BackingStoreManager m_backing_store_manager;- RefPtr<Gfx::PaintingSurface> m_latest_rendered_surface;- // The frame that the latest rendered surface holds, which the presented frame runs ahead of while its GPU work is- // in flight.- Gfx::IntSize m_size_of_latest_rendered_frame;- RefPtr<Gfx::PaintingSurface> m_damage_surface;- Optional<RasterizedFrame> m_last_rasterized_frame;- Gfx::FloatSize m_unbounded_raster_scale_of_embedding { 1, 1 };- Gfx::FloatSize m_raster_scale { 1, 1 };- Gfx::FloatPoint m_raster_translation;- RefPtr<Core::Timer> m_backing_store_shrink_timer;- RefPtr<Core::Timer> m_surplus_backing_store_retirement_timer;-- MediaActivity m_media_activity;- OwnPtr<LayerPlan> m_layer_plan;- Vector<LiveMedia> m_layer_plan_active_media;- Vector<LayerSurface> m_layer_surfaces;- u64 m_last_layer_content_version { 0 };- bool m_repaint_everything_after_dropping_layers { false };-- RemoteLayer const* m_remote_layer_that_may_show_media { nullptr };- bool m_window_server_may_show_high_dynamic_range { true };- // Whether the window server shows the canvases and videos of the latest frame above it.- bool m_window_server_shows_media { false };- bool m_frame_without_store_in_flight { false };- Vector<PaintedLayerPresentation> m_painted_layer_presentations;- PresentableSurfacePool m_compositor_overlay_surfaces;- RefPtr<PresentableSurface> m_latest_compositor_overlay_surface;- Gfx::IntRect m_compositor_overlay_rect;- RefPtr<Core::Timer> m_layer_drop_timer;-- Optional<PendingFrame> m_pending_present_frame;- bool m_pending_present_frame_scheduled { false };- Optional<Gfx::IntRect> m_presented_frame;-};--}diff --git a/Services/Compositor/ContextRasterTargets.cpp b/Services/Compositor/ContextRasterTargets.cppnew file mode 100644index 00000000000..b330c8fcf16--- /dev/null+++ b/Services/Compositor/ContextRasterTargets.cpp@@ -0,0 +1,86 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <Compositor/ContextRasterTargets.h>+#include <Compositor/FontSkia.h>+#include <LibGfx/Font/Font.h>+#include <LibGfx/Font/FontDatabase.h>+#include <LibMedia/Sinks/VideoSink.h>+#include <core/SkFont.h>+#include <core/SkFontMetrics.h>+#include <core/SkFontTypes.h>++namespace Compositor {++ContextRasterTargets::ContextRasterTargets(OwnedCanvasSurfaces canvas_surfaces)+ : m_canvas_surfaces(canvas_surfaces)+{+}++void ContextRasterTargets::apply_resource_transaction(Compositing::DisplayListResourceTransaction&& resource_transaction)+{+ m_raster_cache.evict(m_resource_storage.apply_transaction(move(resource_transaction)));+}++Optional<OverlayLabel> ContextRasterTargets::shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text)+{+ RefPtr<Gfx::Font> font;+ if (font_family.has_value())+ font = Gfx::FontDatabase::the().get(MUST(FlyString::from_utf8(*font_family)), 12, 400, Gfx::FontWidth::Normal, 0);+ if (!font)+ font = Gfx::FontDatabase::the().get("SerenitySans"_fly_string, 12, 400, Gfx::FontWidth::Normal, 0);+ if (!font)+ return {};+ auto skia_font = Compositor::skia_font(*font, static_cast<float>(device_pixel_ratio));+ if (!skia_font.has_value())+ return {};++ OverlayLabel label;+ auto glyph_count = skia_font->countText(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8);+ Vector<SkGlyphID> glyphs;+ glyphs.resize(glyph_count);+ skia_font->textToGlyphs(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8, { glyphs.data(), glyphs.size() });+ label.glyph_x_positions.resize(glyph_count);+ skia_font->getXPos({ glyphs.data(), glyphs.size() }, { label.glyph_x_positions.data(), label.glyph_x_positions.size() });+ label.glyph_ids.ensure_capacity(glyph_count);+ for (auto glyph : glyphs)+ label.glyph_ids.unchecked_append(glyph);+ label.width = skia_font->measureText(text.characters_without_null_termination(), text.length(), SkTextEncoding::kUTF8);+ SkFontMetrics font_metrics;+ skia_font->getMetrics(&font_metrics);+ label.ascent = font_metrics.fAscent;+ label.descent = font_metrics.fDescent;+ label.font_ascent = font->pixel_metrics().ascent;+ label.font_id = m_overlay_resource_storage.add_font(*font).value();+ return label;+}++RefPtr<PresentableSurface> ContextRasterTargets::next_presentable_surface(u32 pool, Gfx::IntSize size, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)+{+ auto surface = m_presentable_surface_pools.ensure(pool).surface_for_next_content(size, skia_backend_context);+ if (surface.is_error())+ return nullptr;+ return surface.release_value();+}++RefPtr<Media::VideoFrame> ContextRasterTargets::current_video_frame(Compositing::VideoSinkResourceId video_sink_id) const+{+ auto sink = m_resource_storage.video_sink(video_sink_id);+ if (!sink)+ return {};+ return sink->current_frame();+}++bool ContextRasterTargets::draws_video_sink(Media::VideoSinkHandle handle) const+{+ for (auto const& [id, sink_handle] : m_resource_storage.video_sink_handles()) {+ if (sink_handle == handle)+ return true;+ }+ return false;+}++}diff --git a/Services/Compositor/ContextRasterTargets.h b/Services/Compositor/ContextRasterTargets.hnew file mode 100644index 00000000000..a34f7c75e40--- /dev/null+++ b/Services/Compositor/ContextRasterTargets.h@@ -0,0 +1,73 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/HashMap.h>+#include <AK/Noncopyable.h>+#include <AK/Optional.h>+#include <AK/RefPtr.h>+#include <AK/StringView.h>+#include <Compositor/BackingStoreManager.h>+#include <Compositor/CanvasSurfaceRegistry.h>+#include <Compositor/CompositorCoreHost.h>+#include <Compositor/DisplayListRasterCache.h>+#include <Compositor/PresentableSurface.h>+#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>+#include <LibGfx/Size.h>+#include <LibMediaCodecs/VideoFrame.h>++namespace Gfx {++class SkiaBackendContext;++}++namespace Compositor {++// What the frames of a context are painted with and into: its backing stores, the resources and raster caches that its+// page and the overlays draw with, and the surfaces that the window server shows above its frames. Which frame is+// painted, and what of it, is decided by the presenting logic in Rust.+class ContextRasterTargets {+ AK_MAKE_NONCOPYABLE(ContextRasterTargets);+ AK_MAKE_NONMOVABLE(ContextRasterTargets);++public:+ explicit ContextRasterTargets(OwnedCanvasSurfaces);++ Compositing::DisplayListResourceStorage& resource_storage() { return m_resource_storage; }+ Compositing::DisplayListResourceStorage const& resource_storage() const { return m_resource_storage; }+ void apply_resource_transaction(Compositing::DisplayListResourceTransaction&&);+ DisplayListRasterCache& raster_cache() { return m_raster_cache; }+ OwnedCanvasSurfaces const& canvas_surfaces() const { return m_canvas_surfaces; }++ // The resources that the overlays draw with, apart from those of the page.+ Compositing::DisplayListResourceStorage& overlay_resource_storage() { return m_overlay_resource_storage; }+ DisplayListRasterCache& overlay_raster_cache() { return m_overlay_raster_cache; }+ // Shapes a label of the overlays, in a font that the overlays' resources then hold.+ Optional<OverlayLabel> shape_overlay_label(Optional<StringView> font_family, double device_pixel_ratio, StringView text);++ BackingStoreManager& backing_stores() { return m_backing_stores; }+ BackingStoreManager const& backing_stores() const { return m_backing_stores; }++ // A surface of the pool for the next content shown from it, which the window server is not busy with.+ RefPtr<PresentableSurface> next_presentable_surface(u32 pool, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&);+ void drop_presentable_surface_pool(u32 pool) { m_presentable_surface_pools.remove(pool); }++ RefPtr<Media::VideoFrame> current_video_frame(Compositing::VideoSinkResourceId) const;+ bool draws_video_sink(Media::VideoSinkHandle) const;++private:+ Compositing::DisplayListResourceStorage m_resource_storage;+ DisplayListRasterCache m_raster_cache;+ OwnedCanvasSurfaces m_canvas_surfaces;+ Compositing::DisplayListResourceStorage m_overlay_resource_storage;+ DisplayListRasterCache m_overlay_raster_cache;+ BackingStoreManager m_backing_stores;+ HashMap<u32, PresentableSurfacePool> m_presentable_surface_pools;+};++}diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cppindex 89976636b95..7ec1ce9a79a 100644--- a/Services/Compositor/DisplayListPlayerSkia.cpp+++ b/Services/Compositor/DisplayListPlayerSkia.cpp@@ -129,14 +129,13 @@ struct DisplayListPlayerSkia::PainterCallbacks {}};-RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSurface& surface, DisplayListResourceStorage const& resource_storage, DisplayListRasterCache& raster_cache, OwnedCanvasSurfaces const* canvas_surfaces, CompositedContextResolver const* composited_context_resolver)+RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSurface& surface, DisplayListResourceStorage const& resource_storage, DisplayListRasterCache& raster_cache, OwnedCanvasSurfaces const* canvas_surfaces){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);}@@ -150,7 +149,6 @@ void DisplayListPlayerSkia::end_painting()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)@@ -379,20 +377,12 @@ void DisplayListPlayerSkia::play_command(PaintCaret const& command)void DisplayListPlayerSkia::draw_composited_context(RustFFI::CompositedContextDraw const& command){- if (!m_composited_context_resolver)- return;-- auto destination_rect = command.dst_rect;- 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;-- auto image = composited_context.surface->sk_image_snapshot<sk_sp<SkImage>>();+ auto image = static_cast<Gfx::PaintingSurface*>(command.surface)->sk_image_snapshot<sk_sp<SkImage>>();if (!image)return;- auto dst_rect = to_skia_rect(destination_rect);- auto src_rect = to_skia_rect(composited_context.content_rect);+ auto dst_rect = to_skia_rect(command.dst_rect);+ auto src_rect = to_skia_rect(command.src_rect);auto& canvas = surface().canvas();SkPaint paint;paint.setAntiAlias(true);diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.hindex 24eedd7c9db..1fa29055982 100644--- a/Services/Compositor/DisplayListPlayerSkia.h+++ b/Services/Compositor/DisplayListPlayerSkia.h@@ -12,7 +12,6 @@#include <AK/Optional.h>#include <AK/RefPtr.h>#include <AK/Vector.h>-#include <Compositor/CompositedContext.h>#include <Compositor/Forward.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>@@ -49,11 +48,11 @@ public:// 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*);+ Compositing::RustFFI::FfiRasterPainter begin_painting(Gfx::PaintingSurface&, Compositing::DisplayListResourceStorage const&, DisplayListRasterCache&, OwnedCanvasSurfaces const*);void end_painting();- void flush(Gfx::PaintingSurface&);- void flush_async(Gfx::PaintingSurface&, Function<void()>&&);+ static void flush(Gfx::PaintingSurface&);+ static void flush_async(Gfx::PaintingSurface&, Function<void()>&&);private:struct PainterCallbacks;@@ -128,7 +127,6 @@ private:Compositing::DisplayListResourceStorage const* m_resource_storage { nullptr };DisplayListRasterCache* m_raster_cache { nullptr };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.diff --git a/Services/Compositor/FrameInputs.cpp b/Services/Compositor/FrameInputs.cppdeleted file mode 100644index beab24bef87..00000000000--- a/Services/Compositor/FrameInputs.cpp+++ /dev/null@@ -1,118 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/StdLibExtras.h>-#include <Compositor/FrameInputs.h>--namespace Compositor {--FrameInputs::FrameInputs(RustFFI::FrameInputs* frame_inputs, Compositing::AccumulatedVisualContextTree visual_context_tree)- : m_frame_inputs(frame_inputs)- , m_visual_context_tree(move(visual_context_tree))-{-}--FrameInputs FrameInputs::adopt(RustFFI::FrameInputs* frame_inputs)-{- VERIFY(frame_inputs);- return { frame_inputs, Compositing::AccumulatedVisualContextTree::adopt_rust_handle(RustFFI::compositor_frame_inputs_retain_visual_context_tree(frame_inputs)) };-}--FrameInputs::FrameInputs(FrameInputs&& other)- : m_frame_inputs(exchange(other.m_frame_inputs, nullptr))- , m_visual_context_tree(move(other.m_visual_context_tree))-{-}--FrameInputs& FrameInputs::operator=(FrameInputs&& other)-{- if (this == &other)- return *this;- if (m_frame_inputs)- RustFFI::compositor_frame_inputs_destroy(m_frame_inputs);- m_frame_inputs = exchange(other.m_frame_inputs, nullptr);- m_visual_context_tree = move(other.m_visual_context_tree);- return *this;-}--FrameInputs::~FrameInputs()-{- if (m_frame_inputs)- RustFFI::compositor_frame_inputs_destroy(m_frame_inputs);-}--ReadonlySpan<ScrollbarOfFrame> FrameInputs::scrollbars() const-{- size_t count = 0;- auto const* scrollbars = RustFFI::compositor_frame_inputs_scrollbars(m_frame_inputs, &count);- return { scrollbars, count };-}--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, &painter);-}--void FrameInputs::paint_overlays(Compositing::RustFFI::FfiRasterPainter const& painter, bool paints_ui_overlays) const-{- RustFFI::compositor_frame_inputs_paint_overlays(m_frame_inputs, &painter, paints_ui_overlays);-}--Gfx::IntRect FrameInputs::overlay_bounds() const-{- Gfx::IntRect bounds;- RustFFI::compositor_frame_inputs_overlay_bounds(m_frame_inputs, &bounds);- return bounds;-}--RustFFI::ContextLayerPlan* FrameInputs::build_layer_plan(Compositing::DisplayList const& display_list, Gfx::IntRect viewport_rect, ReadonlySpan<RustFFI::FfiLiveMedia> active_media) const-{- VERIFY(display_list.compatible_visual_context_tree_structural_epoch() == m_visual_context_tree.structural_epoch());- return RustFFI::compositor_frame_inputs_build_layer_plan(m_frame_inputs, display_list.rust_handle(), viewport_rect, active_media.data(), active_media.size());-}--bool FrameInputs::places_content_like(FrameInputs const& other) const-{- return RustFFI::compositor_frame_inputs_place_content_alike(m_frame_inputs, other.m_frame_inputs);-}--DisplayListDamage FrameInputs::damage_since(Compositing::DisplayList const& display_list, FrameInputs const& last_frame_inputs, Compositing::DisplayList const& last_display_list, Gfx::IntRect viewport_rect, LiveContentChanges live_content_changes, RustFFI::ContextLayerPlan const* last_layer_plan, RustFFI::ContextLayerPlan const* layer_plan) const-{- VERIFY(!last_layer_plan == !layer_plan);- Gfx::IntRect damage_rect;- Vector<Gfx::IntRect> layer_damage_rects;- if (layer_plan)- layer_damage_rects.resize(RustFFI::compositor_layer_plan_layer_count(layer_plan));- u32 unbounded_layer_bits = 0;- DisplayListDamage damage;- bool damage_is_bounded = RustFFI::compositor_frame_inputs_damage_since(- m_frame_inputs, display_list.rust_handle(),- last_frame_inputs.m_frame_inputs, last_display_list.rust_handle(),- viewport_rect,- live_content_changes.canvases.data(), live_content_changes.canvases.size(),- live_content_changes.video_sinks.data(), live_content_changes.video_sinks.size(),- live_content_changes.image_frames.data(), live_content_changes.image_frames.size(),- live_content_changes.forced_damage_rect,- live_content_changes.offsets_of_records_composited_as_media_layers.data(), live_content_changes.offsets_of_records_composited_as_media_layers.size(),- last_layer_plan,- layer_plan,- &damage_rect,- layer_damage_rects.data(),- &unbounded_layer_bits);- if (damage_is_bounded)- damage.rect = damage_rect;- damage.layer_rects.ensure_capacity(layer_damage_rects.size());- for (size_t index = 0; index < layer_damage_rects.size(); ++index) {- if ((unbounded_layer_bits & (1u << index)) != 0)- damage.layer_rects.unchecked_append({});- else- damage.layer_rects.unchecked_append(layer_damage_rects[index]);- }- return damage;-}--}diff --git a/Services/Compositor/FrameInputs.h b/Services/Compositor/FrameInputs.hdeleted file mode 100644index b5915a0cfe6..00000000000--- a/Services/Compositor/FrameInputs.h+++ /dev/null@@ -1,92 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#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>-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>-#include <LibGfx/Color.h>-#include <LibGfx/Rect.h>-#include <math.h>--namespace Compositor {--using PresentedScrollbar = Compositing::RustFFI::PresentedScrollbar;--using ScrollbarOfFrame = RustFFI::ScrollbarOfFrame;-using ReplaySelection = Compositing::RustFFI::FfiReplaySelection;--constexpr ReplaySelection replaying_everything()-{- return { nullptr, 0, false, false };-}--inline ReplaySelection replaying_only(ReadonlySpan<Compositing::RustFFI::RecordSpan> record_spans, bool skip_root_isolation_layer = false)-{- return { record_spans.data(), record_spans.size(), true, skip_root_isolation_layer };-}--// 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 {- ReadonlySpan<Compositing::CanvasId> canvases;- ReadonlySpan<Compositing::VideoSinkResourceId> video_sinks;- ReadonlySpan<Compositing::ImageFrameResourceId> image_frames;- // What the compositor repaints whatever the lists hold, such as a blinking caret.- Gfx::IntRect forced_damage_rect;- ReadonlySpan<u32> offsets_of_records_composited_as_media_layers;-};--struct DisplayListDamage {- // Empty where the damage has no bounds.- Optional<Gfx::IntRect> rect;- // With the frames' layer plans, the damage of each layer, empty where that has no bounds.- Vector<Optional<Gfx::IntRect>> layer_rects;-};--// What a frame is painted with besides the display list and its resources, which the scroll and input logic holds:-// where the frame presents everything that scrolls is known to it alone.-class FrameInputs {- AK_MAKE_NONCOPYABLE(FrameInputs);--public:- static FrameInputs adopt(RustFFI::FrameInputs*);- FrameInputs(FrameInputs&&);- FrameInputs& operator=(FrameInputs&&);- ~FrameInputs();-- Compositing::AccumulatedVisualContextTree const& visual_context_tree() const { return m_visual_context_tree; }- ReadonlySpan<ScrollbarOfFrame> scrollbars() 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;- // Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the- // browser.- void paint_overlays(Compositing::RustFFI::FfiRasterPainter const&, bool paints_ui_overlays) const;- // The part of the viewport that the overlays cover.- Gfx::IntRect overlay_bounds() 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;-- // What painting the list with these inputs repaints of the last frame, which painted its list with its inputs.- // Given the layer plans of both frames, which must have the same layers, also what it repaints of each layer.- DisplayListDamage damage_since(Compositing::DisplayList const&, FrameInputs const& last_frame_inputs, Compositing::DisplayList const& last_display_list, Gfx::IntRect viewport_rect, LiveContentChanges, RustFFI::ContextLayerPlan const* last_layer_plan = nullptr, RustFFI::ContextLayerPlan const* layer_plan = nullptr) const;--private:- FrameInputs(RustFFI::FrameInputs*, Compositing::AccumulatedVisualContextTree);-- RustFFI::FrameInputs* m_frame_inputs { nullptr };- Compositing::AccumulatedVisualContextTree m_visual_context_tree;-};--}diff --git a/Services/Compositor/FramePacer.cpp b/Services/Compositor/FramePacer.cppdeleted file mode 100644index 774d8e3d45f..00000000000--- a/Services/Compositor/FramePacer.cpp+++ /dev/null@@ -1,37 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Math.h>-#include <Compositor/FramePacer.h>--namespace Compositor {--void FramePacer::set_maximum_frames_per_second(double maximum_frames_per_second)-{- VERIFY(maximum_frames_per_second == maximum_frames_per_second);- VERIFY(maximum_frames_per_second > 0);- VERIFY(maximum_frames_per_second < AK::Infinity<double>);- m_maximum_frames_per_second = maximum_frames_per_second;-}--double FramePacer::frame_interval(double display_refresh_rate) const-{- auto ticks_per_frame = max(1.0, AK::ceil(display_refresh_rate / m_maximum_frames_per_second));- return ticks_per_frame * 1000.0 / display_refresh_rate;-}--bool FramePacer::is_due(MonotonicTime frame_time, double display_refresh_rate) const-{- if (!m_last_frame_time_nanoseconds.has_value())- return true;-- auto interval = frame_interval(display_refresh_rate);- auto display_interval = 1000.0 / display_refresh_rate;- auto elapsed = static_cast<double>(frame_time.nanoseconds() - *m_last_frame_time_nanoseconds) / 1'000'000.0;- return elapsed + display_interval / 2.0 >= interval;-}--}diff --git a/Services/Compositor/FramePacer.h b/Services/Compositor/FramePacer.hdeleted file mode 100644index 0cdde592cf7..00000000000--- a/Services/Compositor/FramePacer.h+++ /dev/null@@ -1,57 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Assertions.h>-#include <AK/Optional.h>-#include <AK/StdLibExtras.h>-#include <AK/Time.h>--namespace Compositor {--// Paces rendering opportunities delivered on display ticks to a maximum frame rate.-// Keeps the interval calculation and last-delivery time together for reuse.-class FramePacer {-public:- void set_maximum_frames_per_second(double);- double maximum_frames_per_second() const { return m_maximum_frames_per_second; }-- // The whole number of display ticks between two frames, in milliseconds.- double frame_interval(double display_refresh_rate) const;- bool is_due(MonotonicTime frame_time, double display_refresh_rate) const;- void did_deliver(MonotonicTime frame_time) { m_last_frame_time_nanoseconds = frame_time.nanoseconds(); }--private:- double m_maximum_frames_per_second { 60.0 };- Optional<i64> m_last_frame_time_nanoseconds;-};--// A display tick that was asked for and not delivered yet, paced to the rate it was last asked for at.-class PacedTickRequest {-public:- // Returns whether the tick had not been asked for already.- bool request(double maximum_frames_per_second)- {- m_pacer.set_maximum_frames_per_second(maximum_frames_per_second);- return !exchange(m_requested, true);- }- bool is_requested() const { return m_requested; }- double frame_interval(double display_refresh_rate) const { return m_pacer.frame_interval(display_refresh_rate); }- bool is_due(MonotonicTime frame_time, double display_refresh_rate) const { return m_pacer.is_due(frame_time, display_refresh_rate); }- void did_deliver(MonotonicTime frame_time)- {- VERIFY(m_requested);- m_requested = false;- m_pacer.did_deliver(frame_time);- }--private:- bool m_requested { false };- FramePacer m_pacer;-};--}diff --git a/Services/Compositor/RasterizeDisplayList.cpp b/Services/Compositor/RasterizeDisplayList.cppindex aed72856899..18f01f16ed8 100644--- a/Services/Compositor/RasterizeDisplayList.cpp+++ b/Services/Compositor/RasterizeDisplayList.cpp@@ -35,7 +35,7 @@ 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;- auto painter = display_list_player.begin_painting(*surface, resource_storage, raster_cache, nullptr, nullptr);+ auto painter = display_list_player.begin_painting(*surface, resource_storage, raster_cache, nullptr);display_list.replay(visual_context_tree, painter, MonotonicTime::now().nanoseconds());display_list_player.end_painting();display_list_player.flush(*surface);diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex ddc4b081f7c..3bc60104d9b 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -62,7 +62,8 @@ fn main() -> Result<(), Box<dyn Error>> {"src/ffi.rs","src/host.rs","src/frame_inputs.rs",- "src/layers.rs",+ "src/raster_host.rs",+ "src/core/presenting.rs","src/core/mod.rs",] {println!("cargo:rerun-if-changed={source}");diff --git a/Services/Compositor/Rust/src/context_state/mod.rs b/Services/Compositor/Rust/src/context_state/mod.rsindex 04e67a622f4..675a12ec45a 100644--- a/Services/Compositor/Rust/src/context_state/mod.rs+++ b/Services/Compositor/Rust/src/context_state/mod.rs@@ -456,6 +456,9 @@ impl ContextState {pub fn presents_to_client(&self) -> bool {self.presents_to_client}+ pub fn display_list(&self) -> Option<Rc<DisplayList>> {+ self.scene.display_list().clone()+ }pub fn context_id(&self) -> CompositorContextId {self.context_id}@@ -604,6 +607,8 @@ impl ContextState {return Some(damage_rect);}}+ // The core handles the timers of presenting.+ ContextTimer::BackingStoreShrink | ContextTimer::SurplusStoreRetirement | ContextTimer::LayerDrop => {}}None}diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex 6dd71fc9494..ae0720ae2ce 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -8,18 +8,18 @@mod input;pub mod messages;+pub mod presenting;mod testing;mod wheel;-use crate::context_state::{- ContextState, ContextUpdateResult, FirstWheelStepRoute, ScreenshotInputs, ScrollCapabilities,-};-use crate::frame_inputs::FrameInputs;+use crate::context_state::{ContextState, ContextUpdateResult, FirstWheelStepRoute};use crate::host::{ContextTimer, DisplayTickInputs, DisplayTickResult, Host, PendingFrame, PresentRequest, PresentScheduling,PresentationId, WebContentClientId,};use crate::overlays::UIOverlays;+use crate::presenting::ContextPresenting;+use crate::raster_host::{RasterHost, SurfaceHandle};use crate::wheel_gesture_routing::WheelGestureIdAllocator;use libcompositing_rust::ipc_types::Compositing_ContextVisibility as ContextVisibility;use libcompositing_rust::scrolling::{@@ -27,13 +27,20 @@ use libcompositing_rust::scrolling::{};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{FloatPoint, IntSize};+use presenting::{GpuBackend, PendingAsyncPresent, PresentationCapabilities};use std::cell::{Cell, RefCell};use std::collections::HashMap;use std::rc::Rc;pub struct CompositorCore {host: Rc<Host>,+ raster: RasterHost,+ gpu: GpuBackend,contexts: HashMap<CompositorContextId, RefCell<ContextState>>,+ presenting: HashMap<CompositorContextId, RefCell<ContextPresenting>>,+ presentations: RefCell<HashMap<PresentationId, PresentationCapabilities>>,+ async_presents: RefCell<Vec<PendingAsyncPresent>>,+ window_server_may_show_high_dynamic_range: Cell<bool>,present_requests: RefCell<Vec<PresentRequest>>,is_entered: Cell<bool>,wheel_gesture_id_allocator: Rc<WheelGestureIdAllocator>,@@ -105,10 +112,16 @@ impl Drop for Entered<'_> {}impl CompositorCore {- pub fn new(host: Rc<Host>, scrollbars_always_shown: bool) -> Self {+ pub fn new(host: Rc<Host>, raster: RasterHost, scrollbars_always_shown: bool, gpu: GpuBackend) -> Self {Self {host,+ raster,+ gpu,contexts: HashMap::new(),+ presenting: HashMap::new(),+ presentations: RefCell::new(HashMap::new()),+ async_presents: RefCell::new(Vec::new()),+ window_server_may_show_high_dynamic_range: Cell::new(true),present_requests: RefCell::new(Vec::new()),is_entered: Cell::new(false),wheel_gesture_id_allocator: Rc::new(WheelGestureIdAllocator::default()),@@ -116,11 +129,23 @@ impl CompositorCore {}}+ pub fn raster(&self) -> &RasterHost {+ &self.raster+ }++ /// Schedules what a message the core took asked for.+ pub fn finish_message(&self, now: MonotonicTime) {+ let _entered = self.enter();++ self.finish_entry(now);+ }+pub fn create_context(&mut self,context_id: CompositorContextId,page_id: Option<u64>,web_content_client_id: WebContentClientId,+ now: MonotonicTime,) {let _entered = Entered::new(&self.is_entered);@@ -140,13 +165,19 @@ impl CompositorCore {self.scrollbars_always_shown,))});+ self.presenting+ .insert(context_id, RefCell::new(ContextPresenting::new(page_id.is_some())));+ self.resize_backing_stores_if_needed(context_id, now);+ self.finish_entry(now);}// Also leaves the contexts nested in it without a parent.- pub fn destroy_context(&mut self, context_id: CompositorContextId) {+ pub fn destroy_context(&mut self, context_id: CompositorContextId, now: MonotonicTime) {let _entered = Entered::new(&self.is_entered);assert!(self.context_if_present(context_id).is_some());+ self.cancel_pending_async_presents_for_context(context_id);+ self.clear_parent_context(context_id, now);for (&id, possible_child_context) in &self.contexts {if id == context_id {continue;@@ -157,6 +188,11 @@ impl CompositorCore {}}self.contexts.remove(&context_id);+ self.presenting.remove(&context_id);+ self.update_scroll_capabilities();+ self.raster+ .set_maximum_display_refresh_rate(self.maximum_display_refresh_rate());+ self.finish_entry(now);}pub fn check_context_owner(@@ -176,18 +212,67 @@ impl CompositorCore {ContextOwnerCheckResult::OwnedByClient}- pub fn set_parent_context(&self, context_id: CompositorContextId, parent_context_id: Option<CompositorContextId>) {+ // What a client shows is rooted at the context presented to it, and no context is nested in itself.+ pub fn context_can_be_nested_in(+ &self,+ context_id: CompositorContextId,+ parent_context_id: CompositorContextId,+ ) -> bool {let _entered = self.enter();let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().set_parent_context(parent_context_id);+ !context.borrow().presents_to_client() && parent_context_id != context_id+ }++ pub fn presents_to_client(&self, context_id: CompositorContextId) -> bool {+ let _entered = self.enter();++ self.context_if_present(context_id)+ .is_some_and(|context| context.borrow().presents_to_client())+ }++ pub fn context_is_effectively_visible(&self, context_id: CompositorContextId) -> bool {+ let _entered = self.enter();++ self.context_if_present(context_id).is_some() && self.context_is_effectively_visible_inner(context_id)+ }++ pub fn parent_context(&self, context_id: CompositorContextId) -> Option<CompositorContextId> {+ let _entered = self.enter();++ self.context_if_present(context_id)+ .and_then(|context| context.borrow().parent_context_id())+ }++ pub fn bound_presentation(&self, context_id: CompositorContextId) -> Option<PresentationId> {+ let _entered = self.enter();++ self.context_if_present(context_id)+ .and_then(|context| context.borrow().bound_presentation())+ }++ pub fn set_parent_context(+ &self,+ context_id: CompositorContextId,+ parent_context_id: Option<CompositorContextId>,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ self.set_parent_context_inner(context_id, parent_context_id, now);+ self.finish_entry(now);}- pub fn stop_presenting_to_client(&self, context_id: CompositorContextId) {+ pub fn stop_presenting_to_client(&self, context_id: CompositorContextId, now: MonotonicTime) {let _entered = self.enter();let context = self.context_if_present(context_id).expect("context exists");+ self.unbind_presentation_inner(context_id, now);context.borrow_mut().stop_presenting_to_client();+ if let Some(presenting) = self.presenting_of(context_id) {+ presenting.borrow_mut().presents_to_client = false;+ }+ self.finish_entry(now);}pub fn viewport_size_updated(@@ -195,18 +280,37 @@ impl CompositorCore {context_id: CompositorContextId,viewport_size: IntSize,device_pixel_ratio: f64,+ window_resize_in_progress: bool,+ now: MonotonicTime,) {let _entered = self.enter();- let Some(context) = self.context_if_present(context_id) else {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {return;};let overlays_repaint_everything = context.borrow_mut().viewport_size_updated(viewport_size, device_pixel_ratio);+ let is_page_presentation_context = {+ let context = context.borrow();+ context.page_id().is_some() && context.parent_context_id().is_none()+ };+ presenting.borrow_mut().set_viewport_size(+ viewport_size,+ device_pixel_ratio,+ is_page_presentation_context && window_resize_in_progress,+ );+ self.resize_backing_stores_if_needed(context_id, now);if overlays_repaint_everything {self.request_present_repainting_everything(context_id, context);}+ if presenting.borrow().window_resize_in_progress() {+ presenting+ .borrow()+ .schedule_backing_store_shrink(context_id, &self.host);+ }+ self.finish_entry(now);}pub fn set_ui_overlays(&self, context_id: CompositorContextId, ui_overlays: UIOverlays, now: MonotonicTime) {@@ -218,6 +322,7 @@ impl CompositorCore {if context.borrow_mut().set_ui_overlays(ui_overlays, now) {self.request_present_repainting_everything(context_id, context);}+ self.finish_entry(now);}// A frame at the viewport rect the context is presented at, which repaints all of it.@@ -230,18 +335,351 @@ impl CompositorCore {});}- pub fn set_bound_presentation(&self, context_id: CompositorContextId, presentation_id: Option<PresentationId>) {+ pub fn register_presentation(&self, presentation_id: PresentationId, capabilities: PresentationCapabilities) {let _entered = self.enter();- let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().set_bound_presentation(presentation_id);+ self.presentations.borrow_mut().insert(presentation_id, capabilities);}- pub fn set_scroll_capabilities(&self, context_id: CompositorContextId, capabilities: &ScrollCapabilities) {+ // Leaves every context bound to the presentation unbound.+ pub fn unregister_presentation(&self, presentation_id: PresentationId, now: MonotonicTime) {let _entered = self.enter();- let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().set_scroll_capabilities(capabilities);+ let bound_context_ids: Vec<CompositorContextId> = self+ .contexts+ .iter()+ .filter(|(_, context)| context.borrow().bound_presentation() == Some(presentation_id))+ .map(|(&context_id, _)| context_id)+ .collect();+ for context_id in bound_context_ids {+ self.unbind_presentation_inner(context_id, now);+ }+ self.presentations.borrow_mut().remove(&presentation_id);+ self.finish_entry(now);+ }++ pub fn set_presentation_gpu_capability(+ &self,+ presentation_id: PresentationId,+ supported: bool,+ adapter_luid: u64,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ {+ let mut presentations = self.presentations.borrow_mut();+ let Some(capabilities) = presentations.get_mut(&presentation_id) else {+ return;+ };+ let gpu_presentation_adapter_luid = supported.then_some(adapter_luid);+ if capabilities.gpu_presentation_adapter_luid == gpu_presentation_adapter_luid+ && capabilities.cannot_present_gpu_images == !supported+ {+ return;+ }+ capabilities.gpu_presentation_adapter_luid = gpu_presentation_adapter_luid;+ capabilities.cannot_present_gpu_images = !supported;+ }+ // Reallocate the backing stores of the presentation's contexts so they match the new capability.+ let bound_context_ids: Vec<CompositorContextId> = self+ .contexts+ .iter()+ .filter(|(_, context)| context.borrow().bound_presentation() == Some(presentation_id))+ .map(|(&context_id, _)| context_id)+ .collect();+ for context_id in bound_context_ids {+ self.invalidate_and_resize_backing_stores(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn set_scrollbar_track_press_jumps(&self, presentation_id: PresentationId, jumps: bool) {+ let _entered = self.enter();++ if let Some(capabilities) = self.presentations.borrow_mut().get_mut(&presentation_id) {+ capabilities.scrollbar_track_press_jumps = jumps;+ }+ self.update_scroll_capabilities();+ }++ fn invalidate_and_resize_backing_stores(&self, context_id: CompositorContextId, now: MonotonicTime) {+ if let Some(presenting) = self.presenting_of(context_id) {+ let environment = self.environment(+ context_id,+ now,+ &libcompositing_rust::display_list::replay::NoCompositedContexts,+ );+ presenting.borrow_mut().invalidate_backing_stores(&environment);+ }+ self.resize_backing_stores_if_needed(context_id, now);+ }++ // Each root context presents to the presentation it is bound to. Unbound contexts keep rendering, but publish+ // nothing.+ pub fn bind_presentation(+ &self,+ context_id: CompositorContextId,+ presentation_id: PresentationId,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ if !context.borrow().presents_to_client() {+ use std::io::Write;+ let _ = writeln!(+ std::io::stderr(),+ "Compositor: Ignoring presentation binding for context {}, which is not a root context",+ context_id.0+ );+ return;+ }+ if context.borrow().bound_presentation() == Some(presentation_id) {+ return;+ }+ self.unbind_presentation_inner(context_id, now);+ context.borrow_mut().set_bound_presentation(Some(presentation_id));+ self.update_scroll_capabilities();+ // The new presentation has seen none of the context's buffers, so it gets buffers of its own.+ self.invalidate_and_resize_backing_stores(context_id, now);+ self.finish_entry(now);+ }++ pub fn set_shown_in_remote_layer(&self, context_id: CompositorContextId, shown: bool, now: MonotonicTime) {+ let _entered = self.enter();++ if shown {+ self.start_showing_context_in_remote_layer(context_id, now);+ } else {+ self.stop_showing_context_in_remote_layer(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn set_display_metadata(+ &self,+ context_id: CompositorContextId,+ display_id: Option<u64>,+ refresh_rate: f64,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ assert!(refresh_rate.is_finite() && refresh_rate > 0.0);+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ let (pending_present_frame_scheduled, wants_ticks) = {+ let mut presenting = presenting.borrow_mut();+ presenting.display_id = display_id;+ presenting.display_refresh_rate = refresh_rate;+ (+ presenting.pending_present_frame_scheduled(),+ presenting.rendering_opportunity_request.is_requested() || presenting.clock_tick_request.is_requested(),+ )+ };+ if pending_present_frame_scheduled {+ self.schedule_pending_present_frame(context_id, now);+ }+ self.raster+ .set_maximum_display_refresh_rate(self.maximum_display_refresh_rate());+ if wants_ticks && self.context_is_effectively_visible_inner(context_id) {+ let (display_id, refresh_rate) = self.display_of(context_id);+ self.raster.request_vsync(display_id, refresh_rate);+ }+ self.finish_entry(now);+ }++ pub fn set_window_server_may_show_high_dynamic_range(&self, may_show: bool, now: MonotonicTime) {+ let _entered = self.enter();++ if self.window_server_may_show_high_dynamic_range.replace(may_show) == may_show {+ return;+ }+ let context_ids: Vec<CompositorContextId> = self.presenting.keys().copied().collect();+ for context_id in context_ids {+ self.present_current_frame(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn set_presents_from_cpu_memory(+ &self,+ context_id: CompositorContextId,+ presents_from_cpu_memory: bool,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ if presenting.borrow().presents_from_cpu_memory == presents_from_cpu_memory {+ return;+ }+ let previous_gpu_sharing = self.gpu_sharing_allowed(context_id);+ presenting.borrow_mut().presents_from_cpu_memory = presents_from_cpu_memory;+ // NB: Without a GPU, the backing stores are in CPU memory either way.+ if !self.gpu.has_gpu || self.gpu_sharing_allowed(context_id) == previous_gpu_sharing {+ return;+ }+ // NB: Otherwise, the presentation would read every frame back from GPU memory on its main thread.+ self.invalidate_and_resize_backing_stores(context_id, now);+ self.finish_entry(now);+ }++ pub fn request_rendering_opportunity(+ &self,+ context_id: CompositorContextId,+ maximum_frames_per_second: f64,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ self.request_rendering_opportunity_inner(context_id, maximum_frames_per_second, now);+ }++ // Asks for the next display tick the context's maximum rate lets through, for its render clock.+ pub fn request_clock_tick(&self, context_id: CompositorContextId, maximum_frames_per_second: f64) {+ let _entered = self.enter();++ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ if !presenting+ .borrow_mut()+ .clock_tick_request+ .request(maximum_frames_per_second)+ || !self.context_is_effectively_visible_inner(context_id)+ {+ return;+ }+ let (display_id, refresh_rate) = self.display_of(context_id);+ self.raster.request_vsync(display_id, refresh_rate);+ }++ // Delivers the rendering opportunity a context requested now rather than at the next display tick: a viewport+ // change that arrived while an animation's opportunity was outstanding starts its update at once.+ pub fn hurry_rendering_opportunity(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let _entered = self.enter();++ self.hurry_rendering_opportunity_inner(context_id, now);+ }++ // A frame the page laid out at the viewport rect.+ pub fn present_frame_of_page(+ &self,+ context_id: CompositorContextId,+ viewport_rect: libgfx_rust::IntRect,+ now: MonotonicTime,+ ) {+ let _entered = self.enter();++ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ {+ let mut presenting = presenting.borrow_mut();+ presenting.size_laid_out_by_page = IntSize {+ width: viewport_rect.width,+ height: viewport_rect.height,+ };+ // The frame joins whatever is queued, so a frame queued earlier cannot be presented after it.+ presenting.queue_present_frame(PendingFrame::repainting_changes(viewport_rect));+ }+ if !self.try_present_frame_during_resize(context_id, now) {+ self.schedule_pending_present_frame(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn presented_store_released(&self, context_id: CompositorContextId, bitmap_id: i32, now: MonotonicTime) {+ let _entered = self.enter();++ if self.presenting_of(context_id).is_none() {+ return;+ }+ if !self.raster.release_store(context_id, bitmap_id) {+ return;+ }+ self.schedule_pending_present_frame_if_unblocked(context_id, now);+ self.finish_entry(now);+ }++ pub fn vsync(&self, display_id: Option<u64>, frame_time: MonotonicTime, now: MonotonicTime) {+ let _entered = self.enter();++ self.vsync_inner(display_id, frame_time, now);+ self.finish_entry(now);+ }++ pub fn gpu_work_finished(&self, token: u64, now: MonotonicTime) {+ let _entered = self.enter();++ self.gpu_work_finished_inner(token, now);+ self.finish_entry(now);+ }++ pub fn frame_ready_for_hand_off(&self, token: u64, now: MonotonicTime) {+ let _entered = self.enter();++ self.frame_ready_for_hand_off_inner(token, now);+ self.finish_entry(now);+ }++ // A video sink or an image frame that the context draws has new pixels.+ pub fn context_content_changed(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let _entered = self.enter();++ self.present_changed_live_content(context_id, now);+ self.finish_entry(now);+ }++ // A canvas of the client has new pixels, which the contexts that drew it last show next.+ pub fn canvas_content_changed(&self, client: WebContentClientId, canvas_id: u64, now: MonotonicTime) {+ let _entered = self.enter();++ let context_ids: Vec<CompositorContextId> = self+ .contexts+ .iter()+ .filter(|(context_id, context)| {+ context.borrow().is_owned_by(client)+ && self+ .presenting_of(**context_id)+ .is_some_and(|presenting| presenting.borrow().draws_canvas(canvas_id))+ })+ .map(|(&context_id, _)| context_id)+ .collect();+ for context_id in context_ids {+ self.present_changed_live_content(context_id, now);+ }+ self.finish_entry(now);+ }++ pub fn paint_screenshot(+ &self,+ context_id: CompositorContextId,+ target: &SurfaceHandle,+ now: MonotonicTime,+ ) -> bool {+ let _entered = self.enter();++ let painted = self.paint_screenshot_inner(context_id, target, now);+ self.finish_entry(now);+ painted+ }++ pub fn presented_frame_for_snapshot(+ &self,+ context_id: CompositorContextId,+ now: MonotonicTime,+ ) -> Option<(SurfaceHandle, IntSize)> {+ let _entered = self.enter();++ self.presented_frame_for_snapshot_inner(context_id, now)}// Returns false, leaving everything as it was, for scrolling state with numbers no scroll can be calculated with.@@ -256,9 +694,14 @@ impl CompositorCore {let _entered = self.enter();let context = self.context_if_present(context_id).expect("context exists");- context- .borrow_mut()- .install_display_list_update(display_list, visual_context_tree, scroll_state_snapshot, now)+ let installed = context.borrow_mut().install_display_list_update(+ display_list,+ visual_context_tree,+ scroll_state_snapshot,+ now,+ );+ self.finish_entry(now);+ installed}// Returns false for a tree that does not fit the installed display list, of which only the scroll state is taken.@@ -273,47 +716,40 @@ impl CompositorCore {let _entered = self.enter();let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().update_visual_context_tree(+ let replaced = context.borrow_mut().update_visual_context_tree(visual_context_tree,scroll_state_snapshot,keyboard_scroll_state,now,- )+ );+ self.finish_entry(now);+ replaced}- pub fn needs_animation_frames(&self, context_id: CompositorContextId, now: MonotonicTime) -> bool {- let _entered = self.enter();-- let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().needs_animation_frames(now)- }-- pub fn frame_inputs(&self, context_id: CompositorContextId, now: MonotonicTime) -> Option<FrameInputs> {- let _entered = self.enter();-- let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().frame_inputs(now)- }-- pub fn frame_inputs_for_screenshot(&self, context_id: CompositorContextId, now: MonotonicTime) -> ScreenshotInputs {- let _entered = self.enter();-- let context = self.context_if_present(context_id).expect("context exists");- context.borrow_mut().frame_inputs_for_screenshot(now)- }-- // Ends the fling of a context that is hidden, whether or not it was visible.- pub fn set_visibility(&self, context_id: CompositorContextId, visibility: ContextVisibility, now: MonotonicTime) {+ // Ends the fling of a context that is hidden, whether or not it was visible. Answers whether the context became+ // visible.+ pub fn set_visibility(+ &self,+ context_id: CompositorContextId,+ visibility: ContextVisibility,+ now: MonotonicTime,+ ) -> bool {let _entered = self.enter();let Some(context) = self.context_if_present(context_id) else {- return;+ return false;};if visibility == ContextVisibility::Hidden {let event = context.borrow_mut().end_scroll_fling();self.dispatch_scroll_fling_step(context_id, context, event, now);}+ let became_visible = context.borrow().visibility() != visibility && visibility == ContextVisibility::Visible;context.borrow_mut().set_visibility(visibility);+ if became_visible {+ self.resume_presentation_after_becoming_visible(context_id, now);+ }+ self.finish_entry(now);+ became_visible}pub fn timer_fired(&self, context_id: CompositorContextId, timer: ContextTimer, now: MonotonicTime) {@@ -322,22 +758,37 @@ impl CompositorCore {let Some(context) = self.context_if_present(context_id) else {return;};- let caret_damage_rect = context.borrow_mut().timer_fired(timer, now);- if let Some(caret_damage_rect) = caret_damage_rect {- self.present_requests.borrow_mut().push(PresentRequest {- context_id,- viewport_rect: None,- forced_damage_rect: caret_damage_rect,- scheduling: PresentScheduling::OnNextDisplayTick,- });+ match timer {+ ContextTimer::BackingStoreShrink => {+ if let Some(presenting) = self.presenting_of(context_id) {+ presenting.borrow_mut().finish_window_resize();+ }+ self.resize_backing_stores_if_needed(context_id, now);+ }+ ContextTimer::SurplusStoreRetirement => self.retire_idle_surplus_backing_stores(context_id),+ ContextTimer::LayerDrop => {+ if let Some(presenting) = self.presenting_of(context_id) {+ let environment = self.environment(+ context_id,+ now,+ &libcompositing_rust::display_list::replay::NoCompositedContexts,+ );+ presenting.borrow_mut().layer_drop_timer_fired(&environment);+ }+ }+ _ => {+ let caret_damage_rect = context.borrow_mut().timer_fired(timer, now);+ if let Some(caret_damage_rect) = caret_damage_rect {+ self.present_requests.borrow_mut().push(PresentRequest {+ context_id,+ viewport_rect: None,+ forced_damage_rect: caret_damage_rect,+ scheduling: PresentScheduling::OnNextDisplayTick,+ });+ }+ }}- }-- // The frames asked for since the last call, in the order they were asked for.- pub fn take_present_requests(&self) -> Vec<PresentRequest> {- let _entered = self.enter();-- std::mem::take(&mut *self.present_requests.borrow_mut())+ self.finish_entry(now);}pub(super) fn context_still_nested_in(@@ -399,15 +850,13 @@ impl CompositorCore {});}- pub fn display_tick(+ pub(super) fn display_tick_inner(&self,context_id: CompositorContextId,frame_time: MonotonicTime,now: MonotonicTime,inputs: &DisplayTickInputs,) -> DisplayTickResult {- let _entered = self.enter();-let context = self.context_if_present(context_id).expect("context exists");let has_active_animation_on_display =diff --git a/Services/Compositor/Rust/src/core/presenting.rs b/Services/Compositor/Rust/src/core/presenting.rsnew file mode 100644index 00000000000..7815a6bd288--- /dev/null+++ b/Services/Compositor/Rust/src/core/presenting.rs@@ -0,0 +1,1118 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! When the frames of the contexts are presented, the frames in flight on the GPU, and whom each is delivered to.++use super::CompositorCore;+use crate::context_state::ContextState;+use crate::host::{PendingFrame, PresentScheduling, PresentationId};+use crate::presenting::{ContextPresenting, PresentingEnvironment};+use crate::raster_host::{+ FfiRemoteLayerFrame, FrameHandOff, StorePublication, StoreResizeOutcome, SublayersHandle, SurfaceHandle,+};+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::display_list::replay::{CompositedContexts, NoCompositedContexts, ResolvedCompositedContext};+use libcompositing_rust::ipc_types::{+ Compositing_ContextVisibility as ContextVisibility, compositor_presentation_client, compositor_web_content_client,+};+use libcompositing_rust::scrolling::wheel_gesture_identity::TouchpadGestureEnd;+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::{FloatMatrix4x4, FloatRect, IntRect, IntSize};+use std::cell::RefCell;++/// A frame submitted to the GPU, which is delivered once its work is done, or once it is scheduled where the window+/// server waits for it.+pub(crate) struct PendingAsyncPresent {+ token: u64,+ context_id: CompositorContextId,+ viewport_rect: IntRect,+ damage_rect: IntRect,+ bitmap_id: i32,+ device_pixel_ratio: f64,+ was_cancelled: bool,+ was_delivered: bool,+ // A frame that started rendering before its context was bound has no published buffer to present to.+ publish_to_presentation: bool,+ shows_in_remote_layer: bool,+ // A frame that changes only what the window server shows above the frame on screen.+ keeps_shown_store: bool,+ sublayers: Option<SublayersHandle>,+}++// What delivering a frame needs of its pending present.+struct Delivery {+ context_id: CompositorContextId,+ viewport_rect: IntRect,+ damage_rect: IntRect,+ bitmap_id: i32,+ device_pixel_ratio: f64,+ publish_to_presentation: bool,+ shows_in_remote_layer: bool,+ keeps_shown_store: bool,+ sublayers: Option<SublayersHandle>,+}++/// What a presentation makes of the frames and the scrolling of the contexts it shows.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PresentationCapabilities {+ pub synthesizes_scroll_momentum: bool,+ pub scrolls_elastically: bool,+ // Whether a press on a scrollbar track beside the thumb jumps there rather than paging toward it.+ pub scrollbar_track_press_jumps: bool,+ // LUID of the GPU adapter the presentation can present shared GPU textures on, if any.+ pub gpu_presentation_adapter_luid: Option<u64>,+ // Whether the presentation found it cannot present the shared GPU images it was given.+ pub cannot_present_gpu_images: bool,+}++/// The GPU the compositor renders with, as presenting shared stores depends on it.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct GpuBackend {+ pub has_gpu: bool,+ // Whether a presentation opens shared GPU stores only on the adapter they were made on.+ pub shared_stores_need_the_same_adapter: bool,+ pub adapter_luid: u64,+}++// The frames of the contexts nested in a context, which its replay draws, painted at once where they are behind.+struct ContextsNestedIn<'a> {+ core: &'a CompositorCore,+ parent_context_id: CompositorContextId,+ now: MonotonicTime,+}++impl CompositedContexts for ContextsNestedIn<'_> {+ fn resolve(+ &self,+ child_context_id: u64,+ destination_rect: FloatRect,+ canvas_matrix: &FloatMatrix4x4,+ ) -> Option<ResolvedCompositedContext> {+ self.core.resolve_composited_context(+ self.parent_context_id,+ CompositorContextId(child_context_id),+ destination_rect,+ canvas_matrix,+ self.now,+ )+ }+}++impl CompositorCore {+ pub(super) fn presenting_of(&self, context_id: CompositorContextId) -> Option<&RefCell<ContextPresenting>> {+ self.presenting.get(&context_id)+ }++ pub(super) fn environment<'a>(+ &'a self,+ context_id: CompositorContextId,+ now: MonotonicTime,+ composited_contexts: &'a dyn CompositedContexts,+ ) -> PresentingEnvironment<'a> {+ PresentingEnvironment {+ context_id,+ raster: &self.raster,+ host: &self.host,+ now,+ has_gpu: self.gpu.has_gpu,+ window_server_may_show_high_dynamic_range: self.window_server_may_show_high_dynamic_range.get(),+ composited_contexts,+ }+ }++ fn root_context_id_of(&self, context_id: CompositorContextId) -> CompositorContextId {+ let mut current = context_id;+ for _ in 0..=self.contexts.len() {+ let Some(parent) = self+ .context_if_present(current)+ .and_then(|context| context.borrow().parent_context_id())+ else {+ return current;+ };+ if self.context_if_present(parent).is_none() {+ return current;+ }+ current = parent;+ }+ current+ }++ pub(super) fn context_is_effectively_visible_inner(&self, context_id: CompositorContextId) -> bool {+ self.context_if_present(self.root_context_id_of(context_id))+ .is_some_and(|root| root.borrow().visibility() == ContextVisibility::Visible)+ }++ // The display a context is shown on and its refresh rate: its own, or those of the nearest context it is nested in+ // that knows its display.+ pub(super) fn display_of(&self, context_id: CompositorContextId) -> (Option<u64>, f64) {+ let own_refresh_rate = self+ .presenting_of(context_id)+ .map_or(60.0, |presenting| presenting.borrow().display_refresh_rate);+ let mut current = Some(context_id);+ for _ in 0..=self.contexts.len() {+ let Some(id) = current else { break };+ if let Some(presenting) = self.presenting_of(id) {+ let presenting = presenting.borrow();+ if presenting.display_id.is_some() {+ return (presenting.display_id, presenting.display_refresh_rate);+ }+ }+ current = self+ .context_if_present(id)+ .and_then(|context| context.borrow().parent_context_id());+ }+ (None, own_refresh_rate)+ }++ fn request_vsync_for(&self, context_id: CompositorContextId) {+ let (display_id, refresh_rate) = self.display_of(context_id);+ self.raster.request_vsync(display_id, refresh_rate);+ }++ /// Schedules the frames and display ticks that the call that is ending asked for.+ pub(super) fn finish_entry(&self, now: MonotonicTime) {+ loop {+ let requests = std::mem::take(&mut *self.present_requests.borrow_mut());+ let display_tick_requests = self.host.take_display_tick_requests();+ if requests.is_empty() && display_tick_requests.is_empty() {+ break;+ }+ for context_id in display_tick_requests {+ if self.presenting_of(context_id).is_some() && self.context_is_effectively_visible_inner(context_id) {+ self.request_vsync_for(context_id);+ }+ }+ for request in requests {+ let Some(presenting) = self.presenting_of(request.context_id) else {+ continue;+ };+ let viewport_rect = request+ .viewport_rect+ .or_else(|| presenting.borrow().viewport_rect_of_current_frame());+ let Some(viewport_rect) = viewport_rect else {+ continue;+ };+ let frame = PendingFrame {+ viewport_rect,+ forced_damage_rect: request.forced_damage_rect,+ };+ match request.scheduling {+ PresentScheduling::OnNextDisplayTick => self.schedule_present_frame(request.context_id, frame, now),+ PresentScheduling::WithDisplayTickInProgress => presenting.borrow_mut().queue_present_frame(frame),+ }+ }+ }+ }++ pub(super) fn schedule_present_frame(+ &self,+ context_id: CompositorContextId,+ frame: PendingFrame,+ now: MonotonicTime,+ ) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ presenting.borrow_mut().queue_present_frame(frame);+ self.schedule_pending_present_frame(context_id, now);+ }++ fn schedule_present_frame_repainting_everything(+ &self,+ context_id: CompositorContextId,+ viewport_rect: IntRect,+ now: MonotonicTime,+ ) {+ self.schedule_present_frame(context_id, PendingFrame::repainting_everything(viewport_rect), now);+ }++ pub(super) fn present_current_frame(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ let frame_rect = presenting.borrow().frame_rect_to_repaint();+ if let Some(frame_rect) = frame_rect {+ self.schedule_present_frame_repainting_everything(context_id, frame_rect, now);+ }+ }++ pub(super) fn schedule_pending_present_frame(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ if !presenting.borrow().presents_to_client {+ // A nested context is presented through its containing context, but its own async animations still need a+ // vsync source. The containing frame may already be up to date (and therefore not schedule a new present),+ // so explicitly keep the effective display's scheduler ticking while a nested animation is active.+ if let Some(parent) = self+ .context_if_present(context_id)+ .and_then(|context| context.borrow().parent_context_id())+ {+ self.present_current_frame(parent, now);+ }+ self.schedule_animation_frames_if_needed(context_id, now);+ return;+ }+ if !self.context_is_effectively_visible_inner(context_id) {+ return;+ }+ let mut presenting = presenting.borrow_mut();+ presenting.mark_pending_present_frame_scheduled();+ // NB: A context presented to a client asks for the ticks of its own display, which is the one it knows.+ self.raster+ .request_vsync(presenting.display_id, presenting.display_refresh_rate);+ }++ fn schedule_animation_frames_if_needed(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ let needs_animation_frames = context.borrow_mut().needs_animation_frames(now);+ if needs_animation_frames && self.context_is_effectively_visible_inner(context_id) {+ self.request_vsync_for(context_id);+ }+ }++ pub(super) fn schedule_pending_present_frame_if_unblocked(+ &self,+ context_id: CompositorContextId,+ now: MonotonicTime,+ ) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ if !presenting+ .borrow()+ .can_schedule_pending_present_frame_if_unblocked(&self.raster, context_id)+ {+ return;+ }+ if self.try_present_frame_during_resize(context_id, now) {+ return;+ }+ self.schedule_pending_present_frame(context_id, now);+ }++ pub(super) fn try_present_frame_during_resize(&self, context_id: CompositorContextId, now: MonotonicTime) -> bool {+ let Some(presenting) = self.presenting_of(context_id) else {+ return false;+ };+ {+ let presenting = presenting.borrow();+ if !presenting.window_resize_in_progress() || !presenting.presents_to_client {+ return false;+ }+ }+ if !self.context_is_effectively_visible_inner(context_id) {+ return false;+ }+ let pending_frame = presenting+ .borrow_mut()+ .take_pending_present_frame_if_unblocked(&self.raster, context_id);+ let Some(pending_frame) = pending_frame else {+ return false;+ };+ // Rasterize resize frames as soon as a backing store is available, so the previous size does not remain+ // visible for another display tick. Preparing the frame owns requeuing any blocked frame.+ self.present_frame(context_id, pending_frame, now);+ // The display tick does more than present frames, such as updating the video sinks that are painted.+ self.request_vsync_for(context_id);+ true+ }++ pub(super) fn resolve_composited_context(+ &self,+ parent_context_id: CompositorContextId,+ child_context_id: CompositorContextId,+ destination_rect: FloatRect,+ canvas_matrix: &FloatMatrix4x4,+ now: MonotonicTime,+ ) -> Option<ResolvedCompositedContext> {+ let child_state = self.context_if_present(child_context_id)?;+ if child_state.try_borrow().ok()?.parent_context_id() != Some(parent_context_id) {+ return None;+ }+ // A context nested in itself, through others, is already being painted.+ let mut child_presenting = self.presenting_of(child_context_id)?.try_borrow_mut().ok()?;+ let is_rendering = self.raster.store_state(child_context_id).is_rendering;+ if child_presenting.update_composited_raster_transform(is_rendering, destination_rect, canvas_matrix) {+ let environment = self.environment(child_context_id, now, &NoCompositedContexts);+ let outcome = child_presenting.resize_backing_stores_if_needed(+ &environment,+ StorePublication::Unpublished,+ false,+ None,+ );+ assert!(matches!(+ outcome,+ StoreResizeOutcome::Unchanged | StoreResizeOutcome::ReallocatedOffscreen+ ));+ }+ if child_presenting.needs_rasterization() {+ let (display_list, frame_inputs) = {+ let mut child_state = child_state.try_borrow_mut().ok()?;+ (child_state.display_list(), child_state.frame_inputs(now))+ };+ let nested_contexts = ContextsNestedIn {+ core: self,+ parent_context_id: child_context_id,+ now,+ };+ let environment = self.environment(child_context_id, now, &nested_contexts);+ child_presenting.present_synchronously(&environment, display_list.as_ref(), frame_inputs);+ }+ child_presenting.composited_surface()+ }++ pub(super) fn present_frame(+ &self,+ context_id: CompositorContextId,+ pending_frame: PendingFrame,+ now: MonotonicTime,+ ) {+ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ let (display_list, frame_inputs, bound_presentation) = {+ let mut context = context.borrow_mut();+ (+ context.display_list(),+ context.frame_inputs(now),+ context.bound_presentation(),+ )+ };+ let nested_contexts = ContextsNestedIn {+ core: self,+ parent_context_id: context_id,+ now,+ };+ let environment = self.environment(context_id, now, &nested_contexts);+ let mut presenting = presenting.borrow_mut();+ let Some(prepared_frame) =+ presenting.prepare_frame(&environment, pending_frame, display_list.as_ref(), frame_inputs)+ else {+ return;+ };++ // A frame without a store still waits for what was drawn into the surfaces that the window server shows above+ // the store, such as a canvas that presented.+ let token = self+ .raster+ .submit_frame(context_id, prepared_frame.rendered_surface.as_ref());+ let shows_in_remote_layer = presenting.store_publication() == StorePublication::ShownInRemoteLayer;+ // A frame that the window server shows nothing above needs no list, which a remote layer makes when it shows+ // the frame.+ let sublayers = (!prepared_frame.sublayers.is_empty())+ .then(|| self.raster.build_sublayers(context_id, &prepared_frame.sublayers));+ self.async_presents.borrow_mut().push(PendingAsyncPresent {+ token,+ context_id,+ viewport_rect: pending_frame.viewport_rect,+ damage_rect: prepared_frame.damage_rect,+ bitmap_id: prepared_frame.bitmap_id,+ device_pixel_ratio: prepared_frame.device_pixel_ratio,+ was_cancelled: false,+ was_delivered: false,+ publish_to_presentation: !shows_in_remote_layer && bound_presentation.is_some(),+ shows_in_remote_layer,+ keeps_shown_store: prepared_frame.rendered_surface.is_none(),+ sublayers,+ });+ presenting.did_submit_prepared_frame(pending_frame.viewport_rect);+ // Handing the frame to the client before its GPU work finishes keeps it ahead of the window server's deadline for+ // the next refresh. A client that reads frames from CPU memory does not wait for that work, so it gets each frame+ // once it is done.+ let hands_off_early = presenting.presents_to_client+ && self.gpu.has_gpu+ && !presenting.presents_from_cpu_memory+ && self.raster.frame_hand_off(context_id) == FrameHandOff::OnceGpuWorkIsScheduled;+ drop(presenting);+ if hands_off_early {+ self.raster.hand_off_once_gpu_work_is_scheduled(token);+ }+ }++ fn take_delivery(&self, present: &mut PendingAsyncPresent) -> Option<Delivery> {+ if present.was_cancelled+ && present.keeps_shown_store+ && !present.was_delivered+ && let Some(presenting) = self.presenting_of(present.context_id)+ {+ presenting.borrow_mut().did_deliver_frame_without_store();+ }+ if present.was_cancelled || std::mem::replace(&mut present.was_delivered, true) {+ return None;+ }+ Some(Delivery {+ context_id: present.context_id,+ viewport_rect: present.viewport_rect,+ damage_rect: present.damage_rect,+ bitmap_id: present.bitmap_id,+ device_pixel_ratio: present.device_pixel_ratio,+ publish_to_presentation: present.publish_to_presentation,+ shows_in_remote_layer: present.shows_in_remote_layer,+ keeps_shown_store: present.keeps_shown_store,+ sublayers: present.sublayers.take(),+ })+ }++ pub(super) fn gpu_work_finished_inner(&self, token: u64, now: MonotonicTime) {+ let present = {+ let mut presents = self.async_presents.borrow_mut();+ let Some(index) = presents.iter().position(|present| present.token == token) else {+ return;+ };+ presents.remove(index)+ };+ let mut present = present;+ if let Some(delivery) = self.take_delivery(&mut present) {+ self.deliver_rendered_frame(delivery, now);+ }+ }++ pub(super) fn frame_ready_for_hand_off_inner(&self, token: u64, now: MonotonicTime) {+ let delivery = {+ let mut presents = self.async_presents.borrow_mut();+ let Some(present) = presents.iter_mut().find(|present| present.token == token) else {+ return;+ };+ self.take_delivery(present)+ };+ if let Some(delivery) = delivery {+ self.deliver_rendered_frame(delivery, now);+ }+ }++ fn deliver_rendered_frame(&self, mut delivery: Delivery, now: MonotonicTime) {+ let context_id = delivery.context_id;+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ let viewport_size = IntSize {+ width: delivery.viewport_rect.width,+ height: delivery.viewport_rect.height,+ };+ let presents_to_client = {+ let mut presenting = presenting.borrow_mut();+ if delivery.keeps_shown_store {+ presenting.did_deliver_frame_without_store();+ } else {+ presenting.did_finish_gpu_present(&environment, delivery.bitmap_id, viewport_size);+ }+ presenting.presents_to_client+ };+ let (bound_presentation, page_id, parent_context_id) = {+ let context = context.borrow();+ (+ context.bound_presentation(),+ context.page_id(),+ context.parent_context_id(),+ )+ };+ let presentation = if delivery.publish_to_presentation {+ bound_presentation+ } else {+ None+ };+ let damage_rect = delivery.damage_rect;+ let log_presented_frame = || {+ if let Some(page_id) = page_id {+ self.raster.log_presented_frame(page_id, damage_rect);+ }+ };+ if delivery.shows_in_remote_layer {+ log_presented_frame();+ self.show_frame_in_remote_layer(&mut delivery, viewport_size, now);+ } else if presents_to_client && presentation.is_none() {+ // Nobody shows the frame, so it is released on another turn, as a presentation would release it.+ self.raster.release_store_later(context_id, delivery.bitmap_id);+ } else if presents_to_client && let Some(presentation) = presentation {+ log_presented_frame();+ self.host.post_to_presentation(+ presentation,+ compositor_presentation_client::messages::DidPresentFrame {+ context_id,+ content_rect: delivery.viewport_rect,+ damage_rect: delivery.damage_rect,+ bitmap_id: delivery.bitmap_id,+ device_pixel_ratio: delivery.device_pixel_ratio,+ },+ );+ }+ self.resize_backing_stores_if_needed(context_id, now);+ if let Some(parent_context_id) = parent_context_id {+ self.present_current_frame(parent_context_id, now);+ }+ self.schedule_pending_present_frame_if_unblocked(context_id, now);+ }++ fn show_frame_in_remote_layer(&self, delivery: &mut Delivery, viewport_size: IntSize, now: MonotonicTime) {+ let context_id = delivery.context_id;+ let laid_out_by_page = self+ .presenting_of(context_id)+ .is_some_and(|presenting| presenting.borrow().size_laid_out_by_page == viewport_size);+ // The sublayers go with the frame, which keeps them.+ let sublayers = delivery+ .sublayers+ .take()+ .unwrap_or_else(|| self.raster.build_sublayers(context_id, &[]));+ let frame = FfiRemoteLayerFrame {+ uses_store: !delivery.keeps_shown_store,+ painted_size: viewport_size,+ device_pixel_ratio: delivery.device_pixel_ratio,+ laid_out_by_page,+ };+ let shown = self.raster.show_frame_in_remote_layer(context_id, &frame, sublayers);+ match shown {+ None => self.stop_showing_context_in_remote_layer(context_id, now),+ Some(presentation_id) => self.host.post_to_presentation(+ PresentationId(presentation_id),+ compositor_presentation_client::messages::DidPresentFrameInRemoteLayer {+ context_id,+ content_rect: delivery.viewport_rect,+ damage_rect: delivery.damage_rect,+ device_pixel_ratio: delivery.device_pixel_ratio,+ },+ ),+ }+ }++ // The frames were drawn into stores of the way the context was shown before, so they are released without being+ // shown.+ fn stop_delivering_in_flight_frames_to_their_viewer(&self, context_id: CompositorContextId) {+ for present in self.async_presents.borrow_mut().iter_mut() {+ if present.context_id == context_id {+ present.publish_to_presentation = false;+ present.shows_in_remote_layer = false;+ }+ }+ }++ pub(super) fn cancel_pending_async_presents_for_context(&self, context_id: CompositorContextId) {+ for present in self.async_presents.borrow_mut().iter_mut() {+ if present.context_id == context_id {+ present.was_cancelled = true;+ }+ }+ }++ pub(super) fn stop_showing_context_in_remote_layer(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ presenting.borrow_mut().shown_in_remote_layer = false;+ self.stop_delivering_in_flight_frames_to_their_viewer(context_id);+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ presenting.borrow_mut().invalidate_backing_stores(&environment);+ self.resize_backing_stores_if_needed(context_id, now);+ self.schedule_pending_present_frame_if_unblocked(context_id, now);+ }++ pub(super) fn start_showing_context_in_remote_layer(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(presenting) = self.presenting_of(context_id) else {+ return;+ };+ presenting.borrow_mut().shown_in_remote_layer = true;+ self.stop_delivering_in_flight_frames_to_their_viewer(context_id);+ // The presentation no longer shows the stores it was given, so none of them is waiting to be released by it.+ self.raster.release_all_presented_stores(context_id);+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ presenting.borrow_mut().invalidate_backing_stores(&environment);+ self.resize_backing_stores_if_needed(context_id, now);+ self.schedule_pending_present_frame_if_unblocked(context_id, now);+ }++ pub(super) fn gpu_sharing_allowed(&self, context_id: CompositorContextId) -> bool {+ if self+ .presenting_of(context_id)+ .is_some_and(|presenting| presenting.borrow().presents_from_cpu_memory)+ {+ return false;+ }+ let capabilities = self+ .context_if_present(context_id)+ .and_then(|context| context.borrow().bound_presentation())+ .and_then(|presentation| self.presentations.borrow().get(&presentation).copied());+ if self.gpu.shared_stores_need_the_same_adapter {+ // Shared GPU textures can only be opened by the presentation if it presents on the same adapter.+ return capabilities.is_some_and(|capabilities| {+ self.gpu.has_gpu && capabilities.gpu_presentation_adapter_luid == Some(self.gpu.adapter_luid)+ });+ }+ !capabilities.is_some_and(|capabilities| capabilities.cannot_present_gpu_images)+ }++ pub(super) fn resize_backing_stores_if_needed(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ let bound_presentation = context.borrow().bound_presentation();+ let publication = if presenting.borrow().shown_in_remote_layer {+ StorePublication::ShownInRemoteLayer+ } else if bound_presentation.is_some() {+ StorePublication::Published+ } else {+ StorePublication::Unpublished+ };+ let gpu_sharing_allowed = self.gpu_sharing_allowed(context_id);+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ let outcome = presenting.borrow_mut().resize_backing_stores_if_needed(+ &environment,+ publication,+ gpu_sharing_allowed,+ bound_presentation.map(|presentation| presentation.0),+ );+ match outcome {+ StoreResizeOutcome::Unchanged | StoreResizeOutcome::ReallocatedOffscreen => {}+ StoreResizeOutcome::ReallocatedForViewer => self.present_current_frame(context_id, now),+ StoreResizeOutcome::Failed => {+ self.raster.stop_showing_in_remote_layer(context_id);+ self.stop_showing_context_in_remote_layer(context_id, now);+ }+ }+ }++ pub(super) fn add_backing_store_for_pending_frame_if_needed(&self, context_id: CompositorContextId) {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ let (bound_presentation, display_list) = {+ let context = context.borrow();+ (context.bound_presentation(), context.display_list())+ };+ let mut presenting = presenting.borrow_mut();+ if bound_presentation.is_none() && !presenting.shown_in_remote_layer {+ return;+ }+ if !presenting.wants_backing_store_for_pending_frame(display_list.as_ref(), &self.raster, context_id) {+ return;+ }+ let publishing_presentation = bound_presentation+ .filter(|_| presenting.store_publication() == StorePublication::Published)+ .map(|presentation| presentation.0);+ if self+ .raster+ .add_store_if_window_server_reads_every_released_store(context_id, publishing_presentation)+ {+ presenting.schedule_surplus_store_retirement(context_id, &self.host);+ }+ }++ pub(super) fn retire_idle_surplus_backing_stores(&self, context_id: CompositorContextId) {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ let bound_presentation = context.borrow().bound_presentation();+ let mut presenting = presenting.borrow_mut();+ presenting.surplus_store_retirement_fired();+ let publishing_presentation = bound_presentation+ .filter(|_| presenting.store_publication() == StorePublication::Published)+ .map(|presentation| presentation.0);+ if self+ .raster+ .retire_idle_surplus_stores(context_id, publishing_presentation)+ {+ presenting.schedule_surplus_store_retirement(context_id, &self.host);+ }+ }++ // A context scrolls elastically, takes presses on scrollbar tracks, and ends touchpad gestures as the presentation of+ // its root context does. A platform that reports the momentum of a flick reports when the fingers lift for it.+ pub(super) fn update_scroll_capabilities(&self) {+ for (&context_id, context) in &self.contexts {+ let root = self.root_context_id_of(context_id);+ let capabilities = self+ .context_if_present(root)+ .and_then(|root| root.borrow().bound_presentation())+ .and_then(|presentation| self.presentations.borrow().get(&presentation).copied());+ let mut scroll_capabilities = crate::context_state::ScrollCapabilities::default();+ if let Some(capabilities) = capabilities {+ scroll_capabilities.synthesizes_scroll_momentum = capabilities.synthesizes_scroll_momentum;+ scroll_capabilities.scrolls_elastically = capabilities.scrolls_elastically;+ scroll_capabilities.scrollbar_track_press_jumps = capabilities.scrollbar_track_press_jumps;+ scroll_capabilities.touchpad_gesture_end = if capabilities.synthesizes_scroll_momentum {+ TouchpadGestureEnd::AfterIdleDelay+ } else {+ TouchpadGestureEnd::WhenFingersLift+ };+ }+ context.borrow_mut().set_scroll_capabilities(&scroll_capabilities);+ }+ }++ pub(super) fn unbind_presentation_inner(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ if context.borrow().bound_presentation().is_none() {+ return;+ }+ context.borrow_mut().set_bound_presentation(None);+ for present in self.async_presents.borrow_mut().iter_mut() {+ if present.context_id == context_id {+ present.publish_to_presentation = false;+ }+ }+ // Nobody is left to release the buffers the presentation was showing.+ self.raster.release_all_presented_stores(context_id);+ self.update_scroll_capabilities();+ if let Some(presenting) = self.presenting_of(context_id) {+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ presenting.borrow_mut().invalidate_backing_stores(&environment);+ }+ self.resize_backing_stores_if_needed(context_id, now);+ self.schedule_pending_present_frame_if_unblocked(context_id, now);+ }++ pub(super) fn resume_presentation_after_becoming_visible(+ &self,+ root_context_id: CompositorContextId,+ now: MonotonicTime,+ ) {+ let context_ids: Vec<CompositorContextId> = self.contexts.keys().copied().collect();+ for context_id in context_ids {+ if self.root_context_id_of(context_id) != root_context_id {+ continue;+ }+ self.schedule_animation_frames_if_needed(context_id, now);+ let wants_ticks = self.presenting_of(context_id).is_some_and(|presenting| {+ let presenting = presenting.borrow();+ presenting.rendering_opportunity_request.is_requested() || presenting.clock_tick_request.is_requested()+ });+ if wants_ticks {+ self.request_vsync_for(context_id);+ }+ }+ let frame_rect = self+ .presenting_of(root_context_id)+ .and_then(|presenting| presenting.borrow().frame_rect_to_repaint());+ if let Some(frame_rect) = frame_rect {+ self.schedule_present_frame_repainting_everything(root_context_id, frame_rect, now);+ }+ }++ pub(super) fn set_parent_context_inner(+ &self,+ context_id: CompositorContextId,+ mut parent_context_id: Option<CompositorContextId>,+ now: MonotonicTime,+ ) {+ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ if let Some(parent) = parent_context_id {+ assert!(!context.borrow().presents_to_client());+ assert_ne!(parent, context_id);+ // The parent's context belongs to the process hosting the parent, which can destroy it before this+ // context's process hears that the parent is gone. The context is left without a parent then, as destroying+ // the parent would have left it.+ if self.context_if_present(parent).is_none() {+ parent_context_id = None;+ }+ }+ let current_parent_context_id = context.borrow().parent_context_id();+ if current_parent_context_id == parent_context_id {+ return;+ }+ self.clear_parent_context(context_id, now);+ context.borrow_mut().set_parent_context(parent_context_id);+ self.update_scroll_capabilities();+ let Some(parent_context_id) = parent_context_id else {+ return;+ };+ let has_frame = self.presenting_of(context_id).is_some_and(|presenting| {+ let presenting = presenting.borrow();+ presenting.has_latest_rendered_surface() || presenting.needs_rasterization()+ });+ if has_frame {+ self.present_current_frame(parent_context_id, now);+ }+ }++ pub(super) fn clear_parent_context(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let Some(context) = self.context_if_present(context_id) else {+ return;+ };+ let Some(parent_context_id) = context.borrow().parent_context_id() else {+ return;+ };+ context.borrow_mut().set_parent_context(None);+ self.present_current_frame(parent_context_id, now);+ }++ fn post_rendering_opportunity(+ &self,+ context: &RefCell<ContextState>,+ context_id: CompositorContextId,+ frame_time: MonotonicTime,+ frame_interval: f64,+ ) {+ let web_content_client_id = context.borrow().web_content_client_id();+ self.host.post_to_web_content(+ web_content_client_id,+ compositor_web_content_client::messages::RenderingOpportunity {+ context_id,+ frame_time_nanoseconds: frame_time.nanoseconds(),+ frame_interval_milliseconds: frame_interval,+ },+ );+ }++ pub(super) fn request_rendering_opportunity_inner(+ &self,+ context_id: CompositorContextId,+ maximum_frames_per_second: f64,+ now: MonotonicTime,+ ) {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ if !presenting+ .borrow_mut()+ .rendering_opportunity_request+ .request(maximum_frames_per_second)+ {+ return;+ }+ if !self.context_is_effectively_visible_inner(context_id) {+ return;+ }+ let (display_id, display_refresh_rate) = self.display_of(context_id);+ // INTEROP: Like Chromium's missed BeginFrame delivery, reuse a recent display tick when a context requests its+ // next opportunity after the tick has already happened. This keeps heavy frames from waiting an extra+ // tick.+ if let Some(frame_time) = self.raster.most_recent_tick_time(display_id, now, display_refresh_rate) {+ let delivery = {+ let mut presenting = presenting.borrow_mut();+ let request = &mut presenting.rendering_opportunity_request;+ request.is_due(frame_time, display_refresh_rate).then(|| {+ let frame_interval = request.frame_interval(display_refresh_rate);+ request.did_deliver(frame_time);+ frame_interval+ })+ };+ if let Some(frame_interval) = delivery {+ self.post_rendering_opportunity(context, context_id, frame_time, frame_interval);+ return;+ }+ }+ self.raster.request_vsync(display_id, display_refresh_rate);+ }++ pub(super) fn hurry_rendering_opportunity_inner(&self, context_id: CompositorContextId, now: MonotonicTime) {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return;+ };+ if !presenting.borrow().rendering_opportunity_request.is_requested()+ || !self.context_is_effectively_visible_inner(context_id)+ {+ return;+ }+ let (_, display_refresh_rate) = self.display_of(context_id);+ let frame_interval = {+ let mut presenting = presenting.borrow_mut();+ let frame_interval = presenting+ .rendering_opportunity_request+ .frame_interval(display_refresh_rate);+ presenting.rendering_opportunity_request.did_deliver(now);+ frame_interval+ };+ self.post_rendering_opportunity(context, context_id, now, frame_interval);+ }++ pub(super) fn vsync_inner(&self, display_id: Option<u64>, frame_time: MonotonicTime, now: MonotonicTime) {+ for context_id in self.raster.update_video_sinks() {+ self.present_changed_live_content(context_id, now);+ }+ let context_ids: Vec<CompositorContextId> = self.contexts.keys().copied().collect();++ // Keep this display's vsync ticking while any sink painted on it may require updates.+ for &context_id in &context_ids {+ let (context_display_id, display_refresh_rate) = self.display_of(context_id);+ if context_display_id != display_id || !self.context_is_effectively_visible_inner(context_id) {+ continue;+ }+ if self.raster.context_video_sinks_require_updates(context_id) {+ self.raster.request_vsync(display_id, display_refresh_rate);+ }+ }++ for context_id in context_ids {+ let (Some(context), Some(presenting)) =+ (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ continue;+ };+ if !self.context_is_effectively_visible_inner(context_id) {+ presenting.borrow_mut().unschedule_pending_present_frame();+ continue;+ }+ let (context_display_id, display_refresh_rate) = self.display_of(context_id);+ let context_is_on_tick_display = context_display_id == display_id;++ let rendering_opportunity = {+ let mut presenting = presenting.borrow_mut();+ let request = &mut presenting.rendering_opportunity_request;+ if request.is_requested() && context_is_on_tick_display {+ if request.is_due(frame_time, display_refresh_rate) {+ let frame_interval = request.frame_interval(display_refresh_rate);+ request.did_deliver(frame_time);+ Some(frame_interval)+ } else {+ self.raster.request_vsync(display_id, display_refresh_rate);+ None+ }+ } else {+ None+ }+ };+ if let Some(frame_interval) = rendering_opportunity {+ self.post_rendering_opportunity(context, context_id, frame_time, frame_interval);+ }++ let present_is_scheduled_on_tick_display = {+ let presenting = presenting.borrow();+ presenting.pending_present_frame_scheduled() && presenting.display_id == display_id+ };+ let clock_tick_interval_in_milliseconds = {+ let mut presenting = presenting.borrow_mut();+ let request = &mut presenting.clock_tick_request;+ if request.is_requested() && context_is_on_tick_display {+ if request.is_due(frame_time, display_refresh_rate) {+ let interval = request.frame_interval(display_refresh_rate);+ request.did_deliver(frame_time);+ Some(interval)+ } else {+ self.raster.request_vsync(display_id, display_refresh_rate);+ None+ }+ } else {+ None+ }+ };+ let tick = self.display_tick_inner(+ context_id,+ frame_time,+ now,+ &crate::host::DisplayTickInputs {+ context_is_on_tick_display,+ present_is_scheduled_on_tick_display,+ clock_tick_interval_in_milliseconds,+ },+ );+ self.finish_entry(now);+ if !tick.presents_on_display {+ continue;+ }++ self.add_backing_store_for_pending_frame_if_needed(context_id);+ let pending_frame = presenting+ .borrow_mut()+ .take_pending_present_frame_if_unblocked(&self.raster, context_id);+ let Some(pending_frame) = pending_frame else {+ let present_is_scheduled = {+ let presenting = presenting.borrow();+ presenting.pending_present_frame_scheduled() && presenting.display_id == display_id+ };+ if present_is_scheduled || (tick.needs_animation_frames && context_is_on_tick_display) {+ self.raster.request_vsync(display_id, display_refresh_rate);+ }+ continue;+ };+ if tick.needs_animation_frames {+ self.schedule_present_frame(+ context_id,+ PendingFrame::repainting_changes(pending_frame.viewport_rect),+ now,+ );+ }+ self.present_frame(context_id, pending_frame, now);+ }+ }++ pub(super) fn paint_screenshot_inner(+ &self,+ context_id: CompositorContextId,+ target: &SurfaceHandle,+ now: MonotonicTime,+ ) -> bool {+ let (Some(context), Some(presenting)) = (self.context_if_present(context_id), self.presenting_of(context_id))+ else {+ return false;+ };+ let Some(display_list) = context.borrow().display_list() else {+ return false;+ };+ let screenshot_inputs = context.borrow_mut().frame_inputs_for_screenshot(now);+ let nested_contexts = ContextsNestedIn {+ core: self,+ parent_context_id: context_id,+ now,+ };+ let environment = self.environment(context_id, now, &nested_contexts);+ presenting+ .borrow_mut()+ .paint_screenshot(&environment, target, &display_list, &screenshot_inputs.frame_inputs);+ if !screenshot_inputs.scrollbar_fade_damage_rect.is_empty() {+ let viewport_rect = presenting.borrow().viewport_rect_of_current_frame();+ if let Some(viewport_rect) = viewport_rect {+ self.schedule_present_frame(+ context_id,+ PendingFrame {+ viewport_rect,+ forced_damage_rect: screenshot_inputs.scrollbar_fade_damage_rect,+ },+ now,+ );+ }+ }+ true+ }++ pub(super) fn presented_frame_for_snapshot_inner(+ &self,+ context_id: CompositorContextId,+ now: MonotonicTime,+ ) -> Option<(SurfaceHandle, IntSize)> {+ let presenting = self.presenting_of(context_id)?;+ if !presenting.borrow().presents_to_client {+ return None;+ }+ let environment = self.environment(context_id, now, &NoCompositedContexts);+ presenting.borrow_mut().presented_frame_for_snapshot(&environment)+ }++ // A video, canvas or image that the context draws changed, so its next frame shows the change.+ pub(super) fn present_changed_live_content(&self, context_id: CompositorContextId, now: MonotonicTime) {+ if !self.context_is_effectively_visible_inner(context_id) {+ return;+ }+ let rect = self+ .presenting_of(context_id)+ .and_then(|presenting| presenting.borrow().self_present_rect());+ if let Some(rect) = rect {+ self.schedule_present_frame(context_id, PendingFrame::repainting_changes(rect), now);+ }+ }++ pub(super) fn maximum_display_refresh_rate(&self) -> f64 {+ self.presenting+ .values()+ .map(|presenting| presenting.borrow().display_refresh_rate)+ .fold(60.0, f64::max)+ }+}diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex fa2c47d7a15..22f4c3018da 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -4,52 +4,53 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The entry points of the scroll and input logic for the C++ of the Compositor around it.+//! The entry points of the compositor's logic for the C++ of the Compositor around it, which calls them from its event+//! loop only.-use crate::context_state::ScrollCapabilities;use crate::core::messages::{MessagesFromPresentation, MessagesFromWebContent};+use crate::core::presenting::{GpuBackend, PresentationCapabilities};use crate::core::{CompositorCore, ContextOwnerCheckResult, VisualContextTreeUpdateResult};-use crate::frame_inputs::{FrameInputs, ScrollbarOfFrame};-use crate::host::{- ContextTimer, DisplayTickInputs, DisplayTickResult, FfiCompositorCoreHost, Host, PresentScheduling, PresentationId,- WebContentClientId,-};-use crate::layers::ContextLayerPlan;+use crate::host::{ContextTimer, FfiCompositorCoreHost, Host, PresentationId, WebContentClientId};use crate::overlays::{PausedDebuggerOverlayAction, PausedDebuggerOverlayState, PictureInPictureControl, PictureInPictureControlsState,UIOverlays,};-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, tree_sharing_handle};-use libcompositing_rust::host::{FfiRasterPainter, FfiReplaySelection};+use crate::raster_host::{FfiRasterHost, RasterHost};+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::ffi::{FfiDisplayList, tree_sharing_handle};use libcompositing_rust::ipc_types::{Compositing_ContextVisibility as ContextVisibility, compositor_presentation_server, compositor_web_content_server,};-use libcompositing_rust::scrolling::wheel_gesture_identity::TouchpadGestureEnd;use libcompositing_rust::scrolling::{KeyboardScrollState, ScrollStateSnapshot};use libcompositing_rust::time::MonotonicTime;-use libgfx_rust::{Color, IntRect, IntSize};+use libgfx_rust::{IntRect, IntSize};use libipc_rust::cpp_connection::{EncodedValue, RawMessage};use std::ffi::c_void;use std::rc::Rc;-use std::sync::Arc;++fn time(nanoseconds: i64) -> MonotonicTime {+ MonotonicTime::from_nanoseconds(nanoseconds)+}/// # Safety///-/// `host.host` must outlive the core, and none of the host's entry points may call back into the core.+/// `host.host` and `raster_host.host` must outlive the core, and none of their entry points may call back into the+/// core.#[unsafe(no_mangle)]pub unsafe extern "C" fn compositor_core_create(host: FfiCompositorCoreHost,+ raster_host: FfiRasterHost,scrollbars_always_shown: bool,+ gpu: GpuBackend,) -> *mut CompositorCore {- // SAFETY: The caller keeps the host alive for as long as the core, and its entry points out of the core.- let host = Rc::new(unsafe { Host::new(host) });- Box::into_raw(Box::new(CompositorCore::new(host, scrollbars_always_shown)))+ // SAFETY: The caller keeps the hosts alive for as long as the core, and their entry points out of the core.+ let (host, raster_host) = unsafe { (Rc::new(Host::new(host)), RasterHost::new(raster_host)) };+ Box::into_raw(Box::new(CompositorCore::new(+ host,+ raster_host,+ scrollbars_always_shown,+ gpu,+ )))}/// # Safety@@ -68,29 +69,66 @@ pub extern "C" fn compositor_core_create_context(has_page_id: bool,page_id: u64,web_content_client_id: u64,+ now_nanoseconds: i64,) {core.create_context(CompositorContextId(context_id),has_page_id.then_some(page_id),WebContentClientId(web_content_client_id),+ time(now_nanoseconds),);}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_destroy_context(core: &mut CompositorCore, context_id: u64) {- core.destroy_context(CompositorContextId(context_id));+pub extern "C" fn compositor_core_destroy_context(core: &mut CompositorCore, context_id: u64, now_nanoseconds: i64) {+ core.destroy_context(CompositorContextId(context_id), time(now_nanoseconds));}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_check_context_owner(+pub extern "C" fn compositor_core_context_can_be_nested_in(core: &CompositorCore,context_id: u64,- web_content_client_id: u64,-) -> ContextOwnerCheckResult {- core.check_context_owner(- CompositorContextId(context_id),- WebContentClientId(web_content_client_id),- )+ parent_context_id: u64,+) -> bool {+ core.context_can_be_nested_in(CompositorContextId(context_id), CompositorContextId(parent_context_id))+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_presents_to_client(core: &CompositorCore, context_id: u64) -> bool {+ core.presents_to_client(CompositorContextId(context_id))+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_context_is_effectively_visible(core: &CompositorCore, context_id: u64) -> bool {+ core.context_is_effectively_visible(CompositorContextId(context_id))+}++/// Answers whether the context is nested in another, which is written through `parent_context_id`.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_parent_context(+ core: &CompositorCore,+ context_id: u64,+ parent_context_id: &mut u64,+) -> bool {+ let Some(parent) = core.parent_context(CompositorContextId(context_id)) else {+ return false;+ };+ *parent_context_id = parent.0;+ true+}++/// Answers whether the context is bound to a presentation, which is written through `presentation_id`.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_bound_presentation(+ core: &CompositorCore,+ context_id: u64,+ presentation_id: &mut u64,+) -> bool {+ let Some(bound_presentation) = core.bound_presentation(CompositorContextId(context_id)) else {+ return false;+ };+ *presentation_id = bound_presentation.0;+ true}#[unsafe(no_mangle)]@@ -99,35 +137,22 @@ pub extern "C" fn compositor_core_set_parent_context(context_id: u64,has_parent_context: bool,parent_context_id: u64,+ now_nanoseconds: i64,) {core.set_parent_context(CompositorContextId(context_id),has_parent_context.then_some(CompositorContextId(parent_context_id)),+ time(now_nanoseconds),);}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_stop_presenting_to_client(core: &CompositorCore, context_id: u64) {- core.stop_presenting_to_client(CompositorContextId(context_id));-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_set_visibility(+pub extern "C" fn compositor_core_stop_presenting_to_client(core: &CompositorCore,context_id: u64,- is_visible: bool,now_nanoseconds: i64,) {- let visibility = if is_visible {- ContextVisibility::Visible- } else {- ContextVisibility::Hidden- };- core.set_visibility(- CompositorContextId(context_id),- visibility,- MonotonicTime::from_nanoseconds(now_nanoseconds),- );+ core.stop_presenting_to_client(CompositorContextId(context_id), time(now_nanoseconds));}#[unsafe(no_mangle)]@@ -136,484 +161,283 @@ pub extern "C" fn compositor_core_viewport_size_updated(context_id: u64,viewport_size: IntSize,device_pixel_ratio: f64,+ window_resize_in_progress: bool,+ now_nanoseconds: i64,) {- core.viewport_size_updated(CompositorContextId(context_id), viewport_size, device_pixel_ratio);+ core.viewport_size_updated(+ CompositorContextId(context_id),+ viewport_size,+ device_pixel_ratio,+ window_resize_in_progress,+ time(now_nanoseconds),+ );}-/// What the browser draws over a context's page. An action or control is none where it is out of range.+/// What a presentation makes of the frames and the scrolling of the contexts it shows.#[repr(C)]-pub struct FfiUIOverlays<'a> {- pub has_paused_debugger: bool,- pub paused_debugger_has_font_family: bool,- pub paused_debugger_font_family: ak::Span<'a, u8>,- pub paused_debugger_has_hovered_action: bool,- pub paused_debugger_hovered_action: u8,- pub has_picture_in_picture_controls: bool,- pub picture_in_picture_controls_shown: bool,- pub picture_in_picture_controls_has_hovered_control: bool,- pub picture_in_picture_controls_hovered_control: u8,+pub struct FfiPresentationCapabilities {+ pub synthesizes_scroll_momentum: bool,+ pub scrolls_elastically: bool,+ pub scrollbar_track_press_jumps: bool,+ pub has_gpu_presentation_adapter: bool,+ pub gpu_presentation_adapter_luid: u64,+ pub cannot_present_gpu_images: bool,}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_set_ui_overlays(+pub extern "C" fn compositor_core_register_presentation(core: &CompositorCore,- context_id: u64,- ui_overlays: &FfiUIOverlays<'_>,- now_nanoseconds: i64,+ presentation_id: u64,+ capabilities: &FfiPresentationCapabilities,) {- let paused_debugger = ui_overlays.has_paused_debugger.then(|| PausedDebuggerOverlayState {- font_family: ui_overlays- .paused_debugger_has_font_family- .then(|| String::from_utf8_lossy(ui_overlays.paused_debugger_font_family.as_slice()).into_owned()),- hovered_action: match (- ui_overlays.paused_debugger_has_hovered_action,- ui_overlays.paused_debugger_hovered_action,- ) {- (true, 0) => Some(PausedDebuggerOverlayAction::StepOver),- (true, 1) => Some(PausedDebuggerOverlayAction::Continue),- _ => None,- },- });- let picture_in_picture_controls =- ui_overlays- .has_picture_in_picture_controls- .then_some(PictureInPictureControlsState {- shown: ui_overlays.picture_in_picture_controls_shown,- hovered_control: match (- ui_overlays.picture_in_picture_controls_has_hovered_control,- ui_overlays.picture_in_picture_controls_hovered_control,- ) {- (true, 0) => Some(PictureInPictureControl::BackToTab),- (true, 1) => Some(PictureInPictureControl::Close),- _ => None,- },- });- core.set_ui_overlays(- CompositorContextId(context_id),- UIOverlays {- paused_debugger,- picture_in_picture_controls,+ core.register_presentation(+ PresentationId(presentation_id),+ PresentationCapabilities {+ synthesizes_scroll_momentum: capabilities.synthesizes_scroll_momentum,+ scrolls_elastically: capabilities.scrolls_elastically,+ scrollbar_track_press_jumps: capabilities.scrollbar_track_press_jumps,+ gpu_presentation_adapter_luid: capabilities+ .has_gpu_presentation_adapter+ .then_some(capabilities.gpu_presentation_adapter_luid),+ cannot_present_gpu_images: capabilities.cannot_present_gpu_images,},- MonotonicTime::from_nanoseconds(now_nanoseconds),);}-/// Paints what the compositor draws over the page in the frame: its scrollbars and, unless they are left out, the-/// overlays of the browser.-///-/// # Safety-///-/// `painter` must be live. The painter callbacks run synchronously.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_frame_inputs_paint_overlays(- frame_inputs: &FrameInputs,- painter: *const FfiRasterPainter,- paints_ui_overlays: bool,+pub extern "C" fn compositor_core_unregister_presentation(+ core: &CompositorCore,+ presentation_id: u64,+ now_nanoseconds: i64,) {- // SAFETY: The caller lends a live painter.- let mut painter = unsafe { *painter };- frame_inputs.overlays.paint(&mut painter, paints_ui_overlays);+ core.unregister_presentation(PresentationId(presentation_id), time(now_nanoseconds));}-/// The part of the viewport that what the compositor draws over the page covers in the frame.#[unsafe(no_mangle)]-pub extern "C" fn compositor_frame_inputs_overlay_bounds(frame_inputs: &FrameInputs, bounds: &mut IntRect) {- *bounds = frame_inputs.overlays.bounds;-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_set_bound_presentation(+pub extern "C" fn compositor_core_set_presentation_gpu_capability(core: &CompositorCore,- context_id: u64,- is_bound: bool,presentation_id: u64,+ supported: bool,+ adapter_luid: u64,+ now_nanoseconds: i64,) {- core.set_bound_presentation(- CompositorContextId(context_id),- is_bound.then_some(PresentationId(presentation_id)),+ core.set_presentation_gpu_capability(+ PresentationId(presentation_id),+ supported,+ adapter_luid,+ time(now_nanoseconds),);}-/// What the presentation a context is shown through makes of the user's scrolling.-#[repr(C)]-pub struct FfiScrollCapabilities {- pub synthesizes_scroll_momentum: bool,- pub scrolls_elastically: bool,- pub scrollbar_track_press_jumps: bool,- pub touchpad_gestures_end_when_fingers_lift: bool,+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_scrollbar_track_press_jumps(+ core: &CompositorCore,+ presentation_id: u64,+ jumps: bool,+) {+ core.set_scrollbar_track_press_jumps(PresentationId(presentation_id), jumps);}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_set_scroll_capabilities(+pub extern "C" fn compositor_core_bind_presentation(core: &CompositorCore,context_id: u64,- capabilities: FfiScrollCapabilities,+ presentation_id: u64,+ now_nanoseconds: i64,) {- core.set_scroll_capabilities(+ core.bind_presentation(CompositorContextId(context_id),- &ScrollCapabilities {- synthesizes_scroll_momentum: capabilities.synthesizes_scroll_momentum,- scrolls_elastically: capabilities.scrolls_elastically,- scrollbar_track_press_jumps: capabilities.scrollbar_track_press_jumps,- touchpad_gesture_end: if capabilities.touchpad_gestures_end_when_fingers_lift {- TouchpadGestureEnd::WhenFingersLift- } else {- TouchpadGestureEnd::AfterIdleDelay- },- },+ PresentationId(presentation_id),+ time(now_nanoseconds),);}-/// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode, or that hold-/// numbers no scroll can be calculated with.-///-/// # Safety-///-/// The storage of `display_list` must be a live display list storage handle, and `visual_context_tree` a live retained-/// tree handle.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_install_display_list_update(+pub extern "C" fn compositor_core_set_shown_in_remote_layer(core: &CompositorCore,context_id: u64,- display_list: &FfiDisplayList<'_>,- visual_context_tree: *const c_void,- scroll_state: EncodedValue<'_>,+ shown: bool,now_nanoseconds: i64,-) -> bool {- // SAFETY: The caller lends a strong reference to the storage.- let Ok(display_list) = (unsafe { display_list.share() }) else {- return false;- };- let Ok(scroll_state_snapshot) = scroll_state.decode::<ScrollStateSnapshot>() else {- return false;- };- core.install_display_list_update(- CompositorContextId(context_id),- Rc::new(display_list),- // SAFETY: The caller lends a strong reference to the tree.- unsafe { tree_sharing_handle(visual_context_tree) },- scroll_state_snapshot,- MonotonicTime::from_nanoseconds(now_nanoseconds),- )+) {+ core.set_shown_in_remote_layer(CompositorContextId(context_id), shown, time(now_nanoseconds));}-/// Changes nothing for a scroll state or keyboard scroll state that do not decode, or a scroll state with offsets that-/// are not finite.-///-/// # Safety-///-/// `visual_context_tree` must be a live retained tree handle.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_update_visual_context_tree(+pub extern "C" fn compositor_core_set_display_metadata(core: &CompositorCore,context_id: u64,- visual_context_tree: *const c_void,- scroll_state: EncodedValue<'_>,- keyboard_scroll_state: EncodedValue<'_>,+ has_display_id: bool,+ display_id: u64,+ refresh_rate: f64,now_nanoseconds: i64,-) -> VisualContextTreeUpdateResult {- let (Ok(scroll_state_snapshot), Ok(keyboard_scroll_state)) = (- scroll_state.decode::<ScrollStateSnapshot>(),- keyboard_scroll_state.decode::<KeyboardScrollState>(),- ) else {- return VisualContextTreeUpdateResult::InvalidScrollState;- };- if !scroll_state_snapshot.has_only_finite_offsets() {- return VisualContextTreeUpdateResult::InvalidScrollState;- }- let tree_was_replaced = core.update_visual_context_tree(+) {+ core.set_display_metadata(CompositorContextId(context_id),- // SAFETY: The caller lends a strong reference to the tree.- unsafe { tree_sharing_handle(visual_context_tree) },- scroll_state_snapshot,- keyboard_scroll_state,- MonotonicTime::from_nanoseconds(now_nanoseconds),+ has_display_id.then_some(display_id),+ refresh_rate,+ time(now_nanoseconds),);- if tree_was_replaced {- VisualContextTreeUpdateResult::TreeReplaced- } else {- VisualContextTreeUpdateResult::TreeDropped- }}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_needs_animation_frames(+pub extern "C" fn compositor_core_set_window_server_may_show_high_dynamic_range(core: &CompositorCore,- context_id: u64,+ may_show: bool,now_nanoseconds: i64,-) -> bool {- core.needs_animation_frames(- CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(now_nanoseconds),- )+) {+ core.set_window_server_may_show_high_dynamic_range(may_show, time(now_nanoseconds));}-/// What a frame of the context is painted with besides the display list and its resources, until-/// `compositor_frame_inputs_destroy` frees it. Each frame shows the scrollbars as of when it is painted, so this updates-/// which of them are shown. Null for a context that has no display list yet.#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_frame_inputs(+pub extern "C" fn compositor_core_set_presents_from_cpu_memory(core: &CompositorCore,context_id: u64,+ presents_from_cpu_memory: bool,now_nanoseconds: i64,-) -> *mut FrameInputs {- core.frame_inputs(+) {+ core.set_presents_from_cpu_memory(CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(now_nanoseconds),- )- .map_or(std::ptr::null_mut(), |frame_inputs| {- Box::into_raw(Box::new(frame_inputs))- })+ presents_from_cpu_memory,+ time(now_nanoseconds),+ );}-/// What a screenshot of the context is painted with, until `compositor_frame_inputs_destroy` frees it, with the-/// scrollbar fade damage that the screenshot does not present on screen. The context must have a display list.#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_frame_inputs_for_screenshot(+pub extern "C" fn compositor_core_request_rendering_opportunity(core: &CompositorCore,context_id: u64,+ maximum_frames_per_second: f64,now_nanoseconds: i64,- scrollbar_fade_damage_rect: &mut IntRect,-) -> *mut FrameInputs {- let screenshot_inputs = core.frame_inputs_for_screenshot(+) {+ core.request_rendering_opportunity(CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(now_nanoseconds),+ maximum_frames_per_second,+ time(now_nanoseconds),);- *scrollbar_fade_damage_rect = screenshot_inputs.scrollbar_fade_damage_rect;- Box::into_raw(Box::new(screenshot_inputs.frame_inputs))}-/// # Safety-///-/// `frame_inputs` must be inputs the core handed out that nothing uses afterwards.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_frame_inputs_destroy(frame_inputs: *mut FrameInputs) {- // SAFETY: The caller hands over the inputs the core made.- drop(unsafe { Box::from_raw(frame_inputs) });+pub extern "C" fn compositor_core_request_clock_tick(+ core: &CompositorCore,+ context_id: u64,+ maximum_frames_per_second: f64,+) {+ core.request_clock_tick(CompositorContextId(context_id), maximum_frames_per_second);}-/// One strong reference to the visual context tree the frame is painted with, which the caller takes over.#[unsafe(no_mangle)]-pub extern "C" fn compositor_frame_inputs_retain_visual_context_tree(frame_inputs: &FrameInputs) -> *const c_void {- Arc::into_raw(frame_inputs.visual_context_tree.as_arc().clone()).cast()+pub extern "C" fn compositor_core_hurry_rendering_opportunity(+ core: &CompositorCore,+ context_id: u64,+ now_nanoseconds: i64,+) {+ core.hurry_rendering_opportunity(CompositorContextId(context_id), time(now_nanoseconds));}-/// The scrollbars the frame shows, of which there are `count`, lent for as long as the inputs live.#[unsafe(no_mangle)]-pub extern "C" fn compositor_frame_inputs_scrollbars(- frame_inputs: &FrameInputs,- count: &mut usize,-) -> *const ScrollbarOfFrame {- *count = frame_inputs.scrollbars.len();- frame_inputs.scrollbars.as_ptr()+pub extern "C" fn compositor_core_present_frame_of_page(+ core: &CompositorCore,+ context_id: u64,+ viewport_rect: IntRect,+ now_nanoseconds: i64,+) {+ core.present_frame_of_page(CompositorContextId(context_id), viewport_rect, time(now_nanoseconds));}-/// 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 `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,- painter: *const FfiRasterPainter,+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_presented_store_released(+ core: &CompositorCore,+ context_id: u64,+ bitmap_id: i32,+ now_nanoseconds: i64,) {- // 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,- selection.as_selection(),- painter,- );- }+ core.presented_store_released(CompositorContextId(context_id), bitmap_id, time(now_nanoseconds));}-/// What a frame painted with `frame_inputs` repaints of the frame painted last, with `last_frame_inputs` and the list-/// `last_display_list_storage` holds. Writes the damage rect through `damage_rect` and returns whether the damage is-/// bounded; unbounded damage means the whole viewport must repaint. Live content changes do not damage the records at-/// `offsets_of_records_composited_as_media_layers`. Given the layer plans of both frames, which have the same layers,-/// writes the damage of each layer through `layer_damage_rects` and sets the bit of each layer whose damage is-/// unbounded in `unbounded_layer_bits`.-///-/// # Safety-///-/// Both storages must be live storage handles, and the id and offset pointers must address the stated number of-/// values for the call. Either both plans are null, or `layer_damage_rects` addresses one rect for each of their-/// layers.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_frame_inputs_damage_since(- frame_inputs: &FrameInputs,- display_list_storage: *const c_void,- last_frame_inputs: &FrameInputs,- last_display_list_storage: *const c_void,- viewport_rect: IntRect,- canvases_with_new_content: *const CanvasId,- canvases_with_new_content_len: usize,- video_sinks_with_new_frames: *const VideoSinkResourceId,- video_sinks_with_new_frames_len: usize,- image_frames_with_new_pixels: *const ImageFrameResourceId,- image_frames_with_new_pixels_len: usize,- forced_damage_rect: IntRect,- offsets_of_records_composited_as_media_layers: *const u32,- offsets_of_records_composited_as_media_layers_len: usize,- last_layer_plan: Option<&ContextLayerPlan>,- layer_plan: Option<&ContextLayerPlan>,- damage_rect: &mut IntRect,- layer_damage_rects: *mut IntRect,- unbounded_layer_bits: &mut u32,-) -> bool {- // SAFETY: The caller guarantees live handles and valid slices for the duration of the call.- let (display_list, last_display_list, live_content_changes) = unsafe {- (- storage_from_handle(display_list_storage),- storage_from_handle(last_display_list_storage),- LiveContentChanges {- canvases: ak::slice_from_raw_parts(canvases_with_new_content, canvases_with_new_content_len),- video_sinks: ak::slice_from_raw_parts(video_sinks_with_new_frames, video_sinks_with_new_frames_len),- image_frames: ak::slice_from_raw_parts(image_frames_with_new_pixels, image_frames_with_new_pixels_len),- forced_damage_rect,- offsets_of_records_composited_as_media_layers: ak::slice_from_raw_parts(- offsets_of_records_composited_as_media_layers,- offsets_of_records_composited_as_media_layers_len,- ),- },- )- };- let layer_plans = match (last_layer_plan, layer_plan) {- (Some(last_layer_plan), Some(layer_plan)) => Some(LayerPlans {- old: &last_layer_plan.0,- new: &layer_plan.0,- }),- _ => None,- };- let damage = frame_inputs.damage_since(- display_list,- last_frame_inputs,- last_display_list,- viewport_rect,- live_content_changes,- layer_plans,+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_vsync(+ core: &CompositorCore,+ has_display_id: bool,+ display_id: u64,+ frame_time_nanoseconds: i64,+ now_nanoseconds: i64,+) {+ core.vsync(+ has_display_id.then_some(display_id),+ time(frame_time_nanoseconds),+ time(now_nanoseconds),);- if !damage.layer_rects.is_empty() {- // SAFETY: The caller provides a rect for each layer of the plans.- let layer_damage_rects = unsafe { ak::slice_from_raw_parts_mut(layer_damage_rects, damage.layer_rects.len()) };- *unbounded_layer_bits = 0;- for (index, layer_damage_rect) in damage.layer_rects.iter().enumerate() {- match layer_damage_rect {- Some(rect) => layer_damage_rects[index] = *rect,- None => *unbounded_layer_bits |= 1 << index,- }- }- }- match damage.rect {- Some(bounded_damage_rect) => {- *damage_rect = bounded_damage_rect;- true- }- None => false,- }}-/// What the presentation knows of a context as a tick of a display begins.-#[repr(C)]-pub struct FfiDisplayTickInputs {- pub context_is_on_tick_display: bool,- pub present_is_scheduled_on_tick_display: bool,- /// Whether the render clock of the context is due a tick now, of the interval that follows.- pub clock_tick_is_due: bool,- pub clock_tick_interval_in_milliseconds: f64,+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_gpu_work_finished(core: &CompositorCore, token: u64, now_nanoseconds: i64) {+ core.gpu_work_finished(token, time(now_nanoseconds));}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_display_tick(+pub extern "C" fn compositor_core_frame_ready_for_hand_off(core: &CompositorCore, token: u64, now_nanoseconds: i64) {+ core.frame_ready_for_hand_off(token, time(now_nanoseconds));+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_context_content_changed(core: &CompositorCore,context_id: u64,- frame_time_nanoseconds: i64,now_nanoseconds: i64,- inputs: FfiDisplayTickInputs,-) -> DisplayTickResult {- core.display_tick(- CompositorContextId(context_id),- MonotonicTime::from_nanoseconds(frame_time_nanoseconds),- MonotonicTime::from_nanoseconds(now_nanoseconds),- &DisplayTickInputs {- context_is_on_tick_display: inputs.context_is_on_tick_display,- present_is_scheduled_on_tick_display: inputs.present_is_scheduled_on_tick_display,- clock_tick_interval_in_milliseconds: inputs- .clock_tick_is_due- .then_some(inputs.clock_tick_interval_in_milliseconds),- },- )+) {+ core.context_content_changed(CompositorContextId(context_id), time(now_nanoseconds));}#[unsafe(no_mangle)]-pub extern "C" fn compositor_core_timer_fired(+pub extern "C" fn compositor_core_canvas_content_changed(core: &CompositorCore,- context_id: u64,- timer: ContextTimer,+ web_content_client_id: u64,+ canvas_id: u64,now_nanoseconds: i64,) {- core.timer_fired(- CompositorContextId(context_id),- timer,- MonotonicTime::from_nanoseconds(now_nanoseconds),+ core.canvas_content_changed(+ WebContentClientId(web_content_client_id),+ canvas_id,+ time(now_nanoseconds),);}-/// A frame that the scroll and input logic of a context wants presented.-#[repr(C)]-pub struct FfiPresentRequest {- pub context_id: u64,- /// When false, the frame is at the viewport rect the context is presented at.- pub has_viewport_rect: bool,- pub viewport_rect: IntRect,- pub forced_damage_rect: IntRect,- pub scheduling: PresentScheduling,-}--/// Hands over the frames asked for since the last call, in the order they were asked for.+/// Paints a screenshot of the context into the surface, answering false for a context with nothing to paint yet.////// # Safety///-/// `receive` must not call back into the core.+/// `surface` must be a live surface, which the call lends.#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_core_take_present_requests(+pub unsafe extern "C" fn compositor_core_paint_screenshot(core: &CompositorCore,- receiver: *mut c_void,- receive: unsafe extern "C" fn(*mut c_void, FfiPresentRequest),-) {- for request in core.take_present_requests() {- // SAFETY: The caller's receiver stays out of the core.- unsafe {- receive(- receiver,- FfiPresentRequest {- context_id: request.context_id.0,- has_viewport_rect: request.viewport_rect.is_some(),- viewport_rect: request.viewport_rect.unwrap_or_default(),- forced_damage_rect: request.forced_damage_rect,- scheduling: request.scheduling,- },- );- }- }+ context_id: u64,+ surface: *mut c_void,+ now_nanoseconds: i64,+) -> bool {+ let Some(surface) = core.raster().retain_surface(surface) else {+ return false;+ };+ core.paint_screenshot(CompositorContextId(context_id), &surface, time(now_nanoseconds))+}++/// The surface that holds the frame on screen as a whole, with one reference that the caller takes over, and the size+/// of the frame in it. Answers false where no frame is on screen.+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_presented_frame_for_snapshot(+ core: &CompositorCore,+ context_id: u64,+ now_nanoseconds: i64,+ surface: &mut *mut c_void,+ frame_size: &mut IntSize,+) -> bool {+ let Some((source, size)) =+ core.presented_frame_for_snapshot(CompositorContextId(context_id), time(now_nanoseconds))+ else {+ return false;+ };+ *surface = core.raster().leak_surface(source);+ *frame_size = size;+ true}/// Takes a message of the CompositorWebContentServer endpoint that is marked [RustReceiver].@@ -631,12 +455,13 @@ pub unsafe extern "C" fn compositor_core_handle_web_content_message(let mut stub = MessagesFromWebContent {core,client_id: WebContentClientId(web_content_client_id),- now: MonotonicTime::from_nanoseconds(now_nanoseconds),+ now: time(now_nanoseconds),};// SAFETY: The caller hands over a message of that endpoint.unsafe {message.hand_to(|bytes, attachments| compositor_web_content_server::dispatch(&mut stub, bytes, attachments));};+ core.finish_message(time(now_nanoseconds));}/// Takes a message of the CompositorPresentationServer endpoint that is marked [RustReceiver].@@ -654,10 +479,186 @@ pub unsafe extern "C" fn compositor_core_handle_presentation_message(let mut stub = MessagesFromPresentation {core,presentation_id: PresentationId(presentation_id),- now: MonotonicTime::from_nanoseconds(now_nanoseconds),+ now: time(now_nanoseconds),};// SAFETY: The caller hands over a message of that endpoint.unsafe {message.hand_to(|bytes, attachments| compositor_presentation_server::dispatch(&mut stub, bytes, attachments));};+ core.finish_message(time(now_nanoseconds));+}++/// What the browser draws over a context's page. An action or control is none where it is out of range.+#[repr(C)]+pub struct FfiUIOverlays<'a> {+ pub has_paused_debugger: bool,+ pub paused_debugger_has_font_family: bool,+ pub paused_debugger_font_family: ak::Span<'a, u8>,+ pub paused_debugger_has_hovered_action: bool,+ pub paused_debugger_hovered_action: u8,+ pub has_picture_in_picture_controls: bool,+ pub picture_in_picture_controls_shown: bool,+ pub picture_in_picture_controls_has_hovered_control: bool,+ pub picture_in_picture_controls_hovered_control: u8,+}++/// Answers false, changing nothing, for async scrolling metadata or a scroll state that do not decode, or that hold+/// numbers no scroll can be calculated with.+///+/// # Safety+///+/// The storage of `display_list` must be a live display list storage handle, and `visual_context_tree` a live retained+/// tree handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_install_display_list_update(+ core: &CompositorCore,+ context_id: u64,+ display_list: &FfiDisplayList<'_>,+ visual_context_tree: *const c_void,+ scroll_state: EncodedValue<'_>,+ now_nanoseconds: i64,+) -> bool {+ // SAFETY: The caller lends a strong reference to the storage.+ let Ok(display_list) = (unsafe { display_list.share() }) else {+ return false;+ };+ let Ok(scroll_state_snapshot) = scroll_state.decode::<ScrollStateSnapshot>() else {+ return false;+ };+ core.install_display_list_update(+ CompositorContextId(context_id),+ Rc::new(display_list),+ // SAFETY: The caller lends a strong reference to the tree.+ unsafe { tree_sharing_handle(visual_context_tree) },+ scroll_state_snapshot,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ )+}++/// Changes nothing for a scroll state or keyboard scroll state that do not decode, or a scroll state with offsets that+/// are not finite.+///+/// # Safety+///+/// `visual_context_tree` must be a live retained tree handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn compositor_core_update_visual_context_tree(+ core: &CompositorCore,+ context_id: u64,+ visual_context_tree: *const c_void,+ scroll_state: EncodedValue<'_>,+ keyboard_scroll_state: EncodedValue<'_>,+ now_nanoseconds: i64,+) -> VisualContextTreeUpdateResult {+ let (Ok(scroll_state_snapshot), Ok(keyboard_scroll_state)) = (+ scroll_state.decode::<ScrollStateSnapshot>(),+ keyboard_scroll_state.decode::<KeyboardScrollState>(),+ ) else {+ return VisualContextTreeUpdateResult::InvalidScrollState;+ };+ if !scroll_state_snapshot.has_only_finite_offsets() {+ return VisualContextTreeUpdateResult::InvalidScrollState;+ }+ let tree_was_replaced = core.update_visual_context_tree(+ CompositorContextId(context_id),+ // SAFETY: The caller lends a strong reference to the tree.+ unsafe { tree_sharing_handle(visual_context_tree) },+ scroll_state_snapshot,+ keyboard_scroll_state,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+ if tree_was_replaced {+ VisualContextTreeUpdateResult::TreeReplaced+ } else {+ VisualContextTreeUpdateResult::TreeDropped+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_visibility(+ core: &CompositorCore,+ context_id: u64,+ is_visible: bool,+ now_nanoseconds: i64,+) -> bool {+ let visibility = if is_visible {+ ContextVisibility::Visible+ } else {+ ContextVisibility::Hidden+ };+ core.set_visibility(+ CompositorContextId(context_id),+ visibility,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ )+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_timer_fired(+ core: &CompositorCore,+ context_id: u64,+ timer: ContextTimer,+ now_nanoseconds: i64,+) {+ core.timer_fired(+ CompositorContextId(context_id),+ timer,+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_set_ui_overlays(+ core: &CompositorCore,+ context_id: u64,+ ui_overlays: &FfiUIOverlays<'_>,+ now_nanoseconds: i64,+) {+ let paused_debugger = ui_overlays.has_paused_debugger.then(|| PausedDebuggerOverlayState {+ font_family: ui_overlays+ .paused_debugger_has_font_family+ .then(|| String::from_utf8_lossy(ui_overlays.paused_debugger_font_family.as_slice()).into_owned()),+ hovered_action: match (+ ui_overlays.paused_debugger_has_hovered_action,+ ui_overlays.paused_debugger_hovered_action,+ ) {+ (true, 0) => Some(PausedDebuggerOverlayAction::StepOver),+ (true, 1) => Some(PausedDebuggerOverlayAction::Continue),+ _ => None,+ },+ });+ let picture_in_picture_controls =+ ui_overlays+ .has_picture_in_picture_controls+ .then_some(PictureInPictureControlsState {+ shown: ui_overlays.picture_in_picture_controls_shown,+ hovered_control: match (+ ui_overlays.picture_in_picture_controls_has_hovered_control,+ ui_overlays.picture_in_picture_controls_hovered_control,+ ) {+ (true, 0) => Some(PictureInPictureControl::BackToTab),+ (true, 1) => Some(PictureInPictureControl::Close),+ _ => None,+ },+ });+ core.set_ui_overlays(+ CompositorContextId(context_id),+ UIOverlays {+ paused_debugger,+ picture_in_picture_controls,+ },+ MonotonicTime::from_nanoseconds(now_nanoseconds),+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_check_context_owner(+ core: &CompositorCore,+ context_id: u64,+ web_content_client_id: u64,+) -> ContextOwnerCheckResult {+ core.check_context_owner(+ CompositorContextId(context_id),+ WebContentClientId(web_content_client_id),+ )}diff --git a/Services/Compositor/Rust/src/frame_inputs.rs b/Services/Compositor/Rust/src/frame_inputs.rsindex 39b5a223b4e..7c11d9f3b45 100644--- a/Services/Compositor/Rust/src/frame_inputs.rs+++ b/Services/Compositor/Rust/src/frame_inputs.rs@@ -118,6 +118,14 @@ impl FrameInputs {)}+ // Whether a frame painted with these inputs places content where one painted with `other` does: the same tree,+ // scrolled the same.+ pub fn places_content_like(&self, other: &FrameInputs) -> bool {+ std::sync::Arc::ptr_eq(self.visual_context_tree.as_arc(), other.visual_context_tree.as_arc())+ && self.presented_scroll_state_snapshot.device_offsets()+ == other.presented_scroll_state_snapshot.device_offsets()+ }+fn frame_of<'a>(&'a self, display_list: &'a DisplayListStorage) -> DisplayListFrame<'a> {DisplayListFrame {command_bytes: display_list.bytes(),diff --git a/Services/Compositor/Rust/src/host.rs b/Services/Compositor/Rust/src/host.rsindex aeba1938bd5..f3c5a64eb5d 100644--- a/Services/Compositor/Rust/src/host.rs+++ b/Services/Compositor/Rust/src/host.rs@@ -13,6 +13,7 @@ use libcompositing_rust::time::Duration;use libgfx_rust::IntRect;use libipc_rust::cpp_connection::RawAttachment;use libipc_rust::wire::EndpointMessage;+use std::cell::RefCell;use std::ffi::c_void;#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]@@ -28,6 +29,9 @@ pub enum ContextTimer {ScrollbarPaging,ScrollbarFadeOut,CaretBlink,+ BackingStoreShrink,+ SurplusStoreRetirement,+ LayerDrop,}#[derive(Clone, Copy, Debug, PartialEq)]@@ -112,7 +116,6 @@ pub struct FfiCompositorCoreHost {unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),pub post_message_to_presentation:unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),- pub request_display_ticks: unsafe extern "C" fn(*mut c_void, u64),pub set_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer, i64),pub cancel_timer: unsafe extern "C" fn(*mut c_void, u64, ContextTimer),/// Arguments: the context, whether a font family is given, the font family, the device pixel ratio, the text, and@@ -131,14 +134,14 @@ pub struct FfiCompositorCoreHost {type PostEncodedMessage = unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>);-pub struct Host(FfiCompositorCoreHost);+pub struct Host(FfiCompositorCoreHost, RefCell<Vec<CompositorContextId>>);impl Host {/// # Safety////// `ffi.host` must outlive the `Host`, and none of its entry points may call back into the core.pub unsafe fn new(ffi: FfiCompositorCoreHost) -> Self {- Self(ffi)+ Self(ffi, RefCell::new(Vec::new()))}fn post<M: EndpointMessage>(&self, post_encoded_message: PostEncodedMessage, receiver_id: u64, message: M) {@@ -173,9 +176,14 @@ impl Host {}/// Display ticks reach a context whose scroll and input logic says it needs animation frames, while it is visible.+ /// The core asks for them once the call that wants them is done.pub fn request_display_ticks(&self, context_id: CompositorContextId) {- // SAFETY: The host outlives this.- unsafe { (self.0.request_display_ticks)(self.0.host, context_id.0) };+ self.1.borrow_mut().push(context_id);+ }++ /// The contexts that asked for display ticks since the last call.+ pub fn take_display_tick_requests(&self) -> Vec<CompositorContextId> {+ std::mem::take(&mut *self.1.borrow_mut())}/// Each timer of a context fires once after the delay, and setting it again replaces the delay.diff --git a/Services/Compositor/Rust/src/layers.rs b/Services/Compositor/Rust/src/layers.rsdeleted file mode 100644index 89fee85c08a..00000000000--- a/Services/Compositor/Rust/src/layers.rs+++ /dev/null@@ -1,205 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use crate::frame_inputs::FrameInputs;-use libcompositing_rust::display_list::commands::{CanvasId, VideoSinkResourceId};-use libcompositing_rust::display_list::layers::{LayerKind, LayerPlan, LayerPlanInputs, build_layer_plan};-use libcompositing_rust::display_list::storage::storage_from_handle;-use libcompositing_rust::display_list::summary::LiveContent;-use libcompositing_rust::display_list::window_server_placement::WindowServerPlacement;-use libcompositing_rust::host::RecordSpan;-use libgfx_rust::{FloatRect, IntRect, ScalingMode};-use std::ffi::c_void;-use std::sync::Arc;--pub struct ContextLayerPlan(pub(crate) LayerPlan);--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-pub enum FfiLiveMediaKind {- Canvas,- Video,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(C)]-pub struct FfiLiveMedia {- pub kind: FfiLiveMediaKind,- pub id: u64,-}--impl FfiLiveMedia {- fn as_live_content(self) -> LiveContent {- match self.kind {- FfiLiveMediaKind::Canvas => LiveContent::Canvas(CanvasId(self.id)),- FfiLiveMediaKind::Video => LiveContent::VideoFrame(VideoSinkResourceId(self.id)),- }- }-- fn of_live_content(content: LiveContent) -> Self {- match content {- LiveContent::Canvas(id) => Self {- kind: FfiLiveMediaKind::Canvas,- id: id.0,- },- LiveContent::VideoFrame(id) => Self {- kind: FfiLiveMediaKind::Video,- id: id.0,- },- LiveContent::ImageFrame(_) => unreachable!("an image is never a layer of its own"),- }- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-pub enum FfiLayerKind {- Base,- Painted,- Media,-}--/// Where the window server can show a media layer, as `WindowServerPlacement` describes it.-#[derive(Clone, Copy, Debug, Default)]-#[repr(C)]-pub struct FfiWindowServerPlacement {- pub content_rect: IntRect,- /// The a, b, c, d, e and f of an affine transform.- pub content_to_viewport: [f32; 6],- pub clip_rect: FloatRect,- pub has_rounded_clip: bool,- pub rounded_clip_rect: FloatRect,- pub rounded_clip_radius: f32,- pub rounds_top_left: bool,- pub rounds_top_right: bool,- pub rounds_bottom_right: bool,- pub rounds_bottom_left: bool,- pub scaling_mode: ScalingMode,-}--impl FfiWindowServerPlacement {- fn of(placement: &WindowServerPlacement) -> Self {- let rounded_clip = placement.rounded_clip.unwrap_or(- libcompositing_rust::display_list::window_server_placement::RoundedClip {- rect: FloatRect::default(),- radius: 0.0,- rounded_corners: Default::default(),- },- );- Self {- content_rect: placement.content_rect,- content_to_viewport: placement.content_to_viewport.values,- clip_rect: placement.clip_rect,- has_rounded_clip: placement.rounded_clip.is_some(),- rounded_clip_rect: rounded_clip.rect,- rounded_clip_radius: rounded_clip.radius,- rounds_top_left: rounded_clip.rounded_corners.top_left,- rounds_top_right: rounded_clip.rounded_corners.top_right,- rounds_bottom_right: rounded_clip.rounded_corners.bottom_right,- rounds_bottom_left: rounded_clip.rounded_corners.bottom_left,- scaling_mode: placement.scaling_mode,- }- }-}--#[derive(Clone, Copy, Debug)]-#[repr(C)]-pub struct FfiLayer {- pub kind: FfiLayerKind,- pub media: FfiLiveMedia,- pub rect: IntRect,- pub record_spans: *const RecordSpan,- pub record_span_count: usize,- pub can_be_shown_by_window_server: bool,- pub window_server_placement: FfiWindowServerPlacement,-}--/// # Safety-///-/// `display_list_storage` must be a live storage handle of a list recorded against the inputs' tree, and `active_media`-/// must address `active_media_count` values for the call.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_frame_inputs_build_layer_plan(- frame_inputs: &FrameInputs,- display_list_storage: *const c_void,- viewport_rect: IntRect,- active_media: *const FfiLiveMedia,- active_media_count: usize,-) -> *mut ContextLayerPlan {- // SAFETY: The caller guarantees a live handle and a valid slice for the call.- let (storage, active_media) = unsafe {- (- storage_from_handle(display_list_storage),- ak::slice_from_raw_parts(active_media, active_media_count),- )- };- let active_media: Vec<LiveContent> = active_media.iter().map(|media| media.as_live_content()).collect();- let tree = frame_inputs.visual_context_tree.as_arc();- let plan = build_layer_plan(&LayerPlanInputs {- tape: storage.bytes(),- command_runs: storage.command_runs(),- summary: storage.summary(),- effect_clips: storage.effect_clip_plan(tree),- tree,- scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),- viewport_rect,- active_media: &active_media,- });- plan.map_or(std::ptr::null_mut(), |plan| {- Box::into_raw(Box::new(ContextLayerPlan(plan)))- })-}--/// # Safety-///-/// `plan` must be a plan `compositor_frame_inputs_build_layer_plan` made that nothing uses afterwards.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn compositor_layer_plan_destroy(plan: *mut ContextLayerPlan) {- // SAFETY: The caller hands over the plan.- drop(unsafe { Box::from_raw(plan) });-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_layer_plan_layer_count(plan: &ContextLayerPlan) -> usize {- plan.0.layers.len()-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_layer_plan_layer(plan: &ContextLayerPlan, index: usize, ffi_layer: &mut FfiLayer) {- let layer = &plan.0.layers[index];- let (kind, media) = match layer.kind {- LayerKind::Base => (FfiLayerKind::Base, None),- LayerKind::Painted => (FfiLayerKind::Painted, None),- LayerKind::Media { content, .. } => (FfiLayerKind::Media, Some(FfiLiveMedia::of_live_content(content))),- };- let placement = match &layer.window_server_placement {- Some(Ok(placement)) => Some(FfiWindowServerPlacement::of(placement)),- _ => None,- };- *ffi_layer = FfiLayer {- kind,- media: media.unwrap_or(FfiLiveMedia {- kind: FfiLiveMediaKind::Canvas,- id: 0,- }),- rect: layer.rect,- record_spans: layer.record_spans.as_ptr(),- record_span_count: layer.record_spans.len(),- can_be_shown_by_window_server: placement.is_some(),- window_server_placement: placement.unwrap_or_default(),- };-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_layer_plans_have_same_layers(plan: &ContextLayerPlan, other: &ContextLayerPlan) -> bool {- plan.0.has_same_layers_as(&other.0)-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_frame_inputs_place_content_alike(a: &FrameInputs, b: &FrameInputs) -> bool {- Arc::ptr_eq(a.visual_context_tree.as_arc(), b.visual_context_tree.as_arc())- && a.presented_scroll_state_snapshot.device_offsets() == b.presented_scroll_state_snapshot.device_offsets()-}diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex f21635d3042..d90cb049e23 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -25,8 +25,9 @@ pub mod frame_inputs;pub mod host;pub mod input_event;pub mod keyboard_scroll_controller;-pub mod layers;pub mod overlays;+pub mod presenting;+pub mod raster_host;pub mod scroll_fling_controller;pub mod scroll_snap_controller;pub mod scrollbar_controller;diff --git a/Services/Compositor/Rust/src/presenting/damage.rs b/Services/Compositor/Rust/src/presenting/damage.rsnew file mode 100644index 00000000000..8f1fb203885--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/damage.rs@@ -0,0 +1,375 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a frame repaints of the frame painted before it, and of what each backing store holds.++use super::layers::{LayerUpdate, MediaUpdate};+use super::{ContextPresenting, FrameToPaint, PresentingEnvironment, rect_of_size};+use crate::frame_inputs::FrameInputs;+use crate::host::PendingFrame;+use crate::raster_host::LiveContent;+use libcompositing_rust::display_list::commands::{CanvasId, ImageFrameResourceId, VideoSinkResourceId};+use libcompositing_rust::display_list::damage::{DisplayListDamage, LayerPlans, LiveContentChanges};+use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;+use libcompositing_rust::scrolling::DisplayList;+use libgfx_rust::{IntRect, IntSize};+use std::collections::{HashMap, HashSet};+use std::rc::Rc;++/// The frame painted last: its display list and inputs, and the version of each live content it drew, which comparing+/// lists cannot see change.+pub struct PaintedFrame {+ pub display_list: Rc<DisplayList>,+ pub frame_inputs: FrameInputs,+ pub viewport_size: IntSize,+ canvas_content_generations: HashMap<u64, u64>,+ video_frame_ids: HashMap<u64, Option<u64>>,+ image_frame_pixel_generations: HashMap<u64, u64>,+}++impl PaintedFrame {+ pub fn draws_canvas(&self, canvas_id: u64) -> bool {+ self.canvas_content_generations.contains_key(&canvas_id)+ }+}++/// What each backing store misses of the frames painted since it was last painted into, by its id, which new stores+/// never repeat. The stores painted into least recently are forgotten first, as retired stores are never painted into+/// again, and a store that is forgotten is painted in full.+#[derive(Default)]+pub struct StoreDamage {+ // The store painted into last is last.+ accumulated: Vec<(i32, IntRect)>,+}++// Twice as many as a context ever has at once.+const MAXIMUM_REMEMBERED_STORE_COUNT: usize = 16;++impl StoreDamage {+ pub fn forget_every_store(&mut self) {+ self.accumulated.clear();+ }++ /// What painting a frame into the store repaints: the frame's damage, and what the store missed since it was last+ /// painted, all of it for a store never painted into.+ pub fn take(&mut self, bitmap_id: i32, frame_damage: IntRect, store_rect: IntRect) -> IntRect {+ let mut repaint_rect = store_rect;+ for (id, accumulated) in &mut self.accumulated {+ if *id == bitmap_id {+ repaint_rect = accumulated.united(frame_damage);+ }+ *accumulated = accumulated.united(frame_damage);+ }+ self.accumulated.retain(|(id, _)| *id != bitmap_id);+ self.accumulated.push((bitmap_id, IntRect::default()));+ if self.accumulated.len() > MAXIMUM_REMEMBERED_STORE_COUNT {+ self.accumulated.remove(0);+ }+ repaint_rect+ }+}++// The canvases, video sinks and image frames whose pixels changed since the frame painted last.+#[derive(Default)]+pub struct LiveContentChangesSinceLastPaint {+ pub canvases: Vec<CanvasId>,+ pub video_sinks: Vec<VideoSinkResourceId>,+ pub image_frames: Vec<ImageFrameResourceId>,+ pub media_updates: Vec<MediaUpdate>,+ pub repaints_everything: bool,+}++pub struct FrameDamage {+ pub rect: IntRect,+ pub layers: LayerUpdate,+ pub live_media_changed: bool,+}++impl ContextPresenting {+ /// The live content of the context as it is now, with the canvases of the list and of the frame painted last.+ pub(super) fn live_content(&self, env: &PresentingEnvironment<'_>, display_list: &DisplayList) -> LiveContent {+ let mut canvas_ids = display_list.storage().summary().canvas_ids.clone();+ if let Some(painted_frame) = &self.painted_frame {+ let canvas_ids_of_list: HashSet<u64> = canvas_ids.iter().copied().collect();+ canvas_ids.extend(+ painted_frame+ .canvas_content_generations+ .keys()+ .filter(|id| !canvas_ids_of_list.contains(id)),+ );+ }+ env.raster.live_content(env.context_id, &canvas_ids)+ }++ pub(super) fn remember_painted_frame(+ &mut self,+ viewport_rect: IntRect,+ display_list: &Rc<DisplayList>,+ frame_inputs: FrameInputs,+ live_content: &LiveContent,+ ) {+ let canvas_generation = |id: u64| {+ live_content+ .canvases+ .get(&id)+ .map_or(0, |canvas| canvas.content_generation)+ };+ let canvas_content_generations = display_list+ .storage()+ .summary()+ .canvas_ids+ .iter()+ .map(|id| (*id, canvas_generation(*id)))+ .collect();+ // Every video the context holds is drawn by the list or by a display list it nests.+ let video_frame_ids = live_content+ .video_sinks+ .values()+ .map(|sink| (sink.id, sink.has_frame.then_some(sink.frame_id)))+ .collect();+ let image_frame_pixel_generations = live_content.image_frames.clone();+ self.painted_frame = Some(PaintedFrame {+ display_list: display_list.clone(),+ frame_inputs,+ viewport_size: IntSize {+ width: viewport_rect.width,+ height: viewport_rect.height,+ },+ canvas_content_generations,+ video_frame_ids,+ image_frame_pixel_generations,+ });+ }++ fn live_content_changes_since_last_paint(+ &self,+ viewport_size: IntSize,+ display_list: &DisplayList,+ live_content: &LiveContent,+ ) -> LiveContentChangesSinceLastPaint {+ let mut changes = LiveContentChangesSinceLastPaint::default();+ let Some(painted_frame) = &self.painted_frame else {+ changes.repaints_everything = true;+ return changes;+ };+ if painted_frame.viewport_size != viewport_size+ || painted_frame.display_list.surface_clear_color() != display_list.surface_clear_color()+ {+ changes.repaints_everything = true;+ }++ for (canvas_id, content_generation) in &painted_frame.canvas_content_generations {+ let current_content_generation = live_content+ .canvases+ .get(canvas_id)+ .map_or(0, |canvas| canvas.content_generation);+ if current_content_generation == *content_generation {+ continue;+ }+ changes.canvases.push(CanvasId(*canvas_id));+ changes.media_updates.push(MediaUpdate {+ media: LiveMedia::Canvas(CanvasId(*canvas_id)),+ content_version: current_content_generation,+ });+ }+ let summary = display_list.storage().summary();+ let image_frame_ids_of_list: HashSet<u64> = summary.image_frame_ids.iter().copied().collect();+ let video_sink_ids_of_list: HashSet<u64> = summary.video_sink_ids.iter().copied().collect();+ for (video_sink_id, frame_id) in &painted_frame.video_frame_ids {+ let current_frame_id = live_content+ .video_sinks+ .get(video_sink_id)+ .and_then(|sink| sink.has_frame.then_some(sink.frame_id));+ if current_frame_id == *frame_id {+ continue;+ }+ changes.media_updates.push(MediaUpdate {+ media: LiveMedia::VideoFrame(VideoSinkResourceId(*video_sink_id)),+ content_version: current_frame_id.unwrap_or(0),+ });+ // A video drawn only by a nested display list, such as an SVG image's, has no command in this list to+ // damage.+ if !video_sink_ids_of_list.contains(video_sink_id) {+ changes.repaints_everything = true;+ }+ changes.video_sinks.push(VideoSinkResourceId(*video_sink_id));+ }+ for (&image_frame_id, &pixel_generation) in &live_content.image_frames {+ if painted_frame.image_frame_pixel_generations.get(&image_frame_id) == Some(&pixel_generation) {+ continue;+ }+ // An image drawn only by a nested display list, such as an SVG image's, has no command in this list to+ // damage.+ if !image_frame_ids_of_list.contains(&image_frame_id) {+ changes.repaints_everything = true;+ }+ changes.image_frames.push(ImageFrameResourceId(image_frame_id));+ }+ changes+ }++ pub(super) fn frame_damage_for(+ &mut self,+ env: &PresentingEnvironment<'_>,+ pending_frame: &PendingFrame,+ frame: &FrameToPaint<'_>,+ live_content: &LiveContent,+ ) -> FrameDamage {+ let viewport_size = IntSize {+ width: pending_frame.viewport_rect.width,+ height: pending_frame.viewport_rect.height,+ };+ let viewport_rect = rect_of_size(viewport_size);+ let forced_damage_rect = pending_frame.forced_damage_rect.intersected(viewport_rect);+ let changes = self.live_content_changes_since_last_paint(viewport_size, frame.display_list, live_content);+ self.layers.media_activity.note_updates(&changes.media_updates, env.now);++ let mut layers = self.layer_update_for(env, frame, viewport_rect, live_content);+ let shown_by_window_server = match layers.plan(&self.layers) {+ Some(plan) => self.window_server_can_show_media_layers_of(env, plan, live_content),+ None => false,+ };+ layers.shown_by_window_server = shown_by_window_server;+ let layers_hold_last_frame = self.layers.has_plan() && self.painted_frame.is_some();+ let keeps_layer_rasters = match (layers.plan(&self.layers), self.layers.plan()) {+ (Some(plan), Some(last_plan)) => layers_hold_last_frame && plan.has_same_layers_as(last_plan),+ _ => false,+ };+ let repaints_everything = changes.repaints_everything || forced_damage_rect.contains_rect(viewport_rect);+ let damage = if repaints_everything {+ DisplayListDamage {+ rect: None,+ layer_rects: Vec::new(),+ }+ } else {+ self.damage_since_last_paint(+ viewport_rect,+ frame,+ forced_damage_rect,+ &changes,+ &layers,+ keeps_layer_rasters,+ )+ };+ layers.painted_damage = damage.rect.unwrap_or(viewport_rect).intersected(viewport_rect);++ let layer_count = layers.plan(&self.layers).map(|plan| plan.layers.len());+ match layer_count {+ None => {+ layers.repaints_everything =+ layers_hold_last_frame || self.layers.repaint_everything_after_dropping_layers;+ }+ Some(_) if !keeps_layer_rasters => {+ layers.fully_repainted_layer_bits = u32::MAX;+ layers.repaints_everything = true;+ }+ Some(layer_count) => {+ for index in 0..layer_count {+ let layer_damage = if damage.layer_rects.is_empty() {+ Some(layers.painted_damage)+ } else {+ damage.layer_rects[index]+ };+ if layer_damage.is_none() {+ layers.fully_repainted_layer_bits |= 1 << index;+ }+ layers+ .damage_of_layers+ .push(layer_damage.unwrap_or(viewport_rect).intersected(viewport_rect));+ }+ }+ }++ // A frame holds the canvases and videos only while the window server does not show them, so a switch either+ // way repaints all of it.+ if self.painted_frame.is_some() && layers.shown_by_window_server != self.layers.window_server_shows_media() {+ layers.repaints_everything = true;+ layers.fully_repainted_layer_bits = u32::MAX;+ }++ let live_media_changed = !changes.canvases.is_empty() || !changes.video_sinks.is_empty();+ if layers.repaints_everything {+ return FrameDamage {+ rect: viewport_rect,+ layers,+ live_media_changed,+ };+ }+ let mut damage_rect = layers.painted_damage;+ if let Some(plan) = layers.plan(&self.layers)+ && !layers.shown_by_window_server+ {+ damage_rect = damage_rect.united(+ super::layers::rect_of_media_layers_showing(plan, &changes.canvases, &changes.video_sinks)+ .intersected(viewport_rect),+ );+ }+ FrameDamage {+ rect: damage_rect,+ layers,+ live_media_changed,+ }+ }++ fn damage_since_last_paint(+ &self,+ viewport_rect: IntRect,+ frame: &FrameToPaint<'_>,+ forced_damage_rect: IntRect,+ changes: &LiveContentChangesSinceLastPaint,+ layers: &LayerUpdate,+ keeps_layer_rasters: bool,+ ) -> DisplayListDamage {+ let painted_frame = self+ .painted_frame+ .as_ref()+ .expect("a frame that does not repaint everything has a frame painted before it");+ let plan = layers.plan(&self.layers);+ let media_record_offsets: Vec<u32> = plan.map_or_else(Vec::new, |plan| plan.media_record_offsets().collect());+ let layer_plans = match (plan, self.layers.plan()) {+ (Some(plan), Some(last_plan)) if keeps_layer_rasters => Some(LayerPlans {+ old: last_plan,+ new: plan,+ }),+ _ => None,+ };+ let mut damage = frame.frame_inputs.damage_since(+ frame.display_list.storage(),+ &painted_frame.frame_inputs,+ painted_frame.display_list.storage(),+ viewport_rect,+ LiveContentChanges {+ canvases: &changes.canvases,+ video_sinks: &changes.video_sinks,+ image_frames: &changes.image_frames,+ forced_damage_rect,+ offsets_of_records_composited_as_media_layers: &media_record_offsets,+ },+ layer_plans,+ );+ if let Some(rect) = damage.rect {+ damage.rect = Some(rect.intersected(viewport_rect));+ }+ damage+ }++ pub(super) fn layers_keep_plan_for(+ &self,+ frame: &FrameToPaint<'_>,+ viewport_rect: IntRect,+ active_media: &[LiveMedia],+ ) -> bool {+ let Some(painted_frame) = &self.painted_frame else {+ return false;+ };+ self.layers.has_plan()+ && Rc::ptr_eq(&painted_frame.display_list, frame.display_list)+ && painted_frame.viewport_size.width == viewport_rect.width+ && painted_frame.viewport_size.height == viewport_rect.height+ && self.layers.plan_active_media() == active_media+ && frame.frame_inputs.places_content_like(&painted_frame.frame_inputs)+ }+}diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rsnew file mode 100644index 00000000000..03d67f6b78d--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/layers.rs@@ -0,0 +1,740 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The layers a frame is painted in while canvases and videos update often, and what of them the window server shows+//! above the frame by itself.++use super::{+ ContextPresenting, FrameToPaint, PresentingEnvironment, paint_overlays, rect_of_size, replay_into, replaying_only,+};+use crate::host::ContextTimer;+use crate::raster_host::{+ FfiSublayer, FfiSublayerPlacement, LiveContent, MediaKind, PresentableSurfaceHandle, SublayerContentKind,+ SurfaceBlend, SurfaceHandle,+};+use libcompositing_rust::display_list::commands::{CanvasId, VideoSinkResourceId};+use libcompositing_rust::display_list::layers::{LayerKind, LayerPlan, LayerPlanInputs, build_layer_plan};+use libcompositing_rust::display_list::summary::LiveContent as LiveMedia;+use libcompositing_rust::display_list::window_server_placement::WindowServerPlacement;+use libcompositing_rust::time::{Duration, MonotonicTime};+use libgfx_rust::{Color, IntRect, IntSize, ScalingMode};+use std::collections::HashMap;++const LONGEST_TIME_BETWEEN_UPDATES_THAT_ACTIVATE_MEDIA: Duration = Duration::from_milliseconds(1000);+const TIME_MEDIA_STAYS_ACTIVE_AFTER_AN_UPDATE: Duration = Duration::from_milliseconds(3000);++// The pool of presentable surfaces the overlays are shown from, apart from those of the painted layers.+const COMPOSITOR_OVERLAY_SURFACE_POOL: u32 = u32::MAX;++// Sublayers keep their identity from one frame to the next by what they show.+const CANVAS_SUBLAYER_IDENTITY_TAG: u64 = 1 << 60;+const VIDEO_SUBLAYER_IDENTITY_TAG: u64 = 2 << 60;+const PAINTED_LAYER_SUBLAYER_IDENTITY_TAG: u64 = 3 << 60;+const COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY: u64 = 4 << 60;+// Canvas and video IDs count up from 1, and stay far below this.+const MEDIA_DRAWING_INDEX_SHIFT: u32 = 44;++pub struct MediaUpdate {+ pub media: LiveMedia,+ pub content_version: u64,+}++struct MediaUpdates {+ media: LiveMedia,+ content_version: u64,+ last_update: MonotonicTime,+ active: bool,+}++/// Which canvases and videos update often enough to be layers of their own: those updated twice within a second, for+/// three seconds after their last update.+#[derive(Default)]+pub struct MediaActivity {+ updates: Vec<MediaUpdates>,+}++impl MediaActivity {+ pub fn note_updates(&mut self, updates: &[MediaUpdate], now: MonotonicTime) {+ self.updates+ .retain(|media_updates| now - media_updates.last_update <= TIME_MEDIA_STAYS_ACTIVE_AFTER_AN_UPDATE);+ for update in updates {+ self.note_update(update, now);+ }+ }++ fn note_update(&mut self, update: &MediaUpdate, now: MonotonicTime) {+ for updates in &mut self.updates {+ if updates.media != update.media {+ continue;+ }+ if updates.content_version == update.content_version {+ return;+ }+ if now - updates.last_update <= LONGEST_TIME_BETWEEN_UPDATES_THAT_ACTIVATE_MEDIA {+ updates.active = true;+ }+ updates.content_version = update.content_version;+ updates.last_update = now;+ return;+ }+ self.updates.push(MediaUpdates {+ media: update.media,+ content_version: update.content_version,+ last_update: now,+ active: false,+ });+ }++ pub fn active_media(&self, now: MonotonicTime) -> Vec<LiveMedia> {+ self.updates+ .iter()+ .filter(|updates| updates.active && now - updates.last_update <= TIME_MEDIA_STAYS_ACTIVE_AFTER_AN_UPDATE)+ .map(|updates| updates.media)+ .collect()+ }+}++#[derive(Default)]+struct LayerSurface {+ surface: Option<SurfaceHandle>,+ rect: IntRect,+ // Changes whenever anything is drawn into the surface.+ content_version: u64,+}++// The surface that the window server shows a painted layer from.+#[derive(Default)]+struct PaintedLayerPresentation {+ latest_surface: Option<PresentableSurfaceHandle>,+ rect: IntRect,+ content_version: u64,+}++/// The layers of the frames of a context, and what of them the window server shows.+#[derive(Default)]+pub struct ContextLayers {+ pub media_activity: MediaActivity,+ plan: Option<LayerPlan>,+ plan_active_media: Vec<LiveMedia>,+ surfaces: Vec<LayerSurface>,+ last_content_version: u64,+ pub repaint_everything_after_dropping_layers: bool,+ // Whether the window server shows the canvases and videos of the latest frame above it.+ window_server_shows_media: bool,+ painted_layer_presentations: Vec<PaintedLayerPresentation>,+ latest_overlay_surface: Option<PresentableSurfaceHandle>,+ overlay_rect: IntRect,+}++impl ContextLayers {+ pub fn has_plan(&self) -> bool {+ self.plan.is_some()+ }++ pub fn plan(&self) -> Option<&LayerPlan> {+ self.plan.as_ref()+ }++ pub fn plan_active_media(&self) -> &[LiveMedia] {+ &self.plan_active_media+ }++ pub fn window_server_shows_media(&self) -> bool {+ self.window_server_shows_media+ }++ pub fn drop_layers(&mut self, env: &PresentingEnvironment<'_>) {+ // NB: The drop timer runs only while there is a plan.+ if self.plan.is_none() && self.surfaces.is_empty() && self.painted_layer_presentations.is_empty() {+ return;+ }+ self.plan = None;+ self.plan_active_media.clear();+ self.surfaces.clear();+ for pool in 0..self.painted_layer_presentations.len() {+ env.raster.drop_presentable_surface_pool(env.context_id, pool as u32);+ }+ self.painted_layer_presentations.clear();+ env.host.cancel_timer(env.context_id, ContextTimer::LayerDrop);+ }++ pub fn drop_timer_fired(&mut self, env: &PresentingEnvironment<'_>) {+ // While the window server shows the media, the layers cost nothing, and the frame on screen still needs their+ // plan, as for a snapshot. The next frame without a plan puts the media back into the store.+ if self.plan.is_none() || self.window_server_shows_media {+ return;+ }+ self.drop_layers(env);+ self.repaint_everything_after_dropping_layers = true;+ }+}++/// The layers a frame is painted in, and what of each it repaints.+#[derive(Default)]+pub struct LayerUpdate {+ pub new_plan: Option<LayerPlan>,+ pub keeps_plan: bool,+ pub active_media: Vec<LiveMedia>,+ pub painted_damage: IntRect,+ pub damage_of_layers: Vec<IntRect>,+ pub fully_repainted_layer_bits: u32,+ pub repaints_everything: bool,+ pub shown_by_window_server: bool,+}++impl LayerUpdate {+ pub fn has_plan(&self) -> bool {+ self.new_plan.is_some() || self.keeps_plan+ }++ pub fn plan<'a>(&'a self, layers: &'a ContextLayers) -> Option<&'a LayerPlan> {+ if self.keeps_plan {+ layers.plan.as_ref()+ } else {+ self.new_plan.as_ref()+ }+ }+}++pub fn rect_of_media_layers_showing(+ plan: &LayerPlan,+ canvases: &[CanvasId],+ video_sinks: &[VideoSinkResourceId],+) -> IntRect {+ let mut rect = IntRect::default();+ for layer in &plan.layers {+ let LayerKind::Media { content } = layer.kind else {+ continue;+ };+ let shows_changed_media = match content {+ LiveMedia::Canvas(id) => canvases.contains(&id),+ LiveMedia::VideoFrame(id) => video_sinks.contains(&id),+ LiveMedia::ImageFrame(_) => false,+ };+ if shows_changed_media {+ rect = rect.united(layer.rect);+ }+ }+ rect+}++fn sublayer_placement_of(placement: &WindowServerPlacement) -> FfiSublayerPlacement {+ let rounded_clip = placement.rounded_clip;+ FfiSublayerPlacement {+ content_rect: placement.content_rect,+ content_to_frame: placement.content_to_viewport.values,+ clip_rect: placement.clip_rect,+ has_rounded_clip: rounded_clip.is_some(),+ rounded_clip_rect: rounded_clip.map(|clip| clip.rect).unwrap_or_default(),+ rounded_clip_radius: rounded_clip.map_or(0.0, |clip| clip.radius),+ rounds_top_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_left),+ rounds_top_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.top_right),+ rounds_bottom_right: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_right),+ rounds_bottom_left: rounded_clip.is_some_and(|clip| clip.rounded_corners.bottom_left),+ scaling_mode: placement.scaling_mode,+ }+}++// A sublayer that shows a surface at its own rect, unclipped and untransformed.+fn surface_sublayer(identity: u64, surface: &PresentableSurfaceHandle, rect: IntRect) -> FfiSublayer {+ FfiSublayer {+ identity,+ content_kind: SublayerContentKind::PresentableSurface,+ media_id: 0,+ presentable_surface: surface.as_ptr(),+ placement: FfiSublayerPlacement {+ content_rect: rect,+ content_to_frame: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],+ clip_rect: rect.to_float(),+ scaling_mode: ScalingMode::NearestNeighbor,+ ..Default::default()+ },+ }+}++impl ContextPresenting {+ pub(super) fn layer_update_for(+ &self,+ env: &PresentingEnvironment<'_>,+ frame: &FrameToPaint<'_>,+ viewport_rect: IntRect,+ live_content: &LiveContent,+ ) -> LayerUpdate {+ let mut layers = LayerUpdate::default();+ if !self.presents_to_client {+ return layers;+ }+ layers.active_media = self.layers.media_activity.active_media(env.now);+ // An HDR video is a layer from its first frame for as long as it is drawn, even while paused, so that the window+ // server keeps showing it brighter than SDR white instead of it going back into the frame, which holds SDR.+ if self.remote_layer_may_show_media(env.has_gpu)+ && env.raster.remote_layer_can_show_high_dynamic_range(env.context_id)+ && env.window_server_may_show_high_dynamic_range+ {+ for id in &frame.display_list.storage().summary().video_sink_ids {+ let media = LiveMedia::VideoFrame(VideoSinkResourceId(*id));+ if layers.active_media.contains(&media) {+ continue;+ }+ let holds_high_dynamic_range = live_content+ .video_sinks+ .get(id)+ .is_some_and(|sink| sink.has_frame && sink.frame_holds_high_dynamic_range);+ if holds_high_dynamic_range {+ layers.active_media.push(media);+ }+ }+ }+ if layers.active_media.is_empty() {+ return layers;+ }+ if self.layers_keep_plan_for(frame, viewport_rect, &layers.active_media) {+ layers.keeps_plan = true;+ return layers;+ }+ let storage = frame.display_list.storage();+ let tree = frame.frame_inputs.visual_context_tree.as_arc();+ layers.new_plan = build_layer_plan(&LayerPlanInputs {+ tape: storage.bytes(),+ command_runs: storage.command_runs(),+ summary: storage.summary(),+ effect_clips: storage.effect_clip_plan(tree),+ tree,+ scroll_offsets: frame.frame_inputs.presented_scroll_state_snapshot.device_offsets(),+ viewport_rect,+ active_media: &layers.active_media,+ })+ .ok();+ layers+ }++ pub(super) fn window_server_can_show_media_layers_of(+ &self,+ env: &PresentingEnvironment<'_>,+ plan: &LayerPlan,+ live_content: &LiveContent,+ ) -> bool {+ if !self.remote_layer_may_show_media(env.has_gpu) {+ return false;+ }+ for layer in &plan.layers {+ let LayerKind::Media { content } = layer.kind else {+ continue;+ };+ let Some(Ok(placement)) = &layer.window_server_placement else {+ return false;+ };+ let (kind, id) = match content {+ LiveMedia::Canvas(id) => {+ let has_presentable_surface = live_content+ .canvases+ .get(&id.0)+ .is_some_and(|canvas| canvas.has_presentable_surface);+ if !has_presentable_surface {+ return false;+ }+ (MediaKind::Canvas, id.0)+ }+ LiveMedia::VideoFrame(id) => {+ let Some(sink) = live_content.video_sinks.get(&id.0).filter(|sink| sink.has_frame) else {+ return false;+ };+ if !env.window_server_may_show_high_dynamic_range && sink.frame_holds_high_dynamic_range {+ return false;+ }+ (MediaKind::Video, id.0)+ }+ LiveMedia::ImageFrame(_) => return false,+ };+ if !env.raster.remote_layer_can_show(+ env.context_id,+ kind,+ id,+ &sublayer_placement_of(placement),+ self.device_pixel_ratio,+ ) {+ return false;+ }+ }+ true+ }++ pub(super) fn commit_layer_update(&mut self, env: &PresentingEnvironment<'_>, layer_update: LayerUpdate) {+ let layers = &mut self.layers;+ layers.window_server_shows_media = layer_update.has_plan() && layer_update.shown_by_window_server;+ if layer_update.repaints_everything {+ layers.repaint_everything_after_dropping_layers = false;+ }+ if !layer_update.has_plan() {+ layers.drop_layers(env);+ return;+ }+ if let Some(new_plan) = layer_update.new_plan {+ layers.plan = Some(new_plan);+ }+ layers.plan_active_media = layer_update.active_media;+ env.host.set_timer(+ env.context_id,+ ContextTimer::LayerDrop,+ TIME_MEDIA_STAYS_ACTIVE_AFTER_AN_UPDATE,+ );+ }++ pub(super) fn paint_layered_frame(+ &mut self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ damage_rect: IntRect,+ layer_update: &LayerUpdate,+ ) -> bool {+ // The plan a frame keeps stays with the layers, out of their way while they are painted.+ let kept_plan = if layer_update.keeps_plan {+ self.layers.plan.take()+ } else {+ None+ };+ let plan = kept_plan+ .as_ref()+ .or(layer_update.new_plan.as_ref())+ .expect("a layered frame has a plan");+ let painted = self.paint_layers(env, surface, frame, damage_rect, layer_update, plan);+ if layer_update.keeps_plan {+ self.layers.plan = kept_plan;+ }+ painted+ }++ fn paint_layers(+ &mut self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ damage_rect: IntRect,+ layer_update: &LayerUpdate,+ plan: &LayerPlan,+ ) -> bool {+ let raster = env.raster;+ let viewport_size = self.viewport_size;+ let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);+ raster.start_raster_cache_frame(env.context_id);+ let layer_count = plan.layers.len();++ let mut surfaces = std::mem::take(&mut self.layers.surfaces);+ surfaces.resize_with(layer_count, LayerSurface::default);+ for (index, layer) in plan.layers.iter().enumerate() {+ let layer_surface = &mut surfaces[index];+ let is_base = matches!(layer.kind, LayerKind::Base);+ let rect = if is_base {+ rect_of_size(viewport_size)+ } else {+ layer.rect+ };+ if matches!(layer.kind, LayerKind::Media { .. }) || rect.is_empty() {+ *layer_surface = LayerSurface::default();+ continue;+ }+ let mut repaints_whole_layer = (layer_update.fully_repainted_layer_bits & (1 << index)) != 0;+ let surface_fits = if is_base {+ layer_surface.rect == rect+ } else {+ layer_surface.rect.contains_rect(rect)+ };+ let shares_backend = layer_surface+ .surface+ .as_ref()+ .is_some_and(|layer_surface| raster.surfaces_share_backend(layer_surface, surface));+ if layer_surface.surface.is_none() || !surface_fits || !shares_backend {+ let Some(new_surface) = raster.create_surface(+ IntSize {+ width: rect.width,+ height: rect.height,+ },+ Some(surface),+ ) else {+ self.layers.surfaces = surfaces;+ return false;+ };+ *layer_surface = LayerSurface {+ surface: Some(new_surface),+ rect,+ content_version: 0,+ };+ repaints_whole_layer = true;+ }+ let repaint_rect = if repaints_whole_layer {+ layer_surface.rect+ } else {+ layer_update.damage_of_layers[index].intersected(layer_surface.rect)+ };+ if repaint_rect.is_empty() {+ continue;+ }+ let target = layer_surface.surface.as_ref().expect("the layer has a surface");+ let save_count = raster.save(target);+ raster.translate(target, -layer_surface.rect.x as f32, -layer_surface.rect.y as f32);+ raster.clip_rect(target, repaint_rect);+ raster.clear(+ target,+ if is_base {+ surface_clear_color+ } else {+ Color::TRANSPARENT+ },+ );+ replay_into(env, target, frame, replaying_only(&layer.record_spans, false));+ raster.restore_to_count(target, save_count);+ self.layers.last_content_version += 1;+ layer_surface.content_version = self.layers.last_content_version;+ }+ self.layers.surfaces = surfaces;++ let save_count = raster.save(surface);+ raster.clip_rect(surface, damage_rect);+ if let Some(base_surface) = self.layers.surfaces.first()+ && let Some(base) = &base_surface.surface+ && base_surface.rect.intersected(damage_rect) != IntRect::default()+ {+ raster.draw_surface(+ surface,+ base,+ IntRect::new(0, 0, base_surface.rect.width, base_surface.rect.height),+ base_surface.rect,+ SurfaceBlend::Source,+ );+ }+ if !layer_update.shown_by_window_server {+ self.composite_layers_above_base_with_plan(env, surface, frame, plan, damage_rect);+ paint_overlays(env, surface, frame.frame_inputs, true);+ }+ raster.restore_to_count(surface, save_count);++ // The window server shows everything above the base layer from surfaces of its own.+ if layer_update.shown_by_window_server {+ if !self.present_painted_layers_to_window_server(env, plan, surface) {+ return false;+ }+ if !self.present_compositor_overlays_to_window_server(env, frame, surface) {+ return false;+ }+ }+ true+ }++ pub(super) fn composite_layers_above_base(+ &self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ damage_rect: IntRect,+ ) {+ let Some(plan) = self.layers.plan() else {+ return;+ };+ self.composite_layers_above_base_with_plan(env, surface, frame, plan, damage_rect);+ }++ fn composite_layers_above_base_with_plan(+ &self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ plan: &LayerPlan,+ damage_rect: IntRect,+ ) {+ for (index, layer) in plan.layers.iter().enumerate().skip(1) {+ if matches!(layer.kind, LayerKind::Media { .. }) {+ if !layer.rect.intersected(damage_rect).is_empty() {+ replay_into(env, surface, frame, replaying_only(&layer.record_spans, true));+ }+ continue;+ }+ let Some(layer_surface) = self.layers.surfaces.get(index) else {+ continue;+ };+ let Some(source) = &layer_surface.surface else {+ continue;+ };+ if layer_surface.rect.intersected(damage_rect).is_empty() {+ continue;+ }+ env.raster.draw_surface(+ surface,+ source,+ IntRect::new(0, 0, layer_surface.rect.width, layer_surface.rect.height),+ layer_surface.rect,+ SurfaceBlend::SourceOver,+ );+ }+ }++ // Each painted layer goes to the window server as its own surface, which is copied from its raster when the raster+ // changes. The window server may still show the surface of the frame before, so the copy goes into another one.+ fn present_painted_layers_to_window_server(+ &mut self,+ env: &PresentingEnvironment<'_>,+ plan: &LayerPlan,+ like: &SurfaceHandle,+ ) -> bool {+ let raster = env.raster;+ let layers = &mut self.layers;+ // The surfaces of the layers that the plan no longer has go with them.+ for pool in plan.layers.len()..layers.painted_layer_presentations.len() {+ raster.drop_presentable_surface_pool(env.context_id, pool as u32);+ }+ layers+ .painted_layer_presentations+ .resize_with(plan.layers.len(), PaintedLayerPresentation::default);+ for (index, layer) in plan.layers.iter().enumerate() {+ let presentation = &mut layers.painted_layer_presentations[index];+ let layer_surface = layers.surfaces.get(index);+ let source = layer_surface.and_then(|layer_surface| layer_surface.surface.as_ref());+ let (Some(layer_surface), Some(source)) = (layer_surface, source) else {+ presentation.latest_surface = None;+ continue;+ };+ if !matches!(layer.kind, LayerKind::Painted) || layer.rect.is_empty() {+ presentation.latest_surface = None;+ continue;+ }+ if presentation.latest_surface.is_some()+ && presentation.rect == layer.rect+ && presentation.content_version == layer_surface.content_version+ {+ continue;+ }+ let layer_size = IntSize {+ width: layer.rect.width,+ height: layer.rect.height,+ };+ let Some(presentable) = raster.next_presentable_surface(env.context_id, index as u32, layer_size, like)+ else {+ return false;+ };+ let target = raster.painting_surface_of(&presentable);+ let source_rect = IntRect::new(+ layer.rect.x - layer_surface.rect.x,+ layer.rect.y - layer_surface.rect.y,+ layer.rect.width,+ layer.rect.height,+ );+ raster.draw_surface(+ &target,+ source,+ source_rect,+ rect_of_size(layer_size),+ SurfaceBlend::Source,+ );+ presentation.latest_surface = Some(presentable);+ presentation.rect = layer.rect;+ presentation.content_version = layer_surface.content_version;+ }+ true+ }++ fn present_compositor_overlays_to_window_server(+ &mut self,+ env: &PresentingEnvironment<'_>,+ frame: &FrameToPaint<'_>,+ like: &SurfaceHandle,+ ) -> bool {+ let raster = env.raster;+ let bounds = frame.frame_inputs.overlays.bounds;+ self.layers.overlay_rect = bounds;+ if bounds.is_empty() {+ self.layers.latest_overlay_surface = None;+ return true;+ }+ let bounds_size = IntSize {+ width: bounds.width,+ height: bounds.height,+ };+ let Some(presentable) =+ raster.next_presentable_surface(env.context_id, COMPOSITOR_OVERLAY_SURFACE_POOL, bounds_size, like)+ else {+ return false;+ };+ let target = raster.painting_surface_of(&presentable);+ raster.clear(&target, Color::TRANSPARENT);+ let save_count = raster.save(&target);+ raster.translate(&target, -bounds.x as f32, -bounds.y as f32);+ paint_overlays(env, &target, frame.frame_inputs, true);+ raster.restore_to_count(&target, save_count);+ self.layers.latest_overlay_surface = Some(presentable);+ true+ }++ pub(super) fn sublayers_shown_by_window_server(&self, live_content: &LiveContent) -> Vec<FfiSublayer> {+ let layers = &self.layers;+ let mut sublayers = Vec::new();+ let Some(plan) = layers.plan.as_ref().filter(|_| layers.window_server_shows_media) else {+ return sublayers;+ };+ // The same canvas or video can be drawn by more than one record, and each drawing is a sublayer of its own.+ let mut drawings_of_media: HashMap<u64, u64> = HashMap::new();+ for (index, layer) in plan.layers.iter().enumerate().skip(1) {+ if let LayerKind::Media { content } = layer.kind {+ let Some(Ok(placement)) = &layer.window_server_placement else {+ continue;+ };+ let (kind, id, mut identity, has_content) = match content {+ LiveMedia::Canvas(id) => (+ SublayerContentKind::Canvas,+ id.0,+ CANVAS_SUBLAYER_IDENTITY_TAG | id.0,+ live_content+ .canvases+ .get(&id.0)+ .is_some_and(|canvas| canvas.has_presentable_surface),+ ),+ LiveMedia::VideoFrame(id) => (+ SublayerContentKind::Video,+ id.0,+ VIDEO_SUBLAYER_IDENTITY_TAG | id.0,+ live_content+ .video_sinks+ .get(&id.0)+ .is_some_and(|sink| sink.has_frame && sink.frame_has_surface),+ ),+ LiveMedia::ImageFrame(_) => continue,+ };+ if !has_content {+ continue;+ }+ let earlier_drawings = drawings_of_media.entry(identity).or_insert(0);+ identity |= *earlier_drawings << MEDIA_DRAWING_INDEX_SHIFT;+ *earlier_drawings += 1;+ sublayers.push(FfiSublayer {+ identity,+ content_kind: kind,+ media_id: id,+ presentable_surface: std::ptr::null_mut(),+ placement: sublayer_placement_of(placement),+ });+ continue;+ }+ let Some(presentation) = layers.painted_layer_presentations.get(index) else {+ continue;+ };+ let Some(surface) = &presentation.latest_surface else {+ continue;+ };+ sublayers.push(surface_sublayer(+ PAINTED_LAYER_SUBLAYER_IDENTITY_TAG | index as u64,+ surface,+ presentation.rect,+ ));+ }+ if let Some(surface) = &layers.latest_overlay_surface {+ sublayers.push(surface_sublayer(+ COMPOSITOR_OVERLAY_SUBLAYER_IDENTITY,+ surface,+ layers.overlay_rect,+ ));+ }+ sublayers+ }+}diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rsnew file mode 100644index 00000000000..fd84adf7c10--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/mod.rs@@ -0,0 +1,851 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! How the frames of one context are presented: which frame is next, what of it to repaint, the layers it is painted+//! in, and the rasters of it the backing stores and the window server hold. The painting itself is done by the raster+//! host.++mod damage;+mod layers;+pub mod pacing;++use crate::frame_inputs::FrameInputs;+use crate::host::{ContextTimer, Host, PendingFrame};+use crate::raster_host::{+ FfiStoreResize, FfiSublayer, PaintingResources, RasterHost, StorePublication, StoreResizeOutcome, SurfaceBlend,+ SurfaceHandle,+};+use damage::{PaintedFrame, StoreDamage};+use layers::ContextLayers;+use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::display_list::replay::{+ CompositedContexts, ReplayFrame, ReplaySelection, ResolvedCompositedContext, replay_display_list,+};+use libcompositing_rust::host::RecordSpan;+use libcompositing_rust::scrolling::DisplayList;+use libcompositing_rust::time::{Duration, MonotonicTime};+use libgfx_rust::{Color, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize, enclosing_int_rect};+use pacing::PacedTickRequest;+use std::rc::Rc;++const BACKING_STORE_SHRINK_DELAY: Duration = Duration::from_milliseconds(3000);+const SURPLUS_STORE_RETIREMENT_DELAY: Duration = Duration::from_milliseconds(3000);++/// What presenting a frame of a context works with besides the context's own state.+pub struct PresentingEnvironment<'a> {+ pub context_id: CompositorContextId,+ pub raster: &'a RasterHost,+ pub host: &'a Host,+ pub now: MonotonicTime,+ pub has_gpu: bool,+ pub window_server_may_show_high_dynamic_range: bool,+ pub composited_contexts: &'a dyn CompositedContexts,+}++/// A frame drawn into a store, or for a frame that changes only what the window server shows above the frame on+/// screen, into nothing.+pub struct PreparedFrame {+ pub rendered_surface: Option<SurfaceHandle>,+ pub bitmap_id: i32,+ pub damage_rect: IntRect,+ pub device_pixel_ratio: f64,+ // What the window server shows above the frame, bottom to top, lent by the presenting state until the next frame.+ pub sublayers: Vec<FfiSublayer>,+}++// The display list and the frame inputs a frame is painted with.+pub(crate) struct FrameToPaint<'a> {+ pub display_list: &'a Rc<DisplayList>,+ pub frame_inputs: &'a FrameInputs,+}++// Bounds the embedding scale of a nested context's raster, so that the two backing stores together use at most 128 MiB,+// even when an embedding transform magnifies a large iframe.+fn bounded_composited_raster_scale(mut scale: FloatSize, viewport_size: IntSize) -> FloatSize {+ if viewport_size.width <= 0 || viewport_size.height <= 0 {+ return FloatSize {+ width: 1.0,+ height: 1.0,+ };+ }+ scale = FloatSize {+ width: scale.width.clamp(0.25, 5.0),+ height: scale.height.clamp(0.25, 5.0),+ };+ // Reserve a pixel on each axis for fractional placement.+ const MAXIMUM_DIMENSION: f32 = 16384.0;+ const MAXIMUM_PIXELS: f32 = 16.0 * 1024.0 * 1024.0;+ scale.width = scale.width.min((MAXIMUM_DIMENSION - 1.0) / viewport_size.width as f32);+ scale.height = scale+ .height+ .min((MAXIMUM_DIMENSION - 1.0) / viewport_size.height as f32);+ let pixel_count = (viewport_size.width as f32 * scale.width) * (viewport_size.height as f32 * scale.height);+ const MAXIMUM_CONTENT_PIXELS: f32 = MAXIMUM_PIXELS - 2.0 * MAXIMUM_DIMENSION - 1.0;+ if pixel_count > MAXIMUM_CONTENT_PIXELS {+ let factor = (MAXIMUM_CONTENT_PIXELS / pixel_count).sqrt();+ scale.width *= factor;+ scale.height *= factor;+ }+ scale+}++fn rect_of_size(size: IntSize) -> IntRect {+ IntRect::new(0, 0, size.width, size.height)+}++pub struct ContextPresenting {+ pub presents_to_client: bool,+ pub display_id: Option<u64>,+ pub display_refresh_rate: f64,+ // Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.+ pub presents_from_cpu_memory: bool,+ pub shown_in_remote_layer: bool,+ // The viewport size of the frame that the page presented last, which it laid out at.+ pub size_laid_out_by_page: IntSize,+ pub rendering_opportunity_request: PacedTickRequest,+ pub clock_tick_request: PacedTickRequest,++ viewport_size: IntSize,+ device_pixel_ratio: f64,+ window_resize_in_progress: bool,++ pending_present_frame: Option<PendingFrame>,+ pending_present_frame_scheduled: bool,+ presented_frame: Option<IntRect>,++ store_publication: StorePublication,+ frame_without_store_in_flight: bool,+ latest_rendered_surface: Option<SurfaceHandle>,+ // The frame that the latest rendered surface holds, which the presented frame runs ahead of while its GPU work is in+ // flight.+ size_of_latest_rendered_frame: IntSize,+ store_damage: StoreDamage,+ damage_surface: Option<SurfaceHandle>,+ surplus_store_retirement_is_scheduled: bool,++ unbounded_raster_scale_of_embedding: FloatSize,+ raster_scale: FloatSize,+ raster_translation: FloatPoint,++ painted_frame: Option<PaintedFrame>,+ layers: ContextLayers,+}++impl ContextPresenting {+ pub fn new(presents_to_client: bool) -> Self {+ Self {+ presents_to_client,+ display_id: None,+ display_refresh_rate: 60.0,+ presents_from_cpu_memory: false,+ shown_in_remote_layer: false,+ size_laid_out_by_page: IntSize::default(),+ rendering_opportunity_request: PacedTickRequest::default(),+ clock_tick_request: PacedTickRequest::default(),+ viewport_size: IntSize::default(),+ device_pixel_ratio: 1.0,+ window_resize_in_progress: false,+ pending_present_frame: None,+ pending_present_frame_scheduled: false,+ presented_frame: None,+ store_publication: StorePublication::Unpublished,+ frame_without_store_in_flight: false,+ latest_rendered_surface: None,+ size_of_latest_rendered_frame: IntSize::default(),+ store_damage: StoreDamage::default(),+ damage_surface: None,+ surplus_store_retirement_is_scheduled: false,+ unbounded_raster_scale_of_embedding: FloatSize {+ width: 1.0,+ height: 1.0,+ },+ raster_scale: FloatSize {+ width: 1.0,+ height: 1.0,+ },+ raster_translation: FloatPoint::default(),+ painted_frame: None,+ layers: ContextLayers::default(),+ }+ }++ pub fn store_publication(&self) -> StorePublication {+ self.store_publication+ }++ // The window server reads what it shows above the store straight from GPU memory.+ pub fn remote_layer_may_show_media(&self, has_gpu: bool) -> bool {+ self.shown_in_remote_layer && has_gpu && !self.presents_from_cpu_memory+ }++ pub fn set_viewport_size(+ &mut self,+ viewport_size: IntSize,+ device_pixel_ratio: f64,+ window_resize_in_progress: bool,+ ) {+ self.viewport_size = viewport_size;+ self.device_pixel_ratio = device_pixel_ratio;+ self.window_resize_in_progress = window_resize_in_progress;+ }++ pub fn window_resize_in_progress(&self) -> bool {+ self.window_resize_in_progress+ }++ pub fn schedule_backing_store_shrink(&self, context_id: CompositorContextId, host: &Host) {+ host.set_timer(context_id, ContextTimer::BackingStoreShrink, BACKING_STORE_SHRINK_DELAY);+ }++ pub fn finish_window_resize(&mut self) {+ self.window_resize_in_progress = false;+ }++ // The viewport rect of the next frame, or of the frame presented last, at the viewport size.+ pub fn viewport_rect_of_current_frame(&self) -> Option<IntRect> {+ if self.viewport_size.is_empty() {+ return None;+ }+ let mut viewport_rect = match &self.pending_present_frame {+ Some(pending_frame) => pending_frame.viewport_rect,+ None => self.presented_frame.unwrap_or_default(),+ };+ viewport_rect.width = self.viewport_size.width;+ viewport_rect.height = self.viewport_size.height;+ Some(viewport_rect)+ }++ /// Resizes the stores to the raster size the context presents at, answering whether they were reallocated.+ pub fn resize_backing_stores_if_needed(+ &mut self,+ env: &PresentingEnvironment<'_>,+ mut publication: StorePublication,+ gpu_sharing_allowed: bool,+ presentation_id: Option<u64>,+ ) -> StoreResizeOutcome {+ if env.raster.store_state(env.context_id).is_rendering {+ return StoreResizeOutcome::Unchanged;+ }+ if !self.presents_to_client {+ // A resize can arrive before the parent's next replay supplies the new embedding transform. Bound the+ // existing embedding's scale for the new viewport before allocating backing stores. Bounding the already+ // bounded scale instead can round it differently, which would discard the raster on every replay.+ let scale = bounded_composited_raster_scale(self.unbounded_raster_scale_of_embedding, self.viewport_size);+ if self.raster_scale != scale {+ self.raster_scale = scale;+ self.latest_rendered_surface = None;+ self.painted_frame = None;+ }+ publication = StorePublication::Unpublished;+ }+ let outcome = env.raster.resize_stores(+ env.context_id,+ &FfiStoreResize {+ raster_size: self.raster_size(),+ window_resize_in_progress: self.window_resize_in_progress,+ publication,+ gpu_sharing_allowed,+ has_presentation: presentation_id.is_some(),+ presentation_id: presentation_id.unwrap_or_default(),+ },+ );+ if outcome != StoreResizeOutcome::Unchanged {+ self.store_publication = publication;+ self.latest_rendered_surface = None;+ self.painted_frame = None;+ self.store_damage.forget_every_store();+ }+ outcome+ }++ pub fn invalidate_backing_stores(&mut self, env: &PresentingEnvironment<'_>) {+ env.raster.invalidate_stores(env.context_id);+ self.frame_without_store_in_flight = false;+ }++ pub fn wants_backing_store_for_pending_frame(+ &self,+ display_list: Option<&Rc<DisplayList>>,+ raster: &RasterHost,+ context_id: CompositorContextId,+ ) -> bool {+ self.presents_to_client+ && self.pending_present_frame.is_some()+ && self.can_render_frame(display_list, raster, context_id)+ }++ /// Schedules the retirement of the stores added for a burst of frames, unless it is scheduled already.+ pub fn schedule_surplus_store_retirement(&mut self, context_id: CompositorContextId, host: &Host) {+ if self.surplus_store_retirement_is_scheduled {+ return;+ }+ self.surplus_store_retirement_is_scheduled = true;+ host.set_timer(+ context_id,+ ContextTimer::SurplusStoreRetirement,+ SURPLUS_STORE_RETIREMENT_DELAY,+ );+ }++ pub fn surplus_store_retirement_fired(&mut self) {+ self.surplus_store_retirement_is_scheduled = false;+ }++ pub fn did_finish_gpu_present(&mut self, env: &PresentingEnvironment<'_>, bitmap_id: i32, frame_size: IntSize) {+ env.raster.complete_rendering(env.context_id, bitmap_id);+ self.latest_rendered_surface = env.raster.latest_rendered_store_surface(env.context_id);+ self.size_of_latest_rendered_frame = frame_size;+ }++ pub fn did_deliver_frame_without_store(&mut self) {+ self.frame_without_store_in_flight = false;+ }++ pub fn has_latest_rendered_surface(&self) -> bool {+ self.latest_rendered_surface.is_some()+ }++ /// Answers whether the raster has to be made again, at the scale and phase the embedding now draws it at.+ pub fn update_composited_raster_transform(+ &mut self,+ is_rendering: bool,+ destination_rect: FloatRect,+ transform: &FloatMatrix4x4,+ ) -> bool {+ if self.presents_to_client || is_rendering || self.viewport_size.is_empty() || destination_rect.is_empty() {+ return false;+ }+ let m = &transform.elements;+ // Display list coordinates already include device scale and page zoom. Only the embedding transform and+ // the viewport-to-destination mapping belong here; neither changes the child's layout or scroll geometry.+ let has_perspective = m[3][0] != 0.0 || m[3][1] != 0.0 || m[3][3] != 1.0;+ let mut scale_x = 1.0f32;+ let mut scale_y = 1.0f32;+ if !has_perspective {+ scale_x = ak::math::hypot(m[0][0], m[1][0]) * destination_rect.width / self.viewport_size.width as f32;+ scale_y = ak::math::hypot(m[0][1], m[1][1]) * destination_rect.height / self.viewport_size.height as f32;+ }+ if !scale_x.is_finite() || !scale_y.is_finite() {+ return false;+ }+ self.unbounded_raster_scale_of_embedding = FloatSize {+ width: scale_x,+ height: scale_y,+ };++ // Perspective keeps the native resolution until we can choose a scale from the visible projected region.+ let scale = bounded_composited_raster_scale(self.unbounded_raster_scale_of_embedding, self.viewport_size);++ let mut translation = FloatPoint::default();+ if !has_perspective && m[0][1] == 0.0 && m[1][0] == 0.0 && scale.width == scale_x && scale.height == scale_y {+ let mut x = m[0][0] * destination_rect.x + m[0][3];+ let mut y = m[1][1] * destination_rect.y + m[1][3];+ if !x.is_finite() || !y.is_finite() {+ return false;+ }+ // Mirrored placements need the opposite fractional phase so the remaining image transform still+ // lands on integer device pixels.+ if m[0][0] < 0.0 {+ x = -x;+ }+ if m[1][1] < 0.0 {+ y = -y;+ }+ translation = FloatPoint {+ x: x - x.floor(),+ y: y - y.floor(),+ };+ }++ if self.raster_scale == scale && self.raster_translation == translation {+ return false;+ }+ self.raster_scale = scale;+ self.raster_translation = translation;+ self.latest_rendered_surface = None;+ self.painted_frame = None;+ true+ }++ pub fn composited_surface(&self) -> Option<ResolvedCompositedContext> {+ let surface = self.latest_rendered_surface.as_ref()?;+ let painted_frame = self.painted_frame.as_ref()?;+ Some(ResolvedCompositedContext {+ surface: surface.as_ptr(),+ content_rect: FloatRect::new(+ self.raster_translation.x,+ self.raster_translation.y,+ painted_frame.viewport_size.width as f32 * self.raster_scale.width,+ painted_frame.viewport_size.height as f32 * self.raster_scale.height,+ ),+ })+ }++ pub fn queue_present_frame(&mut self, pending_frame: PendingFrame) {+ let Some(queued) = &mut self.pending_present_frame else {+ self.pending_present_frame = Some(pending_frame);+ return;+ };+ if queued.viewport_rect.width != pending_frame.viewport_rect.width+ || queued.viewport_rect.height != pending_frame.viewport_rect.height+ {+ self.pending_present_frame = Some(PendingFrame::repainting_everything(pending_frame.viewport_rect));+ return;+ }+ queued.viewport_rect = pending_frame.viewport_rect;+ queued.forced_damage_rect = queued.forced_damage_rect.united(pending_frame.forced_damage_rect);+ }++ pub fn mark_pending_present_frame_scheduled(&mut self) {+ self.pending_present_frame_scheduled = true;+ }++ pub fn unschedule_pending_present_frame(&mut self) {+ self.pending_present_frame_scheduled = false;+ }++ pub fn pending_present_frame_scheduled(&self) -> bool {+ self.pending_present_frame_scheduled+ }++ pub fn can_schedule_pending_present_frame_if_unblocked(+ &self,+ raster: &RasterHost,+ context_id: CompositorContextId,+ ) -> bool {+ !self.is_present_blocked(raster, context_id)+ && self.pending_present_frame.is_some()+ && !self.pending_present_frame_scheduled+ }++ pub fn take_pending_present_frame_if_unblocked(+ &mut self,+ raster: &RasterHost,+ context_id: CompositorContextId,+ ) -> Option<PendingFrame> {+ if self.is_present_blocked(raster, context_id) {+ return None;+ }+ self.pending_present_frame_scheduled = false;+ self.pending_present_frame.take()+ }++ pub fn needs_rasterization(&self) -> bool {+ self.pending_present_frame.is_some()+ || (self.latest_rendered_surface.is_none() && self.presented_frame.is_some())+ }++ pub fn frame_rect_to_repaint(&self) -> Option<IntRect> {+ match &self.pending_present_frame {+ Some(pending_frame) => Some(pending_frame.viewport_rect),+ None => self.presented_frame,+ }+ }++ pub fn self_present_rect(&self) -> Option<IntRect> {+ if self.presented_frame.is_some() {+ return self.presented_frame;+ }+ (!self.viewport_size.is_empty()).then(|| rect_of_size(self.viewport_size))+ }++ pub fn draws_canvas(&self, canvas_id: u64) -> bool {+ self.painted_frame+ .as_ref()+ .is_some_and(|painted_frame| painted_frame.draws_canvas(canvas_id))+ }++ pub fn did_submit_prepared_frame(&mut self, viewport_rect: IntRect) {+ self.presented_frame = Some(viewport_rect);+ }++ fn is_present_blocked(&self, raster: &RasterHost, context_id: CompositorContextId) -> bool {+ let state = raster.store_state(context_id);+ state.is_rendering || self.frame_without_store_in_flight || !state.has_available_store+ }++ fn can_render_frame(+ &self,+ display_list: Option<&Rc<DisplayList>>,+ raster: &RasterHost,+ context_id: CompositorContextId,+ ) -> bool {+ display_list.is_some() && raster.store_state(context_id).is_valid+ }++ fn raster_size(&self) -> IntSize {+ if self.viewport_size.is_empty() {+ return IntSize::default();+ }+ if self.presents_to_client {+ return self.viewport_size;+ }+ IntSize {+ width: (self.viewport_size.width as f32 * self.raster_scale.width + self.raster_translation.x).ceil()+ as i32,+ height: (self.viewport_size.height as f32 * self.raster_scale.height + self.raster_translation.y).ceil()+ as i32,+ }+ }++ fn raster_damage_rect(&self, damage_rect: IntRect) -> IntRect {+ if damage_rect.is_empty() {+ return IntRect::default();+ }+ let raster_rect = rect_of_size(self.raster_size());+ if damage_rect.contains_rect(rect_of_size(self.viewport_size)) {+ return raster_rect;+ }+ let rect = damage_rect.to_float();+ let scaled = FloatRect::new(+ rect.x * self.raster_scale.width + self.raster_translation.x,+ rect.y * self.raster_scale.height + self.raster_translation.y,+ rect.width * self.raster_scale.width,+ rect.height * self.raster_scale.height,+ );+ enclosing_int_rect(scaled).intersected(raster_rect)+ }++ /// The frame painted into a store, or none where it is blocked, held back, or has nothing new to show.+ pub fn prepare_frame(+ &mut self,+ env: &PresentingEnvironment<'_>,+ pending_frame: PendingFrame,+ display_list: Option<&Rc<DisplayList>>,+ frame_inputs: Option<FrameInputs>,+ ) -> Option<PreparedFrame> {+ if self.is_present_blocked(env.raster, env.context_id) {+ self.queue_present_frame(pending_frame);+ return None;+ }+ if !self.can_render_frame(display_list, env.raster, env.context_id) {+ self.presented_frame = Some(pending_frame.viewport_rect);+ return None;+ }+ let display_list = display_list.expect("a frame that can render has a display list");+ let frame_inputs = frame_inputs.expect("a context with a display list has frame inputs");+ let live_content = self.live_content(env, display_list);+ let frame = FrameToPaint {+ display_list,+ frame_inputs: &frame_inputs,+ };+ let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);+ let mut damage_rect = frame_damage.rect;+ // NB: A changed content rect must still reach the client even if the pixels are identical.+ if damage_rect.is_empty() && self.presented_frame == Some(pending_frame.viewport_rect) {+ let only_media_shown_by_window_server_changed =+ frame_damage.layers.shown_by_window_server && frame_damage.live_media_changed;+ self.commit_layer_update(env, frame_damage.layers);+ self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ if !only_media_shown_by_window_server_changed {+ return None;+ }+ self.frame_without_store_in_flight = true;+ return Some(PreparedFrame {+ rendered_surface: None,+ bitmap_id: -1,+ damage_rect: IntRect::default(),+ device_pixel_ratio: self.device_pixel_ratio,+ sublayers: self.sublayers_shown_by_window_server(&live_content),+ });+ }+ let raster_damage_rect = self.raster_damage_rect(damage_rect);+ let Some((bitmap_id, store)) = env.raster.acquire_store(env.context_id) else {+ self.queue_present_frame(pending_frame);+ return None;+ };+ let store_rect = rect_of_size(env.raster.surface_size(&store));+ let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);+ let painted_rect = self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);+ if painted_rect != repaint_rect {+ damage_rect = rect_of_size(IntSize {+ width: pending_frame.viewport_rect.width,+ height: pending_frame.viewport_rect.height,+ });+ }+ self.commit_layer_update(env, frame_damage.layers);+ self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ Some(PreparedFrame {+ rendered_surface: Some(store),+ bitmap_id,+ damage_rect,+ device_pixel_ratio: self.device_pixel_ratio,+ sublayers: self.sublayers_shown_by_window_server(&live_content),+ })+ }++ /// Paints the pending frame, or the frame presented last, into a store at once, for a context that its parent draws.+ pub fn present_synchronously(+ &mut self,+ env: &PresentingEnvironment<'_>,+ display_list: Option<&Rc<DisplayList>>,+ frame_inputs: Option<FrameInputs>,+ ) -> bool {+ if !self.can_render_frame(display_list, env.raster, env.context_id) {+ return false;+ }+ let display_list = display_list.expect("a frame that can render has a display list");+ let frame_inputs = frame_inputs.expect("a context with a display list has frame inputs");+ // Don't race an async present already in flight for this context; its own completion will update the output.+ if self.is_present_blocked(env.raster, env.context_id) {+ return false;+ }+ let pending_frame = match self.pending_present_frame {+ Some(pending_frame) => pending_frame,+ None => match self.presented_frame {+ Some(presented_frame) => PendingFrame::repainting_everything(presented_frame),+ None => return false,+ },+ };+ let live_content = self.live_content(env, display_list);+ let frame = FrameToPaint {+ display_list,+ frame_inputs: &frame_inputs,+ };+ let mut frame_damage = self.frame_damage_for(env, &pending_frame, &frame, &live_content);+ let raster_damage_rect = self.raster_damage_rect(frame_damage.rect);+ let Some((bitmap_id, store)) = env.raster.acquire_store(env.context_id) else {+ return false;+ };+ let store_rect = rect_of_size(env.raster.surface_size(&store));+ let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);+ let _ = self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);+ self.commit_layer_update(env, frame_damage.layers);+ self.remember_painted_frame(pending_frame.viewport_rect, display_list, frame_inputs, &live_content);+ env.raster.flush(&store);+ env.raster.complete_rendering(env.context_id, bitmap_id);+ self.latest_rendered_surface = env.raster.latest_rendered_store_surface(env.context_id);+ self.size_of_latest_rendered_frame = IntSize {+ width: pending_frame.viewport_rect.width,+ height: pending_frame.viewport_rect.height,+ };+ self.presented_frame = Some(pending_frame.viewport_rect);+ self.pending_present_frame = None;+ self.pending_present_frame_scheduled = false;+ true+ }++ /// Paints a screenshot into the target, without the overlays of the browser and at the raster's own scale.+ pub fn paint_screenshot(+ &mut self,+ env: &PresentingEnvironment<'_>,+ target: &SurfaceHandle,+ display_list: &Rc<DisplayList>,+ frame_inputs: &FrameInputs,+ ) {+ let frame = FrameToPaint {+ display_list,+ frame_inputs,+ };+ self.paint_current_display_list(env, target, &frame, None, false, false);+ env.raster.flush(target);+ }++ /// The surface that holds the frame on screen as a whole, with what the window server shows above the store+ /// composited into it, and the size of the frame in it.+ pub fn presented_frame_for_snapshot(+ &mut self,+ env: &PresentingEnvironment<'_>,+ ) -> Option<(SurfaceHandle, IntSize)> {+ let latest_rendered_surface = self.latest_rendered_surface.clone()?;+ let mut source = latest_rendered_surface;+ // The store then holds only what is under the canvases, videos and overlays that the window server shows above it.+ if self.layers.window_server_shows_media()+ && self.layers.has_plan()+ && let Some(painted_frame) = self.painted_frame.take()+ {+ let source_size = env.raster.surface_size(&source);+ let composited = env.raster.create_surface(source_size, Some(&source));+ if let Some(composited) = composited {+ let source_rect = rect_of_size(source_size);+ env.raster+ .draw_surface(&composited, &source, source_rect, source_rect, SurfaceBlend::Source);+ let frame = FrameToPaint {+ display_list: &painted_frame.display_list,+ frame_inputs: &painted_frame.frame_inputs,+ };+ let snapshot_env = PresentingEnvironment {+ composited_contexts: &libcompositing_rust::display_list::replay::NoCompositedContexts,+ ..*env+ };+ self.composite_layers_above_base(&snapshot_env, &composited, &frame, source_rect);+ paint_overlays(&snapshot_env, &composited, &painted_frame.frame_inputs, true);+ source = composited;+ }+ self.painted_frame = Some(painted_frame);+ }+ let source_size = env.raster.surface_size(&source);+ let frame_size = IntSize {+ width: self.size_of_latest_rendered_frame.width.min(source_size.width),+ height: self.size_of_latest_rendered_frame.height.min(source_size.height),+ };+ if frame_size.is_empty() {+ return None;+ }+ Some((source, frame_size))+ }++ pub fn layer_drop_timer_fired(&mut self, env: &PresentingEnvironment<'_>) {+ self.layers.drop_timer_fired(env);+ }++ // 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.+ fn paint_frame(+ &mut self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ mut damage_rect: IntRect,+ layer_update: &mut layers::LayerUpdate,+ ) -> IntRect {+ if layer_update.has_plan() {+ if self.paint_layered_frame(env, surface, frame, damage_rect, layer_update) {+ return damage_rect;+ }+ // The sublayers that the window server was to show go away with this frame, so the store has to hold all+ // that they showed.+ if layer_update.shown_by_window_server {+ damage_rect = rect_of_size(self.raster_size());+ }+ layer_update.new_plan = None;+ layer_update.keeps_plan = false;+ layer_update.shown_by_window_server = false;+ self.layers.drop_layers(env);+ self.layers.repaint_everything_after_dropping_layers = true;+ }+ // NB: Only a frame shown on screen ages the rasters it did not use, so a screenshot keeps them.+ env.raster.start_raster_cache_frame(env.context_id);+ self.paint_current_display_list(env, surface, frame, Some(damage_rect), true, true);+ damage_rect+ }++ fn paint_current_display_list(+ &mut self,+ env: &PresentingEnvironment<'_>,+ surface: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ damage_rect: Option<IntRect>,+ paints_ui_overlays: bool,+ applies_raster_transform: bool,+ ) {+ let raster = env.raster;+ let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);+ let paint_display_list = |target: &SurfaceHandle| {+ replay_into(env, target, frame, ReplaySelection::default());+ paint_overlays(env, target, frame.frame_inputs, paints_ui_overlays);+ };++ if let Some(damage_rect) = damage_rect+ && !damage_rect.is_empty()+ && self.presents_to_client+ && (IntSize {+ width: damage_rect.width,+ height: damage_rect.height,+ }) != raster.surface_size(surface)+ && raster.surface_uses_gpu(surface)+ {+ let damage_size = IntSize {+ width: damage_rect.width,+ height: damage_rect.height,+ };+ if self+ .damage_surface+ .as_ref()+ .is_none_or(|damage_surface| raster.surface_size(damage_surface) != damage_size)+ {+ self.damage_surface = raster.create_surface(damage_size, Some(surface));+ }+ if let Some(damage_surface) = &self.damage_surface {+ raster.clear(damage_surface, surface_clear_color);+ let save_count = raster.save(damage_surface);+ raster.translate(damage_surface, -damage_rect.x as f32, -damage_rect.y as f32);+ paint_display_list(damage_surface);+ raster.restore_to_count(damage_surface, save_count);+ raster.draw_surface(+ surface,+ damage_surface,+ rect_of_size(damage_size),+ damage_rect,+ SurfaceBlend::Source,+ );+ return;+ }+ }++ let save_count = raster.save(surface);+ if let Some(damage_rect) = damage_rect {+ raster.clip_rect(surface, damage_rect);+ raster.clear(surface, surface_clear_color);+ }+ if applies_raster_transform {+ raster.translate(surface, self.raster_translation.x, self.raster_translation.y);+ raster.scale(surface, self.raster_scale.width, self.raster_scale.height);+ }+ paint_display_list(surface);+ raster.restore_to_count(surface, save_count);+ }+}++// Replays the frame's display list into the target, through the painter of the context's page.+pub(crate) fn replay_into(+ env: &PresentingEnvironment<'_>,+ target: &SurfaceHandle,+ frame: &FrameToPaint<'_>,+ selection: ReplaySelection<'_>,+) {+ let frame_inputs = frame.frame_inputs;+ let display_list = frame.display_list;+ assert_eq!(+ display_list.compatible_visual_context_tree_structural_epoch(),+ frame_inputs.visual_context_tree.structural_epoch()+ );+ env.raster+ .paint(env.context_id, target, PaintingResources::Page, |painter| {+ let nested_display_lists = painter.nested_display_lists();+ let scrollbars = frame_inputs.scrollbars_shown_for_the_page();+ let replay_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,+ composited_contexts: env.composited_contexts,+ };+ let storage = display_list.storage();+ let tree = frame_inputs.visual_context_tree.as_arc();+ replay_display_list(+ tree,+ storage.bytes(),+ storage.command_runs(),+ storage.effect_clip_plan(tree),+ display_list.root_group_color(),+ &replay_frame,+ selection,+ painter,+ );+ });+}++pub(crate) fn replaying_only(record_spans: &[RecordSpan], skip_root_isolation_layer: bool) -> ReplaySelection<'_> {+ ReplaySelection {+ record_spans: Some(record_spans),+ skip_root_isolation_layer,+ }+}++// Paints what the compositor draws over the page: its scrollbars, and unless they are left out, the overlays of the+// browser.+pub(crate) fn paint_overlays(+ env: &PresentingEnvironment<'_>,+ target: &SurfaceHandle,+ frame_inputs: &FrameInputs,+ paints_ui_overlays: bool,+) {+ env.raster+ .paint(env.context_id, target, PaintingResources::Overlays, |painter| {+ frame_inputs.overlays.paint(painter, paints_ui_overlays);+ });+}diff --git a/Services/Compositor/Rust/src/presenting/pacing.rs b/Services/Compositor/Rust/src/presenting/pacing.rsnew file mode 100644index 00000000000..e52b0932658--- /dev/null+++ b/Services/Compositor/Rust/src/presenting/pacing.rs@@ -0,0 +1,61 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Display ticks paced to a maximum frame rate.++use libcompositing_rust::time::MonotonicTime;++/// A display tick that was asked for and not delivered yet, paced to the rate it was last asked for at.+pub struct PacedTickRequest {+ requested: bool,+ maximum_frames_per_second: f64,+ last_frame_time: Option<MonotonicTime>,+}++impl Default for PacedTickRequest {+ fn default() -> Self {+ Self {+ requested: false,+ maximum_frames_per_second: 60.0,+ last_frame_time: None,+ }+ }+}++impl PacedTickRequest {+ /// Returns whether the tick had not been asked for already.+ pub fn request(&mut self, maximum_frames_per_second: f64) -> bool {+ assert!(maximum_frames_per_second.is_finite() && maximum_frames_per_second > 0.0);+ self.maximum_frames_per_second = maximum_frames_per_second;+ !std::mem::replace(&mut self.requested, true)+ }++ pub fn is_requested(&self) -> bool {+ self.requested+ }++ /// The whole number of display ticks between two frames, in milliseconds.+ pub fn frame_interval(&self, display_refresh_rate: f64) -> f64 {+ let ticks_per_frame = (display_refresh_rate / self.maximum_frames_per_second).ceil().max(1.0);+ ticks_per_frame * 1000.0 / display_refresh_rate+ }++ pub fn is_due(&self, frame_time: MonotonicTime, display_refresh_rate: f64) -> bool {+ let Some(last_frame_time) = self.last_frame_time else {+ return true;+ };+ let interval = self.frame_interval(display_refresh_rate);+ let display_interval = 1000.0 / display_refresh_rate;+ let elapsed = (frame_time.nanoseconds() - last_frame_time.nanoseconds()) as f64 / 1_000_000.0;+ elapsed + display_interval / 2.0 >= interval+ }++ pub fn did_deliver(&mut self, frame_time: MonotonicTime) {+ assert!(self.requested);+ self.requested = false;+ self.last_frame_time = Some(frame_time);+ }+}diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsnew file mode 100644index 00000000000..e4e3f64f2eb--- /dev/null+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -0,0 +1,780 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The mechanism that presenting a frame drives in the C++ around the core: Skia surfaces and the painter, the backing+//! stores of each context, the surfaces the window server shows, the media that live content comes from, GPU+//! submission, and the display ticks. None of these calls comes back into the core before it returns.++use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::host::FfiRasterPainter;+use libcompositing_rust::time::MonotonicTime;+use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};+use std::collections::HashMap;+use std::ffi::c_void;+use std::ptr::NonNull;++/// How a surface is drawn into another.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum SurfaceBlend {+ /// Replaces what the target holds.+ Source,+ SourceOver,+}++/// Whose resources a painting draws with.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum PaintingResources {+ Page,+ Overlays,+}++/// Who shows the backing stores of a context.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(u8)]+pub enum StorePublication {+ #[default]+ Unpublished,+ /// The presentation shows the stores, and releases each when it shows another.+ Published,+ /// The compositor shows the stores itself, in a remote layer, so a store is replaced on screen by the next one.+ ShownInRemoteLayer,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum StoreResizeOutcome {+ Unchanged,+ /// The stores were reallocated, and nothing that shows them was given them.+ ReallocatedOffscreen,+ /// The presentation or the remote layer that shows the stores was given the new ones.+ ReallocatedForViewer,+ /// The stores of a remote layer could not be allocated.+ Failed,+}++/// When a frame can be handed to whoever shows it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum FrameHandOff {+ OnceGpuWorkIsScheduled,+ OnceGpuWorkIsFinished,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct FfiStoreState {+ pub is_valid: bool,+ pub is_rendering: bool,+ pub has_available_store: bool,+}++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiStoreResize {+ pub raster_size: IntSize,+ pub window_resize_in_progress: bool,+ pub publication: StorePublication,+ pub gpu_sharing_allowed: bool,+ pub has_presentation: bool,+ pub presentation_id: u64,+}++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiAcquiredStore {+ pub bitmap_id: i32,+ pub surface: *mut c_void,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct FfiCanvasContent {+ pub id: u64,+ pub content_generation: u64,+ // Whether the window server can show the canvas as it is.+ pub has_presentable_surface: bool,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct FfiVideoSinkContent {+ pub id: u64,+ pub has_frame: bool,+ pub frame_id: u64,+ pub frame_holds_high_dynamic_range: bool,+ // Whether the window server can show the frame as it is.+ pub frame_has_surface: bool,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[repr(C)]+pub struct FfiImageFrameContent {+ pub id: u64,+ pub pixel_generation: u64,+}++/// The live content of a context as it is now: the canvases asked about, every video sink and every image frame the+/// context's resources hold.+#[repr(C)]+pub struct FfiLiveContent<'a> {+ pub canvases: ak::Span<'a, FfiCanvasContent>,+ pub video_sinks: ak::Span<'a, FfiVideoSinkContent>,+ pub image_frames: ak::Span<'a, FfiImageFrameContent>,+}++/// The live content of a context as it is now, by ID: the canvases asked about, every video sink, and the pixel+/// generation of every image frame.+#[derive(Clone, Default, Debug)]+pub struct LiveContent {+ pub canvases: HashMap<u64, FfiCanvasContent>,+ pub video_sinks: HashMap<u64, FfiVideoSinkContent>,+ pub image_frames: HashMap<u64, u64>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum MediaKind {+ Canvas,+ Video,+}++/// Where the window server shows a sublayer, and how it clips it, in device pixels.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct FfiSublayerPlacement {+ pub content_rect: IntRect,+ /// The a, b, c, d, e and f of an affine transform.+ pub content_to_frame: [f32; 6],+ pub clip_rect: FloatRect,+ pub has_rounded_clip: bool,+ pub rounded_clip_rect: FloatRect,+ pub rounded_clip_radius: f32,+ pub rounds_top_left: bool,+ pub rounds_top_right: bool,+ pub rounds_bottom_right: bool,+ pub rounds_bottom_left: bool,+ pub scaling_mode: ScalingMode,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub enum SublayerContentKind {+ Canvas,+ Video,+ PresentableSurface,+}++/// A sublayer the window server shows above a frame: a canvas or video of the context by its id, or a surface.+#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiSublayer {+ pub identity: u64,+ pub content_kind: SublayerContentKind,+ pub media_id: u64,+ pub presentable_surface: *mut c_void,+ pub placement: FfiSublayerPlacement,+}++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiRemoteLayerFrame {+ /// Without the store, the frame shown before stays, and only the sublayers change.+ pub uses_store: bool,+ pub painted_size: IntSize,+ pub device_pixel_ratio: f64,+ /// Whether the page laid out the frame at the size it is painted at.+ pub laid_out_by_page: bool,+}++/// The entry points of the mechanism the core drives, and the object they are called on:+/// `Compositor::RustFFI::FfiRasterHost`.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiRasterHost {+ pub host: *mut c_void,++ pub surface_retain: unsafe extern "C" fn(*mut c_void),+ pub surface_release: unsafe extern "C" fn(*mut c_void),+ /// Writes the size of the surface. NB: A C++ function returns Gfx::IntSize in memory rather than in a register+ /// on Windows, so the size does not come back as the return value.+ pub surface_size: unsafe extern "C" fn(*mut c_void, *mut IntSize),+ /// Null where the surface could not be made. The surface is made like the one given, or for the GPU the compositor+ /// renders with where none is given.+ pub create_surface: unsafe extern "C" fn(*mut c_void, IntSize, *mut c_void) -> *mut c_void,+ pub surfaces_share_backend: unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool,+ pub surface_uses_gpu: unsafe extern "C" fn(*mut c_void) -> bool,+ pub surface_save: unsafe extern "C" fn(*mut c_void) -> i32,+ pub surface_restore_to_count: unsafe extern "C" fn(*mut c_void, i32),+ pub surface_translate: unsafe extern "C" fn(*mut c_void, f32, f32),+ pub surface_scale: unsafe extern "C" fn(*mut c_void, f32, f32),+ pub surface_clip_rect: unsafe extern "C" fn(*mut c_void, IntRect),+ pub surface_clear: unsafe extern "C" fn(*mut c_void, Color),+ /// Arguments: the target, the source, the rect of the source drawn, the rect of the target it is drawn into, and+ /// how it is blended.+ pub surface_draw_surface: unsafe extern "C" fn(*mut c_void, *mut c_void, IntRect, IntRect, SurfaceBlend),+ pub flush_surface: unsafe extern "C" fn(*mut c_void, *mut c_void),++ /// Arguments: the context, the surface, whose resources it draws with, and where the painter is written. The+ /// painting lasts until `end_painting`, and paintings nest.+ pub begin_painting: unsafe extern "C" fn(*mut c_void, u64, *mut c_void, PaintingResources, *mut FfiRasterPainter),+ pub end_painting: unsafe extern "C" fn(*mut c_void),+ /// Lets the raster caches of the context's page drop what the frames before the one that starts did not use.+ pub start_raster_cache_frame: unsafe extern "C" fn(*mut c_void, u64),++ pub store_state: unsafe extern "C" fn(*mut c_void, u64) -> FfiStoreState,+ pub resize_stores: unsafe extern "C" fn(*mut c_void, u64, *const FfiStoreResize) -> StoreResizeOutcome,+ pub invalidate_stores: unsafe extern "C" fn(*mut c_void, u64),+ pub acquire_store: unsafe extern "C" fn(*mut c_void, u64, *mut FfiAcquiredStore) -> bool,+ pub complete_rendering: unsafe extern "C" fn(*mut c_void, u64, i32),+ pub release_store: unsafe extern "C" fn(*mut c_void, u64, i32) -> bool,+ pub release_all_presented_stores: unsafe extern "C" fn(*mut c_void, u64),+ /// Lent; null before any store was rendered into.+ pub latest_rendered_store_surface: unsafe extern "C" fn(*mut c_void, u64) -> *mut c_void,+ /// Arguments: the context, and the presentation that shows its stores, if it has one. Answers whether a store was+ /// added.+ pub add_store_if_window_server_reads_every_released_store:+ unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,+ /// The same arguments. Answers whether surplus stores are left.+ pub retire_idle_surplus_stores: unsafe extern "C" fn(*mut c_void, u64, bool, u64) -> bool,++ /// Arguments: the context, the pool, the size, and a surface the new one is made like. Null where none could be had.+ pub next_presentable_surface: unsafe extern "C" fn(*mut c_void, u64, u32, IntSize, *mut c_void) -> *mut c_void,+ pub drop_presentable_surface_pool: unsafe extern "C" fn(*mut c_void, u64, u32),+ pub presentable_surface_retain: unsafe extern "C" fn(*mut c_void),+ pub presentable_surface_release: unsafe extern "C" fn(*mut c_void),+ /// Lent for as long as the presentable surface lives.+ pub presentable_surface_painting_surface: unsafe extern "C" fn(*mut c_void) -> *mut c_void,++ pub live_content: unsafe extern "C" fn(+ *mut c_void,+ u64,+ ak::Span<'_, u64>,+ *mut c_void,+ unsafe extern "C" fn(*mut c_void, *const FfiLiveContent<'_>),+ ),+ pub remote_layer_can_show:+ unsafe extern "C" fn(*mut c_void, u64, MediaKind, u64, *const FfiSublayerPlacement, f64) -> bool,+ pub remote_layer_can_show_high_dynamic_range: unsafe extern "C" fn(*mut c_void, u64) -> bool,+ /// Resolves the content of the sublayers, which the window server then holds busy until the list is destroyed or+ /// shown.+ pub build_sublayers: unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, FfiSublayer>) -> *mut c_void,+ pub destroy_sublayers: unsafe extern "C" fn(*mut c_void),++ pub frame_hand_off: unsafe extern "C" fn(*mut c_void, u64) -> FrameHandOff,+ /// Submits the GPU work drawn into the surface, or into the surfaces the window server shows where it is null,+ /// answering a token that `compositor_core_gpu_work_finished` hands back once it is done, on a later turn.+ pub submit_frame: unsafe extern "C" fn(*mut c_void, u64, *mut c_void) -> u64,+ /// Calls `compositor_core_frame_ready_for_hand_off` with the token on a later turn, once the work is scheduled.+ pub hand_off_once_gpu_work_is_scheduled: unsafe extern "C" fn(*mut c_void, u64),+ /// Shows a frame in the remote layer that shows the context, with the sublayers given, which it takes over. Answers+ /// false where the layer could not show it, after which the context is no longer shown in it. Writes the+ /// presentation the layer is in.+ pub show_frame_in_remote_layer:+ unsafe extern "C" fn(*mut c_void, u64, *const FfiRemoteLayerFrame, *mut c_void, *mut u64) -> bool,+ pub stop_showing_in_remote_layer: unsafe extern "C" fn(*mut c_void, u64),+ pub log_presented_frame: unsafe extern "C" fn(*mut c_void, u64, IntRect),+ /// Calls `compositor_core_presented_store_released` on a later turn.+ pub release_store_later: unsafe extern "C" fn(*mut c_void, u64, i32),++ /// Arguments: whether the display is known, the display, and its refresh rate.+ pub request_vsync: unsafe extern "C" fn(*mut c_void, bool, u64, f64),+ pub most_recent_tick_time: unsafe extern "C" fn(*mut c_void, bool, u64, i64, f64, *mut i64) -> bool,+ /// Updates every video sink, and hands the receiver the contexts that draw a sink with a new frame.+ pub update_video_sinks:+ unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void, ak::Span<'_, u64>)),+ pub context_video_sinks_require_updates: unsafe extern "C" fn(*mut c_void, u64) -> bool,+ pub set_maximum_display_refresh_rate: unsafe extern "C" fn(*mut c_void, f64),+}++/// A surface of the C++ side, which this keeps alive.+pub struct SurfaceHandle {+ surface: NonNull<c_void>,+ release: unsafe extern "C" fn(*mut c_void),+ retain: unsafe extern "C" fn(*mut c_void),+}++impl SurfaceHandle {+ pub fn as_ptr(&self) -> *mut c_void {+ self.surface.as_ptr()+ }+}++impl Clone for SurfaceHandle {+ fn clone(&self) -> Self {+ // SAFETY: The surface is live, as this holds it.+ unsafe { (self.retain)(self.surface.as_ptr()) };+ Self {+ surface: self.surface,+ release: self.release,+ retain: self.retain,+ }+ }+}++impl Drop for SurfaceHandle {+ fn drop(&mut self) {+ // SAFETY: This holds the reference it gives back.+ unsafe { (self.release)(self.surface.as_ptr()) };+ }+}++/// A surface the window server shows, which this keeps alive.+pub struct PresentableSurfaceHandle {+ surface: NonNull<c_void>,+ release: unsafe extern "C" fn(*mut c_void),+}++impl PresentableSurfaceHandle {+ pub fn as_ptr(&self) -> *mut c_void {+ self.surface.as_ptr()+ }+}++impl Drop for PresentableSurfaceHandle {+ fn drop(&mut self) {+ // SAFETY: This holds the reference it gives back.+ unsafe { (self.release)(self.surface.as_ptr()) };+ }+}++/// Sublayers whose content the C++ side resolved, which keep that content busy until they are shown or dropped.+pub struct SublayersHandle {+ sublayers: NonNull<c_void>,+ destroy: unsafe extern "C" fn(*mut c_void),+}++impl SublayersHandle {+ pub fn into_raw(self) -> *mut c_void {+ let sublayers = self.sublayers.as_ptr();+ std::mem::forget(self);+ sublayers+ }+}++impl Drop for SublayersHandle {+ fn drop(&mut self) {+ // SAFETY: This owns the sublayers.+ unsafe { (self.destroy)(self.sublayers.as_ptr()) };+ }+}++pub struct RasterHost(FfiRasterHost);++impl RasterHost {+ /// # Safety+ ///+ /// `ffi.host` must outlive the `RasterHost`, and none of its entry points may call back into the core.+ pub unsafe fn new(ffi: FfiRasterHost) -> Self {+ Self(ffi)+ }++ fn host(&self) -> *mut c_void {+ self.0.host+ }++ /// Takes a reference to a surface the C++ side lends.+ pub fn retain_surface(&self, surface: *mut c_void) -> Option<SurfaceHandle> {+ let surface = NonNull::new(surface)?;+ // SAFETY: The C++ side lends a live surface.+ unsafe { (self.0.surface_retain)(surface.as_ptr()) };+ Some(SurfaceHandle {+ surface,+ release: self.0.surface_release,+ retain: self.0.surface_retain,+ })+ }++ /// Hands the reference the handle holds over to the C++ side.+ pub fn leak_surface(&self, surface: SurfaceHandle) -> *mut c_void {+ let pointer = surface.as_ptr();+ std::mem::forget(surface);+ pointer+ }++ // Adopts the reference the C++ side handed over with a new surface.+ fn adopt_surface(&self, surface: *mut c_void) -> Option<SurfaceHandle> {+ Some(SurfaceHandle {+ surface: NonNull::new(surface)?,+ release: self.0.surface_release,+ retain: self.0.surface_retain,+ })+ }++ pub fn surface_size(&self, surface: &SurfaceHandle) -> IntSize {+ let mut size = IntSize::default();+ // SAFETY: The surface is live, and the host writes the size during the call.+ unsafe { (self.0.surface_size)(surface.as_ptr(), &raw mut size) };+ size+ }++ pub fn create_surface(&self, size: IntSize, like: Option<&SurfaceHandle>) -> Option<SurfaceHandle> {+ let like = like.map_or(std::ptr::null_mut(), SurfaceHandle::as_ptr);+ // SAFETY: The host outlives this, and the surface it is made like is live.+ self.adopt_surface(unsafe { (self.0.create_surface)(self.host(), size, like) })+ }++ pub fn surfaces_share_backend(&self, a: &SurfaceHandle, b: &SurfaceHandle) -> bool {+ // SAFETY: Both surfaces are live.+ unsafe { (self.0.surfaces_share_backend)(a.as_ptr(), b.as_ptr()) }+ }++ pub fn surface_uses_gpu(&self, surface: &SurfaceHandle) -> bool {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_uses_gpu)(surface.as_ptr()) }+ }++ pub fn start_raster_cache_frame(&self, context_id: CompositorContextId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.start_raster_cache_frame)(self.host(), context_id.0) };+ }++ pub fn save(&self, surface: &SurfaceHandle) -> i32 {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_save)(surface.as_ptr()) }+ }++ pub fn restore_to_count(&self, surface: &SurfaceHandle, count: i32) {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_restore_to_count)(surface.as_ptr(), count) };+ }++ pub fn translate(&self, surface: &SurfaceHandle, x: f32, y: f32) {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_translate)(surface.as_ptr(), x, y) };+ }++ pub fn scale(&self, surface: &SurfaceHandle, x: f32, y: f32) {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_scale)(surface.as_ptr(), x, y) };+ }++ pub fn clip_rect(&self, surface: &SurfaceHandle, rect: IntRect) {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_clip_rect)(surface.as_ptr(), rect) };+ }++ pub fn clear(&self, surface: &SurfaceHandle, color: Color) {+ // SAFETY: The surface is live.+ unsafe { (self.0.surface_clear)(surface.as_ptr(), color) };+ }++ pub fn draw_surface(+ &self,+ target: &SurfaceHandle,+ source: &SurfaceHandle,+ source_rect: IntRect,+ target_rect: IntRect,+ blend: SurfaceBlend,+ ) {+ // SAFETY: Both surfaces are live.+ unsafe { (self.0.surface_draw_surface)(target.as_ptr(), source.as_ptr(), source_rect, target_rect, blend) };+ }++ pub fn flush(&self, surface: &SurfaceHandle) {+ // SAFETY: The host outlives this, and the surface is live.+ unsafe { (self.0.flush_surface)(self.host(), surface.as_ptr()) };+ }++ /// Paints into the surface through a painter, which `paint` drives.+ pub fn paint(+ &self,+ context_id: CompositorContextId,+ surface: &SurfaceHandle,+ resources: PaintingResources,+ paint: impl FnOnce(&mut FfiRasterPainter),+ ) {+ let mut painter = std::mem::MaybeUninit::<FfiRasterPainter>::uninit();+ // SAFETY: The host outlives this, the surface is live, and the host writes the painter.+ let mut painter = unsafe {+ (self.0.begin_painting)(+ self.host(),+ context_id.0,+ surface.as_ptr(),+ resources,+ painter.as_mut_ptr(),+ );+ painter.assume_init()+ };+ paint(&mut painter);+ // SAFETY: The host outlives this, and the painting began above.+ unsafe { (self.0.end_painting)(self.host()) };+ }++ pub fn store_state(&self, context_id: CompositorContextId) -> FfiStoreState {+ // SAFETY: The host outlives this.+ unsafe { (self.0.store_state)(self.host(), context_id.0) }+ }++ pub fn resize_stores(&self, context_id: CompositorContextId, resize: &FfiStoreResize) -> StoreResizeOutcome {+ // SAFETY: The host outlives this.+ unsafe { (self.0.resize_stores)(self.host(), context_id.0, resize) }+ }++ pub fn invalidate_stores(&self, context_id: CompositorContextId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.invalidate_stores)(self.host(), context_id.0) };+ }++ pub fn acquire_store(&self, context_id: CompositorContextId) -> Option<(i32, SurfaceHandle)> {+ let mut acquired = FfiAcquiredStore {+ bitmap_id: -1,+ surface: std::ptr::null_mut(),+ };+ // SAFETY: The host outlives this.+ if !unsafe { (self.0.acquire_store)(self.host(), context_id.0, &raw mut acquired) } {+ return None;+ }+ Some((acquired.bitmap_id, self.retain_surface(acquired.surface)?))+ }++ pub fn complete_rendering(&self, context_id: CompositorContextId, bitmap_id: i32) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.complete_rendering)(self.host(), context_id.0, bitmap_id) };+ }++ pub fn release_store(&self, context_id: CompositorContextId, bitmap_id: i32) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.release_store)(self.host(), context_id.0, bitmap_id) }+ }++ pub fn release_all_presented_stores(&self, context_id: CompositorContextId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.release_all_presented_stores)(self.host(), context_id.0) };+ }++ pub fn latest_rendered_store_surface(&self, context_id: CompositorContextId) -> Option<SurfaceHandle> {+ // SAFETY: The host outlives this.+ self.retain_surface(unsafe { (self.0.latest_rendered_store_surface)(self.host(), context_id.0) })+ }++ pub fn add_store_if_window_server_reads_every_released_store(+ &self,+ context_id: CompositorContextId,+ presentation_id: Option<u64>,+ ) -> bool {+ // SAFETY: The host outlives this.+ unsafe {+ (self.0.add_store_if_window_server_reads_every_released_store)(+ self.host(),+ context_id.0,+ presentation_id.is_some(),+ presentation_id.unwrap_or_default(),+ )+ }+ }++ pub fn retire_idle_surplus_stores(&self, context_id: CompositorContextId, presentation_id: Option<u64>) -> bool {+ // SAFETY: The host outlives this.+ unsafe {+ (self.0.retire_idle_surplus_stores)(+ self.host(),+ context_id.0,+ presentation_id.is_some(),+ presentation_id.unwrap_or_default(),+ )+ }+ }++ pub fn next_presentable_surface(+ &self,+ context_id: CompositorContextId,+ pool: u32,+ size: IntSize,+ like: &SurfaceHandle,+ ) -> Option<PresentableSurfaceHandle> {+ // SAFETY: The host outlives this, and the surface is live.+ let surface =+ unsafe { (self.0.next_presentable_surface)(self.host(), context_id.0, pool, size, like.as_ptr()) };+ Some(PresentableSurfaceHandle {+ surface: NonNull::new(surface)?,+ release: self.0.presentable_surface_release,+ })+ }++ pub fn drop_presentable_surface_pool(&self, context_id: CompositorContextId, pool: u32) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.drop_presentable_surface_pool)(self.host(), context_id.0, pool) };+ }++ pub fn painting_surface_of(&self, surface: &PresentableSurfaceHandle) -> SurfaceHandle {+ // SAFETY: The presentable surface is live, and lends its painting surface.+ self.retain_surface(unsafe { (self.0.presentable_surface_painting_surface)(surface.as_ptr()) })+ .expect("a presentable surface has a painting surface")+ }++ pub fn live_content(&self, context_id: CompositorContextId, canvas_ids: &[u64]) -> LiveContent {+ unsafe extern "C" fn receive(receiver: *mut c_void, content: *const FfiLiveContent<'_>) {+ // SAFETY: The receiver is the content below, and the host lends what it found for the call.+ let (receiver, content) = unsafe { (&mut *receiver.cast::<LiveContent>(), &*content) };+ receiver.canvases = content+ .canvases+ .as_slice()+ .iter()+ .map(|canvas| (canvas.id, *canvas))+ .collect();+ receiver.video_sinks = content+ .video_sinks+ .as_slice()+ .iter()+ .map(|sink| (sink.id, *sink))+ .collect();+ receiver.image_frames = content+ .image_frames+ .as_slice()+ .iter()+ .map(|image| (image.id, image.pixel_generation))+ .collect();+ }+ let mut content = LiveContent::default();+ // SAFETY: The host outlives this, and answers synchronously.+ unsafe {+ (self.0.live_content)(+ self.host(),+ context_id.0,+ ak::Span::new(canvas_ids),+ (&raw mut content).cast(),+ receive,+ );+ }+ content+ }++ pub fn remote_layer_can_show(+ &self,+ context_id: CompositorContextId,+ kind: MediaKind,+ id: u64,+ placement: &FfiSublayerPlacement,+ device_pixel_ratio: f64,+ ) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.remote_layer_can_show)(self.host(), context_id.0, kind, id, placement, device_pixel_ratio) }+ }++ pub fn remote_layer_can_show_high_dynamic_range(&self, context_id: CompositorContextId) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.remote_layer_can_show_high_dynamic_range)(self.host(), context_id.0) }+ }++ pub fn build_sublayers(&self, context_id: CompositorContextId, sublayers: &[FfiSublayer]) -> SublayersHandle {+ // SAFETY: The host outlives this, and the presentable surfaces of the sublayers are live.+ let built = unsafe { (self.0.build_sublayers)(self.host(), context_id.0, ak::Span::new(sublayers)) };+ SublayersHandle {+ sublayers: NonNull::new(built).expect("the host builds a list of sublayers"),+ destroy: self.0.destroy_sublayers,+ }+ }++ pub fn frame_hand_off(&self, context_id: CompositorContextId) -> FrameHandOff {+ // SAFETY: The host outlives this.+ unsafe { (self.0.frame_hand_off)(self.host(), context_id.0) }+ }++ pub fn submit_frame(&self, context_id: CompositorContextId, surface: Option<&SurfaceHandle>) -> u64 {+ let surface = surface.map_or(std::ptr::null_mut(), SurfaceHandle::as_ptr);+ // SAFETY: The host outlives this, and the surface is live.+ unsafe { (self.0.submit_frame)(self.host(), context_id.0, surface) }+ }++ pub fn hand_off_once_gpu_work_is_scheduled(&self, token: u64) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.hand_off_once_gpu_work_is_scheduled)(self.host(), token) };+ }++ /// Answers the presentation of the remote layer that showed the frame, or none where it could not show it.+ pub fn show_frame_in_remote_layer(+ &self,+ context_id: CompositorContextId,+ frame: &FfiRemoteLayerFrame,+ sublayers: SublayersHandle,+ ) -> Option<u64> {+ let mut presentation_id = 0;+ // SAFETY: The host outlives this, and takes the sublayers over.+ let shown = unsafe {+ (self.0.show_frame_in_remote_layer)(+ self.host(),+ context_id.0,+ frame,+ sublayers.into_raw(),+ &raw mut presentation_id,+ )+ };+ shown.then_some(presentation_id)+ }++ pub fn stop_showing_in_remote_layer(&self, context_id: CompositorContextId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.stop_showing_in_remote_layer)(self.host(), context_id.0) };+ }++ pub fn log_presented_frame(&self, page_id: u64, damage_rect: IntRect) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.log_presented_frame)(self.host(), page_id, damage_rect) };+ }++ pub fn release_store_later(&self, context_id: CompositorContextId, bitmap_id: i32) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.release_store_later)(self.host(), context_id.0, bitmap_id) };+ }++ pub fn request_vsync(&self, display_id: Option<u64>, refresh_rate: f64) {+ // SAFETY: The host outlives this.+ unsafe {+ (self.0.request_vsync)(+ self.host(),+ display_id.is_some(),+ display_id.unwrap_or_default(),+ refresh_rate,+ );+ }+ }++ pub fn most_recent_tick_time(+ &self,+ display_id: Option<u64>,+ now: MonotonicTime,+ refresh_rate: f64,+ ) -> Option<MonotonicTime> {+ let mut tick_time = 0;+ // SAFETY: The host outlives this.+ let has_tick = unsafe {+ (self.0.most_recent_tick_time)(+ self.host(),+ display_id.is_some(),+ display_id.unwrap_or_default(),+ now.nanoseconds(),+ refresh_rate,+ &raw mut tick_time,+ )+ };+ has_tick.then(|| MonotonicTime::from_nanoseconds(tick_time))+ }++ /// Answers the contexts that draw a video sink with a new frame.+ pub fn update_video_sinks(&self) -> Vec<CompositorContextId> {+ unsafe extern "C" fn receive(receiver: *mut c_void, context_ids: ak::Span<'_, u64>) {+ // SAFETY: The receiver is the list below, and the host lends the IDs for the call.+ let receiver = unsafe { &mut *receiver.cast::<Vec<CompositorContextId>>() };+ receiver.extend(context_ids.as_slice().iter().map(|id| CompositorContextId(*id)));+ }+ let mut context_ids = Vec::new();+ // SAFETY: The host outlives this, and answers synchronously.+ unsafe { (self.0.update_video_sinks)(self.host(), (&raw mut context_ids).cast(), receive) };+ context_ids+ }++ pub fn context_video_sinks_require_updates(&self, context_id: CompositorContextId) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.context_video_sinks_require_updates)(self.host(), context_id.0) }+ }++ pub fn set_maximum_display_refresh_rate(&self, refresh_rate: f64) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.set_maximum_display_refresh_rate)(self.host(), refresh_rate) };+ }+}diff --git a/Tests/Compositor/TestDisplayListImageFilters.cpp b/Tests/Compositor/TestDisplayListImageFilters.cppindex d621aebf998..be8a90ad394 100644--- a/Tests/Compositor/TestDisplayListImageFilters.cpp+++ b/Tests/Compositor/TestDisplayListImageFilters.cpp@@ -31,7 +31,7 @@ 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);- auto painter = player.begin_painting(*surface, storage, cache, nullptr, nullptr);+ auto painter = player.begin_painting(*surface, storage, cache, nullptr);list.replay(tree, painter, 0);player.end_painting();player.flush(*surface);diff --git a/Tests/Compositor/TestPaintingSurface.cpp b/Tests/Compositor/TestPaintingSurface.cppindex 50a9a0a3c41..1ee961608b1 100644--- a/Tests/Compositor/TestPaintingSurface.cpp+++ b/Tests/Compositor/TestPaintingSurface.cpp@@ -51,7 +51,7 @@ 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);- auto painter = player.begin_painting(*surface, storage, cache, nullptr, nullptr);+ auto painter = player.begin_painting(*surface, storage, cache, nullptr);list->replay(tree, painter, 0);player.end_painting();surface->read_into_bitmap(*bitmap);