Truly independent web browser
LibCompositing+LibWeb+Compositor: Replay the canvas 2D stream in Rust
Aliaksandr Kalenikbfce29638e39
diff --git a/Libraries/LibCompositing/CMakeLists.txt b/Libraries/LibCompositing/CMakeLists.txtindex 832b52b173b..b95c30c0350 100644--- a/Libraries/LibCompositing/CMakeLists.txt+++ b/Libraries/LibCompositing/CMakeLists.txt@@ -1,7 +1,7 @@include(libcompositing_generators)set(SOURCES- DisplayList/Canvas2DTape.cpp+ CanvasColorSpace.cppDisplayList/DisplayListResourceEncoding.cppDisplayList/DisplayListResources.cppDisplayList/RegisteredImageFrames.cppdiff --git a/Libraries/LibCompositing/CanvasColorSpace.cpp b/Libraries/LibCompositing/CanvasColorSpace.cppnew file mode 100644index 00000000000..439cc3776e0--- /dev/null+++ b/Libraries/LibCompositing/CanvasColorSpace.cpp@@ -0,0 +1,42 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCompositing/CanvasColorSpace.h>++namespace Compositing {++// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace+Media::CodingIndependentCodePoints coding_independent_code_points_for(Web::Bindings::PredefinedColorSpace color_space)+{+ auto code_points = [](Media::ColorPrimaries color_primaries, Media::TransferCharacteristics transfer_characteristics) {+ return Media::CodingIndependentCodePoints { color_primaries, transfer_characteristics, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full };+ };++ switch (color_space) {+ // The "srgb" value indicates the 'srgb' color space.+ case Web::Bindings::PredefinedColorSpace::Srgb:+ return code_points(Media::ColorPrimaries::BT709, Media::TransferCharacteristics::SRGB);+ // The "srgb-linear" value indicates the 'srgb-linear' color space.+ case Web::Bindings::PredefinedColorSpace::SrgbLinear:+ return code_points(Media::ColorPrimaries::BT709, Media::TransferCharacteristics::Linear);+ // The "display-p3" value indicates the 'display-p3' color space.+ case Web::Bindings::PredefinedColorSpace::DisplayP3:+ return code_points(Media::ColorPrimaries::SMPTE432, Media::TransferCharacteristics::SRGB);+ // The "display-p3-linear" value indicates the 'display-p3-linear' color space.+ case Web::Bindings::PredefinedColorSpace::DisplayP3Linear:+ return code_points(Media::ColorPrimaries::SMPTE432, Media::TransferCharacteristics::Linear);+ }+ VERIFY_NOT_REACHED();+}++Gfx::ColorSpace gfx_color_space_for(Web::Bindings::PredefinedColorSpace color_space)+{+ if (color_space == Web::Bindings::PredefinedColorSpace::Srgb)+ return {};+ return MUST(Gfx::ColorSpace::from_cicp(coding_independent_code_points_for(color_space)));+}++}diff --git a/Libraries/LibCompositing/CanvasColorSpace.h b/Libraries/LibCompositing/CanvasColorSpace.hnew file mode 100644index 00000000000..7e98dae4c42--- /dev/null+++ b/Libraries/LibCompositing/CanvasColorSpace.h@@ -0,0 +1,24 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibCompositing/Export.h>+#include <LibGfx/ColorSpace.h>+#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>+#include <LibWebCommon/Bindings/PredefinedColorSpace.h>++namespace Compositing {++// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace+// The coding-independent code points that describe the predefined color space.+COMPOSITING_API Media::CodingIndependentCodePoints coding_independent_code_points_for(Web::Bindings::PredefinedColorSpace);++// The color space of the pixels of a bitmap in the predefined color space. That of "srgb" is the color space that a+// bitmap without color space information is in.+COMPOSITING_API Gfx::ColorSpace gfx_color_space_for(Web::Bindings::PredefinedColorSpace);++}diff --git a/Libraries/LibCompositing/DisplayList/Canvas2DTape.cpp b/Libraries/LibCompositing/DisplayList/Canvas2DTape.cppdeleted file mode 100644index 30343799160..00000000000--- a/Libraries/LibCompositing/DisplayList/Canvas2DTape.cpp+++ /dev/null@@ -1,28 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCompositing/DisplayList/Canvas2DTape.h>-#include <LibCompositing/RustFFI.h>--namespace Compositing {--ErrorOr<void> validate_canvas_2d_tape(ReadonlyBytes tape)-{- u8 const* error = nullptr;- size_t error_size = 0;- if (!RustFFI::canvas_2d_tape_validate(tape, &error, &error_size))- return Error::from_string_view({ reinterpret_cast<char const*>(error), error_size });- return {};-}--void for_each_canvas_2d_command(ReadonlyBytes tape, Function<void(DisplayListCommandType, ReadonlyBytes payload)> const& callback)-{- RustFFI::canvas_2d_tape_for_each_command(tape, const_cast<void*>(static_cast<void const*>(&callback)), [](void* context, DisplayListCommandType command_type, ReadonlyBytes payload) {- (*static_cast<Function<void(DisplayListCommandType, ReadonlyBytes)> const*>(context))(command_type, payload);- });-}--}diff --git a/Libraries/LibCompositing/DisplayList/Canvas2DTape.h b/Libraries/LibCompositing/DisplayList/Canvas2DTape.hdeleted file mode 100644index e307d88d606..00000000000--- a/Libraries/LibCompositing/DisplayList/Canvas2DTape.h+++ /dev/null@@ -1,23 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <AK/Function.h>-#include <AK/Span.h>-#include <LibCompositing/DisplayList/DisplayListCommandsGenerated.h>-#include <LibCompositing/Export.h>--namespace Compositing {--// Checks the tape of a segment that came from WebContent.-COMPOSITING_API ErrorOr<void> validate_canvas_2d_tape(ReadonlyBytes);--// Calls the callback with the type and the payload of each record of a checked tape, in order.-COMPOSITING_API void for_each_canvas_2d_command(ReadonlyBytes tape, Function<void(DisplayListCommandType, ReadonlyBytes payload)> const&);--}diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rsindex 611bc6759cc..96f62cad6bc 100644--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs@@ -4,18 +4,16 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The tape of a 2D canvas: the records that a recorder writes for the commands of the canvas, and the entry points-//! through which the compositor checks and reads a tape that it received.+//! The tape of a 2D canvas: the records that a recorder writes for the commands of the canvas, and how the compositor+//! reads a tape that it received.use super::builder::{append_record, for_each_command};use super::commands::*;use super::ffi_bytes::FfiBytes;-use super::validate::validate_canvas_2d_tape;use libgfx_rust::{AffineTransform, CapStyle, Color, CompositingAndBlendingOperator, FloatPoint, FloatRect, IntPoint, JoinStyle,ScalingMode, WindingRule,};-use std::ffi::c_void;/// The stops of a gradient, as parallel arrays of colors and positions.#[derive(Clone, Copy, Debug, Default)]@@ -373,39 +371,11 @@ impl TapeWriter {}}-/// Checks the tape of a segment of the canvas 2D stream that came from another process. Returns false with a static-/// error message, whose address and size it writes, if the tape does not pass.-#[unsafe(no_mangle)]-pub extern "C" fn canvas_2d_tape_validate(- tape: ak::Span<'_, u8>,- error: &mut *const u8,- error_size: &mut usize,-) -> bool {- match validate_canvas_2d_tape(tape.as_slice()) {- Ok(()) => true,- Err(message) => {- *error = message.as_ptr();- *error_size = message.len();- false- }- }-}--/// Calls `visit` with the type and the payload of each record of a tape that passed `canvas_2d_tape_validate`, in-/// order.-///-/// # Safety-/// `visit` runs synchronously and reads the payload only while it runs.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn canvas_2d_tape_for_each_command(- tape: ak::Span<'_, u8>,- context: *mut c_void,- visit: unsafe extern "C" fn(*mut c_void, DisplayListCommandType, ak::Span<'_, u8>),-) {- for_each_command(tape.as_slice(), |header, _, payload| {+/// Calls `play` with the type and the payload of each record of a tape that passed `validate_canvas_2d_tape`, in order.+pub fn for_each_canvas_2d_command<'a>(tape: &'a [u8], mut play: impl FnMut(DisplayListCommandType, &'a [u8])) {+ for_each_command(tape, |header, _, payload| {debug_assert!(header.command_type.is_canvas_2d());- // SAFETY: The caller reads the payload synchronously.- unsafe { visit(context, header.command_type, ak::Span::new(payload)) };+ play(header.command_type, payload);});}@@ -415,6 +385,7 @@ mod tests {use crate::display_list::builder::{HEADER_SIZE, read_command, read_header};use crate::display_list::nested_records::span_bytes;use crate::display_list::storage::write_run_with_zeroed_padding;+ use crate::display_list::validate::validate_canvas_2d_tape;use crate::display_list::validate::validate_tape;use libgfx_rust::IntRect;diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rsindex 03578fa967f..3c518bc8860 100644--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs@@ -9,6 +9,7 @@use super::canvas_2d::{Compositing, Paint, Stroke, TapeWriter};use super::commands::*;+use crate::ipc_types::Web_Bindings_PredefinedColorSpace;use libgfx_rust::{AffineTransform, Color, FloatPoint, FloatRect, IntPoint, IntRect, IntSize, ScalingMode, WindingRule,};@@ -37,6 +38,17 @@ pub enum ColorSpace {DisplayP3Linear,}+impl From<ColorSpace> for Web_Bindings_PredefinedColorSpace {+ fn from(color_space: ColorSpace) -> Self {+ match color_space {+ ColorSpace::Srgb => Self::Srgb,+ ColorSpace::SrgbLinear => Self::SrgbLinear,+ ColorSpace::DisplayP3 => Self::DisplayP3,+ ColorSpace::DisplayP3Linear => Self::DisplayP3Linear,+ }+ }+}+/// The context of a canvas in the Compositor, and the stream that the commands of every canvas of WebContent share./// In the product that is the CompositorTransport of Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs.pub trait Transport {diff --git a/Libraries/LibCompositing/Types.ipc b/Libraries/LibCompositing/Types.ipcindex 23106008422..811fc9c62bb 100644--- a/Libraries/LibCompositing/Types.ipc+++ b/Libraries/LibCompositing/Types.ipc@@ -9,6 +9,7 @@#include <LibCompositing/Types.h>#include <LibCompositing/WebGL/Types.h>#include <LibGfx/Rect.h>+#include <LibWebCommon/Bindings/PredefinedColorSpace.h>[ExistingCpp]enum Compositing::WindowResizingInProgress : u8 {@@ -252,3 +253,12 @@ struct Compositing::Canvas2DCommandStreamSegment {ByteBuffer tape;bool present;}++// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace+[ExistingCpp]+enum Web::Bindings::PredefinedColorSpace : u8 {+ Srgb,+ SrgbLinear,+ DisplayP3,+ DisplayP3Linear,+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rsindex 1296ede67a3..a06590559a3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs@@ -15,25 +15,34 @@ use std::rc::Rc;use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, ColorSpace, Transport};use libcompositing_rust::display_list::commands::{CanvasId, FontResourceId, ImageFrameResourceId};+use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{+ CreateCanvas2dContext, DestroyCanvas2dContext,+};use libgfx_rust::font::FontHandle;use libgfx_rust::image_frame::ImageFrameHandle;use libgfx_rust::{IntRect, IntSize};use libipc_rust::cpp_connection::{FfiThreadSafeMessagePoster, ThreadSafeMessagePoster};+use libipc_rust::wire::EndpointMessage;use super::stream::{Canvas2DStream, flush, shared_stream};unsafe extern "C" {fn web_canvas_2d_connection_unref(connection: *mut c_void);- fn web_canvas_2d_connection_create_context(+ fn web_canvas_2d_connection_poster(connection: *mut c_void, out_poster: *mut FfiThreadSafeMessagePoster) -> bool;+ fn web_canvas_2d_connection_reserve_context_id(connection: *mut c_void,width: i32,height: i32,- alpha: bool,- will_read_frequently: bool,- color_space: ColorSpace,out_canvas_id: *mut u64,) -> bool;- fn web_canvas_2d_connection_destroy_context(connection: *mut c_void, canvas_id: u64);+ fn web_canvas_2d_connection_post_stream_batch_fonts_and_image_frames(+ connection: *mut c_void,+ fonts: *const *const c_void,+ font_count: usize,+ image_frames: *const *const c_void,+ image_frame_count: usize,+ ) -> bool;+ fn web_canvas_2d_connection_did_fail_to_post(connection: *mut c_void);fn web_canvas_2d_connection_read_back_pixels(connection: *mut c_void,canvas_id: u64,@@ -44,15 +53,6 @@ unsafe extern "C" {alpha_type: AlphaType,color_space: ColorSpace,) -> *mut c_void;- fn web_canvas_2d_connection_prepare_stream_batch(- connection: *mut c_void,- fonts: *const *const c_void,- font_count: usize,- image_frames: *const *const c_void,- image_frame_count: usize,- out_poster: *mut FfiThreadSafeMessagePoster,- ) -> bool;- fn web_canvas_2d_connection_did_fail_to_post_stream_batch(connection: *mut c_void);fn web_canvas_2d_video_frame_hold_ref(hold: *mut c_void);fn web_canvas_2d_video_frame_hold_unref(hold: *mut c_void);fn web_canvas_2d_video_frame_hold_note_sent_to_compositor(hold: *mut c_void);@@ -71,30 +71,49 @@ impl CompositorConnection {Self(connection)}- fn create_context(+ pub(crate) fn poster_while_compositor_is_reachable(self) -> Option<ThreadSafeMessagePoster> {+ let mut poster = MaybeUninit::<FfiThreadSafeMessagePoster>::uninit();+ let reachable = unsafe { web_canvas_2d_connection_poster(self.0.as_ptr(), poster.as_mut_ptr()) };+ // SAFETY: C++ sets the poster to one reference to the poster of the connection where it answers true.+ reachable.then(|| unsafe { ThreadSafeMessagePoster::adopt(poster.assume_init()) })+ }++ pub(crate) fn post_or_lose_compositor<M: EndpointMessage>(self,- size: IntSize,- alpha: bool,- will_read_frequently: bool,- color_space: ColorSpace,- ) -> Option<CanvasId> {+ poster: &ThreadSafeMessagePoster,+ message: M,+ ) -> bool {+ let posted = poster.try_post(message).expect("a message of a 2D canvas encodes");+ if !posted {+ unsafe { web_canvas_2d_connection_did_fail_to_post(self.0.as_ptr()) };+ }+ posted+ }++ fn reserve_context_id(self, size: IntSize) -> Option<CanvasId> {let mut canvas_id = 0;unsafe {- web_canvas_2d_connection_create_context(- self.0.as_ptr(),- size.width,- size.height,- alpha,- will_read_frequently,- color_space,- &raw mut canvas_id,- )+ web_canvas_2d_connection_reserve_context_id(self.0.as_ptr(), size.width, size.height, &raw mut canvas_id)}.then_some(CanvasId(canvas_id))}- fn destroy_context(self, canvas_id: CanvasId) {- unsafe { web_canvas_2d_connection_destroy_context(self.0.as_ptr(), canvas_id.0) };+ pub(crate) fn post_stream_batch_fonts_and_image_frames(+ self,+ fonts: &[&FontHandle],+ image_frames: &[&ImageFrameHandle],+ ) -> bool {+ let fonts: Vec<*const c_void> = fonts.iter().map(|font| font.as_raw()).collect();+ let image_frames: Vec<*const c_void> = image_frames.iter().map(|frame| frame.as_raw()).collect();+ unsafe {+ web_canvas_2d_connection_post_stream_batch_fonts_and_image_frames(+ self.0.as_ptr(),+ fonts.as_ptr(),+ fonts.len(),+ image_frames.as_ptr(),+ image_frames.len(),+ )+ }}fn read_back_pixels(@@ -119,32 +138,6 @@ impl CompositorConnection {// SAFETY: LibWeb hands over a frame that it allocated with new, or null.(!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })}-- pub(crate) fn prepare_stream_batch(- self,- fonts: &[&FontHandle],- image_frames: &[&ImageFrameHandle],- ) -> Option<ThreadSafeMessagePoster> {- let fonts: Vec<*const c_void> = fonts.iter().map(|font| font.as_raw()).collect();- let image_frames: Vec<*const c_void> = image_frames.iter().map(|frame| frame.as_raw()).collect();- let mut poster = MaybeUninit::<FfiThreadSafeMessagePoster>::uninit();- let prepared = unsafe {- web_canvas_2d_connection_prepare_stream_batch(- self.0.as_ptr(),- fonts.as_ptr(),- fonts.len(),- image_frames.as_ptr(),- image_frames.len(),- poster.as_mut_ptr(),- )- };- // SAFETY: C++ sets the poster to one reference to the poster of the connection where it answers true.- prepared.then(|| unsafe { ThreadSafeMessagePoster::adopt(poster.assume_init()) })- }-- pub(crate) fn did_fail_to_post_stream_batch(self) {- unsafe { web_canvas_2d_connection_did_fail_to_post_stream_batch(self.0.as_ptr()) };- }}pub(crate) struct VideoFrameHold(NonNull<c_void>);@@ -238,12 +231,22 @@ impl Transport for CompositorTransport {fn create_context(&self, size: IntSize, alpha: bool, will_read_frequently: bool, color_space: ColorSpace) -> bool {assert!(self.canvas_id.get().is_none(), "a transport creates one context");- let Some(canvas_id) = self- .connection- .create_context(size, alpha, will_read_frequently, color_space)- else {+ let Some(canvas_id) = self.connection.reserve_context_id(size) else {+ return false;+ };+ let Some(poster) = self.connection.poster_while_compositor_is_reachable() else {return false;};+ let message = CreateCanvas2dContext {+ canvas_id,+ size,+ alpha,+ will_read_frequently,+ color_space: color_space.into(),+ };+ if !self.connection.post_or_lose_compositor(&poster, message) {+ return false;+ }self.canvas_id.set(Some(canvas_id));true}@@ -253,8 +256,12 @@ impl Transport for CompositorTransport {}fn destroy_context(&self) {- if let Some(canvas_id) = self.canvas_id.take() {- self.connection.destroy_context(canvas_id);+ let Some(canvas_id) = self.canvas_id.take() else {+ return;+ };+ if let Some(poster) = self.connection.poster_while_compositor_is_reachable() {+ self.connection+ .post_or_lose_compositor(&poster, DestroyCanvas2dContext { canvas_id });}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rsindex 46b8d474a93..9018dcf3c01 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs@@ -109,17 +109,20 @@ pub(crate) fn flush(stream: &RefCell<Canvas2DStream>, connection: CompositorConnstream.borrow_mut().pending.put_back_ahead(batch);return;}+ let Some(poster) = connection.poster_while_compositor_is_reachable() else {+ stream.borrow_mut().pending.put_back_ahead(batch);+ return;+ };let fonts: Vec<&FontHandle> = batch.fonts.values().collect();let image_frames: Vec<&ImageFrameHandle> = batch.image_frames.values().collect();- let Some(poster) = connection.prepare_stream_batch(&fonts, &image_frames) else {+ if !connection.post_stream_batch_fonts_and_image_frames(&fonts, &image_frames) {stream.borrow_mut().pending.put_back_ahead(batch);return;- };+ }let message = UpdateCanvas2dStream {segments: std::mem::take(&mut batch.segments),};- if !poster.try_post(message).expect("a canvas 2D stream encodes") {- connection.did_fail_to_post_stream_batch();+ if !connection.post_or_lose_compositor(&poster, message) {return;}for hold in &batch.video_frame_holds {diff --git a/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp b/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cppindex 0223a407ea1..786d8ccc685 100644--- a/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp+++ b/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp@@ -5,6 +5,7 @@*/#include <AK/Span.h>+#include <LibCompositing/CanvasColorSpace.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibGfx/Bitmap.h>@@ -26,11 +27,11 @@ static_assert(to_underlying(Gfx::AlphaType::Unpremultiplied) == 1);extern "C" {void web_canvas_2d_connection_unref(CompositorConnection*);-bool web_canvas_2d_connection_create_context(CompositorConnection*, i32 width, i32 height, bool alpha, bool will_read_frequently, u8 color_space, u64* out_canvas_id);-void web_canvas_2d_connection_destroy_context(CompositorConnection*, u64 canvas_id);+bool web_canvas_2d_connection_poster(CompositorConnection*, IPC::FfiThreadSafeMessagePoster* out_poster);+bool web_canvas_2d_connection_reserve_context_id(CompositorConnection*, i32 width, i32 height, u64* out_canvas_id);+bool web_canvas_2d_connection_post_stream_batch_fonts_and_image_frames(CompositorConnection*, Gfx::Font const* const* fonts, size_t font_count, Gfx::DecodedImageFrame const* const* image_frames, size_t image_frame_count);+void web_canvas_2d_connection_did_fail_to_post(CompositorConnection*);Gfx::DecodedImageFrame* web_canvas_2d_connection_read_back_pixels(CompositorConnection*, u64 canvas_id, i32 x, i32 y, i32 width, i32 height, u8 alpha_type, u8 color_space);-bool web_canvas_2d_connection_prepare_stream_batch(CompositorConnection*, Gfx::Font const* const* fonts, size_t font_count, Gfx::DecodedImageFrame const* const* image_frames, size_t image_frame_count, IPC::FfiThreadSafeMessagePoster* out_poster);-void web_canvas_2d_connection_did_fail_to_post_stream_batch(CompositorConnection*);void web_canvas_2d_video_frame_hold_ref(Compositing::VideoFrameHold*);void web_canvas_2d_video_frame_hold_unref(Compositing::VideoFrameHold*);void web_canvas_2d_video_frame_hold_note_sent_to_compositor(Compositing::VideoFrameHold*);@@ -41,26 +42,40 @@ void web_canvas_2d_connection_unref(CompositorConnection* connection)connection->unref();}-// NB: A color space is the underlying value of a Bindings::PredefinedColorSpace.-bool web_canvas_2d_connection_create_context(CompositorConnection* connection, i32 width, i32 height, bool alpha, bool will_read_frequently, u8 color_space, u64* out_canvas_id)+bool web_canvas_2d_connection_poster(CompositorConnection* connection, IPC::FfiThreadSafeMessagePoster* out_poster){- auto canvas_id = connection->create_canvas_2d_context({ width, height }, alpha, will_read_frequently, HTML::gfx_color_space_for(HTML::predefined_color_space_from_underlying(color_space)));+ auto poster = connection->poster_while_compositor_is_reachable();+ if (!poster)+ return false;+ *out_poster = poster->to_ffi_with_one_reference();+ return true;+}++bool web_canvas_2d_connection_reserve_context_id(CompositorConnection* connection, i32 width, i32 height, u64* out_canvas_id)+{+ auto canvas_id = connection->reserve_canvas_2d_context_id({ width, height });if (!canvas_id.has_value())return false;*out_canvas_id = canvas_id->value();return true;}-void web_canvas_2d_connection_destroy_context(CompositorConnection* connection, u64 canvas_id)+bool web_canvas_2d_connection_post_stream_batch_fonts_and_image_frames(CompositorConnection* connection, Gfx::Font const* const* fonts, size_t font_count, Gfx::DecodedImageFrame const* const* image_frames, size_t image_frame_count)+{+ return connection->post_canvas_2d_stream_batch_fonts_and_image_frames({ fonts, font_count }, { image_frames, image_frame_count });+}++void web_canvas_2d_connection_did_fail_to_post(CompositorConnection* connection){- connection->destroy_canvas_context(Compositing::CanvasId { canvas_id });+ connection->did_fail_to_post_canvas_2d_message();}+// NB: A color space is the underlying value of a Bindings::PredefinedColorSpace.// Unpremultiplied pixels come back as RGBA8888 and premultiplied pixels as BGRA8888, in the color space.Gfx::DecodedImageFrame* web_canvas_2d_connection_read_back_pixels(CompositorConnection* connection, u64 canvas_id, i32 x, i32 y, i32 width, i32 height, u8 alpha_type, u8 color_space){VERIFY(Gfx::is_valid_alpha_type(alpha_type));- auto gfx_color_space = HTML::gfx_color_space_for(HTML::predefined_color_space_from_underlying(color_space));+ auto gfx_color_space = Compositing::gfx_color_space_for(HTML::predefined_color_space_from_underlying(color_space));auto shareable_bitmap = connection->get_canvas_pixels(Compositing::CanvasId { canvas_id }, { x, y, width, height }, static_cast<Gfx::AlphaType>(alpha_type), gfx_color_space);if (!shareable_bitmap.is_valid())return nullptr;@@ -70,20 +85,6 @@ Gfx::DecodedImageFrame* web_canvas_2d_connection_read_back_pixels(CompositorConnreturn new Gfx::DecodedImageFrame { frame.release_value() };}-bool web_canvas_2d_connection_prepare_stream_batch(CompositorConnection* connection, Gfx::Font const* const* fonts, size_t font_count, Gfx::DecodedImageFrame const* const* image_frames, size_t image_frame_count, IPC::FfiThreadSafeMessagePoster* out_poster)-{- auto poster = connection->prepare_canvas_2d_stream_batch({ fonts, font_count }, { image_frames, image_frame_count });- if (!poster)- return false;- *out_poster = poster->to_ffi_with_one_reference();- return true;-}--void web_canvas_2d_connection_did_fail_to_post_stream_batch(CompositorConnection* connection)-{- connection->did_fail_to_post_canvas_2d_stream_batch();-}-void web_canvas_2d_video_frame_hold_ref(Compositing::VideoFrameHold* hold){hold->ref();diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 0fd2828b4f9..45ffe5a5ffd 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -365,7 +365,14 @@ void CompositorConnection::set_video_sink_ticking(Media::VideoSinkHandle video_sasync_set_video_sink_ticking(video_sink_handle, should_tick);}-Optional<Compositing::CanvasId> CompositorConnection::create_canvas_2d_context(Gfx::IntSize size, bool alpha, bool will_read_frequently, Gfx::ColorSpace const& color_space)+RefPtr<IPC::ThreadSafeMessagePoster> CompositorConnection::poster_while_compositor_is_reachable()+{+ if (!can_send_message_to_compositor())+ return nullptr;+ return m_poster;+}++Optional<Compositing::CanvasId> CompositorConnection::reserve_canvas_2d_context_id(Gfx::IntSize size){if (!can_send_message_to_compositor())return {};@@ -389,39 +396,35 @@ Optional<Compositing::CanvasId> CompositorConnection::create_canvas_2d_context(G}auto canvas_id = Compositing::CanvasId { m_next_reserved_canvas_id++ };--m_reserved_canvas_ids_remaining;-- async_create_canvas_2d_context(canvas_id, size, alpha, will_read_frequently, color_space);return canvas_id;}-RefPtr<IPC::ThreadSafeMessagePoster> CompositorConnection::prepare_canvas_2d_stream_batch(ReadonlySpan<Gfx::Font const*> fonts, ReadonlySpan<Gfx::DecodedImageFrame const*> image_frames)+bool CompositorConnection::post_canvas_2d_stream_batch_fonts_and_image_frames(ReadonlySpan<Gfx::Font const*> fonts, ReadonlySpan<Gfx::DecodedImageFrame const*> image_frames){- if (!can_send_message_to_compositor())- return nullptr;if (!register_typefaces_of_fonts_with_compositor(*m_poster, fonts) || !register_image_frames_with_compositor(*m_poster, image_frames)) {did_lose_compositor();- return nullptr;+ return false;}- if (!fonts.is_empty()) {- auto encoded_message = MUST(Messages::CompositorWebContentServer::DescribeCanvas2dFonts::static_encode(descriptions_of_fonts(fonts)));- if (!m_poster->try_post(encoded_message)) {- did_lose_compositor();- return nullptr;- }+ if (fonts.is_empty())+ return true;+ auto encoded_message = MUST(Messages::CompositorWebContentServer::DescribeCanvas2dFonts::static_encode(descriptions_of_fonts(fonts)));+ if (!m_poster->try_post(encoded_message)) {+ did_lose_compositor();+ return false;}- return m_poster;+ return true;}-void CompositorConnection::did_fail_to_post_canvas_2d_stream_batch()+void CompositorConnection::did_fail_to_post_canvas_2d_message(){did_lose_compositor();}-void CompositorConnection::destroy_canvas_context(Compositing::CanvasId canvas_id)+void CompositorConnection::destroy_webgl_context(Compositing::CanvasId canvas_id){if (!can_send_message_to_compositor())return;- async_destroy_canvas_context(canvas_id);+ async_destroy_webgl_context(canvas_id);}Gfx::ShareableBitmap CompositorConnection::get_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space)diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex 35150dcbce1..ced5a5900ec 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -70,10 +70,11 @@ public:void remove_video_sink(Media::VideoSinkHandle);void release_video_frame_hold(Media::VideoSinkHandle, u64 generation);void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick);- Optional<Compositing::CanvasId> create_canvas_2d_context(Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace const&);- RefPtr<IPC::ThreadSafeMessagePoster> prepare_canvas_2d_stream_batch(ReadonlySpan<Gfx::Font const*>, ReadonlySpan<Gfx::DecodedImageFrame const*>);- void did_fail_to_post_canvas_2d_stream_batch();- void destroy_canvas_context(Compositing::CanvasId);+ RefPtr<IPC::ThreadSafeMessagePoster> poster_while_compositor_is_reachable();+ Optional<Compositing::CanvasId> reserve_canvas_2d_context_id(Gfx::IntSize);+ bool post_canvas_2d_stream_batch_fonts_and_image_frames(ReadonlySpan<Gfx::Font const*>, ReadonlySpan<Gfx::DecodedImageFrame const*>);+ void did_fail_to_post_canvas_2d_message();+ void destroy_webgl_context(Compositing::CanvasId);Gfx::ShareableBitmap get_canvas_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType = Gfx::AlphaType::Premultiplied, Gfx::ColorSpace const& = {});Optional<Web::Compositor::PlaceholderCanvasLink> allocate_placeholder_canvas();void release_placeholder_canvas(Compositing::CanvasId);diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex cfb79880e3e..927e3ffa413 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -207,7 +207,7 @@ private:{if (!m_canvas_id.has_value())return;- m_connection->destroy_canvas_context(*m_canvas_id);+ m_connection->destroy_webgl_context(*m_canvas_id);m_canvas_id.clear();}diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex 57bd0ef9bd8..4c97beef10e 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -12,6 +12,7 @@*/#include <AK/Utf16StringBuilder.h>+#include <LibCompositing/CanvasColorSpace.h>#include <LibCompositing/RustFFI.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibGfx/AffineTransform.h>@@ -707,7 +708,7 @@ Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_roauto row_size = static_cast<size_t>(width) * sizeof(Gfx::RawPixel);for (int y = 0; y < height; ++y)__builtin_memcpy(bitmap.value()->scanline(y), first_row + static_cast<size_t>(y) * pitch, row_size);- auto frame = Gfx::DecodedImageFrame::create(*bitmap.release_value(), gfx_color_space_for(predefined_color_space_from_underlying(color_space)));+ auto frame = Gfx::DecodedImageFrame::create(*bitmap.release_value(), Compositing::gfx_color_space_for(predefined_color_space_from_underlying(color_space)));if (frame.is_error())return nullptr;return new Gfx::DecodedImageFrame { frame.release_value() };diff --git a/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.cpp b/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.cppindex f389bf9170d..cd780f2ea43 100644--- a/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.cpp+++ b/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.cpp@@ -13,37 +13,6 @@ static_assert(to_underlying(Bindings::PredefinedColorSpace::SrgbLinear) == 1);static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3) == 2);static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3Linear) == 3);-// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace-Media::CodingIndependentCodePoints coding_independent_code_points_for(Bindings::PredefinedColorSpace color_space)-{- auto code_points = [](Media::ColorPrimaries color_primaries, Media::TransferCharacteristics transfer_characteristics) {- return Media::CodingIndependentCodePoints { color_primaries, transfer_characteristics, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full };- };-- switch (color_space) {- // The "srgb" value indicates the 'srgb' color space.- case Bindings::PredefinedColorSpace::Srgb:- return code_points(Media::ColorPrimaries::BT709, Media::TransferCharacteristics::SRGB);- // The "srgb-linear" value indicates the 'srgb-linear' color space.- case Bindings::PredefinedColorSpace::SrgbLinear:- return code_points(Media::ColorPrimaries::BT709, Media::TransferCharacteristics::Linear);- // The "display-p3" value indicates the 'display-p3' color space.- case Bindings::PredefinedColorSpace::DisplayP3:- return code_points(Media::ColorPrimaries::SMPTE432, Media::TransferCharacteristics::SRGB);- // The "display-p3-linear" value indicates the 'display-p3-linear' color space.- case Bindings::PredefinedColorSpace::DisplayP3Linear:- return code_points(Media::ColorPrimaries::SMPTE432, Media::TransferCharacteristics::Linear);- }- VERIFY_NOT_REACHED();-}--Gfx::ColorSpace gfx_color_space_for(Bindings::PredefinedColorSpace color_space)-{- if (color_space == Bindings::PredefinedColorSpace::Srgb)- return {};- return MUST(Gfx::ColorSpace::from_cicp(coding_independent_code_points_for(color_space)));-}-CSS::ColorStyleValue::ColorType css_color_type_for(Bindings::PredefinedColorSpace color_space){switch (color_space) {diff --git a/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.h b/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.hindex e13304e9090..566c6ae9b0f 100644--- a/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.h+++ b/Libraries/LibWeb/HTML/Canvas/PredefinedColorSpace.h@@ -6,22 +6,12 @@#pragma once-#include <LibGfx/ColorSpace.h>-#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>#include <LibWeb/CSS/StyleValues/ColorStyleValue.h>#include <LibWeb/Export.h>#include <LibWebCommon/Bindings/PredefinedColorSpace.h>namespace Web::HTML {-// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace-// The coding-independent code points that describe the predefined color space.-WEB_API Media::CodingIndependentCodePoints coding_independent_code_points_for(Bindings::PredefinedColorSpace);--// The color space of the pixels of a bitmap in the predefined color space. That of "srgb" is the color space that a-// bitmap without color space information is in.-WEB_API Gfx::ColorSpace gfx_color_space_for(Bindings::PredefinedColorSpace);-// The CSS color space of the predefined color space.WEB_API CSS::ColorStyleValue::ColorType css_color_type_for(Bindings::PredefinedColorSpace);diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 2ee67804e0e..a22b8b3a638 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -14,6 +14,7 @@#include <AK/StringBuilder.h>#include <AK/Utf8View.h>#include <AK/Vector.h>+#include <LibCompositing/CanvasColorSpace.h>#include <LibCore/Timer.h>#include <LibGC/Function.h>#include <LibGC/Heap.h>@@ -36,7 +37,6 @@#include <LibWeb/EventTiming/PerformanceEventTiming.h>#include <LibWeb/Fetch/BindingsGlue.h>#include <LibWeb/Fetch/FetchMethod.h>-#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>#include <LibWeb/HTML/CanvasRenderingContext2D.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/EventSource.h>@@ -638,7 +638,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,}// 3. Set imageBitmap's bitmap data to image's image data, cropped to the source rectangle with formatting.- auto cropped_bitmap_or_error = crop_to_the_source_rectangle_with_formatting(compositor_host_for(realm.global_object()), *bitmap_or_error.release_value(), gfx_color_space_for(image_data->color_space()), sx, sy, sw, sh, options);+ auto cropped_bitmap_or_error = crop_to_the_source_rectangle_with_formatting(compositor_host_for(realm.global_object()), *bitmap_or_error.release_value(), Compositing::gfx_color_space_for(image_data->color_space()), sx, sy, sw, sh, options);// AD-HOC: Reject promise with an "InvalidStateError" DOMException on allocation failure// Spec issue: https://github.com/whatwg/html/issues/3323if (cropped_bitmap_or_error.is_error()) {diff --git a/Services/Compositor/Canvas2DCommandPlayer.cpp b/Services/Compositor/Canvas2DCommandPlayer.cppindex a97914c7c54..642fefe5681 100644--- a/Services/Compositor/Canvas2DCommandPlayer.cpp+++ b/Services/Compositor/Canvas2DCommandPlayer.cpp@@ -16,7 +16,6 @@#include <Compositor/PaintingSurface.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/SkiaUtils.h>-#include <LibCompositing/DisplayList/Canvas2DTape.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibGfx/Bitmap.h>#include <LibGfx/Color.h>@@ -73,22 +72,20 @@ void Canvas2DCommandPlayer::clear(Gfx::Color color)clear_rect({ {}, m_surface->size().to_type<float>() }, color);}-void Canvas2DCommandPlayer::play(ReadonlyBytes tape)+void Canvas2DCommandPlayer::play_command(DisplayListCommandType command_type, ReadonlyBytes payload){- for_each_canvas_2d_command(tape, [&](DisplayListCommandType command_type, ReadonlyBytes payload) {- m_payload = payload;- switch (command_type) {+ m_payload = payload;+ switch (command_type) {#define PLAY_CANVAS_2D_COMMAND(command_type) \case DisplayListCommandType::command_type: \play_command(read_display_list_object<Compositing::command_type>(payload)); \break;- ENUMERATE_CANVAS_2D_COMMANDS(PLAY_CANVAS_2D_COMMAND)+ ENUMERATE_CANVAS_2D_COMMANDS(PLAY_CANVAS_2D_COMMAND)#undef PLAY_CANVAS_2D_COMMAND- default:- // NB: Validation lets only the commands of the canvas 2D stream onto the tape of a canvas.- VERIFY_NOT_REACHED();- }- });+ default:+ // NB: Validation lets only the commands of the canvas 2D stream onto the tape of a canvas.+ VERIFY_NOT_REACHED();+ }m_payload = {};}diff --git a/Services/Compositor/Canvas2DCommandPlayer.h b/Services/Compositor/Canvas2DCommandPlayer.hindex 648ef578647..85f49bec38d 100644--- a/Services/Compositor/Canvas2DCommandPlayer.h+++ b/Services/Compositor/Canvas2DCommandPlayer.h@@ -60,8 +60,7 @@ public:void clear(Gfx::Color);- // Plays a tape that passed Compositing::validate_canvas_2d_tape().- void play(ReadonlyBytes tape);+ void play_command(Compositing::DisplayListCommandType, ReadonlyBytes payload);private:#define DECLARE_PLAY_COMMAND(command_type) \diff --git a/Services/Compositor/CanvasHost.cpp b/Services/Compositor/CanvasHost.cppindex 31ec9abe943..23f1505b762 100644--- a/Services/Compositor/CanvasHost.cpp+++ b/Services/Compositor/CanvasHost.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/TemporaryChange.h>#include <Compositor/Canvas2DCommandPlayer.h>#include <Compositor/CanvasHost.h>#include <Compositor/CanvasSurfaceRegistry.h>@@ -14,7 +13,6 @@#include <Compositor/VideoFrameHolds.h>#include <Compositor/VideoFrameSkia.h>#include <LibCompositing/CanvasSize.h>-#include <LibCompositing/DisplayList/Canvas2DCommandStreamSegment.h>#include <LibCompositing/DisplayList/RegisteredImageFrames.h>#include <LibGfx/Bitmap.h>#include <LibGfx/ColorSpace.h>@@ -79,9 +77,9 @@ OwnPtr<Canvas2DCommandPlayer> CanvasHost::create_2d_command_player(Gfx::IntSizereturn &m_described_canvas_2d_fonts.font(Compositing::FontResourceId { font_id });};auto image_frame_resolver = [this](u64 frame_id) -> Gfx::DecodedImageFrame const* {- if (!m_image_frames_registered_while_stream_batch_plays)+ if (!m_image_frames_registered_while_painting)return nullptr;- auto image_frame = m_image_frames_registered_while_stream_batch_plays->image_frame(Compositing::ImageFrameResourceId { frame_id });+ auto image_frame = m_image_frames_registered_while_painting->image_frame(Compositing::ImageFrameResourceId { frame_id });if (!image_frame)return nullptr;return &image_frame->frame();@@ -169,10 +167,21 @@ CanvasHost::CreateWebGLContextResult CanvasHost::create_webgl_context(Compositinreturn { .success = true, .canvas_id = canvas_id, .supported_extensions = move(supported_extensions) };}-void CanvasHost::destroy_context(Compositing::CanvasId canvas_id)+void CanvasHost::destroy_2d_context(Compositing::CanvasId canvas_id){- if (m_contexts.remove(canvas_id))- m_canvas_surface_registry.remove_canvas_surface(canvas_id);+ auto* context = this->context(canvas_id);+ VERIFY(context && context->has<Canvas2DContext>());+ m_contexts.remove(canvas_id);+ m_canvas_surface_registry.remove_canvas_surface(canvas_id);+}++void CanvasHost::destroy_webgl_context(Compositing::CanvasId canvas_id)+{+ auto* context = this->context(canvas_id);+ if (!context || !context->has<WebGLContext>())+ return;+ m_contexts.remove(canvas_id);+ m_canvas_surface_registry.remove_canvas_surface(canvas_id);}CanvasHost::Context* CanvasHost::context(Compositing::CanvasId canvas_id)@@ -183,18 +192,26 @@ CanvasHost::Context* CanvasHost::context(Compositing::CanvasId canvas_id)return &it->value;}-void CanvasHost::present_canvas_2d_context(Compositing::CanvasId canvas_id, Canvas2DContext& context)+CanvasHost::Canvas2DContext& CanvasHost::canvas_2d_context(Compositing::CanvasId canvas_id)+{+ auto* context = this->context(canvas_id);+ VERIFY(context);+ return context->get<Canvas2DContext>();+}++bool CanvasHost::try_present_2d_context(Compositing::CanvasId canvas_id){+ auto& context = canvas_2d_context(canvas_id);auto presented_surface_or_error = present_into_surface_of_pool(context.presented_surfaces, context.command_player->surface(), m_skia_backend_context);// The canvas goes on showing what it presented before, and presents again with its next commands.if (presented_surface_or_error.is_error()) {dbgln("Unable to present a 2D canvas context: {}", presented_surface_or_error.error());- return;+ return false;}auto presented_surface = presented_surface_or_error.release_value();m_canvas_surface_registry.set_canvas_surface(m_canvas_surface_owner_id, canvas_id, *presented_surface);context.presented_surface = presented_surface->painting_surface();- context.has_uncommitted_commands = false;+ return true;}bool CanvasHost::describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription> const& fonts, Compositing::RegisteredTypefaces const& registered_typefaces)@@ -209,36 +226,26 @@ bool CanvasHost::describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDesreturn true;}-void CanvasHost::execute_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> const& segments, Compositing::RegisteredImageFrames const& registered_image_frames)+Canvas2DCommandPlayer& CanvasHost::begin_2d_painting(Compositing::CanvasId canvas_id, Compositing::RegisteredImageFrames const& registered_image_frames){- TemporaryChange image_frames_registered_while_stream_batch_plays { m_image_frames_registered_while_stream_batch_plays, ®istered_image_frames };- Vector<NonnullRefPtr<Gfx::PaintingSurface>> surfaces_that_sample_video_frames;- for (auto const& segment : segments) {- // The canvas may have been destroyed while this segment was pending in- // WebContent, so a missing context is not a protocol violation.- auto* context = this->context(segment.canvas_id);- auto* canvas_context = context ? context->get_pointer<Canvas2DContext>() : nullptr;- if (!canvas_context)- continue;-- if (!segment.tape.is_empty()) {- m_drew_video_frame_in_segment = false;- canvas_context->command_player->play(segment.tape);- canvas_context->has_uncommitted_commands = true;- if (m_drew_video_frame_in_segment && !surfaces_that_sample_video_frames.contains_slow(canvas_context->command_player->surface()))- surfaces_that_sample_video_frames.append(canvas_context->command_player->surface());- }-- if (segment.present && canvas_context->has_uncommitted_commands)- present_canvas_2d_context(segment.canvas_id, *canvas_context);- }+ VERIFY(!m_image_frames_registered_while_painting);+ m_image_frames_registered_while_painting = ®istered_image_frames;+ m_painting_sampled_video_frame_on_gpu = false;+ return *canvas_2d_context(canvas_id).command_player;+}- // The frames stay held only until WebContent releases them, which follows this stream, so the GPU has to have- // finished sampling them by then.- if (m_skia_backend_context) {- for (auto& surface : surfaces_that_sample_video_frames)- m_skia_backend_context->flush_and_submit(surface);- }+bool CanvasHost::end_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu()+{+ m_image_frames_registered_while_painting = nullptr;+ return m_painting_sampled_video_frame_on_gpu;+}++void CanvasHost::flush_2d_contexts(ReadonlySpan<Compositing::CanvasId> canvas_ids)+{+ if (!m_skia_backend_context)+ return;+ for (auto canvas_id : canvas_ids)+ m_skia_backend_context->flush_and_submit(canvas_2d_context(canvas_id).command_player->surface());}sk_sp<SkImage> CanvasHost::held_video_frame_image(Media::VideoSinkHandle handle, u64 generation, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context_of_canvas)@@ -262,7 +269,7 @@ sk_sp<SkImage> CanvasHost::held_video_frame_image(Media::VideoSinkHandle handle,if (!video_frame_image->image_on_gpu) {video_frame_image->image_on_gpu = sk_image_from_video_frame(*video_frame_image->frame, skia_backend_context_of_canvas);if (video_frame_image->image_on_gpu)- m_drew_video_frame_in_segment = true;+ m_painting_sampled_video_frame_on_gpu = true;}return video_frame_image->image_on_gpu;}diff --git a/Services/Compositor/CanvasHost.h b/Services/Compositor/CanvasHost.hindex b613df86add..b393044cb4c 100644--- a/Services/Compositor/CanvasHost.h+++ b/Services/Compositor/CanvasHost.h@@ -64,10 +64,14 @@ public:bool create_2d_context(Compositing::CanvasId, Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace const&);CreateWebGLContextResult create_webgl_context(Compositing::WebGL::WebGLVersion, Gfx::IntSize, bool depth, bool stencil, bool antialias);- void destroy_context(Compositing::CanvasId);+ void destroy_2d_context(Compositing::CanvasId);+ void destroy_webgl_context(Compositing::CanvasId);[[nodiscard]] bool describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription> const&, Compositing::RegisteredTypefaces const&);- void execute_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> const&, Compositing::RegisteredImageFrames const&);+ Canvas2DCommandPlayer& begin_2d_painting(Compositing::CanvasId, Compositing::RegisteredImageFrames const&);+ bool end_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu();+ bool try_present_2d_context(Compositing::CanvasId);+ void flush_2d_contexts(ReadonlySpan<Compositing::CanvasId>);void execute_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const&);void set_webgl_shared_command_buffer(Compositing::CanvasId, Compositing::WebGL::WebGLSharedCommandBuffer);[[nodiscard]] bool execute_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const&);@@ -92,7 +96,6 @@ private:NonnullOwnPtr<Canvas2DCommandPlayer> command_player;PresentableSurfacePool presented_surfaces;NonnullRefPtr<Gfx::PaintingSurface> presented_surface;- bool has_uncommitted_commands { false };};using WebGLContext = NonnullOwnPtr<HostWebGLContext>;using Context = Variant<Canvas2DContext, WebGLContext>;@@ -100,7 +103,7 @@ private:Context* context(Compositing::CanvasId);OwnPtr<Canvas2DCommandPlayer> create_2d_command_player(Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace const&);static HostWebGLContext& as_webgl(Context&);- void present_canvas_2d_context(Compositing::CanvasId, Canvas2DContext&);+ Canvas2DContext& canvas_2d_context(Compositing::CanvasId);sk_sp<SkImage> held_video_frame_image(Media::VideoSinkHandle, u64 generation, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context_of_canvas);Vector<HostWebGLContext::UploadSource> resolve_webgl_upload_sources(Vector<Compositing::WebGL::ImageSourceFrame> const&) const;@@ -109,12 +112,12 @@ private:Compositing::CanvasSurfaceOwnerId m_canvas_surface_owner_id;HashMap<Compositing::CanvasId, Context> m_contexts;DrawnFonts m_described_canvas_2d_fonts;- Compositing::RegisteredImageFrames const* m_image_frames_registered_while_stream_batch_plays { nullptr };+ Compositing::RegisteredImageFrames const* m_image_frames_registered_while_painting { nullptr };VideoFrameHolds const& m_video_frame_holds;struct VideoFrameImage;HashMap<Media::VideoSinkHandle, NonnullOwnPtr<VideoFrameImage>> m_video_frame_images;- bool m_drew_video_frame_in_segment { false };+ bool m_painting_sampled_video_frame_on_gpu { false };};}diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cppindex 073bea46570..e52e3ff2a30 100644--- a/Services/Compositor/CompositorCore.cpp+++ b/Services/Compositor/CompositorCore.cpp@@ -288,6 +288,11 @@ void CompositorCore::canvas_content_changed(WebContentClientId client, CompositiRustFFI::compositor_core_canvas_content_changed(m_core, client.value(), canvas_id.value(), now().nanoseconds());}+void CompositorCore::forget_web_content_client(WebContentClientId client)+{+ RustFFI::compositor_core_forget_web_content_client(m_core, client.value());+}+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());diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.hindex cc3ebff8124..71d01a4d337 100644--- a/Services/Compositor/CompositorCore.h+++ b/Services/Compositor/CompositorCore.h@@ -71,6 +71,7 @@ public:// 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);+ void forget_web_content_client(WebContentClientId);// Answers false for a context with nothing to paint yet.bool paint_screenshot(Web::CompositorContextId, Gfx::PaintingSurface&);diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 0cfb4006039..b2aa4115927 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -9,9 +9,11 @@#include <AK/StdLibExtras.h>#include <AK/TemporaryChange.h>#include <Compositor/BackingStoreFactory.h>+#include <Compositor/Canvas2DCommandPlayer.h>#include <Compositor/CanvasHost.h>#include <Compositor/CompositorState.h>#include <Compositor/SkiaUtils.h>+#include <LibCompositing/CanvasColorSpace.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/DisplayList/RegisteredImageFrames.h>#include <LibCore/AnonymousBuffer.h>@@ -197,6 +199,7 @@ CompositorState::ContextOwnerCheckResult CompositorState::check_context_owner(Wevoid CompositorState::destroy_contexts_for_web_content_client(CompositorStateWebContentClient& client){+ m_core.forget_web_content_client(client.web_content_client_id());Vector<Web::CompositorContextId> context_ids;for (auto& context : m_presented_contexts) {if (context.value->web_content_client.web_content_client_id() == client.web_content_client_id())@@ -1081,6 +1084,31 @@ bool CompositorState::staged_rasterization_has_resources(WebContentClientId clie// The largest frame WebContent rasterizes for an SVG image.static constexpr int max_rasterization_target_dimension = 16384;+CanvasHost& CompositorState::canvas_host_of(WebContentClientId client_id)+{+ auto* client = web_content_client_if_present(client_id);+ VERIFY(client);+ return client->canvas_host();+}++void CompositorState::begin_canvas_2d_painting(WebContentClientId client_id, Compositing::CanvasId canvas_id, RustFFI::FfiCanvas2DPainter& painter)+{+ auto* client = web_content_client_if_present(client_id);+ VERIFY(client);+ VERIFY(!m_canvas_host_painting_2d_context);+ m_canvas_host_painting_2d_context = &client->canvas_host();+ auto& player = m_canvas_host_painting_2d_context->begin_2d_painting(canvas_id, client->registered_image_frames());+ painter = {+ .player = &player,+ .play_command = [](void* player, Compositing::DisplayListCommandType command_type, ReadonlyBytes payload) { static_cast<Canvas2DCommandPlayer*>(player)->play_command(command_type, payload); },+ };+}++bool CompositorState::end_canvas_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu()+{+ return exchange(m_canvas_host_painting_2d_context, nullptr)->end_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu();+}+bool CompositorState::begin_staged_rasterization(WebContentClientId client, u64 token, Compositing::RustFFI::FfiRasterPainter& painter){auto* rasterization = staged_rasterization(client, token);@@ -1525,6 +1553,13 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).staged_rasterization_has_resources = [](void* host, u64 client, u64 token, ReadonlySpan<u64> font_ids, ReadonlySpan<u64> image_frame_ids) { return state_of(host).staged_rasterization_has_resources(WebContentClientId { client }, token, font_ids, image_frame_ids); },.begin_staged_rasterization = [](void* host, u64 client, u64 token, Compositing::RustFFI::FfiRasterPainter* painter) { return state_of(host).begin_staged_rasterization(WebContentClientId { client }, token, *painter); },.finish_staged_rasterization = [](void* host, u64 client, u64 token) { state_of(host).finish_staged_rasterization(WebContentClientId { client }, token); },+ .reserve_canvas_ids = [](void* host, u64 count) { return state_of(host).m_canvas_surface_registry.reserve_canvas_ids(count).value(); },+ .create_canvas_2d_context = [](void* host, u64 client, Compositing::CanvasId canvas_id, Gfx::IntSize size, bool alpha, bool will_read_frequently, Web::Bindings::PredefinedColorSpace color_space) { return state_of(host).canvas_host_of(WebContentClientId { client }).create_2d_context(canvas_id, size, alpha, will_read_frequently, Compositing::gfx_color_space_for(color_space)); },+ .destroy_canvas_2d_context = [](void* host, u64 client, Compositing::CanvasId canvas_id) { state_of(host).canvas_host_of(WebContentClientId { client }).destroy_2d_context(canvas_id); },+ .begin_canvas_2d_painting = [](void* host, u64 client, Compositing::CanvasId canvas_id, RustFFI::FfiCanvas2DPainter* painter) { state_of(host).begin_canvas_2d_painting(WebContentClientId { client }, canvas_id, *painter); },+ .end_canvas_2d_painting = [](void* host) { return state_of(host).end_canvas_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu(); },+ .present_canvas_2d_context = [](void* host, u64 client, Compositing::CanvasId canvas_id) { return state_of(host).canvas_host_of(WebContentClientId { client }).try_present_2d_context(canvas_id); },+ .flush_canvas_2d_contexts = [](void* host, u64 client, ReadonlySpan<Compositing::CanvasId> canvas_ids) { state_of(host).canvas_host_of(WebContentClientId { client }).flush_2d_contexts(canvas_ids); },};}diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.hindex e5e404429f9..ced82e6e6db 100644--- a/Services/Compositor/CompositorState.h+++ b/Services/Compositor/CompositorState.h@@ -65,6 +65,7 @@ public:// The owner of this client's canvases, which are the only ones its contexts may draw.virtual Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const = 0;virtual Compositing::RegisteredImageFrames const& registered_image_frames() const = 0;+ virtual CanvasHost& canvas_host() = 0;virtual void ask_to_paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> const&) = 0;virtual void tell_remote_descendants_prepared_for_screenshot(u64 request_id) = 0;};@@ -226,6 +227,9 @@ private:bool staged_rasterization_has_resources(WebContentClientId, u64 token, ReadonlySpan<u64> font_ids, ReadonlySpan<u64> image_frame_ids);bool begin_staged_rasterization(WebContentClientId, u64 token, Compositing::RustFFI::FfiRasterPainter&);void finish_staged_rasterization(WebContentClientId, u64 token);+ CanvasHost& canvas_host_of(WebContentClientId);+ void begin_canvas_2d_painting(WebContentClientId, Compositing::CanvasId, RustFFI::FfiCanvas2DPainter&);+ bool end_canvas_2d_painting_reporting_whether_video_frames_were_sampled_on_gpu();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(RemoteLayer&, Web::CompositorContextId, RustFFI::MediaKind, u64 media_id, RustFFI::FfiSublayerPlacement const&, double device_pixel_ratio);@@ -288,6 +292,7 @@ private:RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;CanvasSurfaceRegistry m_canvas_surface_registry;+ CanvasHost* m_canvas_host_painting_2d_context { nullptr };// 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 };diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex e5ced1c21b4..b420bc1c9ed 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -59,14 +59,14 @@ endpoint CompositorWebContentServer[RustReceiver, RustSender] update_scroll_state(Web::CompositorContextId context_id, Compositing::ScrollStateSnapshot scroll_state, Compositing::KeyboardScrollState keyboard_scroll_state, Optional<Compositing::LayerPlan> layer_plan) =|// Hands WebContent a range of canvas IDs it may name its own 2D contexts with, so creating one needs no round trip.- reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)+ [RustReceiver] reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)// The pixels of the context, and the colors of its commands, are in the color space.- create_canvas_2d_context(Compositing::CanvasId canvas_id, Gfx::IntSize size, bool alpha, bool will_read_frequently, Gfx::ColorSpace color_space) =|+ [RustReceiver, RustSender] create_canvas_2d_context(Compositing::CanvasId canvas_id, Gfx::IntSize size, bool alpha, bool will_read_frequently, Web::Bindings::PredefinedColorSpace color_space) =|// The fonts are those that the segments of the canvas 2D stream that follow draw. The fonts described before that// are not among them are released.describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription> fonts) =|- [RustSender] update_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> segments) =|- destroy_canvas_context(Compositing::CanvasId canvas_id) =|+ [RustReceiver, RustSender] update_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> segments) =|+ [RustReceiver, RustSender] destroy_canvas_2d_context(Compositing::CanvasId canvas_id) =|// The pixels come back in the color space.get_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace color_space) => (Gfx::ShareableBitmap pixels)@@ -82,6 +82,7 @@ endpoint CompositorWebContentServer[RustReceiver, RustSender] rasterize_display_list(u64 token, Compositing::DisplayList display_list, Compositing::VisualContextTree visual_context_tree) =|create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) => (bool success, Compositing::CanvasId canvas_id, Vector<String> supported_extensions)+ destroy_webgl_context(Compositing::CanvasId canvas_id) =|webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) =|webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames) =|webgl_drain_command_buffer(Compositing::CanvasId canvas_id) => ()diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex af013b4a193..431fbb615b9 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -7,7 +7,6 @@#include <AK/Debug.h>#include <AK/Math.h>#include <Compositor/ConnectionFromWebContent.h>-#include <LibCompositing/DisplayList/Canvas2DTape.h>#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>#include <LibGfx/ColorSpace.h>#include <LibWebCommon/Page/InputEvent.h>@@ -303,18 +302,6 @@ void ConnectionFromWebContent::describe_display_list_fonts(Web::CompositorContexdid_misbehave("WebContent described a font of a typeface it has not registered");}-Messages::CompositorWebContentServer::ReserveCanvasIdsResponse ConnectionFromWebContent::reserve_canvas_ids()-{- static constexpr u64 reserved_canvas_id_count = 1 << 20;- if (!m_reserved_canvas_ids.is_used_up()) {- did_misbehave("WebContent reserved canvas IDs before using up its range");- return { Compositing::CanvasId { 0 }, 0 };- }- auto first_canvas_id = m_compositor_state->canvas_surface_registry().reserve_canvas_ids(reserved_canvas_id_count);- m_reserved_canvas_ids = { first_canvas_id.value(), first_canvas_id.value() + reserved_canvas_id_count };- return { first_canvas_id, reserved_canvas_id_count };-}-// NB: The pixels of a 2D context are in one of the predefined color spaces of a canvas, which WebContent describes by// coding-independent code points, or as sRGB without color space data. Nothing else can name one.// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace@@ -330,44 +317,12 @@ static bool is_predefined_canvas_color_space(Gfx::ColorSpace const& color_space)[](NonnullRefPtr<Gfx::ColorSpace::ICCProfile const> const&) { return false; });}-void ConnectionFromWebContent::create_canvas_2d_context(Compositing::CanvasId canvas_id, Gfx::IntSize size, bool alpha, bool will_read_frequently, Gfx::ColorSpace color_space)-{- // NB: WebContent names its contexts with the IDs of its range in order, so each ID names one context only.- if (m_reserved_canvas_ids.is_used_up() || canvas_id.value() != m_reserved_canvas_ids.next) {- did_misbehave("WebContent named a 2D canvas context with an ID other than the next one it reserved");- return;- }- if (!is_predefined_canvas_color_space(color_space)) {- did_misbehave("WebContent asked for a 2D canvas context in a color space that is not a predefined one");- return;- }- ++m_reserved_canvas_ids.next;- // NB: A context that cannot be created is not a protocol violation: commands recorded for it are dropped.- (void)m_canvas_host.create_2d_context(canvas_id, size, alpha, will_read_frequently, color_space);-}-void ConnectionFromWebContent::describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription> fonts){if (!m_canvas_host.describe_canvas_2d_fonts(fonts, m_registered_typefaces))did_misbehave("WebContent described a font of a typeface it has not registered");}-void ConnectionFromWebContent::update_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> segments)-{- for (auto const& segment : segments) {- if (Compositing::validate_canvas_2d_tape(segment.tape).is_error()) {- did_misbehave("WebContent sent a canvas 2D stream that does not validate");- return;- }- }- m_canvas_host.execute_canvas_2d_stream(segments, m_registered_image_frames);-}--void ConnectionFromWebContent::destroy_canvas_context(Compositing::CanvasId canvas_id)-{- m_canvas_host.destroy_context(canvas_id);-}-Messages::CompositorWebContentServer::GetCanvasPixelsResponse ConnectionFromWebContent::get_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace color_space){if (!Gfx::is_valid_alpha_type(to_underlying(alpha_type))) {@@ -426,6 +381,11 @@ Messages::CompositorWebContentServer::CreateWebglContextResponse ConnectionFromWreturn { result.success, result.canvas_id, move(result.supported_extensions) };}+void ConnectionFromWebContent::destroy_webgl_context(Compositing::CanvasId canvas_id)+{+ m_canvas_host.destroy_webgl_context(canvas_id);+}+void ConnectionFromWebContent::webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer){auto shared_command_buffer = Compositing::WebGL::WebGLSharedCommandBuffer::adopt_received_buffer(move(command_buffer));diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex 286529cb70b..55f06fa94f1 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -64,11 +64,7 @@ private:virtual void register_image_frames(Vector<Compositing::DisplayListImageFrameResource>) override;virtual void unregister_image_frame(Compositing::ImageFrameResourceId) override;virtual void describe_display_list_fonts(Web::CompositorContextId, Vector<Compositing::DisplayListFontDescription>) override;- virtual Messages::CompositorWebContentServer::ReserveCanvasIdsResponse reserve_canvas_ids() override;- virtual void create_canvas_2d_context(Compositing::CanvasId, Gfx::IntSize, bool alpha, bool will_read_frequently, Gfx::ColorSpace) override;virtual void describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription>) override;- virtual void update_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment>) override;- virtual void destroy_canvas_context(Compositing::CanvasId) override;virtual Messages::CompositorWebContentServer::GetCanvasPixelsResponse get_canvas_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType, Gfx::ColorSpace) override;virtual Messages::CompositorWebContentServer::AllocatePlaceholderCanvasResponse allocate_placeholder_canvas() override;virtual void release_placeholder_canvas(Compositing::CanvasId) override;@@ -77,6 +73,7 @@ private:virtual void stage_rasterization(u64 token, Vector<Compositing::DisplayListFontDescription>, Vector<Compositing::ImageFrameResourceId>, Gfx::ShareableBitmap target_bitmap) override;virtual Messages::CompositorWebContentServer::CreateWebglContextResponse create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) override;+ virtual void destroy_webgl_context(Compositing::CanvasId canvas_id) override;virtual void webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) override;virtual void webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames) override;virtual void webgl_drain_command_buffer(Compositing::CanvasId canvas_id) override;@@ -106,6 +103,7 @@ private:virtual void video_sink_counted_frames(Media::VideoSinkHandle, Media::DisplayingVideoSinkFrameCounts) override;virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) override;virtual Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const override { return m_canvas_host.canvas_surface_owner_id(); }+ virtual CanvasHost& canvas_host() override { return m_canvas_host; }virtual Compositing::RegisteredImageFrames const& registered_image_frames() const override { return m_registered_image_frames; }virtual void ask_to_paint_contexts_for_screenshot(u64 preparation_id, Vector<Web::CompositorContextId> const& context_ids) override { async_paint_contexts_for_screenshot(preparation_id, context_ids); }virtual void tell_remote_descendants_prepared_for_screenshot(u64 request_id) override { async_remote_descendants_prepared_for_screenshot(request_id); }@@ -118,14 +116,6 @@ private:Compositing::RegisteredTypefaces m_registered_typefaces;Compositing::RegisteredImageFrames m_registered_image_frames;- // The canvas IDs this WebContent has reserved and not yet named a 2D context with.- struct ReservedCanvasIds {- u64 next { 0 };- u64 end { 0 };-- bool is_used_up() const { return next == end; }- };- ReservedCanvasIds m_reserved_canvas_ids;Function<void(ConnectionFromWebContent&)> m_on_death;// The presentation client end of this WebContent's video presentation channel (connect-only for now).diff --git a/Services/Compositor/Forward.h b/Services/Compositor/Forward.hindex 85f17911e65..58bdd2afbf0 100644--- a/Services/Compositor/Forward.h+++ b/Services/Compositor/Forward.h@@ -15,6 +15,7 @@ class SkiaBackendContext;namespace Compositor {+class CanvasHost;class CanvasSurfaceRegistry;class ConnectionFromClient;class ConnectionFromPresentation;diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex ad76b698c65..11b280a54cb 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -32,6 +32,11 @@ fn main() -> Result<(), Box<dyn Error>> {("EncodedValue", "AK::ReadonlyBytes"),("FfiRasterPainter", "Compositing::RustFFI::FfiRasterPainter"),("CanvasId", "Compositing::CanvasId"),+ ("DisplayListCommandType", "Compositing::DisplayListCommandType"),+ (+ "Web_Bindings_PredefinedColorSpace",+ "Web::Bindings::PredefinedColorSpace",+ ),("ImageFrameResourceId", "Compositing::ImageFrameResourceId"),("PaintingSurface", "Gfx::PaintingSurface"),("PresentableSurface", "Compositor::PresentableSurface"),@@ -56,6 +61,7 @@ fn main() -> Result<(), Box<dyn Error>> {"Compositor/PaintingSurface.h","Compositor/PresentableSurface.h","LibCompositing/DisplayList/ContextRef.h",+ "LibCompositing/DisplayList/DisplayListCommandsGenerated.h","LibCompositing/DisplayList/DisplayListResourceIds.h","LibGfx/Color.h","LibGfx/Point.h",@@ -65,6 +71,7 @@ fn main() -> Result<(), Box<dyn Error>> {"LibIPC/RawAttachment.h","LibCompositing/RustFFI.h","LibIPC/RawMessage.h",+ "LibWebCommon/Bindings/PredefinedColorSpace.h",].map(String::from),);diff --git a/Services/Compositor/Rust/src/canvas_2d_contexts.rs b/Services/Compositor/Rust/src/canvas_2d_contexts.rsnew file mode 100644index 00000000000..e94d6d24899--- /dev/null+++ b/Services/Compositor/Rust/src/canvas_2d_contexts.rs@@ -0,0 +1,136 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::host::WebContentClientId;+use crate::raster_host::RasterHost;+use libcompositing_rust::display_list::canvas_2d::for_each_canvas_2d_command;+use libcompositing_rust::display_list::commands::CanvasId;+use libcompositing_rust::display_list::validate::validate_canvas_2d_tape;+use libcompositing_rust::ipc_types::{Compositing_Canvas2DCommandStreamSegment, Web_Bindings_PredefinedColorSpace};+use libgfx_rust::IntSize;+use std::collections::HashMap;+use std::ops::Range;++const RESERVED_CANVAS_ID_COUNT: u64 = 1 << 20;++#[derive(Default)]+pub struct Canvas2DContexts {+ clients: HashMap<WebContentClientId, ClientContexts>,+}++#[derive(Default)]+struct ClientContexts {+ reserved_ids: Range<u64>,+ drew_since_presenting: HashMap<CanvasId, bool>,+}++pub struct ContextCreation {+ pub canvas_id: CanvasId,+ pub size: IntSize,+ pub alpha: bool,+ pub will_read_frequently: bool,+ pub color_space: Web_Bindings_PredefinedColorSpace,+}++impl Canvas2DContexts {+ pub fn reserve_ids(&mut self, client: WebContentClientId, raster: &RasterHost) -> Result<Range<u64>, &'static str> {+ let contexts = self.clients.entry(client).or_default();+ if !contexts.reserved_ids.is_empty() {+ return Err("WebContent reserved canvas IDs before using up its range");+ }+ let first_id = raster.reserve_canvas_ids(RESERVED_CANVAS_ID_COUNT);+ contexts.reserved_ids = first_id..first_id + RESERVED_CANVAS_ID_COUNT;+ Ok(contexts.reserved_ids.clone())+ }++ pub fn create(+ &mut self,+ client: WebContentClientId,+ raster: &RasterHost,+ creation: ContextCreation,+ ) -> Result<(), &'static str> {+ let contexts = self.clients.entry(client).or_default();+ // NB: WebContent names its contexts with the IDs of its range in order, so each ID names one context only.+ if contexts.reserved_ids.is_empty() || creation.canvas_id.0 != contexts.reserved_ids.start {+ return Err("WebContent named a 2D canvas context with an ID other than the next one it reserved");+ }+ contexts.reserved_ids.start += 1;+ // NB: A context that cannot be created is not a protocol violation: commands recorded for it are dropped.+ if raster.create_canvas_2d_context(+ client.0,+ creation.canvas_id,+ creation.size,+ creation.alpha,+ creation.will_read_frequently,+ creation.color_space,+ ) {+ contexts.drew_since_presenting.insert(creation.canvas_id, false);+ }+ Ok(())+ }++ pub fn destroy(&mut self, client: WebContentClientId, raster: &RasterHost, canvas_id: CanvasId) {+ let Some(contexts) = self.clients.get_mut(&client) else {+ return;+ };+ if contexts.drew_since_presenting.remove(&canvas_id).is_some() {+ raster.destroy_canvas_2d_context(client.0, canvas_id);+ }+ }++ pub fn play_stream(+ &mut self,+ client: WebContentClientId,+ raster: &RasterHost,+ segments: &[Compositing_Canvas2DCommandStreamSegment],+ ) -> Result<(), &'static str> {+ if segments+ .iter()+ .any(|segment| validate_canvas_2d_tape(&segment.tape).is_err())+ {+ return Err("WebContent sent a canvas 2D stream that does not validate");+ }+ let Some(contexts) = self.clients.get_mut(&client) else {+ return Ok(());+ };+ let mut contexts_that_sampled_video_frames = Vec::new();+ for segment in segments {+ // The canvas may have been destroyed while this segment was pending in+ // WebContent, so a missing context is not a protocol violation.+ let Some(drew_since_presenting) = contexts.drew_since_presenting.get_mut(&segment.canvas_id) else {+ continue;+ };+ if !segment.tape.is_empty() {+ let painting = raster.begin_canvas_2d_painting(client.0, segment.canvas_id);+ for_each_canvas_2d_command(&segment.tape, |command_type, payload| {+ painting.play_command(command_type, payload);+ });+ if painting.end_reporting_whether_video_frames_were_sampled_on_the_gpu()+ && !contexts_that_sampled_video_frames.contains(&segment.canvas_id)+ {+ contexts_that_sampled_video_frames.push(segment.canvas_id);+ }+ *drew_since_presenting = true;+ }+ if segment.present+ && *drew_since_presenting+ && raster.try_present_canvas_2d_context(client.0, segment.canvas_id)+ {+ *drew_since_presenting = false;+ }+ }+ // The frames stay held only until WebContent releases them, which follows this stream, so the GPU has to have+ // finished sampling them by then.+ if !contexts_that_sampled_video_frames.is_empty() {+ raster.flush_canvas_2d_contexts(client.0, &contexts_that_sampled_video_frames);+ }+ Ok(())+ }++ pub fn forget_client(&mut self, client: WebContentClientId) {+ self.clients.remove(&client);+ }+}diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex e89973de7ba..3da3f48b866 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -8,8 +8,10 @@//! sender may ask for, and the answer a synchronous one gets.use super::{CompositorCore, ContextOwnerCheckResult};+use crate::canvas_2d_contexts::ContextCreation;use crate::display_list_chunk_stores::chunks_of_list_sent_whole;use crate::host::{PresentationId, WebContentClientId};+use libcompositing_rust::display_list::commands::CanvasId;use libcompositing_rust::display_list::replay::{ReplayFrame, ReplaySelection, replay_display_list};use libcompositing_rust::display_list::storage::DisplayListStorage;use libcompositing_rust::display_list::window::RecordedWindow;@@ -24,13 +26,14 @@ use libcompositing_rust::ipc_types::compositor_presentation_server::messages::{use libcompositing_rust::ipc_types::compositor_web_content_client::messages::DidRasterizeDisplayList;use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,- ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, InvalidateKeyboardScrollState,- InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState, RasterizeDisplayList,+ ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, CreateCanvas2dContext,+ DestroyCanvas2dContext, InvalidateKeyboardScrollState, InvalidateKeyboardScrollStateResponse,+ InvalidateWheelEventListenerState, RasterizeDisplayList, ReserveCanvasIds, ReserveCanvasIdsResponse,RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse, ScrollStateForTesting,ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,- TakeWheelEventFromMainThreadResponse, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree,- WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,+ TakeWheelEventFromMainThreadResponse, UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState,+ UpdateVisualContextTree, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,};use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind,@@ -283,6 +286,46 @@ impl MessagesFromWebContent<'_> {}impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {+ fn reserve_canvas_ids(&mut self, _: ReserveCanvasIds) -> Result<ReserveCanvasIdsResponse, Misbehavior> {+ let reserved_ids = self+ .core+ .canvas_2d_contexts()+ .reserve_ids(self.client_id, self.core.raster())+ .map_err(Misbehavior)?;+ Ok(ReserveCanvasIdsResponse {+ first_canvas_id: CanvasId(reserved_ids.start),+ count: reserved_ids.end - reserved_ids.start,+ })+ }++ fn create_canvas_2d_context(&mut self, message: CreateCanvas2dContext) -> Result<(), Misbehavior> {+ let creation = ContextCreation {+ canvas_id: message.canvas_id,+ size: message.size,+ alpha: message.alpha,+ will_read_frequently: message.will_read_frequently,+ color_space: message.color_space,+ };+ self.core+ .canvas_2d_contexts()+ .create(self.client_id, self.core.raster(), creation)+ .map_err(Misbehavior)+ }++ fn update_canvas_2d_stream(&mut self, message: UpdateCanvas2dStream) -> Result<(), Misbehavior> {+ self.core+ .canvas_2d_contexts()+ .play_stream(self.client_id, self.core.raster(), &message.segments)+ .map_err(Misbehavior)+ }++ fn destroy_canvas_2d_context(&mut self, message: DestroyCanvas2dContext) -> Result<(), Misbehavior> {+ self.core+ .canvas_2d_contexts()+ .destroy(self.client_id, self.core.raster(), message.canvas_id);+ Ok(())+ }+fn update_display_list(&mut self, message: UpdateDisplayList) -> Result<(), Misbehavior> {let started_at = std::time::Instant::now();let SharedDisplayList {diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rsindex 7abfcb8d434..c97264acd3c 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -51,6 +51,7 @@ pub struct CompositorCore {scrollbars_always_shown: bool,display_list_chunk_stores: RefCell<crate::display_list_chunk_stores::DisplayListChunkStores>,remote_layers: RefCell<RemoteLayers>,+ canvas_2d_contexts: RefCell<crate::canvas_2d_contexts::Canvas2DContexts>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -124,6 +125,7 @@ impl CompositorCore {scrollbars_always_shown,display_list_chunk_stores: RefCell::default(),remote_layers: RefCell::default(),+ canvas_2d_contexts: RefCell::default(),}}@@ -146,6 +148,10 @@ impl CompositorCore {&self.raster}+ pub fn canvas_2d_contexts(&self) -> std::cell::RefMut<'_, crate::canvas_2d_contexts::Canvas2DContexts> {+ self.canvas_2d_contexts.borrow_mut()+ }+/// Schedules what a message the core took asked for.pub fn finish_message(&self, now: MonotonicTime) {let _entered = self.enter();diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rsindex c4a96cd0401..1ef7d31bc4c 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -611,6 +611,12 @@ pub extern "C" fn compositor_core_set_ui_overlays();}+#[unsafe(no_mangle)]+pub extern "C" fn compositor_core_forget_web_content_client(core: &CompositorCore, web_content_client_id: u64) {+ core.canvas_2d_contexts()+ .forget_client(WebContentClientId(web_content_client_id));+}+#[unsafe(no_mangle)]pub extern "C" fn compositor_core_check_context_owner(core: &CompositorCore,diff --git a/Services/Compositor/Rust/src/lib.rs b/Services/Compositor/Rust/src/lib.rsindex faa89c303f2..c271a11e9a3 100644--- a/Services/Compositor/Rust/src/lib.rs+++ b/Services/Compositor/Rust/src/lib.rs@@ -17,6 +17,7 @@ mod rust_panic;pub mod async_scroll_update_outbox;pub mod backing_stores;+pub mod canvas_2d_contexts;pub mod context_scene;pub mod context_state;pub mod core;diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex 9547cc15114..0d7bcc30ce3 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -13,13 +13,14 @@ use crate::cpp_object::FfiCppObject;use crate::remote_layers::{RemoteLayerHost, RemoteLayerObject, WindowServerObject};use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;-use libcompositing_rust::display_list::commands::CompositorContextId;+use libcompositing_rust::display_list::commands::{CanvasId, CompositorContextId, DisplayListCommandType};use libcompositing_rust::display_list::storage::{ListChunk, PackedChunkSize, receive_packed_chunks_from_shared_memory,};use libcompositing_rust::host::FfiRasterPainter;use libcompositing_rust::ipc_types::{Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Core_AnonymousBuffer,+ Web_Bindings_PredefinedColorSpace,};use libcompositing_rust::time::MonotonicTime;use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};@@ -164,6 +165,14 @@ pub struct FfiRemoteLayerHostHandle {pub id: u64,}+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiCanvas2DPainter {+ pub player: *mut c_void,+ /// Plays a command, whose payload is lent for the call.+ pub play_command: unsafe extern "C" fn(*mut c_void, DisplayListCommandType, ak::Span<'_, u8>),+}+/// The entry points of the mechanism the core drives, and the object they are called on:/// `Compositor::RustFFI::FfiRasterHost`.#[repr(C)]@@ -291,6 +300,31 @@ pub struct FfiRasterHost {pub begin_staged_rasterization: unsafe extern "C" fn(*mut c_void, u64, u64, *mut FfiRasterPainter) -> bool,/// Ends the painting that began, flushes it into the target, and drops what was staged.pub finish_staged_rasterization: unsafe extern "C" fn(*mut c_void, u64, u64),++ /// Reserves canvas IDs that name nothing else, as many as asked for, and answers the first of them.+ pub reserve_canvas_ids: unsafe extern "C" fn(*mut c_void, u64) -> u64,+ /// Arguments: the client, the canvas, the size of the context, whether it has alpha, whether it will be read+ /// frequently, and the color space of its pixels. Answers whether the context could be made.+ pub create_canvas_2d_context: unsafe extern "C" fn(+ *mut c_void,+ u64,+ CanvasId,+ IntSize,+ bool,+ bool,+ Web_Bindings_PredefinedColorSpace,+ ) -> bool,+ pub destroy_canvas_2d_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId),+ /// Arguments: the client, the canvas of a context it made, and where the painter is written. The painting lasts+ /// until `end_canvas_2d_painting`.+ pub begin_canvas_2d_painting: unsafe extern "C" fn(*mut c_void, u64, CanvasId, *mut FfiCanvas2DPainter),+ /// Answers whether the painting sampled a frame of a video on the GPU.+ pub end_canvas_2d_painting: unsafe extern "C" fn(*mut c_void) -> bool,+ /// Arguments: the client and the canvas. Makes what the context drew the content the canvas shows, and answers+ /// whether it could.+ pub present_canvas_2d_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId) -> bool,+ /// Arguments: the client and canvases of its contexts. Submits the GPU work drawn into their surfaces.+ pub flush_canvas_2d_contexts: unsafe extern "C" fn(*mut c_void, u64, ak::Span<'_, CanvasId>),}/// Sublayers whose content the C++ side resolved, which keep that content busy until they are shown or dropped.@@ -767,6 +801,77 @@ impl RasterHost {unsafe { (self.0.finish_staged_rasterization)(self.host(), client, token) };began}++ pub fn reserve_canvas_ids(&self, count: u64) -> u64 {+ // SAFETY: The host outlives this.+ unsafe { (self.0.reserve_canvas_ids)(self.host(), count) }+ }++ pub fn create_canvas_2d_context(+ &self,+ client: u64,+ canvas_id: CanvasId,+ size: IntSize,+ alpha: bool,+ will_read_frequently: bool,+ color_space: Web_Bindings_PredefinedColorSpace,+ ) -> bool {+ // SAFETY: The host outlives this.+ unsafe {+ (self.0.create_canvas_2d_context)(+ self.host(),+ client,+ canvas_id,+ size,+ alpha,+ will_read_frequently,+ color_space,+ )+ }+ }++ pub fn destroy_canvas_2d_context(&self, client: u64, canvas_id: CanvasId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.destroy_canvas_2d_context)(self.host(), client, canvas_id) };+ }++ pub fn begin_canvas_2d_painting(&self, client: u64, canvas_id: CanvasId) -> Canvas2DPainting<'_> {+ let mut painter = std::mem::MaybeUninit::<FfiCanvas2DPainter>::uninit();+ // SAFETY: The host outlives this, and writes the painter.+ unsafe { (self.0.begin_canvas_2d_painting)(self.host(), client, canvas_id, painter.as_mut_ptr()) };+ Canvas2DPainting {+ raster: self,+ // SAFETY: The host wrote the painter.+ painter: unsafe { painter.assume_init() },+ }+ }++ pub fn try_present_canvas_2d_context(&self, client: u64, canvas_id: CanvasId) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.present_canvas_2d_context)(self.host(), client, canvas_id) }+ }++ pub fn flush_canvas_2d_contexts(&self, client: u64, canvas_ids: &[CanvasId]) {+ // SAFETY: The host outlives this, and reads the IDs during the call.+ unsafe { (self.0.flush_canvas_2d_contexts)(self.host(), client, ak::Span::new(canvas_ids)) };+ }+}++pub struct Canvas2DPainting<'a> {+ raster: &'a RasterHost,+ painter: FfiCanvas2DPainter,+}++impl Canvas2DPainting<'_> {+ pub fn play_command(&self, command_type: DisplayListCommandType, payload: &[u8]) {+ // SAFETY: The painting has not ended, and the player reads the payload during the call.+ unsafe { (self.painter.play_command)(self.painter.player, command_type, ak::Span::new(payload)) };+ }++ pub fn end_reporting_whether_video_frames_were_sampled_on_the_gpu(self) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.raster.0.end_canvas_2d_painting)(self.raster.host()) }+ }}impl RemoteLayerHost for RasterHost {