Truly independent web browser
LibWeb+LibCompositing+Compositor: Send canvas 2D sync messages from Rust
Aliaksandr Kalenik88e1437f44c6
diff --git a/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp b/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cppindex db667fedb96..82e882410ff 100644--- a/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp+++ b/Libraries/LibCompositing/DisplayList/RustFFIAssertions.cpp@@ -5,6 +5,7 @@*/#include <AK/StdLibExtras.h>+#include <LibCompositing/CanvasSize.h>#include <LibCompositing/DisplayList/ContextRef.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>@@ -30,6 +31,8 @@namespace Compositing {+static_assert(Compositing::RustFFI::MAX_CANVAS_AREA == max_canvas_area);+static_assert(sizeof(Compositing::RustFFI::IntPoint) == sizeof(Gfx::IntPoint));static_assert(alignof(Compositing::RustFFI::IntPoint) == alignof(Gfx::IntPoint));static_assert(sizeof(Compositing::RustFFI::FloatPoint) == sizeof(Gfx::FloatPoint));diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rsindex 3c518bc8860..1e09b49f04d 100644--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs@@ -13,13 +13,14 @@ use crate::ipc_types::Web_Bindings_PredefinedColorSpace;use libgfx_rust::{AffineTransform, Color, FloatPoint, FloatRect, IntPoint, IntRect, IntSize, ScalingMode, WindingRule,};+use libipc_rust::wire::{Decode, Encode};/// The number of commands that the shared stream carries to the Compositor at most in one batch. A batch holds the/// image frames of its commands, each a bitmap that an IPC attachment carries, so it has to stay small.pub const MAX_PENDING_COMMANDS: usize = 64;// The values of Gfx::AlphaType.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode)]#[repr(u8)]pub enum AlphaType {Premultiplied,@@ -38,6 +39,12 @@ pub enum ColorSpace {DisplayP3Linear,}+pub const MAX_CANVAS_AREA: i64 = 16384 * 16384;++pub fn is_valid_canvas_2d_size(size: IntSize) -> bool {+ size.width > 0 && size.height > 0 && i64::from(size.width) * i64::from(size.height) <= MAX_CANVAS_AREA+}+impl From<ColorSpace> for Web_Bindings_PredefinedColorSpace {fn from(color_space: ColorSpace) -> Self {match color_space {diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex 067fc9aec50..79149087cb2 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -22,6 +22,7 @@ use std::sync::Arc;pub type Web_CompositorContextId = CompositorContextId;pub type Compositing_CanvasId = CanvasId;pub type Compositing_WebGL_ImageSource = crate::webgl::ImageSource;+pub type Gfx_AlphaType = crate::display_list::canvas_2d_recorder::AlphaType;pub type Web_UniqueNodeID = UniqueNodeId;pub type Web_CSSPixelPoint = CssPixelPoint;pub type Gfx_IntPoint = libgfx_rust::IntPoint;diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rsindex 88c003902bf..f8b9276781f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs@@ -10,28 +10,25 @@use core::cell::{Cell, RefCell};use core::ffi::c_void;use core::ptr::NonNull;+use std::ops::Range;use std::rc::Rc;-use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, ColorSpace, Transport};+use libcompositing_rust::display_list::canvas_2d_recorder::{+ AlphaType, ColorSpace, Transport, is_valid_canvas_2d_size,+};use libcompositing_rust::display_list::commands::{CanvasId, FontResourceId, ImageFrameResourceId};use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{- CreateCanvas2dContext, DestroyCanvas2dContext,+ CreateCanvas2dContext, DestroyCanvas2dContext, ReadBackCanvas2dPixels, ReserveCanvasIds,};use libgfx_rust::font::FontHandle;use libgfx_rust::image_frame::ImageFrameHandle;use libgfx_rust::{IntRect, IntSize};-use crate::compositor_connection::CompositorConnection;+use crate::compositor_connection::{CompositorConnection, SharedBuffer};use super::stream::{Canvas2DStream, flush, shared_stream};unsafe extern "C" {- fn web_canvas_2d_connection_reserve_context_id(- connection: *mut c_void,- width: i32,- height: i32,- out_canvas_id: *mut u64,- ) -> bool;fn web_canvas_2d_connection_post_stream_batch_fonts_and_image_frames(connection: *mut c_void,fonts: *const *const c_void,@@ -39,30 +36,46 @@ unsafe extern "C" {image_frames: *const *const c_void,image_frame_count: usize,) -> bool;- fn web_canvas_2d_connection_read_back_pixels(- connection: *mut c_void,- canvas_id: u64,- x: i32,- y: i32,- width: i32,- height: i32,- alpha_type: AlphaType,- color_space: ColorSpace,- ) -> *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);}+struct ReservedCanvasIds {+ connection_serial: u64,+ ids: Range<u64>,+}++thread_local! {+ static RESERVED_CANVAS_IDS: RefCell<Option<ReservedCanvasIds>> = const { RefCell::new(None) };+}+// SAFETY (of every call below): The connection is live, and the fonts and image frames are lent for the call, in which// C++ takes references of its own.impl CompositorConnection {fn reserve_context_id(self, size: IntSize) -> Option<CanvasId> {- let mut canvas_id = 0;- unsafe {- web_canvas_2d_connection_reserve_context_id(self.as_ptr(), size.width, size.height, &raw mut canvas_id)+ // NB: The Compositor refuses the same sizes, so a context it is asked to create always exists afterwards.+ if !is_valid_canvas_2d_size(size) {+ return None;+ }+ let connection_serial = self.serial();+ let reserved_id = RESERVED_CANVAS_IDS.with_borrow_mut(|reserved| {+ reserved+ .as_mut()+ .filter(|reserved| reserved.connection_serial == connection_serial)+ .and_then(|reserved| reserved.ids.next())+ });+ if let Some(canvas_id) = reserved_id {+ return Some(CanvasId(canvas_id));}- .then_some(CanvasId(canvas_id))+ // OPTIMIZATION: Creating a context is asynchronous, under an ID from a range reserved up front. A synchronous+ // reply would wait for the Compositor to replay every canvas command queued before it.+ let response = self.send_sync(ReserveCanvasIds)?;+ let first_canvas_id = response.first_canvas_id.0;+ let mut ids = first_canvas_id..first_canvas_id.checked_add(response.count)?;+ let canvas_id = ids.next();+ RESERVED_CANVAS_IDS.set(Some(ReservedCanvasIds { connection_serial, ids }));+ canvas_id.map(CanvasId)}pub(crate) fn post_stream_batch_fonts_and_image_frames(@@ -90,20 +103,23 @@ impl CompositorConnection {alpha_type: AlphaType,color_space: ColorSpace,) -> Option<ImageFrameHandle> {- let frame = unsafe {- web_canvas_2d_connection_read_back_pixels(- self.as_ptr(),- canvas_id.0,- rect.x,- rect.y,- rect.width,- rect.height,- alpha_type,- color_space,- )- };- // SAFETY: LibWeb hands over a frame that it allocated with new, or null.- (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })+ let size = usize::try_from(rect.width)+ .ok()?+ .checked_mul(usize::try_from(rect.height).ok()?)?+ .checked_mul(4)?;+ let pixels = SharedBuffer::create(size)?;+ let response = self.send_sync(ReadBackCanvas2dPixels {+ canvas_id,+ rect,+ alpha_type,+ color_space: color_space.into(),+ pixels: pixels.for_message(),+ })?;+ let IntSize { width, height } = response.size;+ if width <= 0 || height <= 0 {+ return None;+ }+ pixels.into_image_frame(width, height, alpha_type, color_space)}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rs b/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rsindex 98cb084735f..e1158c72a2e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rs@@ -8,6 +8,7 @@ use core::ffi::c_void;use core::mem::MaybeUninit;use core::ptr::NonNull;+use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, ColorSpace};use libcompositing_rust::ipc_types::Core_AnonymousBuffer;use libgfx_rust::image_frame::ImageFrameHandle;use libipc_rust::cpp_connection::{CppConnection, FfiConnection, FfiThreadSafeMessagePoster, ThreadSafeMessagePoster};@@ -27,7 +28,14 @@ unsafe extern "C" {fn web_compositor_create_shared_buffer(size: usize, out: &mut FfiSharedBuffer) -> bool;fn web_compositor_shared_buffer_release(owner: *mut c_void);fn web_compositor_shared_buffer_clone_descriptor(owner: *mut c_void) -> i32;- fn web_compositor_shared_buffer_image_frame(owner: *mut c_void, width: i32, height: i32) -> *mut c_void;+ fn web_compositor_shared_buffer_image_frame(+ owner: *mut c_void,+ width: i32,+ height: i32,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> *mut c_void;+ fn web_compositor_connection_serial(connection: *mut c_void) -> u64;}#[derive(Clone, Copy)]@@ -47,6 +55,10 @@ impl CompositorConnection {self.0.as_ptr()}+ pub(crate) fn serial(self) -> u64 {+ unsafe { web_compositor_connection_serial(self.0.as_ptr()) }+ }+/// # Safety////// The caller owns a reference to the connection, which it gives up.@@ -156,10 +168,18 @@ impl SharedBuffer {}}- pub(crate) fn into_image_frame(self, width: i32, height: i32) -> Option<ImageFrameHandle> {+ pub(crate) fn into_image_frame(+ self,+ width: i32,+ height: i32,+ alpha_type: AlphaType,+ color_space: ColorSpace,+ ) -> Option<ImageFrameHandle> {// SAFETY: The value owns the memory, which the frame shares, and LibWeb hands over a frame it allocated with new,// or null.- let frame = unsafe { web_compositor_shared_buffer_image_frame(self.owner.as_ptr(), width, height) };+ let frame = unsafe {+ web_compositor_shared_buffer_image_frame(self.owner.as_ptr(), width, height, alpha_type, color_space)+ };(!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rsindex f6f01905b46..c9f3d50e1fa 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs@@ -9,6 +9,7 @@use core::cell::Cell;+use libcompositing_rust::display_list::canvas_2d_recorder::{AlphaType, ColorSpace};use libcompositing_rust::display_list::commands::{CanvasId, ImageFrameResourceId, VideoSinkHandle};use libcompositing_rust::ipc_types::Compositing_WebGL_WebGLVersion;use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{@@ -329,6 +330,6 @@ impl Transport for RemoteContext {if width <= 0 || height <= 0 {return None;}- pixels.into_image_frame(width, height)+ pixels.into_image_frame(width, height, AlphaType::Premultiplied, ColorSpace::Srgb)}}diff --git a/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp b/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cppindex 786d8ccc685..baf52a545b1 100644--- a/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp+++ b/Libraries/LibWeb/Compositor/Canvas2DStreamFFI.cpp@@ -5,15 +5,12 @@*/#include <AK/Span.h>-#include <LibCompositing/CanvasColorSpace.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Video/VideoFrameHold.h>-#include <LibGfx/Bitmap.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Font/Font.h>#include <LibIPC/ThreadSafeMessagePoster.h>#include <LibWeb/Compositor/CompositorConnection.h>-#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>namespace Web::Compositor {@@ -28,10 +25,8 @@ extern "C" {void web_canvas_2d_connection_unref(CompositorConnection*);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);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*);@@ -51,15 +46,6 @@ bool web_canvas_2d_connection_poster(CompositorConnection* connection, IPC::FfiTreturn 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;-}-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 });@@ -70,21 +56,6 @@ void web_canvas_2d_connection_did_fail_to_post(CompositorConnection* connection)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 = 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;- auto frame = Gfx::DecodedImageFrame::create(*shareable_bitmap.bitmap(), gfx_color_space);- if (frame.is_error())- return nullptr;- return new Gfx::DecodedImageFrame { frame.release_value() };-}-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 b8c50ec492f..ea1fd139d81 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -10,7 +10,7 @@#include <AK/Debug.h>#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>-#include <LibCompositing/CanvasSize.h>+#include <LibCompositing/CanvasColorSpace.h>#include <LibCore/AnonymousBuffer.h>#include <LibCore/ElapsedTimer.h>#include <LibCore/Environment.h>@@ -25,6 +25,7 @@#include <LibMediaClient/Client.h>#include <LibWeb/Compositor/RenderClock.h>#include <LibWeb/DOM/Document.h>+#include <LibWeb/HTML/Canvas/PredefinedColorSpace.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/HTMLCanvasElement.h>#include <LibWeb/HTML/LocalNavigable.h>@@ -241,9 +242,12 @@ static bool post_fonts_and_register_image_frames(IPC::ThreadSafeMessagePoster& preturn poster.try_post(encoded_message);}+static Atomic<u64> s_next_connection_serial { 1 };+CompositorConnection::CompositorConnection(NonnullOwnPtr<IPC::Transport> transport): IPC::ConnectionToServer<CompositorWebContentClientEndpoint, CompositorWebContentServerEndpoint>(*this, move(transport)), m_poster(IPC::ThreadSafeMessagePoster::create(this->transport()))+ , m_serial(s_next_connection_serial++){start_registering_resources_with_compositor(*m_poster);}@@ -364,33 +368,6 @@ RefPtr<IPC::ThreadSafeMessagePoster> CompositorConnection::poster_while_compositreturn m_poster;}-Optional<Compositing::CanvasId> CompositorConnection::reserve_canvas_2d_context_id(Gfx::IntSize size)-{- if (!can_send_message_to_compositor())- return {};-- // NB: The Compositor refuses the same sizes, so a context it is asked to create always exists afterwards.- if (!Compositing::is_valid_canvas_2d_size(size))- return {};-- // OPTIMIZATION: Creating a context is asynchronous, under an ID from a range reserved up front. A synchronous- // reply would wait for the Compositor to replay every canvas command queued before it.- if (m_reserved_canvas_ids_remaining == 0) {- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::ReserveCanvasIds>();- if (!response) {- did_lose_compositor();- return {};- }- m_next_reserved_canvas_id = response->first_canvas_id().value();- m_reserved_canvas_ids_remaining = response->count();- if (m_reserved_canvas_ids_remaining == 0)- return {};- }- auto canvas_id = Compositing::CanvasId { m_next_reserved_canvas_id++ };- --m_reserved_canvas_ids_remaining;- return canvas_id;-}-bool CompositorConnection::post_canvas_2d_stream_batch_fonts_and_image_frames(ReadonlySpan<Gfx::Font const*> fonts, ReadonlySpan<Gfx::DecodedImageFrame const*> image_frames){if (!register_typefaces_of_fonts_with_compositor(*m_poster, fonts) || !register_image_frames_with_compositor(*m_poster, image_frames)) {@@ -419,19 +396,6 @@ bool CompositorConnection::register_image_frames(ReadonlySpan<Gfx::DecodedImageFreturn register_image_frames_with_compositor(*m_poster, image_frames);}-Gfx::ShareableBitmap CompositorConnection::get_canvas_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space)-{- if (!can_send_message_to_compositor())- return {};-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::GetCanvasPixels>(canvas_id, rect, alpha_type, color_space);- if (!response) {- did_lose_compositor();- return {};- }- return response->take_pixels();-}-Optional<Web::Compositor::PlaceholderCanvasLink> CompositorConnection::allocate_placeholder_canvas(){if (!can_send_message_to_compositor())@@ -918,7 +882,8 @@ extern "C" WEB_API bool web_compositor_post_fonts_and_image_frames(void* poster,extern "C" WEB_API bool web_compositor_create_shared_buffer(size_t size, Web::Compositor::FfiSharedBuffer* out);extern "C" WEB_API void web_compositor_shared_buffer_release(void* owner);extern "C" WEB_API int web_compositor_shared_buffer_clone_descriptor(void* owner);-extern "C" WEB_API Gfx::DecodedImageFrame* web_compositor_shared_buffer_image_frame(void* owner, i32 width, i32 height);+extern "C" WEB_API Gfx::DecodedImageFrame* web_compositor_shared_buffer_image_frame(void* owner, i32 width, i32 height, u8 alpha_type, u8 color_space);+extern "C" WEB_API u64 web_compositor_connection_serial(Web::Compositor::CompositorConnection const*);extern "C" WEB_API bool web_compositor_connection_for_sync_requests(Web::Compositor::CompositorConnection*, IPC::FfiConnection* out_connection);extern "C" WEB_API bool web_compositor_connection_register_image_frames(Web::Compositor::CompositorConnection*, void const* const* image_frames, size_t image_frame_count);extern "C" WEB_API bool web_compositor_post_screenshot_request(void* poster, void* request);@@ -966,15 +931,24 @@ extern "C" WEB_API int web_compositor_shared_buffer_clone_descriptor(void* ownerreturn descriptor.value().take_fd();}-extern "C" WEB_API Gfx::DecodedImageFrame* web_compositor_shared_buffer_image_frame(void* owner, i32 width, i32 height)+// NB: A color space is the underlying value of a Bindings::PredefinedColorSpace.+extern "C" WEB_API Gfx::DecodedImageFrame* web_compositor_shared_buffer_image_frame(void* owner, i32 width, i32 height, u8 alpha_type, u8 color_space){+ VERIFY(Gfx::is_valid_alpha_type(alpha_type));auto& buffer = static_cast<Web::Compositor::SharedBufferForRust*>(owner)->buffer;- auto frame = Gfx::DecodedImageFrame::create_over_shared_memory(buffer, 0, { width, height }, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied);+ auto format = static_cast<Gfx::AlphaType>(alpha_type) == Gfx::AlphaType::Unpremultiplied ? Gfx::BitmapFormat::RGBA8888 : Gfx::BitmapFormat::BGRA8888;+ auto gfx_color_space = Compositing::gfx_color_space_for(Web::HTML::predefined_color_space_from_underlying(color_space));+ auto frame = Gfx::DecodedImageFrame::create_over_shared_memory(buffer, 0, { width, height }, format, static_cast<Gfx::AlphaType>(alpha_type), move(gfx_color_space));if (frame.is_error())return nullptr;return new Gfx::DecodedImageFrame { frame.release_value() };}+extern "C" WEB_API u64 web_compositor_connection_serial(Web::Compositor::CompositorConnection const* connection)+{+ return connection->serial();+}+extern "C" WEB_API bool web_compositor_connection_for_sync_requests(Web::Compositor::CompositorConnection* connection, IPC::FfiConnection* out_connection){if (!connection->can_send_message_to_compositor())diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex c975911041d..51ed94fb3b6 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -71,12 +71,11 @@ public:void release_video_frame_hold(Media::VideoSinkHandle, u64 generation);void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick);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();bool register_image_frames(ReadonlySpan<Gfx::DecodedImageFrame const*>);bool can_send_message_to_compositor() const;- Gfx::ShareableBitmap get_canvas_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType = Gfx::AlphaType::Premultiplied, Gfx::ColorSpace const& = {});+ u64 serial() const { return m_serial; }Optional<Web::Compositor::PlaceholderCanvasLink> allocate_placeholder_canvas();void release_placeholder_canvas(Compositing::CanvasId);void commit_placeholder_canvas(Web::Compositor::PlaceholderCanvasLink, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean);@@ -148,8 +147,6 @@ private:// Posts to the transport from any thread: the Paint thread presents through it, and Rust posts what it encodes.NonnullRefPtr<IPC::ThreadSafeMessagePoster> m_poster;- u64 m_next_reserved_canvas_id { 0 };- u64 m_reserved_canvas_ids_remaining { 0 };HashMap<Compositing::ScreenshotRequestId, PendingScreenshot> m_screenshots;HashMap<u64, Function<void()>> m_remote_descendant_preparations;@@ -158,6 +155,7 @@ private:HashMap<Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates> m_pending_async_scroll_updates;u64 m_next_screenshot_request_id { 1 };Atomic<u64> m_next_rasterization_token { 1 };+ u64 m_serial { 0 };bool m_has_lost_compositor { false };// The media server whose presentation channel the Compositor holds; a replacement server needs a new channel.Optional<u64> m_video_presentation_channel_media_client_generation;diff --git a/Services/Compositor/CanvasHost.cpp b/Services/Compositor/CanvasHost.cppindex b5848771c32..b9d9e257fb9 100644--- a/Services/Compositor/CanvasHost.cpp+++ b/Services/Compositor/CanvasHost.cpp@@ -305,20 +305,7 @@ Optional<Gfx::IntSize> CanvasHost::read_back_webgl_drawing_buffer(Compositing::Cauto surface = from_presented_frame ? gl_context.presented_surface() : gl_context.drawing_buffer_surface();if (!surface)return {};-- auto clipped_rect = rect.intersected(surface->rect());- if (clipped_rect.is_empty())- return {};- auto pitch = static_cast<size_t>(clipped_rect.width()) * sizeof(u32);- if (pitch * static_cast<size_t>(clipped_rect.height()) > pixels.size())- return {};-- auto bitmap = Gfx::Bitmap::create_wrapper(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, clipped_rect.size(), pitch, pixels.data());- if (bitmap.is_error())- return {};- surface->flush();- surface->read_into_bitmap(*bitmap.value(), clipped_rect.location());- return clipped_rect.size();+ return read_back_surface_into(*surface, rect, Gfx::AlphaType::Premultiplied, {}, pixels);}RefPtr<Media::VideoFrame> CanvasHost::held_video_frame(Media::VideoSinkHandle handle, u64 generation) const@@ -386,6 +373,24 @@ Gfx::ShareableBitmap CanvasHost::read_back_surface(Gfx::PaintingSurface& surfacereturn Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };}+Optional<Gfx::IntSize> CanvasHost::read_back_surface_into(Gfx::PaintingSurface& surface, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space, Bytes pixels)+{+ auto clipped_rect = rect.intersected(surface.rect());+ if (clipped_rect.is_empty())+ return {};+ auto pitch = static_cast<size_t>(clipped_rect.width()) * sizeof(u32);+ if (pitch * static_cast<size_t>(clipped_rect.height()) > pixels.size())+ return {};++ auto format = alpha_type == Gfx::AlphaType::Unpremultiplied ? Gfx::BitmapFormat::RGBA8888 : Gfx::BitmapFormat::BGRA8888;+ auto bitmap = Gfx::Bitmap::create_wrapper(format, alpha_type, clipped_rect.size(), pitch, pixels.data());+ if (bitmap.is_error())+ return {};+ surface.flush();+ surface.read_into_bitmap(*bitmap.value(), clipped_rect.location(), color_space);+ return clipped_rect.size();+}+RefPtr<Gfx::PaintingSurface> CanvasHost::presented_surface(Compositing::CanvasId canvas_id){auto* context = this->context(canvas_id);@@ -401,19 +406,15 @@ RefPtr<Gfx::PaintingSurface> CanvasHost::presented_surface(Compositing::CanvasId});}-Gfx::ShareableBitmap CanvasHost::read_back_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space)+Optional<Gfx::IntSize> CanvasHost::read_back_canvas_2d_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space, Bytes pixels){auto* context = this->context(canvas_id);if (!context)return {};-- return context->visit(- [rect, alpha_type, &color_space](Canvas2DContext& canvas_context) {- return read_back_surface(canvas_context.command_player->surface(), rect, alpha_type, color_space);- },- [](WebGLContext&) -> Gfx::ShareableBitmap {- return {};- });+ auto* canvas_context = context->get_pointer<Canvas2DContext>();+ if (!canvas_context)+ return {};+ return read_back_surface_into(canvas_context->command_player->surface(), rect, alpha_type, color_space, pixels);}}diff --git a/Services/Compositor/CanvasHost.h b/Services/Compositor/CanvasHost.hindex 6bb8ce2d485..54d29a60867 100644--- a/Services/Compositor/CanvasHost.h+++ b/Services/Compositor/CanvasHost.h@@ -92,12 +92,13 @@ public:RefPtr<Media::VideoFrame> held_video_frame(Media::VideoSinkHandle, u64 generation) const;WebGLImageConversion convert_image_for_webgl_upload(WebGLImageSource, Compositing::RegisteredImageFrames const&, Gfx::ExportFormat, int export_flags, Optional<Gfx::IntSize> target_size, Gfx::BitmapExportResult& out_pixels) const;// The pixels come back in the color space.- Gfx::ShareableBitmap read_back_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType, Gfx::ColorSpace const& = {});+ Optional<Gfx::IntSize> read_back_canvas_2d_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType, Gfx::ColorSpace const&, Bytes pixels);RefPtr<Gfx::PaintingSurface> presented_surface(Compositing::CanvasId);void forget_video_sink(Media::VideoSinkHandle);static Gfx::ShareableBitmap read_back_surface(Gfx::PaintingSurface&, Gfx::IntRect, Gfx::AlphaType = Gfx::AlphaType::Premultiplied, Gfx::ColorSpace const& = {});+ static Optional<Gfx::IntSize> read_back_surface_into(Gfx::PaintingSurface&, Gfx::IntRect, Gfx::AlphaType, Gfx::ColorSpace const&, Bytes pixels);private:struct Canvas2DContext {diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex 59e4552d836..3ea962e05b1 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -1582,6 +1582,13 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).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); },+ .read_back_canvas_2d_pixels = [](void* host, u64 client, Compositing::CanvasId canvas_id, Gfx::IntRect rect, u8 alpha_type, Web::Bindings::PredefinedColorSpace color_space, u8* pixels, size_t pixels_size, Gfx::IntSize* size) {+ VERIFY(Gfx::is_valid_alpha_type(alpha_type));+ auto read_size = state_of(host).canvas_host_of(WebContentClientId { client }).read_back_canvas_2d_pixels(canvas_id, rect, static_cast<Gfx::AlphaType>(alpha_type), Compositing::gfx_color_space_for(color_space), { pixels, pixels_size });+ if (!read_size.has_value())+ return false;+ *size = *read_size;+ return true; },.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); },diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex 44e33afa5ac..d6048d7f21f 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -57,7 +57,7 @@ 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.- [RustReceiver] reserve_canvas_ids() => (Compositing::CanvasId first_canvas_id, u64 count)+ [RustReceiver, RustSender] 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.[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@@ -66,7 +66,8 @@ endpoint CompositorWebContentServer[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)+ // Unpremultiplied pixels are RGBA8888 and premultiplied ones BGRA8888, as rows of the size answered.+ [RustReceiver, RustSender] read_back_canvas_2d_pixels(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Web::Bindings::PredefinedColorSpace color_space, Core::AnonymousBuffer pixels) => (Gfx::IntSize size)allocate_placeholder_canvas() => (Compositing::CanvasId canvas_id, u64 secret)release_placeholder_canvas(Compositing::CanvasId canvas_id) =|diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex c01492ab407..75c0ef12924 100644--- a/Services/Compositor/ConnectionFromWebContent.cpp+++ b/Services/Compositor/ConnectionFromWebContent.cpp@@ -301,40 +301,12 @@ void ConnectionFromWebContent::describe_display_list_fonts(Web::CompositorContexdid_misbehave("WebContent described a font of a typeface it has not registered");}-// 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-static bool is_predefined_canvas_color_space(Gfx::ColorSpace const& color_space)-{- return color_space.data().visit(- [](Empty) { return true; },- [](Gfx::ColorSpace::CICP const& cicp) {- auto has_valid_primaries = cicp.color_primaries == Media::ColorPrimaries::BT709 || cicp.color_primaries == Media::ColorPrimaries::SMPTE432;- auto has_valid_transfer_characteristics = cicp.transfer_characteristics == Media::TransferCharacteristics::SRGB || cicp.transfer_characteristics == Media::TransferCharacteristics::Linear;- return has_valid_primaries && has_valid_transfer_characteristics;- },- [](NonnullRefPtr<Gfx::ColorSpace::ICCProfile const> const&) { return false; });-}-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");}-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))) {- did_misbehave("WebContent asked for canvas pixels with an invalid alpha type");- return Gfx::ShareableBitmap {};- }- if (!is_predefined_canvas_color_space(color_space)) {- did_misbehave("WebContent asked for canvas pixels in a color space that is not a predefined one");- return Gfx::ShareableBitmap {};- }- return m_canvas_host.read_back_pixels(canvas_id, rect, alpha_type, color_space);-}-void ConnectionFromWebContent::stage_rasterization(u64 token, Vector<Compositing::DisplayListFontDescription> fonts, Vector<Compositing::ImageFrameResourceId> image_frame_ids, Gfx::ShareableBitmap target_bitmap){if (!m_compositor_state->stage_rasterization(*this, token, fonts, image_frame_ids, m_registered_typefaces, move(target_bitmap)))diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex d762a0f760c..b412f207c9a 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -64,7 +64,6 @@ private:virtual void unregister_image_frame(Compositing::ImageFrameResourceId) override;virtual void describe_display_list_fonts(Web::CompositorContextId, Vector<Compositing::DisplayListFontDescription>) override;virtual void describe_canvas_2d_fonts(Vector<Compositing::DisplayListFontDescription>) 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;virtual void commit_placeholder_canvas(Compositing::CanvasId, u64 secret, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean) override;diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex fc4ae771525..4005d14e4a9 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -31,9 +31,9 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, CreateCanvas2dContext,CreateWebglContext, CreateWebglContextResponse, DestroyCanvas2dContext, DestroyWebglContext,InvalidateKeyboardScrollState, InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState,- RasterizeDisplayList, RasterizeDisplayListResponse, ReserveCanvasIds, ReserveCanvasIdsResponse,- RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse, ScrollStateForTesting,- ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,+ RasterizeDisplayList, RasterizeDisplayListResponse, ReadBackCanvas2dPixels, ReadBackCanvas2dPixelsResponse,+ ReserveCanvasIds, ReserveCanvasIdsResponse, RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse,+ ScrollStateForTesting, ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,TakeWheelEventFromMainThreadResponse, UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState,UpdateVisualContextTree, WebglClearDrawingBuffer, WebglCommands, WebglCommandsFromSharedBuffer,@@ -504,6 +504,26 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {Ok(WebglReadBufferSubDataResponse { success })}+ fn read_back_canvas_2d_pixels(+ &mut self,+ message: ReadBackCanvas2dPixels,+ ) -> Result<ReadBackCanvas2dPixelsResponse, Misbehavior> {+ let pixels = self.map_shared_memory(message.pixels)?;+ let size = pixels.and_then(|pixels| {+ self.core.raster().read_back_canvas_2d_pixels(+ self.client_id.0,+ message.canvas_id,+ message.rect,+ message.alpha_type,+ message.color_space,+ &pixels,+ )+ });+ Ok(ReadBackCanvas2dPixelsResponse {+ size: size.unwrap_or_default(),+ })+ }+fn webgl_read_back_drawing_buffer(&mut self,message: WebglReadBackDrawingBuffer,diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex f4388c8bb88..e114ce1432b 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -24,7 +24,7 @@ use libcompositing_rust::display_list::storage::{};use libcompositing_rust::host::FfiRasterPainter;use libcompositing_rust::ipc_types::{- Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Core_AnonymousBuffer,+ Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Core_AnonymousBuffer, Gfx_AlphaType,Web_Bindings_PredefinedColorSpace,};use libcompositing_rust::time::MonotonicTime;@@ -321,6 +321,19 @@ pub struct FfiRasterHost {Web_Bindings_PredefinedColorSpace,) -> bool,pub destroy_canvas_2d_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId),+ /// Arguments: the client, the canvas, the rect, the alpha type and the color space of the pixels, where they go,+ /// how many bytes fit there, and where the size of what was read is written.+ pub read_back_canvas_2d_pixels: unsafe extern "C" fn(+ *mut c_void,+ u64,+ CanvasId,+ IntRect,+ u8,+ Web_Bindings_PredefinedColorSpace,+ *mut u8,+ usize,+ *mut IntSize,+ ) -> bool,/// 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),@@ -952,6 +965,33 @@ impl RasterHost {unsafe { (self.0.destroy_canvas_2d_context)(self.host(), client, canvas_id) };}+ pub fn read_back_canvas_2d_pixels(+ &self,+ client: u64,+ canvas_id: CanvasId,+ rect: IntRect,+ alpha_type: Gfx_AlphaType,+ color_space: Web_Bindings_PredefinedColorSpace,+ pixels: &SharedMemory,+ ) -> Option<IntSize> {+ let mut size = IntSize::default();+ // SAFETY: The host outlives this, the mapping holds as many writable bytes, and the host writes the size.+ unsafe {+ (self.0.read_back_canvas_2d_pixels)(+ self.host(),+ client,+ canvas_id,+ rect,+ alpha_type as u8,+ color_space,+ pixels.as_ptr(),+ pixels.len(),+ &raw mut size,+ )+ }+ .then_some(size)+ }+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.diff --git a/Tests/LibWebView/test-webdriver-compositor-reconnect.py b/Tests/LibWebView/test-webdriver-compositor-reconnect.pyindex 8b28d22da69..e17ed923ed1 100755--- a/Tests/LibWebView/test-webdriver-compositor-reconnect.py+++ b/Tests/LibWebView/test-webdriver-compositor-reconnect.py@@ -7,7 +7,8 @@# When the Compositor dies, the browser connects a new one, and the page's next rendering update# has to bring the new Compositor up to date: its first frame carries the whole display list again,# not only what changed since the old Compositor's last frame. Every WebGL context of the page, of a-# canvas element or of an OffscreenCanvas, is lost with the Compositor.+# canvas element or of an OffscreenCanvas, is lost with the Compositor, and a 2D canvas made after+# the reconnect draws in the new one.import argparseimport base64@@ -36,6 +37,12 @@ function createWebGLContextThatRecordsItsEvents(name, canvas) {});return canvas.getContext("webgl") !== null;}+function pixelOfNew2DCanvas() {+ const context = document.createElement("canvas").getContext("2d");+ context.fillStyle = "rgb(0, 128, 0)";+ context.fillRect(0, 0, 1, 1);+ return Array.from(context.getImageData(0, 0, 1, 1).data).join(",");+}function createWebGLContexts() {window.offscreenCanvas = new OffscreenCanvas(16, 16);return createWebGLContextThatRecordsItsEvents("canvas element", document.getElementById("canvas"))@@ -98,6 +105,7 @@ def run_test(webdriver_binary):assert status == 200, bodywebdriver_helpers.wait_for_compositor(port, session)assert execute(port, session, "return createWebGLContexts();"), "WebGL contexts could not be created"+ assert execute(port, session, "return pixelOfNew2DCanvas();") == "0,128,0,255"first = take_screenshot(port, session)compositors = descendants_named(webdriver.pid, "Compositor")@@ -117,6 +125,7 @@ def run_test(webdriver_binary):assert take_screenshot(port, session) == firstexecute(port, session, "document.getElementById('box').style.background = 'green';")assert take_screenshot(port, session) != first+ assert execute(port, session, "return pixelOfNew2DCanvas();") == "0,128,0,255"expected_webgl_context_events = ["OffscreenCanvas lost", "canvas element lost"]deadline = time.monotonic() + webdriver_helpers.EVENT_TIMEOUT_SECONDS