Truly independent web browser
LibWeb+LibCompositing+Compositor: Exchange WebGL messages in Rust
Aliaksandr Kalenikcc29246ad188
diff --git a/Libraries/LibCompositing/Rust/src/ipc_types.rs b/Libraries/LibCompositing/Rust/src/ipc_types.rsindex 8962313b9e7..067fc9aec50 100644--- a/Libraries/LibCompositing/Rust/src/ipc_types.rs+++ b/Libraries/LibCompositing/Rust/src/ipc_types.rs@@ -21,6 +21,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 Web_UniqueNodeID = UniqueNodeId;pub type Web_CSSPixelPoint = CssPixelPoint;pub type Gfx_IntPoint = libgfx_rust::IntPoint;diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.cpp b/Libraries/LibCompositing/Video/VideoFrameHold.cppindex f5c52340121..fbbbe1597ca 100644--- a/Libraries/LibCompositing/Video/VideoFrameHold.cpp+++ b/Libraries/LibCompositing/Video/VideoFrameHold.cpp@@ -5,8 +5,6 @@*/#include <LibCompositing/Video/VideoFrameHold.h>-#include <LibIPC/Decoder.h>-#include <LibIPC/Encoder.h>namespace Compositing {@@ -42,25 +40,3 @@ VideoFrameHold::~VideoFrameHold()}}--namespace IPC {--template<>-ErrorOr<void> encode(Encoder& encoder, Compositing::CapturedVideoFrame const& frame)-{- TRY(encoder.encode(frame.sink_handle));- TRY(encoder.encode(frame.generation));- return {};-}--template<>-ErrorOr<Compositing::CapturedVideoFrame> decode(Decoder& decoder)-{- return Compositing::CapturedVideoFrame {- .sink_handle = TRY(decoder.decode<Media::VideoSinkHandle>()),- .generation = TRY(decoder.decode<u64>()),- .hold = nullptr,- };-}--}diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.h b/Libraries/LibCompositing/Video/VideoFrameHold.hindex 9312d6caaea..7a2fdf84a8a 100644--- a/Libraries/LibCompositing/Video/VideoFrameHold.h+++ b/Libraries/LibCompositing/Video/VideoFrameHold.h@@ -12,7 +12,6 @@#include <AK/Weakable.h>#include <LibCompositing/Export.h>#include <LibCompositing/Video/VideoFramePresentationPage.h>-#include <LibIPC/Forward.h>#include <LibMedia/VideoSinkHandle.h>namespace Compositing {@@ -49,13 +48,3 @@ struct COMPOSITING_API CapturedVideoFrame {};}--namespace IPC {--template<>-COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::CapturedVideoFrame const&);--template<>-COMPOSITING_API ErrorOr<Compositing::CapturedVideoFrame> decode(Decoder&);--}diff --git a/Libraries/LibCompositing/WebGL/ImageSourceFrame.h b/Libraries/LibCompositing/WebGL/ImageSourceFrame.hdeleted file mode 100644index c2e136bfc38..00000000000--- a/Libraries/LibCompositing/WebGL/ImageSourceFrame.h+++ /dev/null@@ -1,17 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Variant.h>-#include <LibCompositing/Video/VideoFrameHold.h>-#include <LibGfx/DecodedImageFrame.h>--namespace Compositing::WebGL {--using ImageSourceFrame = Variant<Gfx::DecodedImageFrame, CapturedVideoFrame>;--}diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rsindex a06590559a3..88c003902bf 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/host.rs@@ -9,7 +9,6 @@use core::cell::{Cell, RefCell};use core::ffi::c_void;-use core::mem::MaybeUninit;use core::ptr::NonNull;use std::rc::Rc;@@ -21,14 +20,12 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::{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 crate::compositor_connection::CompositorConnection;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_poster(connection: *mut c_void, out_poster: *mut FfiThreadSafeMessagePoster) -> bool;fn web_canvas_2d_connection_reserve_context_id(connection: *mut c_void,width: i32,@@ -42,7 +39,6 @@ unsafe extern "C" {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,@@ -58,42 +54,13 @@ unsafe extern "C" {fn web_canvas_2d_video_frame_hold_note_sent_to_compositor(hold: *mut c_void);}-#[derive(Clone, Copy)]-pub(crate) struct CompositorConnection(NonNull<c_void>);-// 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 {- /// # Safety- ///- /// `connection` must be a CompositorConnection that outlives the value.- pub(crate) unsafe fn lent(connection: NonNull<c_void>) -> Self {- Self(connection)- }-- 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,- 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_reserve_context_id(self.0.as_ptr(), size.width, size.height, &raw mut canvas_id)+ web_canvas_2d_connection_reserve_context_id(self.as_ptr(), size.width, size.height, &raw mut canvas_id)}.then_some(CanvasId(canvas_id))}@@ -107,7 +74,7 @@ impl CompositorConnection {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(),+ self.as_ptr(),fonts.as_ptr(),fonts.len(),image_frames.as_ptr(),@@ -125,7 +92,7 @@ impl CompositorConnection {) -> Option<ImageFrameHandle> {let frame = unsafe {web_canvas_2d_connection_read_back_pixels(- self.0.as_ptr(),+ self.as_ptr(),canvas_id.0,rect.x,rect.y,@@ -220,7 +187,7 @@ impl CompositorTransport {impl Drop for CompositorTransport {fn drop(&mut self) {// SAFETY: The value owns a reference to the connection.- unsafe { web_canvas_2d_connection_unref(self.connection.0.as_ptr()) };+ unsafe { self.connection.release() };}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rsindex 9018dcf3c01..11bbafcf3ba 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/stream.rs@@ -16,7 +16,8 @@ use libcompositing_rust::ipc_types::compositor_web_content_server::messages::Upduse libgfx_rust::font::FontHandle;use libgfx_rust::image_frame::ImageFrameHandle;-use super::host::{CompositorConnection, VideoFrameHold};+use super::host::VideoFrameHold;+use crate::compositor_connection::CompositorConnection;#[derive(Default)]pub(crate) struct Canvas2DStream {diff --git a/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rs b/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rsnew file mode 100644index 00000000000..98cb084735f--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/compositor_connection.rs@@ -0,0 +1,182 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;+use core::mem::MaybeUninit;+use core::ptr::NonNull;++use libcompositing_rust::ipc_types::Core_AnonymousBuffer;+use libgfx_rust::image_frame::ImageFrameHandle;+use libipc_rust::cpp_connection::{CppConnection, FfiConnection, FfiThreadSafeMessagePoster, ThreadSafeMessagePoster};+use libipc_rust::wire::{EndpointMessage, File, SyncMessage};++unsafe extern "C" {+ fn web_canvas_2d_connection_unref(connection: *mut c_void);+ fn web_canvas_2d_connection_poster(connection: *mut c_void, out_poster: *mut FfiThreadSafeMessagePoster) -> bool;+ fn web_canvas_2d_connection_did_fail_to_post(connection: *mut c_void);+ fn web_compositor_connection_for_sync_requests(connection: *mut c_void, out_connection: *mut FfiConnection)+ -> bool;+ fn web_compositor_connection_register_image_frames(+ connection: *mut c_void,+ image_frames: *const *const c_void,+ image_frame_count: usize,+ ) -> bool;+ 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;+}++#[derive(Clone, Copy)]+pub(crate) struct CompositorConnection(NonNull<c_void>);++// SAFETY (of every call below): The connection is live, and what is passed to it is lent for the call, in which C+++// takes references of its own.+impl CompositorConnection {+ /// # Safety+ ///+ /// `connection` must be a CompositorConnection that outlives the value.+ pub(crate) unsafe fn lent(connection: NonNull<c_void>) -> Self {+ Self(connection)+ }++ pub(crate) fn as_ptr(self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// # Safety+ ///+ /// The caller owns a reference to the connection, which it gives up.+ pub(crate) unsafe fn release(self) {+ unsafe { web_canvas_2d_connection_unref(self.0.as_ptr()) };+ }++ 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 lose_compositor(self) {+ unsafe { web_canvas_2d_connection_did_fail_to_post(self.0.as_ptr()) };+ }++ pub(crate) fn post_or_lose_compositor<M: EndpointMessage>(+ self,+ poster: &ThreadSafeMessagePoster,+ message: M,+ ) -> bool {+ let posted = poster.try_post(message).expect("a message to the compositor encodes");+ if !posted {+ self.lose_compositor();+ }+ posted+ }++ pub(crate) fn post<M: EndpointMessage>(self, message: M) -> bool {+ self.poster_while_compositor_is_reachable()+ .is_some_and(|poster| poster.try_post(message).expect("a message to the compositor encodes"))+ }++ pub(crate) fn send_sync<M: SyncMessage>(self, request: M) -> Option<M::Response> {+ let mut connection = MaybeUninit::<FfiConnection>::uninit();+ if !unsafe { web_compositor_connection_for_sync_requests(self.0.as_ptr(), connection.as_mut_ptr()) } {+ return None;+ }+ // SAFETY: C++ set the connection to one reference to the connection of this thread.+ let connection = unsafe { CppConnection::adopt(connection.assume_init()) };+ let response = connection.send_sync(request);+ if response.is_none() {+ self.lose_compositor();+ }+ response+ }++ pub(crate) fn register_image_frames(self, image_frames: &[&ImageFrameHandle]) -> bool {+ let image_frames: Vec<*const c_void> = image_frames.iter().map(|frame| frame.as_raw()).collect();+ unsafe {+ web_compositor_connection_register_image_frames(self.0.as_ptr(), image_frames.as_ptr(), image_frames.len())+ }+ }+}++/// Mirrors `Web::Compositor::FfiSharedBuffer`.+#[repr(C)]+pub(crate) struct FfiSharedBuffer {+ data: *mut u8,+ size: usize,+ descriptor: i32,+ owner: *mut c_void,+}++pub(crate) struct SharedBuffer {+ data: NonNull<u8>,+ size: usize,+ owner: NonNull<c_void>,+}++impl SharedBuffer {+ pub(crate) fn create(size: usize) -> Option<Self> {+ let mut buffer = FfiSharedBuffer {+ data: core::ptr::null_mut(),+ size: 0,+ descriptor: -1,+ owner: core::ptr::null_mut(),+ };+ // SAFETY: C++ fills `buffer` where it answers true.+ if size == 0 || !unsafe { web_compositor_create_shared_buffer(size, &mut buffer) } {+ return None;+ }+ drop(descriptor_into_file(buffer.descriptor));+ Some(Self {+ data: NonNull::new(buffer.data).expect("C++ maps the memory"),+ size: buffer.size,+ owner: NonNull::new(buffer.owner).expect("C++ passes the owner of the memory"),+ })+ }++ pub(crate) fn as_ptr(&self) -> *mut u8 {+ self.data.as_ptr()+ }++ pub(crate) fn len(&self) -> usize {+ self.size+ }++ pub(crate) fn for_message(&self) -> Core_AnonymousBuffer {+ // SAFETY: The value owns the memory.+ let descriptor = unsafe { web_compositor_shared_buffer_clone_descriptor(self.owner.as_ptr()) };+ assert!(descriptor >= 0, "the descriptor of shared memory can be cloned");+ Core_AnonymousBuffer {+ shared_memory: Some((self.size as u64, descriptor_into_file(descriptor))),+ }+ }++ pub(crate) fn into_image_frame(self, width: i32, height: i32) -> 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) };+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })+ }+}++impl Drop for SharedBuffer {+ fn drop(&mut self) {+ // SAFETY: The value owns the memory, which nothing uses after this.+ unsafe { web_compositor_shared_buffer_release(self.owner.as_ptr()) };+ }+}++fn descriptor_into_file(descriptor: i32) -> File {+ #[cfg(unix)]+ // SAFETY: C++ hands over a descriptor of its own.+ let descriptor = unsafe { <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(descriptor) };+ #[cfg(windows)]+ // SAFETY: C++ hands over a descriptor of its own.+ let descriptor = unsafe { libipc_rust::transport_windows::OwnedDescriptor::from_raw(descriptor) };+ File(descriptor)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 8b552fc2c8a..af1720a297f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -66,6 +66,8 @@ pub(crate) mod canvas_2d;)]pub(crate) mod clipboard;#[cfg(not(test))]+pub(crate) mod compositor_connection;+#[cfg(not(test))]#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rsindex 4d162bfadee..437c514acd6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs@@ -4,8 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! What a WebGL context asks of the rest of LibWeb, which is C++: its canvas, the sources of texture images, and-//! the helpers that LibCompositing shares between the two sides of the command stream.+//! What a WebGL context asks of the rest of LibWeb, which is C++: its canvas and the sources of texture images.//! Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp defines these functions.use core::ffi::c_void;@@ -14,51 +13,27 @@ use core::ptr::NonNull;use libgfx_rust::image_frame::ImageFrameHandle;use libjs_rust::api::{Gc, Object, Realm};-use super::host::Frame;use crate::bindings::conversions::CppInterface;+use crate::canvas_2d::host::TransportAbi;+use crate::compositor_connection::CompositorConnection;-/// The sources of texture images that are implemented in C++, in the order of the C++ enum of the same name.+/// The sources of texture images whose frame LibWeb reads, in the order of the C++ enum of the same name.#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]pub(crate) enum TexImageSourceKind {HTMLImageElement,HTMLCanvasElement,- HTMLVideoElement,OffscreenCanvas,}-/// The values of the C++ enum `TexImageSourceResult`.-const TEX_IMAGE_SOURCE_RESULT_FRAME: u8 = 0;-const TEX_IMAGE_SOURCE_RESULT_NO_FRAME: u8 = 1;-const TEX_IMAGE_SOURCE_RESULT_INVALID_VALUE: u8 = 2;-unsafe extern "C" {fn web_webgl_canvas_did_change_content(canvas_host: *mut c_void);fn web_webgl_canvas_bitmap_size(canvas_host: *mut c_void, out_width: *mut i32, out_height: *mut i32);fn web_webgl_canvas_wrapper(canvas: *mut c_void, canvas_is_offscreen: bool, realm: *mut c_void) -> *mut c_void;fn web_webgl_canvas_relevant_realm(canvas_host: *mut c_void) -> *mut c_void;safe fn web_webgl_expose_experimental_interfaces() -> bool;- fn web_webgl_read_tex_image_source(- source_wrapper: *mut c_void,- source_kind: TexImageSourceKind,- format: u32,- r#type: u32,- out_frame: *mut *mut c_void,- ) -> u8;- fn web_webgl_read_tex_image_frame(- image_frame: *const c_void,- format: u32,- r#type: u32,- out_frame: *mut *mut c_void,- ) -> u8;- fn web_webgl_read_tex_image_pixels(- pixels: *const u8,- width: u32,- height: u32,- format: u32,- r#type: u32,- out_frame: *mut *mut c_void,- ) -> u8;+ fn web_webgl_texture_image_frame(source_wrapper: *mut c_void, source_kind: TexImageSourceKind) -> *mut c_void;+ fn web_canvas_2d_canvas_create_transport(canvas_host: *mut c_void, out_transport: *mut TransportAbi) -> bool;}#[derive(Clone, Copy)]@@ -76,6 +51,16 @@ impl Canvas {unsafe { web_webgl_canvas_did_change_content(self.host.as_ptr()) };}+ pub(crate) fn compositor_connection(self) -> Option<CompositorConnection> {+ let mut transport = TransportAbi::default();+ // SAFETY: LibWeb hands over a reference to the connection where it answers true.+ unsafe { web_canvas_2d_canvas_create_transport(self.host.as_ptr(), &raw mut transport) }.then(|| {+ let connection = NonNull::new(transport.connection).expect("LibWeb passes the connection");+ // SAFETY: The caller takes over the reference to the connection, which outlives the value.+ unsafe { CompositorConnection::lent(connection) }+ })+ }+pub(crate) fn bitmap_size(self) -> (i32, i32) {let (mut width, mut height) = (0, 0);unsafe { web_webgl_canvas_bitmap_size(self.host.as_ptr(), &raw mut width, &raw mut height) };@@ -101,71 +86,9 @@ pub(crate) fn expose_experimental_interfaces() -> bool {web_webgl_expose_experimental_interfaces()}-pub(crate) enum TexImageSourceFrame {- Frame(Frame),- /// The source has no image, or no image is uploaded with this format and type.- NoFrame,- InvalidValue,-}--pub(crate) fn read_tex_image_source(- source: CppInterface,- source_kind: TexImageSourceKind,- format: u32,- r#type: u32,-) -> TexImageSourceFrame {- let mut frame = core::ptr::null_mut();- // SAFETY: The wrapper is live and of the interface that the kind names, and the frame is stored when the- // function returns that there is one.- let result = unsafe {- web_webgl_read_tex_image_source(- source.wrapper().as_ptr().cast(),- source_kind,- format,- r#type,- &raw mut frame,- )- };- tex_image_source_frame(result, frame)-}--/// The frame of an image, a frame of an ImageBitmap, for the format and the type.-pub(crate) fn read_tex_image_frame(image_frame: &ImageFrameHandle, format: u32, r#type: u32) -> TexImageSourceFrame {- let mut frame = core::ptr::null_mut();- // SAFETY: The handle keeps the image frame alive, and the frame is stored when the function returns that there is- // one.- let result = unsafe { web_webgl_read_tex_image_frame(image_frame.as_raw(), format, r#type, &raw mut frame) };- tex_image_source_frame(result, frame)-}--/// The frame of a copy of the pixels of an ImageData, for the format and the type.-///-/// # Safety-///-/// `pixels` must be the width × height RGBA8888 pixels of the ImageData, which no script may change during the call.-pub(crate) unsafe fn read_tex_image_pixels(- pixels: NonNull<u8>,- width: u32,- height: u32,- format: u32,- r#type: u32,-) -> TexImageSourceFrame {- let mut frame = core::ptr::null_mut();- // SAFETY: The caller passes the pixels, and the frame is stored when the function returns that there is one.- let result =- unsafe { web_webgl_read_tex_image_pixels(pixels.as_ptr(), width, height, format, r#type, &raw mut frame) };- tex_image_source_frame(result, frame)-}--fn tex_image_source_frame(result: u8, frame: *mut c_void) -> TexImageSourceFrame {- match result {- TEX_IMAGE_SOURCE_RESULT_FRAME => {- let frame = NonNull::new(frame).expect("LibWeb returns the frame");- // SAFETY: LibWeb hands over a frame that it allocated.- TexImageSourceFrame::Frame(unsafe { Frame::from_raw(frame) })- }- TEX_IMAGE_SOURCE_RESULT_NO_FRAME => TexImageSourceFrame::NoFrame,- TEX_IMAGE_SOURCE_RESULT_INVALID_VALUE => TexImageSourceFrame::InvalidValue,- unknown_result => unreachable!("LibWeb returned {unknown_result} for the reading of a texture image source"),- }+pub(crate) fn texture_image_frame(source: CppInterface, source_kind: TexImageSourceKind) -> Option<ImageFrameHandle> {+ // SAFETY: The wrapper is live and of the interface that the kind names, and LibWeb hands over a frame that it+ // allocated with new, or null.+ let frame = unsafe { web_webgl_texture_image_frame(source.wrapper().as_ptr().cast(), source_kind) };+ (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rsindex 6fd7887a9e7..cc7fde0a8fd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs@@ -15,7 +15,7 @@ use ak::Utf16String;use super::canvas::Canvas;use super::fingerprint::verify_that_rust_and_cpp_agree_on_layouts_and_constants;-use super::host::CppTransport;+use super::host::{ContextCreation, RemoteContext};use super::proxy::recorder::Proxy;use super::state::{ContextParameters, ContextRef, ContextState, RenderingContext, WebGL1, WebGL2, WebGLVersion,@@ -27,11 +27,6 @@ use super::web_gl_rendering_context_base::WebGLContextAttributes;use crate::bindings::interface::{Interface, allocate, cell_into_abi, realm_arguments};use crate::dom::event::EventInit;-/// The bytes of the names of the extensions C++ lends.-fn extension_names(names: ak::Span<'_, ak::Span<'_, u8>>) -> Vec<Vec<u8>> {- names.as_slice().iter().map(|name| name.as_slice().to_vec()).collect()-}-/// Mirrors `Web::WebGL::ContextAttributes`.#[derive(Clone, Copy)]#[repr(C)]@@ -91,16 +86,34 @@ impl From<WebGLContextAttributes> for ContextAttributes {/// Mirrors `Web::WebGL::ContextCreationArguments`.#[repr(C)]-pub struct ContextCreationArguments<'a> {- /// A RemoteWebGLTransport that has created its context, with a reference that the new context takes over.- transport: *mut c_void,+pub struct ContextCreationArguments {is_webgl2: bool,realm: *mut c_void,canvas: *mut c_void,canvas_host: *mut c_void,canvas_is_offscreen: bool,context_attributes: ContextAttributes,- supported_extensions: ak::Span<'a, ak::Span<'a, u8>>,+}++fn create_remote_context(+ canvas: Canvas,+ webgl2: bool,+ context_attributes: &WebGLContextAttributes,+) -> Option<(RemoteContext, Vec<Vec<u8>>)> {+ let (width, height) = canvas.bitmap_size();+ let creation = ContextCreation {+ webgl2,+ size: libgfx_rust::IntSize {+ width: drawing_buffer_dimension(width),+ height: drawing_buffer_dimension(height),+ },+ depth: context_attributes.depth,+ stencil: context_attributes.stencil,+ antialias: context_attributes.antialias,+ };+ let connection = canvas.compositor_connection()?;+ // SAFETY: The canvas handed over a reference to the connection.+ unsafe { RemoteContext::create(connection, &creation) }}/// The cell of a WebGLRenderingContext or of a WebGL2RenderingContext, which only C++ lends out, for as long as the@@ -133,13 +146,12 @@ fn with_context<R>(context: &ContextCell, function: impl FnOnce(&ContextState) -#[unsafe(no_mangle)]pub unsafe extern "C" fn web_webgl_context_create(vm: *mut c_void,- arguments: &ContextCreationArguments<'_>,+ arguments: &ContextCreationArguments,) -> *mut c_void {// SAFETY: The caller passes the live VM and a live realm.let (vm, realm) = unsafe { realm_arguments(vm, arguments.realm) };verify_that_rust_and_cpp_agree_on_layouts_and_constants();- let transport = NonNull::new(arguments.transport).expect("C++ passes the transport");let canvas = Canvas {cell: NonNull::new(arguments.canvas).expect("C++ passes the canvas"),host: NonNull::new(arguments.canvas_host).expect("C++ passes the canvas"),@@ -150,14 +162,19 @@ pub unsafe extern "C" fn web_webgl_context_create(} else {WebGLVersion::WebGL1};+ let context_attributes: WebGLContextAttributes = arguments.context_attributes.into();+ let Some((remote_context, supported_opengl_extensions)) =+ create_remote_context(canvas, version == WebGLVersion::WebGL2, &context_attributes)+ else {+ return core::ptr::null_mut();+ };let parameters = ContextParameters {- // SAFETY: The caller hands over a reference to the transport.- proxy: Proxy::new(unsafe { CppTransport::from_raw(transport) }),+ proxy: Proxy::new(remote_context),version,realm,canvas,- context_attributes: arguments.context_attributes.into(),- supported_opengl_extensions: extension_names(arguments.supported_extensions),+ context_attributes,+ supported_opengl_extensions,};match version {WebGLVersion::WebGL1 => {@@ -182,11 +199,6 @@ pub extern "C" fn web_webgl_context_canvas_host(context: &ContextCell) -> *mut cwith_context(context, |context| context.canvas().host.as_ptr())}-#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_is_webgl2(context: &ContextCell) -> bool {- with_context(context, ContextState::is_webgl2)-}-#[unsafe(no_mangle)]pub extern "C" fn web_webgl_context_is_lost(context: &ContextCell) -> bool {with_context(context, ContextState::is_context_lost)@@ -255,32 +267,18 @@ pub extern "C" fn web_webgl_context_wants_restoring(context: &ContextCell) -> bo}#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_actual_context_parameters(- context: &ContextCell,- out_context_attributes: &mut ContextAttributes,-) {- let context_attributes = with_context(context, |context| context.actual_context_parameters);- *out_context_attributes = context_attributes.into();-}--/// The context takes over the reference to `transport`.-///-/// # Safety-///-/// `transport` is a RemoteWebGLTransport that has created its context.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_webgl_context_restore(- context: &ContextCell,- transport: *mut c_void,- supported_extensions: ak::Span<'_, ak::Span<'_, u8>>,-) {- let transport = NonNull::new(transport).expect("C++ passes the transport");- // SAFETY: The caller hands over a reference to the transport.- let transport = unsafe { CppTransport::from_raw(transport) };- let supported_opengl_extensions = extension_names(supported_extensions);+pub extern "C" fn web_webgl_context_restore(context: &ContextCell) -> bool {with_context(context, |context| {- context.restore(transport, supported_opengl_extensions);- });+ let Some((remote_context, supported_opengl_extensions)) = create_remote_context(+ context.canvas(),+ context.is_webgl2(),+ &context.actual_context_parameters,+ ) else {+ return false;+ };+ context.restore(remote_context, supported_opengl_extensions);+ true+ })}/// Converts the options of getContext() to the dictionary, and answers true with the exception that the conversiondiff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rsindex 7bbf9b7c3ea..f6f01905b46 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs@@ -4,187 +4,191 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The transport of a context in the product: a RemoteWebGLTransport of LibWeb, through the C ABI that-//! Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp gives it.--use core::ffi::c_void;-use core::ptr::{self, NonNull};-+//! The transport of a context in the product: the CompositorConnection of the page of its canvas, which its messages go+//! through, and the shared memory that they carry.++use core::cell::Cell;++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::{+ CreateWebglContext, DestroyWebglContext, WebglClearDrawingBuffer, WebglCommands, WebglCommandsFromSharedBuffer,+ WebglDrainCommandBuffer, WebglPresentCanvas, WebglReadBackDrawingBuffer, WebglReadBufferSubData, WebglReadPixels,+ WebglSetCommandBuffer, WebglSyncCall,+};+use libcompositing_rust::webgl::ImageSource;use libgfx_rust::image_frame::ImageFrameHandle;+use libgfx_rust::{IntRect, IntSize};use super::proxy::transport::{ReadPixelsResult, SharedMemory, Transport};--unsafe extern "C" {- fn web_webgl_transport_unref(transport: *mut c_void);- fn web_webgl_transport_canvas_id(transport: *const c_void, out_canvas_id: *mut u64) -> bool;- fn web_webgl_transport_destroy_context(transport: *mut c_void);- fn web_webgl_transport_set_shared_command_buffer(transport: *mut c_void, anonymous_buffer: *const c_void);- fn web_webgl_transport_send_commands_from_shared_buffer(- transport: *mut c_void,- offset: u64,- size_in_bytes: u64,- flush_sequence_number: u64,- frames: *const Frame,- frame_count: usize,- );- fn web_webgl_transport_wait_until_published_commands_executed(transport: *mut c_void) -> bool;- fn web_webgl_transport_send_commands(- transport: *mut c_void,- commands: *const u8,- size_in_bytes: usize,- frames: *const Frame,- frame_count: usize,- );- fn web_webgl_transport_present_canvas(transport: *mut c_void, preserve_drawing_buffer: bool);- fn web_webgl_transport_clear_drawing_buffer(transport: *mut c_void);- fn web_webgl_transport_sync_call(- transport: *mut c_void,- request: *const u8,- request_size: usize,- reply_sink: *mut c_void,- write_reply: unsafe extern "C" fn(reply_sink: *mut c_void, reply: *const u8, reply_size: usize),- );- fn web_webgl_transport_read_pixels_robust_angle(- transport: *mut c_void,- x: i32,- y: i32,- width: i32,- height: i32,- format: u32,- r#type: u32,- buf_size: i32,- pixels_anonymous_buffer_or_null: *const c_void,- out_result: *mut ReadPixelsResult,- );- fn web_webgl_transport_read_buffer_sub_data(- transport: *mut c_void,- target: u32,- offset: i64,- size: i64,- data_anonymous_buffer: *const c_void,- ) -> bool;- fn web_webgl_transport_read_back_drawing_buffer(- transport: *mut c_void,- x: i32,- y: i32,- width: i32,- height: i32,- ) -> *mut c_void;- safe fn web_webgl_max_frames_per_message() -> usize;- safe fn web_webgl_anonymous_buffer_create(size: usize, out_data: &mut *mut u8) -> *mut c_void;- fn web_webgl_anonymous_buffer_destroy(anonymous_buffer: *mut c_void);- fn web_webgl_frame_destroy(frame: *mut c_void);-}--pub(crate) struct AnonymousBuffer {- buffer: NonNull<c_void>,- data: *mut u8,- size: usize,-}--impl AnonymousBuffer {- fn create(size: usize) -> Option<Self> {- let mut data = ptr::null_mut();- let buffer = NonNull::new(web_webgl_anonymous_buffer_create(size, &mut data))?;- Some(Self { buffer, data, size })- }+use super::state::MAX_WEBGL_DRAWING_BUFFER_DIMENSION;+use crate::canvas_2d::canvas::CapturedVideoFrame;+use crate::compositor_connection::{CompositorConnection, SharedBuffer};++fn rect_inside_largest_drawing_buffer(x: i32, y: i32, width: i32, height: i32) -> Option<IntRect> {+ let clamp = |coordinate: i32| coordinate.clamp(0, MAX_WEBGL_DRAWING_BUFFER_DIMENSION);+ let (left, top) = (clamp(x), clamp(y));+ let (right, bottom) = (clamp(x.saturating_add(width)), clamp(y.saturating_add(height)));+ (left < right && top < bottom).then_some(IntRect {+ x: left,+ y: top,+ width: right - left,+ height: bottom - top,+ })}-impl Drop for AnonymousBuffer {- fn drop(&mut self) {- // SAFETY: The value owns the buffer, which nothing uses after this.- unsafe { web_webgl_anonymous_buffer_destroy(self.buffer.as_ptr()) };- }-}--impl SharedMemory for AnonymousBuffer {+impl SharedMemory for SharedBuffer {fn as_ptr(&self) -> *mut u8 {- self.data+ SharedBuffer::as_ptr(self)}fn len(&self) -> usize {- self.size+ SharedBuffer::len(self)}}-#[repr(transparent)]-pub(crate) struct Frame(NonNull<c_void>);--impl Frame {- /// # Safety- ///- /// `frame` is a Compositing::WebGL::ImageSourceFrame allocated with `new`, which the value takes over.- pub(crate) unsafe fn from_raw(frame: NonNull<c_void>) -> Self {- Self(frame)- }+pub(crate) enum Frame {+ Image(ImageFrameHandle),+ Video(CapturedVideoFrame),}-impl Drop for Frame {- fn drop(&mut self) {- // SAFETY: The value owns the frame, which nothing uses after this.- unsafe { web_webgl_frame_destroy(self.0.as_ptr()) };- }+pub(crate) struct ContextCreation {+ pub(crate) webgl2: bool,+ pub(crate) size: IntSize,+ pub(crate) depth: bool,+ pub(crate) stencil: bool,+ pub(crate) antialias: bool,}-pub(crate) struct CppTransport(NonNull<c_void>);+pub(crate) struct RemoteContext {+ connection: CompositorConnection,+ canvas_id: Cell<Option<CanvasId>>,+}-impl CppTransport {+impl RemoteContext {/// # Safety///- /// `transport` is a RemoteWebGLTransport, one reference to which the value takes over.- pub(crate) unsafe fn from_raw(transport: NonNull<c_void>) -> Self {- Self(transport)+ /// `connection` holds a reference to the connection, which the call takes over.+ pub(crate) unsafe fn create(+ connection: CompositorConnection,+ creation: &ContextCreation,+ ) -> Option<(Self, Vec<Vec<u8>>)> {+ let context = Self {+ connection,+ canvas_id: Cell::new(None),+ };+ let response = connection.send_sync(CreateWebglContext {+ webgl_version: if creation.webgl2 {+ Compositing_WebGL_WebGLVersion::WebGL2+ } else {+ Compositing_WebGL_WebGLVersion::WebGL1+ },+ size: creation.size,+ depth: creation.depth,+ stencil: creation.stencil,+ antialias: creation.antialias,+ })?;+ if !response.success {+ return None;+ }+ context.canvas_id.set(Some(response.canvas_id));+ let supported_extensions = response+ .supported_extensions+ .into_iter()+ .map(|extension| extension.into_bytes())+ .collect();+ Some((context, supported_extensions))}- fn as_ptr(&self) -> *mut c_void {- self.0.as_ptr()+ fn image_sources_of(&self, frames: &[Frame]) -> Option<Vec<ImageSource>> {+ let image_frames: Vec<&ImageFrameHandle> = frames+ .iter()+ .filter_map(|frame| match frame {+ Frame::Image(image_frame) => Some(image_frame),+ Frame::Video(_) => None,+ })+ .collect();+ if !image_frames.is_empty() && !self.connection.register_image_frames(&image_frames) {+ self.connection.lose_compositor();+ return None;+ }+ Some(+ frames+ .iter()+ .map(|frame| match frame {+ Frame::Image(image_frame) => {+ ImageSource::RegisteredImageFrame(ImageFrameResourceId(image_frame.id()))+ }+ Frame::Video(video_frame) => ImageSource::HeldVideoFrame {+ sink_handle: VideoSinkHandle(video_frame.sink_handle),+ generation: video_frame.generation,+ },+ })+ .collect(),+ )}-}-impl Drop for CppTransport {- fn drop(&mut self) {- // SAFETY: The value owns one reference to the transport.- unsafe { web_webgl_transport_unref(self.as_ptr()) };+ fn post_commands(&self, frames: &[Frame], message: impl FnOnce(CanvasId, Vec<ImageSource>) -> bool) {+ let Some(canvas_id) = self.canvas_id.get() else {+ return;+ };+ if self.connection.poster_while_compositor_is_reachable().is_none() {+ return;+ }+ let Some(image_sources) = self.image_sources_of(frames) else {+ return;+ };+ if !message(canvas_id, image_sources) {+ return;+ }+ for frame in frames {+ if let Frame::Video(video_frame) = frame {+ video_frame.hold.note_sent_to_compositor();+ }+ }}-}-unsafe extern "C" fn append_reply(reply_sink: *mut c_void, reply: *const u8, reply_size: usize) {- if reply_size == 0 {- return;+ fn post_or_lose_compositor<M: libipc_rust::wire::EndpointMessage>(&self, message: M) -> bool {+ match self.connection.poster_while_compositor_is_reachable() {+ Some(poster) => self.connection.post_or_lose_compositor(&poster, message),+ None => false,+ }}- // SAFETY: sync_call() passes its vector as the sink, and the transport passes the bytes of its reply.- unsafe {- let reply_sink = &mut *reply_sink.cast::<Vec<u8>>();- reply_sink.extend_from_slice(ak::slice_from_raw_parts(reply, reply_size));+}++impl Drop for RemoteContext {+ fn drop(&mut self) {+ // SAFETY: The value owns a reference to the connection.+ unsafe { self.connection.release() };}}-// SAFETY (of every call below): The value holds a reference to the transport, the buffers and the frames passed are-// alive for the call, and a pointer with a length is the pointer and the length of one slice.-impl Transport for CppTransport {- type SharedMemory = AnonymousBuffer;+impl Transport for RemoteContext {+ type SharedMemory = SharedBuffer;type Frame = Frame;type DrawingBufferPixels = ImageFrameHandle;- fn max_frames_per_message(&self) -> usize {- web_webgl_max_frames_per_message()- }-- fn create_shared_memory(&self, size: usize) -> Option<AnonymousBuffer> {- AnonymousBuffer::create(size)+ fn create_shared_memory(&self, size: usize) -> Option<SharedBuffer> {+ SharedBuffer::create(size)}fn canvas_id(&self) -> Option<u64> {- let mut canvas_id = 0;- unsafe { web_webgl_transport_canvas_id(self.as_ptr(), &raw mut canvas_id) }.then_some(canvas_id)+ self.canvas_id.get().map(|canvas_id| canvas_id.0)}fn destroy_context(&self) {- unsafe { web_webgl_transport_destroy_context(self.as_ptr()) };+ if let Some(canvas_id) = self.canvas_id.take() {+ self.connection.post(DestroyWebglContext { canvas_id });+ }}- fn set_shared_command_buffer(&self, buffer: &AnonymousBuffer) {- unsafe { web_webgl_transport_set_shared_command_buffer(self.as_ptr(), buffer.buffer.as_ptr()) };+ fn set_shared_command_buffer(&self, buffer: &SharedBuffer) {+ if let Some(canvas_id) = self.canvas_id.get() {+ self.post_or_lose_compositor(WebglSetCommandBuffer {+ canvas_id,+ command_buffer: buffer.for_message(),+ });+ }}fn send_commands_from_shared_buffer(@@ -194,51 +198,65 @@ impl Transport for CppTransport {flush_sequence_number: u64,frames: &[Frame],) {- unsafe {- web_webgl_transport_send_commands_from_shared_buffer(- self.as_ptr(),+ self.post_commands(frames, |canvas_id, image_sources| {+ self.post_or_lose_compositor(WebglCommandsFromSharedBuffer {+ canvas_id,offset,size_in_bytes,flush_sequence_number,- frames.as_ptr(),- frames.len(),- );- }+ image_sources,+ })+ });}fn wait_until_published_commands_executed(&self) -> bool {- unsafe { web_webgl_transport_wait_until_published_commands_executed(self.as_ptr()) }+ let Some(canvas_id) = self.canvas_id.get() else {+ return false;+ };+ self.connection+ .send_sync(WebglDrainCommandBuffer { canvas_id })+ .is_some()}fn send_commands(&self, commands: &[u8], frames: &[Frame]) {- unsafe {- web_webgl_transport_send_commands(- self.as_ptr(),- commands.as_ptr(),- commands.len(),- frames.as_ptr(),- frames.len(),- );- }+ self.post_commands(frames, |canvas_id, image_sources| {+ let Some(buffer) = SharedBuffer::create(commands.len()) else {+ return false;+ };+ // SAFETY: The buffer has room for the commands, and nothing else writes it yet.+ unsafe { core::ptr::copy_nonoverlapping(commands.as_ptr(), buffer.as_ptr(), commands.len()) };+ self.post_or_lose_compositor(WebglCommands {+ canvas_id,+ commands: buffer.for_message(),+ image_sources,+ })+ });}fn present_canvas(&self, preserve_drawing_buffer: bool) {- unsafe { web_webgl_transport_present_canvas(self.as_ptr(), preserve_drawing_buffer) };+ if let Some(canvas_id) = self.canvas_id.get() {+ self.connection.post(WebglPresentCanvas {+ canvas_id,+ preserve_drawing_buffer,+ });+ }}fn clear_drawing_buffer(&self) {- unsafe { web_webgl_transport_clear_drawing_buffer(self.as_ptr()) };+ if let Some(canvas_id) = self.canvas_id.get() {+ self.connection.post(WebglClearDrawingBuffer { canvas_id });+ }}fn sync_call(&self, request: &[u8], reply: &mut Vec<u8>) {- unsafe {- web_webgl_transport_sync_call(- self.as_ptr(),- request.as_ptr(),- request.len(),- ptr::from_mut(reply).cast::<c_void>(),- append_reply,- );+ let Some(canvas_id) = self.canvas_id.get() else {+ return;+ };+ if let Some(response) = self.connection.send_sync(WebglSyncCall {+ canvas_id,+ request: request.to_vec(),+ }) {+ reply.extend_from_slice(&response.reply);}}@@ -251,13 +269,18 @@ impl Transport for CppTransport {format: u32,r#type: u32,buf_size: i32,- pixels: Option<&AnonymousBuffer>,+ pixels: Option<&SharedBuffer>,) -> ReadPixelsResult {- let mut result = ReadPixelsResult::default();- let pixels = pixels.map_or(ptr::null(), |pixels| pixels.buffer.as_ptr().cast_const());- unsafe {- web_webgl_transport_read_pixels_robust_angle(- self.as_ptr(),+ let Some(canvas_id) = self.canvas_id.get() else {+ return ReadPixelsResult::default();+ };+ let pixels = pixels.map_or(+ libcompositing_rust::ipc_types::Core_AnonymousBuffer { shared_memory: None },+ SharedBuffer::for_message,+ );+ self.connection+ .send_sync(WebglReadPixels {+ canvas_id,x,y,width,@@ -266,19 +289,46 @@ impl Transport for CppTransport {r#type,buf_size,pixels,- &raw mut result,- );- }- result+ })+ .map_or_else(ReadPixelsResult::default, |response| ReadPixelsResult {+ length: response.length,+ columns: response.columns,+ rows: response.rows,+ })}- fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &AnonymousBuffer) -> bool {- unsafe { web_webgl_transport_read_buffer_sub_data(self.as_ptr(), target, offset, size, data.buffer.as_ptr()) }+ fn read_buffer_sub_data(&self, target: u32, offset: i64, size: i64, data: &SharedBuffer) -> bool {+ let Some(canvas_id) = self.canvas_id.get() else {+ return false;+ };+ self.connection+ .send_sync(WebglReadBufferSubData {+ canvas_id,+ target,+ offset,+ size,+ data: data.for_message(),+ })+ .is_some_and(|response| response.success)}fn read_back_drawing_buffer(&self, x: i32, y: i32, width: i32, height: i32) -> Option<ImageFrameHandle> {- let frame = unsafe { web_webgl_transport_read_back_drawing_buffer(self.as_ptr(), x, y, width, height) };- // SAFETY: LibWeb hands over a frame that it allocated with new, or null.- (!frame.is_null()).then(|| unsafe { ImageFrameHandle::adopt(frame) })+ let canvas_id = self.canvas_id.get()?;+ let rect = rect_inside_largest_drawing_buffer(x, y, width, height)?;+ 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.connection.send_sync(WebglReadBackDrawingBuffer {+ canvas_id,+ rect,+ pixels: pixels.for_message(),+ })?;+ let IntSize { width, height } = response.size;+ if width <= 0 || height <= 0 {+ return None;+ }+ pixels.into_image_frame(width, height)}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rsindex b9a0d91ca44..cf23d23ec23 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/recorder.rs@@ -25,6 +25,9 @@ use crate::web_gl::constants::GL_OUT_OF_MEMORY;pub(crate) const MAX_PENDING_COMMAND_BYTES: usize = 4 * 1024 * 1024;+/// Each frame that waits for a flush holds the descriptor of its pixels.+pub(crate) const MAX_PENDING_FRAMES: usize = 64;+/// What is kept free in the region of records for the command that names a frame, before the frame is added to the/// pending ones. Making room only when the command is recorded could flush in between, and that flush would publish/// the frame with the wrong batch.@@ -56,7 +59,6 @@ pub(crate) struct Proxy<T: Transport> {sync_reply_bytes: Cell<Vec<u8>>,/// By GL name. The strings do not change while a context lives.string_cache: RefCell<Vec<(u32, Rc<[u8]>)>>,- max_frames_per_message: Cell<usize>,transport_calls_are_deferred: Cell<bool>,deferred_record_count: Cell<usize>,@@ -72,7 +74,6 @@ impl<T: Transport> Proxy<T> {pub(super) fn with_shared_data_capacity(transport: T, shared_data_capacity: usize) -> Self {let proxy = Self {- max_frames_per_message: Cell::new(transport.max_frames_per_message()),transport: RefCell::new(Rc::new(transport)),lost: Cell::new(false),pending_local_error: Cell::new(0),@@ -100,7 +101,6 @@ impl<T: Transport> Proxy<T> {/// Nothing that was recorded for the lost context reaches the new one.pub(crate) fn restore(&self, transport: T) {- self.max_frames_per_message.set(transport.max_frames_per_message());self.transport.replace(Rc::new(transport));self.lost.set(false);self.out_of_line_commands.take();@@ -405,7 +405,7 @@ impl<T: Transport> Proxy<T> {/// Returns the index that the command which uses the frame names it by.pub(super) fn append_pending_frame(&self, frame: T::Frame) -> u32 {- if self.with_pending_frames(|frames| frames.len()) >= self.max_frames_per_message.get() {+ if self.with_pending_frames(|frames| frames.len()) >= MAX_PENDING_FRAMES {self.flush_commands();}if self.has_shared_command_buffer() {diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rsindex 7937d8773a1..ffc02d48d6a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/tests.rs@@ -18,7 +18,7 @@ use libcompositing_rust::webgl::SHARED_DATA_REGION_OFFSET;use libcompositing_rust::webgl::vocabulary::{CommandType, SyncCallType, commands, sync_calls};use libcompositing_rust::webgl::wire::{Command, DataSpan, HEADER_SIZE, WireStruct};-use super::recorder::{MAX_PENDING_COMMAND_BYTES, Proxy, bytes_of};+use super::recorder::{MAX_PENDING_COMMAND_BYTES, MAX_PENDING_FRAMES, Proxy, bytes_of};use super::transport::{ReadPixelsResult, SharedMemory, Transport};use crate::web_gl::constants::{GL_ARRAY_BUFFER, GL_INVALID_ENUM, GL_OUT_OF_MEMORY, GL_RGBA, GL_UNSIGNED_BYTE};@@ -131,7 +131,6 @@ struct MockReplayer {refuses_shared_memory: Cell<bool>,executes_at_once: Cell<bool>,wait_succeeds: Cell<bool>,- max_frames_per_message: Cell<usize>,sync_replies: RefCell<VecDeque<Vec<u8>>>,read_data: RefCell<Vec<u8>>,read_pixels_result: Cell<ReadPixelsResult>,@@ -149,7 +148,6 @@ impl MockReplayer {refuses_shared_memory: Cell::new(false),executes_at_once: Cell::new(true),wait_succeeds: Cell::new(true),- max_frames_per_message: Cell::new(16),sync_replies: RefCell::new(VecDeque::new()),read_data: RefCell::new(Vec::new()),read_pixels_result: Cell::new(ReadPixelsResult::default()),@@ -238,10 +236,6 @@ impl Transport for MockTransport {type Frame = u32;type DrawingBufferPixels = (i32, i32, i32, i32);- fn max_frames_per_message(&self) -> usize {- self.replayer.max_frames_per_message.get()- }-fn create_shared_memory(&self, size: usize) -> Option<MockMemory> {(!self.replayer.refuses_shared_memory.get()).then(|| MockMemory::new(size))}@@ -606,6 +600,29 @@ fn a_record_larger_than_the_region_is_sent_on_its_own() {);}+#[test]+fn a_flush_comes_before_the_frame_that_would_exceed_the_pending_frames() {+ let replayer = MockReplayer::new();+ let recorder = replayer.recorder(SMALL_CAPACITY * 1024);+ replayer.take_calls();++ for frame in 0..=MAX_PENDING_FRAMES as u32 {+ upload_frame(&recorder, frame);+ }+ let calls = replayer.take_calls();+ let [Call::SendFromSharedBuffer { records, frames, .. }] = calls.as_slice() else {+ panic!("{} calls", calls.len());+ };+ assert_eq!(records.len(), MAX_PENDING_FRAMES);+ assert_eq!(*frames, (0..MAX_PENDING_FRAMES as u32).collect::<Vec<_>>());++ recorder.flush_commands();+ let calls = replayer.take_calls();+ assert!(+ matches!(calls.as_slice(), [Call::SendFromSharedBuffer { frames, .. }] if *frames == [MAX_PENDING_FRAMES as u32])+ );+}+#[test]fn without_a_shared_buffer_commands_are_sent_as_bytes() {let replayer = MockReplayer::new();@@ -692,37 +709,6 @@ fn a_frame_is_published_with_the_command_that_names_it() {);}-#[test]-fn a_message_carries_no_more_frames_than_the_transport_allows() {- let replayer = MockReplayer::new();- replayer.max_frames_per_message.set(2);- let recorder = replayer.recorder(SMALL_CAPACITY);- replayer.take_calls();-- for frame in [70, 80, 90] {- upload_frame(&recorder, frame);- }- assert_eq!(- replayer.take_calls(),- [Call::SendFromSharedBuffer {- offset: 0,- records: vec![frame_record(0), frame_record(1)],- flush_sequence_number: 1,- frames: vec![70, 80],- }]- );- recorder.flush_commands();- assert_eq!(- replayer.take_calls(),- [Call::SendFromSharedBuffer {- offset: 0,- records: vec![frame_record(0)],- flush_sequence_number: 2,- frames: vec![90],- }]- );-}-#[test]fn room_for_the_command_of_a_frame_is_made_before_the_frame_is_pending() {let replayer = MockReplayer::new();diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rsindex a330d8c7f04..aab78b0b1d2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/proxy/transport.rs@@ -28,7 +28,6 @@ pub(crate) trait Transport {type Frame;type DrawingBufferPixels;- fn max_frames_per_message(&self) -> usize;fn create_shared_memory(&self, size: usize) -> Option<Self::SharedMemory>;fn canvas_id(&self) -> Option<u64>;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rsindex c2215702f69..eaa6c645ed7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs@@ -14,14 +14,12 @@ use core::ops::Deref;use ak::Utf16String;use libjs_rust::api::{DeferGc, ForeignCellSlot, Gc, GcRefCell, Realm, Trace, Visitor};-use super::canvas::{- Canvas, TexImageSourceFrame, TexImageSourceKind, read_tex_image_frame, read_tex_image_pixels, read_tex_image_source,-};+use super::canvas::{Canvas, TexImageSourceKind, texture_image_frame};use super::constants::{GL_BROWSER_DEFAULT_WEBGL, GL_CONTEXT_LOST_WEBGL, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_NO_ERROR,};use super::extensions::{EnabledEmptyExtension, EnabledExtension};-use super::host::{CppTransport, Frame};+use super::host::{Frame, RemoteContext};use super::pixel_unpacking::PixelUnpackState;use super::proxy::custom::FrameUpload;use super::proxy::recorder::Proxy;@@ -40,7 +38,9 @@ use super::web_gl_vertex_array_object::WebGLVertexArrayObject;use super::web_gl_vertex_array_object_oes::WebGLVertexArrayObjectOES;use crate::bindings::interface::{Inherits, Interface, Ref, Wrappable};use crate::bindings::{Exception, WebIdlResult};-use crate::canvas_2d::canvas::CanvasImageSourceKind;+use crate::canvas_2d::canvas::{CanvasImageSourceKind, capture_video_frame, image_frame_from_pixels};+use libcompositing_rust::display_list::canvas_2d_recorder::ColorSpace;+use libcompositing_rust::webgl::texture_upload::texture_export_format;pub(crate) const MAX_WEBGL_DRAWING_BUFFER_DIMENSION: i32 = 16384;@@ -130,7 +130,7 @@ pub(crate) type Binding<T> = Cell<Option<Ref<T>>>;#[gc(crate = libjs_rust)]pub(crate) struct ContextState {#[gc(untraced)]- pub(crate) proxy: Proxy<CppTransport>,+ pub(crate) proxy: Proxy<RemoteContext>,#[gc(untraced)]version: WebGLVersion,context_ref: Cell<Option<ContextRef>>,@@ -197,7 +197,7 @@ pub(crate) struct ContextState {}pub(crate) struct ContextParameters {- pub(crate) proxy: Proxy<CppTransport>,+ pub(crate) proxy: Proxy<RemoteContext>,pub(crate) version: WebGLVersion,pub(crate) realm: Gc<Realm>,pub(crate) canvas: Canvas,@@ -356,35 +356,50 @@ impl ContextState {));}- let source_frame = match *source {+ let format_and_type_upload_images = texture_export_format(format, r#type).is_some();+ let frame = match *source {TexImageSource::ImageBitmap(image_bitmap) => match image_bitmap.frame() {- Some(image_frame) => read_tex_image_frame(&image_frame, format, r#type),+ Some(image_frame) => format_and_type_upload_images.then_some(Frame::Image(image_frame)),// If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE error is// generated.- None => TexImageSourceFrame::InvalidValue,+ None => {+ self.set_error(GL_INVALID_VALUE);+ return Ok(None);+ }},TexImageSource::ImageData(image_data) => match image_data.pixels() {+ Some(_) if !format_and_type_upload_images => None,Some(pixels) => {let (width, height) = image_data.size();+ let pitch = width as usize * 4;// SAFETY: Nothing runs script while the pixels are copied.- unsafe { read_tex_image_pixels(pixels, width, height, format, r#type) }+ let Some(image_frame) = (unsafe {+ image_frame_from_pixels(pixels, pitch, width as i32, height as i32, ColorSpace::Srgb)+ }) else {+ self.set_error(GL_INVALID_VALUE);+ return Ok(None);+ };+ Some(Frame::Image(image_frame))}// If this function is called with an ImageData whose data attribute has been neutered, an// INVALID_VALUE error is generated.- None => TexImageSourceFrame::InvalidValue,+ None => {+ self.set_error(GL_INVALID_VALUE);+ return Ok(None);+ }},- TexImageSource::HTMLImageElement(object) => {- read_tex_image_source(object, TexImageSourceKind::HTMLImageElement, format, r#type)- }- TexImageSource::HTMLCanvasElement(object) => {- read_tex_image_source(object, TexImageSourceKind::HTMLCanvasElement, format, r#type)- }- TexImageSource::HTMLVideoElement(object) => {- read_tex_image_source(object, TexImageSourceKind::HTMLVideoElement, format, r#type)- }- TexImageSource::OffscreenCanvas(object) => {- read_tex_image_source(object, TexImageSourceKind::OffscreenCanvas, format, r#type)- }+ TexImageSource::HTMLImageElement(object) => format_and_type_upload_images+ .then(|| texture_image_frame(object, TexImageSourceKind::HTMLImageElement).map(Frame::Image))+ .flatten(),+ TexImageSource::HTMLCanvasElement(object) => format_and_type_upload_images+ .then(|| texture_image_frame(object, TexImageSourceKind::HTMLCanvasElement).map(Frame::Image))+ .flatten(),+ TexImageSource::OffscreenCanvas(object) => format_and_type_upload_images+ .then(|| texture_image_frame(object, TexImageSourceKind::OffscreenCanvas).map(Frame::Image))+ .flatten(),+ TexImageSource::HTMLVideoElement(object) => format_and_type_upload_images+ .then(|| capture_video_frame(object).map(Frame::Video))+ .flatten(),};if tex_image_source_is_not_origin_clean(source) {return Err(Exception::Dom(@@ -392,13 +407,8 @@ impl ContextState {Utf16String::from_ascii(b"Cannot upload a texture source that is not origin-clean"),));}- let frame = match source_frame {- TexImageSourceFrame::Frame(frame) => frame,- TexImageSourceFrame::NoFrame => return Ok(None),- TexImageSourceFrame::InvalidValue => {- self.set_error(GL_INVALID_VALUE);- return Ok(None);- }+ let Some(frame) = frame else {+ return Ok(None);};// The first pixel transferred from the source to the WebGL implementation corresponds to the upper left// corner of the source. This behavior is modified by the UNPACK_FLIP_Y_WEBGL pixel storage parameter,@@ -456,7 +466,7 @@ impl ContextState {}/// The new replayer context has no GL objects: the page creates its objects anew once told of the restore.- pub(crate) fn restore(&self, transport: CppTransport, supported_opengl_extensions: Vec<Vec<u8>>) {+ pub(crate) fn restore(&self, transport: RemoteContext, supported_opengl_extensions: Vec<Vec<u8>>) {self.proxy.restore(transport);self.supported_opengl_extensions.replace(supported_opengl_extensions);diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cppindex 45ffe5a5ffd..5903dd2f6ab 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp@@ -350,14 +350,6 @@ void CompositorConnection::release_video_frame_hold(Media::VideoSinkHandle videoasync_release_video_frame_hold(video_sink_handle, generation);}-static void note_video_frame_holds_sent_to_compositor(Vector<Compositing::WebGL::ImageSourceFrame> const& frames)-{- for (auto const& frame : frames) {- if (auto const* captured_frame = frame.get_pointer<Compositing::CapturedVideoFrame>(); captured_frame && captured_frame->hold)- captured_frame->hold->note_sent_to_compositor();- }-}-void CompositorConnection::set_video_sink_ticking(Media::VideoSinkHandle video_sink_handle, bool should_tick){if (!can_send_message_to_compositor())@@ -420,11 +412,11 @@ void CompositorConnection::did_fail_to_post_canvas_2d_message()did_lose_compositor();}-void CompositorConnection::destroy_webgl_context(Compositing::CanvasId canvas_id)+bool CompositorConnection::register_image_frames(ReadonlySpan<Gfx::DecodedImageFrame const*> image_frames){if (!can_send_message_to_compositor())- return;- async_destroy_webgl_context(canvas_id);+ return false;+ return 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)@@ -748,133 +740,6 @@ void CompositorConnection::hurry_rendering_opportunity(Web::CompositorContextIdasync_hurry_rendering_opportunity(context_id);}-Optional<Compositing::CanvasId> CompositorConnection::create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias, Vector<String>& out_supported_extensions)-{- if (!can_send_message_to_compositor())- return {};-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::CreateWebglContext>(webgl_version, size, depth, stencil, antialias);- if (!response) {- did_lose_compositor();- return {};- }- out_supported_extensions = response->take_supported_extensions();- if (!response->success())- return {};- return response->canvas_id();-}--void CompositorConnection::set_webgl_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer const& command_buffer)-{- if (!can_send_message_to_compositor())- return;-- auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglSetCommandBuffer::static_encode(canvas_id, command_buffer));- if (post_message(encoded_message).is_error())- did_lose_compositor();-}--void CompositorConnection::send_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)-{- if (!can_send_message_to_compositor())- return;-- auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommandsFromSharedBuffer::static_encode(canvas_id, offset, size_in_bytes, flush_sequence_number, frames));- if (post_message(encoded_message).is_error()) {- did_lose_compositor();- return;- }- note_video_frame_holds_sent_to_compositor(frames);-}--bool CompositorConnection::drain_webgl_command_buffer(Compositing::CanvasId canvas_id)-{- if (!can_send_message_to_compositor())- return false;-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::WebglDrainCommandBuffer>(canvas_id);- if (!response) {- did_lose_compositor();- return false;- }- return true;-}--void CompositorConnection::send_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)-{- if (!can_send_message_to_compositor())- return;-- auto shared_commands = MUST(Core::AnonymousBuffer::create_with_size(commands.size()));- commands.copy_to({ shared_commands.data<u8>(), shared_commands.size() });-- auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommands::static_encode(canvas_id, shared_commands, frames));- if (post_message(encoded_message).is_error()) {- did_lose_compositor();- return;- }- note_video_frame_holds_sent_to_compositor(frames);-}--void CompositorConnection::present_webgl_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer)-{- if (!can_send_message_to_compositor())- return;-- async_webgl_present_canvas(canvas_id, preserve_drawing_buffer);-}--void CompositorConnection::clear_webgl_drawing_buffer(Compositing::CanvasId canvas_id)-{- if (!can_send_message_to_compositor())- return;-- async_webgl_clear_drawing_buffer(canvas_id);-}--ByteBuffer CompositorConnection::webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request)-{- if (!can_send_message_to_compositor())- return {};-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::WebglSyncCall>(canvas_id, move(request));- if (!response) {- did_lose_compositor();- return {};- }- return response->take_reply();-}--Compositing::WebGL::ReadPixelsResult CompositorConnection::read_webgl_pixels(Compositing::CanvasId canvas_id, Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer const& pixels)-{- if (!can_send_message_to_compositor())- return {};-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::WebglReadPixels>(canvas_id, x, y, width, height, format, type, buf_size, pixels);- if (!response) {- did_lose_compositor();- return {};- }- return {- .length = response->length(),- .columns = response->columns(),- .rows = response->rows(),- };-}--bool CompositorConnection::read_webgl_buffer_sub_data(Compositing::CanvasId canvas_id, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer const& data)-{- if (!can_send_message_to_compositor())- return false;-- auto response = send_sync_but_allow_failure<Messages::CompositorWebContentServer::WebglReadBufferSubData>(canvas_id, target, offset, size, data);- if (!response) {- did_lose_compositor();- return false;- }- return response->success();-}-void CompositorConnection::request_screenshot(Web::CompositorContextId context_id, NonnullRefPtr<Gfx::Bitmap> target_bitmap, Function<void(ScreenshotResult)>&& callback){if (!can_send_message_to_compositor()) {@@ -1060,6 +925,10 @@ Optional<CompositorConnection::PendingScreenshot> CompositorConnection::take_scrextern "C" WEB_API bool web_compositor_post_fonts_and_image_frames(void* poster, u64 context_id, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count);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 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);extern "C" WEB_API void web_screenshot_request_destroy(void* request);extern "C" WEB_API bool web_compositor_stage_rasterization(void* poster, u64 token, void const* const* fonts, size_t font_count, void const* const* image_frames, size_t image_frame_count, void const* target_bitmap);@@ -1097,6 +966,36 @@ extern "C" WEB_API void web_compositor_shared_buffer_release(void* owner)delete static_cast<Web::Compositor::SharedBufferForRust*>(owner);}+extern "C" WEB_API int web_compositor_shared_buffer_clone_descriptor(void* owner)+{+ auto descriptor = IPC::File::clone_fd(static_cast<Web::Compositor::SharedBufferForRust*>(owner)->buffer.fd());+ if (descriptor.is_error())+ return -1;+ return descriptor.value().take_fd();+}++extern "C" WEB_API Gfx::DecodedImageFrame* web_compositor_shared_buffer_image_frame(void* owner, i32 width, i32 height)+{+ 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);+ if (frame.is_error())+ return nullptr;+ return new Gfx::DecodedImageFrame { frame.release_value() };+}++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())+ return false;+ *out_connection = connection->to_ffi_with_one_reference();+ return true;+}++extern "C" WEB_API bool web_compositor_connection_register_image_frames(Web::Compositor::CompositorConnection* connection, void const* const* image_frames, size_t image_frame_count)+{+ return connection->register_image_frames({ reinterpret_cast<Gfx::DecodedImageFrame const* const*>(image_frames), image_frame_count });+}+extern "C" WEB_API bool web_compositor_post_screenshot_request(void* poster, void* request_pointer){auto request = adopt_own(*static_cast<Web::Compositor::ScreenshotRequestForPaintThread*>(request_pointer));diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.hindex ced5a5900ec..599629e265c 100644--- a/Libraries/LibWeb/Compositor/CompositorConnection.h+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h@@ -15,7 +15,6 @@#include <Compositor/CompositorWebContentServerEndpoint.h>#include <LibCompositing/DisplayList/DisplayListResources.h>#include <LibCompositing/Types.h>-#include <LibCompositing/WebGL/Types.h>#include <LibGfx/Forward.h>#include <LibGfx/Point.h>#include <LibGfx/Rect.h>@@ -74,7 +73,8 @@ public: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);+ 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& = {});Optional<Web::Compositor::PlaceholderCanvasLink> allocate_placeholder_canvas();void release_placeholder_canvas(Compositing::CanvasId);@@ -105,17 +105,6 @@ public:// compositor has their frames, or once it is lost.void prepare_remote_descendants_for_screenshot(Web::CompositorContextId, Function<void()>&& callback);- Optional<Compositing::CanvasId> create_webgl_context(Compositing::WebGL::WebGLVersion, Gfx::IntSize, bool depth, bool stencil, bool antialias, Vector<String>& out_supported_extensions);- void set_webgl_command_buffer(Compositing::CanvasId, Core::AnonymousBuffer const&);- void send_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames);- bool drain_webgl_command_buffer(Compositing::CanvasId);- void send_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const& frames);- void present_webgl_canvas(Compositing::CanvasId, bool preserve_drawing_buffer);- void clear_webgl_drawing_buffer(Compositing::CanvasId);- ByteBuffer webgl_sync_call(Compositing::CanvasId, ByteBuffer request);- Compositing::WebGL::ReadPixelsResult read_webgl_pixels(Compositing::CanvasId, Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer const& pixels);- bool read_webgl_buffer_sub_data(Compositing::CanvasId, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer const& data);-void ensure_video_presentation_channel();void ensure_image_decoder_channel();// Takes up the render clock channel the Browser made between this process and the Compositor, which delivers@@ -154,7 +143,6 @@ private:virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) override;virtual void overlay_scrollbar_visibilities_changed(Vector<Web::OverlayScrollbarVisibility>) override;- bool can_send_message_to_compositor() const;void merge_async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates);Optional<PendingScreenshot> take_screenshot(Compositing::ScreenshotRequestId);diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cppindex 927e3ffa413..dbecd259d82 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp@@ -10,7 +10,6 @@#include <LibWeb/Compositor/CompositorConnection.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/Compositor/RenderClock.h>-#include <LibWeb/WebGL/RemoteWebGLTransport.h>// The Paint stage keeps what the compositor keeps of the display lists sent for each context.extern "C" void paint_stage_forget_destroyed_compositor_context(u64 context_id);@@ -178,120 +177,6 @@ void CompositorHost::discard_canvas_2d_stream()web_canvas_2d_stream_discard(m_canvas_2d_stream);}-class CompositorRemoteWebGLTransport final : public Web::WebGL::RemoteWebGLTransport {-public:- explicit CompositorRemoteWebGLTransport(NonnullRefPtr<CompositorConnection> connection)- : m_connection(move(connection))- {- }--private:- virtual CreateResult create_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize initial_size, bool depth, bool stencil, bool antialias) override- {- VERIFY(!m_canvas_id.has_value());- CreateResult result;- auto canvas_id = m_connection->create_webgl_context(webgl_version, initial_size, depth, stencil, antialias, result.supported_extensions);- if (canvas_id.has_value()) {- result.success = true;- m_canvas_id = *canvas_id;- }- return result;- }-- virtual Optional<Compositing::CanvasId> canvas_id() const override- {- return m_canvas_id;- }-- virtual void destroy_context() override- {- if (!m_canvas_id.has_value())- return;- m_connection->destroy_webgl_context(*m_canvas_id);- m_canvas_id.clear();- }-- virtual void set_shared_command_buffer(Core::AnonymousBuffer const& command_buffer) override- {- if (!m_canvas_id.has_value())- return;- m_connection->set_webgl_command_buffer(*m_canvas_id, command_buffer);- }-- virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) override- {- if (!m_canvas_id.has_value())- return;- m_connection->send_webgl_commands_from_shared_buffer(*m_canvas_id, offset, size_in_bytes, flush_sequence_number, frames);- }-- virtual bool wait_until_published_commands_executed() override- {- if (!m_canvas_id.has_value())- return false;- return m_connection->drain_webgl_command_buffer(*m_canvas_id);- }-- virtual void send_commands(ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) override- {- if (!m_canvas_id.has_value())- return;- m_connection->send_webgl_commands(*m_canvas_id, commands, frames);- }-- virtual void present_canvas(bool preserve_drawing_buffer) override- {- if (!m_canvas_id.has_value())- return;- m_connection->present_webgl_canvas(*m_canvas_id, preserve_drawing_buffer);- }-- virtual void clear_drawing_buffer() override- {- if (!m_canvas_id.has_value())- return;- m_connection->clear_webgl_drawing_buffer(*m_canvas_id);- }-- virtual ByteBuffer sync_call(ByteBuffer request) override- {- if (!m_canvas_id.has_value())- return {};- return m_connection->webgl_sync_call(*m_canvas_id, move(request));- }-- virtual Compositing::WebGL::ReadPixelsResult read_pixels_robust_angle(Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer pixels) override- {- if (!m_canvas_id.has_value())- return {};- return m_connection->read_webgl_pixels(*m_canvas_id, x, y, width, height, format, type, buf_size, pixels);- }-- virtual bool read_buffer_sub_data(Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data) override- {- if (!m_canvas_id.has_value())- return false;- return m_connection->read_webgl_buffer_sub_data(*m_canvas_id, target, offset, size, data);- }-- virtual Gfx::ShareableBitmap read_back_drawing_buffer(Gfx::IntRect const& rect) override- {- if (!m_canvas_id.has_value())- return {};- return m_connection->get_canvas_pixels(*m_canvas_id, rect);- }-- NonnullRefPtr<CompositorConnection> m_connection;- Optional<Compositing::CanvasId> m_canvas_id;-};--RefPtr<Web::WebGL::RemoteWebGLTransport> CompositorHost::create_webgl_transport()-{- if (auto* connection = compositor_connection())- return adopt_ref(*new CompositorRemoteWebGLTransport(*connection));- return nullptr;-}-Optional<Web::Compositor::PlaceholderCanvasLink> CompositorHost::allocate_placeholder_canvas(){if (auto* connection = compositor_connection())diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.hindex ab803deb444..4405da51422 100644--- a/Libraries/LibWeb/Compositor/CompositorHost.h+++ b/Libraries/LibWeb/Compositor/CompositorHost.h@@ -137,8 +137,6 @@ public:void flush_canvas_2d_stream();void discard_canvas_2d_stream();- RefPtr<WebGL::RemoteWebGLTransport> create_webgl_transport();-Optional<PlaceholderCanvasLink> allocate_placeholder_canvas();void release_placeholder_canvas(Compositing::CanvasId);void commit_placeholder_canvas(PlaceholderCanvasLink, Optional<Compositing::CanvasId> source_canvas_id, Gfx::IntSize, bool origin_clean);diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 5951f13bc5b..8d15dec4363 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1218,7 +1218,6 @@ class PeriodicWave;namespace Web::WebGL {-class RemoteWebGLTransport;class WebGL2RenderingContext;class WebGLRenderingContext;class WebGLRenderingContextBase;diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h b/Libraries/LibWeb/WebGL/RemoteWebGLTransport.hdeleted file mode 100644index d1dc2c5c676..00000000000--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h+++ /dev/null@@ -1,58 +0,0 @@-/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Optional.h>-#include <AK/RefCounted.h>-#include <AK/String.h>-#include <AK/Vector.h>-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>-#include <LibCompositing/Types.h>-#include <LibCompositing/WebGL/ImageSourceFrame.h>-#include <LibCore/AnonymousBuffer.h>-#include <LibGfx/Forward.h>-#include <LibGfx/ShareableBitmap.h>-#include <LibWeb/Export.h>-#include <LibWeb/WebGL/Types.h>--namespace Web::WebGL {--class WEB_API RemoteWebGLTransport : public RefCounted<RemoteWebGLTransport> {-public:- virtual ~RemoteWebGLTransport() = default;-- struct CreateResult {- bool success { false };- Vector<String> supported_extensions;- };- virtual CreateResult create_context(WebGLVersion, Gfx::IntSize initial_size, bool depth, bool stencil, bool antialias) = 0;- virtual Optional<Compositing::CanvasId> canvas_id() const = 0;- virtual void destroy_context() = 0;-- virtual void set_shared_command_buffer(Core::AnonymousBuffer const&) = 0;- virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) = 0;- virtual bool wait_until_published_commands_executed() = 0;-- virtual void send_commands(ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) = 0;- virtual void present_canvas(bool preserve_drawing_buffer) = 0;- virtual void clear_drawing_buffer() = 0;- virtual ByteBuffer sync_call(ByteBuffer request) = 0;- virtual ReadPixelsResult read_pixels_robust_angle(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei buf_size, Core::AnonymousBuffer pixels) = 0;- virtual bool read_buffer_sub_data(GLenum target, GLintptr offset, GLintptr size, Core::AnonymousBuffer data) = 0;-- virtual Gfx::ShareableBitmap read_back_drawing_buffer(Gfx::IntRect const&) = 0;-};--// NB: The frame is a Variant, which cannot be allocated with kmalloc itself.-struct ImageSourceFrameOwnedByRecorder {- AK_ALLOC_WITH_KMALLOC;-- Compositing::WebGL::ImageSourceFrame frame;-};--}diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cppindex 21d32f9853b..2145c9083c2 100644--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp@@ -4,33 +4,16 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ByteBuffer.h>-#include <AK/Vector.h>-#include <AK/kmalloc.h>+#include <LibCompositing/WebGL/Types.h>#include <LibCompositing/WebGL/WebGLCommandList.h>#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>-#include <LibCore/AnonymousBuffer.h>-#include <LibGfx/Bitmap.h>-#include <LibGfx/ShareableBitmap.h>-#include <LibIPC/Limits.h>#include <LibWeb/Loader/ResourceLoader.h>-#include <LibWeb/WebGL/RemoteWebGLTransport.h>-// The C ABI of RemoteWebGLTransport, for the WebGL command recorder in Libraries/LibWeb/Bindings/Rust/src/web_gl,-// which declares these functions in host.rs.-//-// The recorder holds a transport and a bitmap as a pointer that owns one reference, and an anonymous buffer and an-// image frame as a pointer to an AnonymousBufferOwnedByRecorder or an ImageSourceFrameOwnedByRecorder that it owns.+// What the WebGL implementation in Libraries/LibWeb/Bindings/Rust/src/web_gl asks of the rest of LibWeb besides its+// canvas.namespace Web::WebGL {-// NB: `ReadPixelsResult` of proxy/transport.rs is three `i32`s in this order.-static_assert(sizeof(ReadPixelsResult) == 3 * sizeof(i32));-static_assert(offsetof(ReadPixelsResult, length) == 0);-static_assert(offsetof(ReadPixelsResult, columns) == sizeof(i32));-static_assert(offsetof(ReadPixelsResult, rows) == 2 * sizeof(i32));-static_assert(sizeof(Compositing::CanvasId) == sizeof(u64));-// What the WebGL implementation in Rust states for itself besides the command structs: the framing and the shared// data region that the recorder and the replayer of the command stream have to agree on, and the largest drawing// buffer that the compositor allocates. Rust compares its own constants with these before the first context records@@ -58,138 +41,8 @@ static_assert(offsetof(Compositing::WebGL::WebGLDataSpan, size) == sizeof(u32));extern "C" {-void web_webgl_transport_unref(void* transport);-bool web_webgl_transport_canvas_id(void const* transport, u64* out_canvas_id);-void web_webgl_transport_destroy_context(void* transport);-void web_webgl_transport_set_shared_command_buffer(void* transport, void const* anonymous_buffer);-void web_webgl_transport_send_commands_from_shared_buffer(void* transport, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, void const* const* frames, size_t frame_count);-bool web_webgl_transport_wait_until_published_commands_executed(void* transport);-void web_webgl_transport_send_commands(void* transport, u8 const* commands, size_t size_in_bytes, void const* const* frames, size_t frame_count);-void web_webgl_transport_present_canvas(void* transport, bool preserve_drawing_buffer);-void web_webgl_transport_clear_drawing_buffer(void* transport);-void web_webgl_transport_sync_call(void* transport, u8 const* request, size_t request_size, void* reply_sink, void (*write_reply)(void* reply_sink, u8 const* reply, size_t reply_size));-void web_webgl_transport_read_pixels_robust_angle(void* transport, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, void const* pixels_anonymous_buffer_or_null, ReadPixelsResult* out_result);-bool web_webgl_transport_read_buffer_sub_data(void* transport, u32 target, i64 offset, i64 size, void const* data_anonymous_buffer);-void* web_webgl_transport_read_back_drawing_buffer(void* transport, i32 x, i32 y, i32 width, i32 height);-size_t web_webgl_max_frames_per_message();u8 web_navigator_compatibility_mode();void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constants);-void* web_webgl_anonymous_buffer_create(size_t size, u8** out_data);-void web_webgl_anonymous_buffer_destroy(void* anonymous_buffer);-void web_webgl_frame_destroy(void* frame);-}--static RemoteWebGLTransport& transport_from(void* transport)-{- return *static_cast<RemoteWebGLTransport*>(transport);-}--// NB: Core::AnonymousBuffer cannot be allocated with kmalloc itself: a class that derives from it and from a-// ref-counted base would then have two operator new.-struct AnonymousBufferOwnedByRecorder {- AK_ALLOC_WITH_KMALLOC;-- Core::AnonymousBuffer buffer;-};--static Core::AnonymousBuffer const& anonymous_buffer_from(void const* anonymous_buffer)-{- return static_cast<AnonymousBufferOwnedByRecorder const*>(anonymous_buffer)->buffer;-}--static Vector<Compositing::WebGL::ImageSourceFrame> copy_frames(void const* const* frames, size_t frame_count)-{- Vector<Compositing::WebGL::ImageSourceFrame> copied_frames;- copied_frames.ensure_capacity(frame_count);- for (size_t i = 0; i < frame_count; ++i)- copied_frames.unchecked_append(static_cast<ImageSourceFrameOwnedByRecorder const*>(frames[i])->frame);- return copied_frames;-}--void web_webgl_transport_unref(void* transport)-{- transport_from(transport).unref();-}--bool web_webgl_transport_canvas_id(void const* transport, u64* out_canvas_id)-{- auto canvas_id = static_cast<RemoteWebGLTransport const*>(transport)->canvas_id();- if (!canvas_id.has_value())- return false;- *out_canvas_id = canvas_id->value();- return true;-}--void web_webgl_transport_destroy_context(void* transport)-{- transport_from(transport).destroy_context();-}--void web_webgl_transport_set_shared_command_buffer(void* transport, void const* anonymous_buffer)-{- transport_from(transport).set_shared_command_buffer(anonymous_buffer_from(anonymous_buffer));-}--void web_webgl_transport_send_commands_from_shared_buffer(void* transport, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, void const* const* frames, size_t frame_count)-{- transport_from(transport).send_commands_from_shared_buffer(offset, size_in_bytes, flush_sequence_number, copy_frames(frames, frame_count));-}--bool web_webgl_transport_wait_until_published_commands_executed(void* transport)-{- return transport_from(transport).wait_until_published_commands_executed();-}--void web_webgl_transport_send_commands(void* transport, u8 const* commands, size_t size_in_bytes, void const* const* frames, size_t frame_count)-{- transport_from(transport).send_commands({ commands, size_in_bytes }, copy_frames(frames, frame_count));-}--void web_webgl_transport_present_canvas(void* transport, bool preserve_drawing_buffer)-{- transport_from(transport).present_canvas(preserve_drawing_buffer);-}--void web_webgl_transport_clear_drawing_buffer(void* transport)-{- transport_from(transport).clear_drawing_buffer();-}--void web_webgl_transport_sync_call(void* transport, u8 const* request, size_t request_size, void* reply_sink, void (*write_reply)(void* reply_sink, u8 const* reply, size_t reply_size))-{- auto reply = transport_from(transport).sync_call(MUST(ByteBuffer::copy(request, request_size)));- write_reply(reply_sink, reply.data(), reply.size());-}--void web_webgl_transport_read_pixels_robust_angle(void* transport, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, void const* pixels_anonymous_buffer_or_null, ReadPixelsResult* out_result)-{- Core::AnonymousBuffer pixels;- if (pixels_anonymous_buffer_or_null)- pixels = anonymous_buffer_from(pixels_anonymous_buffer_or_null);- *out_result = transport_from(transport).read_pixels_robust_angle(x, y, width, height, format, type, buf_size, move(pixels));-}--bool web_webgl_transport_read_buffer_sub_data(void* transport, u32 target, i64 offset, i64 size, void const* data_anonymous_buffer)-{- return transport_from(transport).read_buffer_sub_data(target, offset, size, anonymous_buffer_from(data_anonymous_buffer));-}--void* web_webgl_transport_read_back_drawing_buffer(void* transport, i32 x, i32 y, i32 width, i32 height)-{- auto shareable_bitmap = transport_from(transport).read_back_drawing_buffer({ x, y, width, height });- if (!shareable_bitmap.is_valid())- return nullptr;- auto frame = Gfx::DecodedImageFrame::create(*shareable_bitmap.bitmap());- if (frame.is_error())- return nullptr;- return new Gfx::DecodedImageFrame { frame.release_value() };-}--size_t web_webgl_max_frames_per_message()-{- // NB: The bytes of the commands take one of the attachments of a message.- static_assert(IPC::MAX_MESSAGE_FD_COUNT > 1);- return IPC::MAX_MESSAGE_FD_COUNT - 1;}// The navigator compatibility mode, numbered as Web::NavigatorCompatibilityMode is: Chrome, Gecko, WebKit.@@ -210,24 +63,4 @@ void web_webgl_constants_restated_in_rust(ConstantsRestatedInRust* out_constants};}-void* web_webgl_anonymous_buffer_create(size_t size, u8** out_data)-{- auto buffer_or_error = Core::AnonymousBuffer::create_with_size(size);- if (buffer_or_error.is_error())- return nullptr;- auto* owned_buffer = new AnonymousBufferOwnedByRecorder { buffer_or_error.release_value() };- *out_data = owned_buffer->buffer.data<u8>();- return owned_buffer;-}--void web_webgl_anonymous_buffer_destroy(void* anonymous_buffer)-{- delete static_cast<AnonymousBufferOwnedByRecorder*>(anonymous_buffer);-}--void web_webgl_frame_destroy(void* frame)-{- delete static_cast<ImageSourceFrameOwnedByRecorder*>(frame);-}-}diff --git a/Libraries/LibWeb/WebGL/Types.h b/Libraries/LibWeb/WebGL/Types.hdeleted file mode 100644index c99394b41b8..00000000000--- a/Libraries/LibWeb/WebGL/Types.h+++ /dev/null@@ -1,44 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibCompositing/WebGL/GLFunctions.h>-#include <LibCompositing/WebGL/TextureUpload.h>-#include <LibCompositing/WebGL/Types.h>-#include <LibCompositing/WebGL/WebGLCommandList.h>-#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>--// The WebGL objects LibWeb implements speak the command stream LibCompositing defines.--namespace Web::WebGL {--namespace Commands = Compositing::WebGL::Commands;-namespace SyncCalls = Compositing::WebGL::SyncCalls;--using Compositing::WebGL::GLchar;-using Compositing::WebGL::GLenum;-using Compositing::WebGL::GLFunctions;-using Compositing::WebGL::GLint;-using Compositing::WebGL::GLintptr;-using Compositing::WebGL::GLsizei;-using Compositing::WebGL::GLsyncInternal;-using Compositing::WebGL::GLuint;-using Compositing::WebGL::max_webgl_drawing_buffer_dimension;-using Compositing::WebGL::ReadPixelsResult;-using Compositing::WebGL::texture_export_format;-using Compositing::WebGL::WebGLCommandHeader;-using Compositing::WebGL::WebGLCommandList;-using Compositing::WebGL::WebGLCommandType;-using Compositing::WebGL::WebGLDataSpan;-using Compositing::WebGL::WebGLObjectId;-using Compositing::WebGL::WebGLSharedCommandBuffer;-using Compositing::WebGL::WebGLSyncCall;-using Compositing::WebGL::WebGLSyncCallHeader;-using Compositing::WebGL::WebGLSyncCallType;-using Compositing::WebGL::WebGLVersion;--}diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cppindex 71374cea6c4..b478e5e7ce9 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp@@ -9,7 +9,6 @@#include <AK/Utf16FlyString.h>#include <AK/Vector.h>-#include <LibCompositing/WebGL/TextureUpload.h>#include <LibGfx/Bitmap.h>#include <LibGfx/DecodedImageFrame.h>#include <LibJS/HostClassBuilder.h>@@ -17,19 +16,16 @@#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/DOM/EventTarget.h>#include <LibWeb/HTML/Canvas/CanvasHost.h>#include <LibWeb/HTML/EventLoop/Task.h>#include <LibWeb/HTML/HTMLCanvasElement.h>#include <LibWeb/HTML/HTMLImageElement.h>-#include <LibWeb/HTML/HTMLVideoElement.h>#include <LibWeb/HTML/OffscreenCanvas.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Page/Page.h>#include <LibWeb/WebGL/EventNames.h>-#include <LibWeb/WebGL/RemoteWebGLTransport.h>#include <LibWeb/WebGL/WebGL2RenderingContext.h>#include <LibWeb/WebGL/WebGLRenderingContext.h>#include <LibWeb/WebGL/WebGLRenderingContextBase.h>@@ -40,31 +36,21 @@ namespace {// `ContextCreationArguments` of Bindings/Rust/src/web_gl/exports.rs.struct ContextCreationArguments {- void* transport { nullptr };bool is_webgl2 { false };void* realm { nullptr };void* canvas { nullptr };void* canvas_host { nullptr };bool canvas_is_offscreen { false };ContextAttributes context_attributes;- ReadonlySpan<ReadonlyBytes> supported_extensions;};-// `TexImageSourceKind` and `TexImageSourceResult` of Bindings/Rust/src/web_gl/canvas.rs. The kinds are the sources-// that are implemented in C++.+// `TexImageSourceKind` of Bindings/Rust/src/web_gl/canvas.rs: the sources whose frame LibWeb reads.enum class TexImageSourceKind : u8 {HTMLImageElement,HTMLCanvasElement,- HTMLVideoElement,OffscreenCanvas,};-enum class TexImageSourceResult : u8 {- Frame,- NoFrame,- InvalidValue,-};-}extern "C" {@@ -72,7 +58,6 @@ extern "C" {// Defined in Bindings/Rust/src/web_gl/exports.rs. A context is the cell of a context of either kind.void* web_webgl_context_create(JSVM*, ContextCreationArguments const*);void* web_webgl_context_canvas_host(void* context);-bool web_webgl_context_is_webgl2(void* context);bool web_webgl_context_is_lost(void* context);bool web_webgl_context_canvas_id(void* context, u64* out_canvas_id);void web_webgl_context_set_size(void* context, i32 width, i32 height);@@ -82,8 +67,7 @@ void* web_webgl_context_read_back_drawing_buffer(void* context, i32 x, i32 y, i3bool web_webgl_context_mark_lost(void* context);void web_webgl_context_set_restore_requested(void* context, bool requested);bool web_webgl_context_wants_restoring(void* context);-void web_webgl_context_actual_context_parameters(void* context, ContextAttributes* out_context_attributes);-void web_webgl_context_restore(void* context, void* transport, ReadonlySpan<ReadonlyBytes> supported_extensions);+bool web_webgl_context_restore(void* context);void* web_webgl_context_event_create(JSVM*, void* realm, FlatPtr type);bool web_webgl_context_attributes_from_value(JSVM*, JSValue, ContextAttributes* out_context_attributes, JSValue* out_exception);@@ -93,9 +77,7 @@ void web_webgl_canvas_bitmap_size(void* canvas_host, i32* out_width, i32* out_hevoid* web_webgl_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm);void* web_webgl_canvas_relevant_realm(void* canvas_host);bool web_webgl_expose_experimental_interfaces();-TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind, u32 format, u32 type, void** out_frame);-TexImageSourceResult web_webgl_read_tex_image_frame(Gfx::DecodedImageFrame const* image_frame, u32 format, u32 type, void** out_frame);-TexImageSourceResult web_webgl_read_tex_image_pixels(u8 const* pixels, u32 width, u32 height, u32 format, u32 type, void** out_frame);+Gfx::DecodedImageFrame* web_webgl_texture_image_frame(void* source_wrapper, TexImageSourceKind);}static void* cell_of(WebGLRenderingContextBase const& context)@@ -135,77 +117,28 @@ static void fire_webgl_context_creation_error(HTML::CanvasHost& canvas)fire_webgl_context_event(canvas, EventNames::webglcontextcreationerror);}-// The drawing buffer's creation-time size, clamped like set_size() clamps resizes;-// later resizes travel as SetDrawingBufferSize commands.-static Gfx::IntSize initial_drawing_buffer_size(HTML::CanvasHost& canvas)-{- auto size = canvas.bitmap_size_for_canvas();- return {- clamp(size.width(), 1, max_webgl_drawing_buffer_dimension),- clamp(size.height(), 1, max_webgl_drawing_buffer_dimension),- };-}--namespace {--struct RemoteWebGLContext {- NonnullRefPtr<RemoteWebGLTransport> transport;- Vector<String> supported_extensions;-- Vector<ReadonlyBytes> supported_extension_spans() const- {- Vector<ReadonlyBytes> spans;- spans.ensure_capacity(supported_extensions.size());- for (auto const& extension : supported_extensions)- spans.unchecked_append(extension.bytes());- return spans;- }-};--Optional<RemoteWebGLContext> create_remote_webgl_context(HTML::CanvasHost& canvas, WebGLVersion webgl_version, bool depth, bool stencil, bool antialias)-{- auto& page = canvas.canvas_page();- if (!page.has_compositor_host())- return {};- auto transport = page.compositor_host().create_webgl_transport();- if (!transport)- return {};-- auto result = transport->create_context(webgl_version, initial_drawing_buffer_size(canvas), depth, stencil, antialias);- if (!result.success)- return {};-- // NB: The display list must be re-recorded so its DrawCanvas command refers to the new remote context's- // canvas id. Content updates alone don't invalidate the display list, so do it here.- canvas.did_create_canvas_backing_storage();-- return RemoteWebGLContext { transport.release_nonnull(), move(result.supported_extensions) };-}--}-WebGLRenderingContextBase* WebGLRenderingContextBase::create(JS::Realm& realm, CanvasOwner canvas, ContextAttributes const& context_attributes, WebGLVersion webgl_version){// We should be coming here from getContext being called on a wrapped <canvas> element or OffscreenCanvas.auto& canvas_host = canvas_host_for(canvas);- auto remote = create_remote_webgl_context(canvas_host, webgl_version, context_attributes.depth, context_attributes.stencil, context_attributes.antialias);- if (!remote.has_value()) {- fire_webgl_context_creation_error(canvas_host);- return nullptr;- }-- auto supported_extensions = remote->supported_extension_spans();ContextCreationArguments arguments {- .transport = &remote->transport.leak_ref(),.is_webgl2 = webgl_version == WebGLVersion::WebGL2,.realm = &realm,.canvas = canvas.visit([](auto const& canvas) -> void* { return static_cast<GC::Cell*>(canvas.ptr()); }),.canvas_host = &canvas_host,.canvas_is_offscreen = canvas.has<GC::Ref<HTML::OffscreenCanvas>>(),.context_attributes = context_attributes,- .supported_extensions = supported_extensions.span(),};- return static_cast<WebGLRenderingContextBase*>(web_webgl_context_create(JS::HostABI::vm_to_abi(realm.vm()), &arguments));+ auto* context = static_cast<WebGLRenderingContextBase*>(web_webgl_context_create(JS::HostABI::vm_to_abi(realm.vm()), &arguments));+ if (!context) {+ fire_webgl_context_creation_error(canvas_host);+ return nullptr;+ }++ // NB: The display list must be re-recorded so its DrawCanvas command refers to the new remote context's+ // canvas id. Content updates alone don't invalidate the display list, so do it here.+ canvas_host.did_create_canvas_backing_storage();+ return context;}GC::Ptr<WebGLRenderingContext> WebGLRenderingContext::create(JS::Realm& realm, CanvasOwner canvas, ContextAttributes const& context_attributes)@@ -278,15 +211,9 @@ void WebGLRenderingContextBase::restore_context_after_compositor_reconnect()// A fresh host context starts with no GL objects; per the spec the page re-creates them// in its webglcontextrestored handler.- ContextAttributes actual_context_parameters;- web_webgl_context_actual_context_parameters(this, &actual_context_parameters);- auto webgl_version = web_webgl_context_is_webgl2(this) ? WebGLVersion::WebGL2 : WebGLVersion::WebGL1;- auto remote = create_remote_webgl_context(canvas_host(), webgl_version, actual_context_parameters.depth, actual_context_parameters.stencil, actual_context_parameters.antialias);- if (!remote.has_value())+ if (!web_webgl_context_restore(this))return;-- auto supported_extensions = remote->supported_extension_spans();- web_webgl_context_restore(this, &remote->transport.leak_ref(), supported_extensions.span());+ canvas_host().did_create_canvas_backing_storage();HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](WebGLRenderingContextBase& self) {fire_webgl_context_event(self.canvas_host(), EventNames::webglcontextrestored);@@ -325,73 +252,28 @@ bool web_webgl_expose_experimental_interfaces()return HTML::WindowOrWorkerGlobalScopeMixin::expose_experimental_interfaces();}-// The frame that a texture image source uploads, which the recorder takes over, if this format and type upload one.-static TexImageSourceResult tex_image_source_frame(Optional<Compositing::WebGL::ImageSourceFrame> frame, u32 format, u32 type, void** out_frame)-{- if (!frame.has_value())- return TexImageSourceResult::NoFrame;-- // Validate the combination before recording; the pixels travel to the host as shared- // memory and the host performs the conversion next to GL.- if (!texture_export_format(format, type).has_value())- return TexImageSourceResult::NoFrame;-- // FIXME: Respect unpackColorSpace- *out_frame = new ImageSourceFrameOwnedByRecorder { frame.release_value() };- return TexImageSourceResult::Frame;-}--TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind source_kind, u32 format, u32 type, void** out_frame)+// The frame that a texture upload from an image or a canvas takes, allocated with new, or null.+Gfx::DecodedImageFrame* web_webgl_texture_image_frame(void* source_wrapper, TexImageSourceKind source_kind){// FIXME: If source is null then an INVALID_VALUE error is generated.auto& wrapper = *static_cast<JS::Object*>(source_wrapper);- Optional<Compositing::WebGL::ImageSourceFrame> frame;+ Optional<Gfx::DecodedImageFrame> frame;switch (source_kind) {case TexImageSourceKind::HTMLImageElement:- if (auto image_frame = Bindings::impl_from<HTML::HTMLImageElement>(wrapper).current_image_frame(); image_frame.has_value())- frame = image_frame.release_value();+ // NB: The frame of an animated image that the Compositor moves through has another id than this one.+ frame = Bindings::impl_from<HTML::HTMLImageElement>(wrapper).default_image_frame();break;case TexImageSourceKind::HTMLCanvasElement:- if (auto canvas_frame = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_srgb_frame_from_surface(); canvas_frame.has_value())- frame = canvas_frame.release_value();+ frame = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_srgb_frame_from_surface();break;case TexImageSourceKind::OffscreenCanvas:- if (auto canvas_frame = Bindings::impl_from<HTML::OffscreenCanvas>(wrapper).get_srgb_frame_from_surface(); canvas_frame.has_value())- frame = canvas_frame.release_value();- break;- case TexImageSourceKind::HTMLVideoElement:- if (auto captured_frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).capture_current_video_frame(); captured_frame.has_value())- frame = captured_frame.release_value();+ frame = Bindings::impl_from<HTML::OffscreenCanvas>(wrapper).get_srgb_frame_from_surface();break;}- return tex_image_source_frame(move(frame), format, type, out_frame);-}--// The bitmap data of an ImageBitmap.-TexImageSourceResult web_webgl_read_tex_image_frame(Gfx::DecodedImageFrame const* image_frame, u32 format, u32 type, void** out_frame)-{- return tex_image_source_frame(Compositing::WebGL::ImageSourceFrame { *image_frame }, format, type, out_frame);-}--// The pixels of an ImageData, which are copied: script can change them, and detach or free their buffer, before the-// recorder sends the frame.-TexImageSourceResult web_webgl_read_tex_image_pixels(u8 const* pixels, u32 width, u32 height, u32 format, u32 type, void** out_frame)-{- // NB: Check the format first, so that pixels that are not uploaded are not copied.- if (!texture_export_format(format, type).has_value())- return TexImageSourceResult::NoFrame;-- // NB: The bitmap is shareable, so that the frame shares its memory instead of copying the pixels again.- auto bitmap = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, { static_cast<int>(width), static_cast<int>(height) });- if (bitmap.is_error())- return TexImageSourceResult::InvalidValue;- auto row_size = static_cast<size_t>(width) * sizeof(u32);- for (u32 y = 0; y < height; ++y)- memcpy(bitmap.value()->scanline_u8(static_cast<int>(y)), pixels + y * row_size, row_size);- auto pixels_frame = Gfx::DecodedImageFrame::create(*bitmap.value());- if (pixels_frame.is_error())- return TexImageSourceResult::InvalidValue;- return tex_image_source_frame(Compositing::WebGL::ImageSourceFrame { pixels_frame.release_value() }, format, type, out_frame);+ // FIXME: Respect unpackColorSpace+ if (!frame.has_value())+ return nullptr;+ return new Gfx::DecodedImageFrame { frame.release_value() };}}diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.hindex ea4bf2a8878..713d67b3cb5 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h@@ -10,6 +10,7 @@#include <AK/RefPtr.h>#include <AK/Variant.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>+#include <LibCompositing/WebGL/Types.h>#include <LibGC/Ptr.h>#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Forward.h>@@ -19,10 +20,11 @@#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>-#include <LibWeb/WebGL/Types.h>namespace Web::WebGL {+using Compositing::WebGL::WebGLVersion;+using CanvasOwner = Variant<GC::Ref<HTML::HTMLCanvasElement>, GC::Ref<HTML::OffscreenCanvas>>;HTML::CanvasHost& canvas_host_for(CanvasOwner const&);diff --git a/Meta/Generators/generate_compositor_webgl_replayer.py b/Meta/Generators/generate_compositor_webgl_replayer.pydeleted file mode 100644index 4a64732acea..00000000000--- a/Meta/Generators/generate_compositor_webgl_replayer.py+++ /dev/null@@ -1,353 +0,0 @@-#!/usr/bin/env python3--# Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>-#-# SPDX-License-Identifier: BSD-2-Clause--import re-import sys--from io import StringIO-from pathlib import Path-from typing import TextIO--sys.path.append(str(Path(__file__).resolve().parent))--from libweb_webgl import command_name-from libweb_webgl import deref_type-from libweb_webgl import is_const_pointer-from libweb_webgl import is_pointer-from libweb_webgl import is_wire_command-from libweb_webgl import is_wire_sync-from libweb_webgl import method_name-from libweb_webgl import run_generator-from libweb_webgl import snake_case-from libweb_webgl import sync_reply_fields--# Generates the Compositor-side replayer for the WebGL command stream: one-# replay_webgl_command() overload per command. The stream crosses a process boundary, so-# every payload span is asserted against the size the command's own fields imply before-# anything reaches GL; object ids are translated through WebGLObjectMap. GL-level-# validation stays in ANGLE (the host context runs with EGL_CONTEXT_WEBGL_COMPATIBILITY_ANGLE),-# exactly as it did when WebGL lived in WebContent.---def element_type(pointer_type: str):- base = pointer_type.replace("const", "").replace("*", "").strip()- return None if base in ("void", "GLchar") else base---def rewrite_size_expression(expression: str, function: dict, holder: str = "command") -> str:- # Wire fields are GLsizei/GLint (32-bit) and arrive unvalidated from WebContent. Widen- # each to i64 before it participates in the size product so that an attacker-chosen- # count cannot overflow the multiplication (which is signed-overflow UB, and on a- # wraparound to a small value would let a mismatched payload pass the size check).- for arg_name in sorted((a["name"] for a in function["args"]), key=len, reverse=True):- expression = re.sub(- rf"\b{re.escape(arg_name)}\b", f"static_cast<i64>({holder}.{snake_case(arg_name)})", expression- )- return expression---def emit_payload_resolution(lines: list, function: dict, arg: dict) -> str:- field = snake_case(arg["name"])- expression = rewrite_size_expression(arg["payload"], function)- size_check = f"static_cast<i64>({field}_bytes.size()) != static_cast<i64>({expression})"- if arg.get("nullable"):- lines.append(f" ReadonlyBytes {field}_bytes;")- lines.append(f" if (command.has_{field}) {{")- lines.append(f" if (command.{field}.size != 0)")- lines.append(f" {field}_bytes = WebGLCommandList::resolve_data_span(payload, command.{field});")- lines.append(f" VERIFY(!({size_check}));")- lines.append(" } else {")- lines.append(f" VERIFY(command.{field}.size == 0);")- lines.append(" }")- else:- lines.append(f" auto {field}_bytes = WebGLCommandList::resolve_data_span(payload, command.{field});")- lines.append(f" VERIFY(!({size_check}));")-- typed = element_type(arg["type"])- if typed:- if arg.get("nullable"):- lines.append(f" Span<{typed} const> {field};")- lines.append(f" if (command.has_{field} && command.{field}.size != 0)")- lines.append(f" {field} = WebGLCommandList::resolve_typed_span<{typed}>(payload, command.{field});")- else:- lines.append(f" auto {field} = WebGLCommandList::resolve_typed_span<{typed}>(payload, command.{field});")- data_expression = f"{field}.data()"- else:- data_expression = f"{field}_bytes.data()"- if arg.get("nullable"):- return f"command.has_{field} ? {data_expression} : nullptr"- return data_expression---def emit_command_body(out: TextIO, function: dict) -> bool:- lines: list = []- call_args: list = []- payload_used = False- deletes = function.get("deletes_objects", False)-- for arg in function["args"]:- field = snake_case(arg["name"])- if arg.get("string"):- payload_used = True- lines.append(f" auto {field}_bytes = WebGLCommandList::resolve_string_span(payload, command.{field});")- call_args.append(f"reinterpret_cast<GLchar const*>({field}_bytes.data())")- elif arg.get("offset"):- call_args.append(f"reinterpret_cast<void const*>(static_cast<uintptr_t>(command.{field}))")- elif arg.get("object") and not is_pointer(arg):- if arg["type"] == "GLsync":- lookup = "take_sync" if deletes else "lookup_sync"- lines.append(f" auto {field} = objects.{lookup}(command.{field});")- elif arg.get("zero_means_default"):- # The JSON names the OpenGLContext getter that supplies the host-side- # object for client id 0.- default_getter = arg["zero_means_default"]- assert default_getter in (- "default_framebuffer",- "default_renderbuffer",- ), f"unknown zero_means_default getter {default_getter!r} on {function['name']}.{arg['name']}"- lines.append(- f" GLuint {field} = command.{field} ? objects.lookup(command.{field}) : gl.{default_getter}();"- )- else:- lookup = "take" if deletes else "lookup"- lines.append(f" auto {field} = objects.{lookup}(command.{field});")- call_args.append(field)- elif arg.get("object") and is_const_pointer(arg):- payload_used = True- data_expression = emit_payload_resolution(lines, function, arg)- assert data_expression == f"{field}.data()", "object arrays are typed WebGLObjectId spans"- lines.append(f" Vector<GLuint> {field}_names;")- lines.append(f" {field}_names.ensure_capacity({field}.size());")- lines.append(f" for (auto id : {field})")- lines.append(f" {field}_names.unchecked_append(objects.{'take' if deletes else 'lookup'}(id));")- call_args.append(f"{field}_names.data()")- elif "payload" in arg:- payload_used = True- call_args.append(emit_payload_resolution(lines, function, arg))- else:- call_args.append(f"command.{field}")-- lines.append(f" gl.{method_name(function)}({', '.join(call_args)});")- out.write("\n".join(lines) + "\n")- return payload_used---def emit_gen_body(out: TextIO, function: dict) -> bool:- if function["return"] != "void":- scalar_args = ", ".join(f"command.{snake_case(a['name'])}" for a in function["args"])- add = "add_sync" if function["return"] == "GLsync" else "add"- out.write(f" TRY(objects.{add}(command.id, gl.{method_name(function)}({scalar_args})));\n")- return False-- # glGen*(GLsizei n, GLuint* out) shape: the span carries the client-allocated ids.- count_field = snake_case(function["args"][0]["name"])- span_field = snake_case(function["args"][1]["name"])- out.write(f""" auto ids = WebGLCommandList::resolve_typed_span<WebGLObjectId>(payload, command.{span_field});- VERIFY(static_cast<i64>(ids.size()) == static_cast<i64>(command.{count_field}));- for (auto id : ids) {{- GLuint name = 0;- gl.{method_name(function)}(1, &name);- TRY(objects.add(id, name));- }}-""")- return True---def signature(function: dict, payload_used: bool) -> str:- uses_command = function["category"] == "gen" or function["args"]- uses_objects = function["category"] == "gen" or any(a.get("object") for a in function["args"])- command = "const& command" if uses_command else "const&"- objects = "WebGLObjectMap& objects" if uses_objects else "WebGLObjectMap&"- payload = "ReadonlyBytes payload" if payload_used else "ReadonlyBytes"- return (- f"ErrorOr<void> replay_webgl_command(OpenGLContext& gl, {objects}, "- f"Compositing::WebGL::Commands::{command_name(function)} {command}, {payload})"- )---def emit_sync_body(out: TextIO, function: dict) -> tuple:- lines: list = []- call_args: list = []- out_blobs: list = [] # field names of Vector-backed reply blobs, in arg order- payload_used = False- objects_used = False-- for arg in function["args"]:- field = snake_case(arg["name"])- # An arg-level "host_override" in GLFunctions.json replaces the wire value with a- # host-chosen constant (e.g. a page must never be able to block the compositor).- override = arg.get("host_override")- if override is not None:- call_args.append(override)- elif arg.get("out"):- if "payload" in arg:- element = deref_type(arg["type"])- expression = rewrite_size_expression(arg["payload"], function, "request")- lines.append(f" auto {field}_byte_size = static_cast<size_t>({expression});")- lines.append(f" Vector<{element}> {field};")- lines.append(f" {field}.resize({field}_byte_size / sizeof({element}));")- call_args.append(f"{field}.data()")- out_blobs.append((field, element))- else:- lines.append(f" {deref_type(arg['type'])} {field} {{}};")- call_args.append(f"&{field}")- elif arg.get("object") and not is_pointer(arg):- objects_used = True- lookup = "lookup_sync" if arg["type"] == "GLsync" else "lookup"- lines.append(f" auto {field} = objects.{lookup}(request.{field});")- call_args.append(field)- elif arg.get("string"):- payload_used = True- lines.append(f" auto {field}_bytes = WebGLCommandList::resolve_string_span(payload, request.{field});")- call_args.append(f"reinterpret_cast<GLchar const*>({field}_bytes.data())")- elif "payload" in arg:- payload_used = True- element = deref_type(arg["type"].replace("const", "").strip())- expression = rewrite_size_expression(arg["payload"], function, "request")- lines.append(- f" auto {field} = WebGLCommandList::resolve_typed_span<{element}>(payload, request.{field});"- )- lines.append(- f" VERIFY(static_cast<i64>({field}.size() * sizeof({element})) == static_cast<i64>({expression}));"- )- call_args.append(f"{field}.data()")- else:- call_args.append(f"request.{field}")-- invocation = f"gl.{method_name(function)}({', '.join(call_args)});"- if function["return"] != "void":- invocation = "auto return_value = " + invocation- lines.append(f" {invocation}")-- # Assemble the reply: span fields point at the Vector blobs, laid out in order.- reply_type = f"SyncCalls::{command_name(function)}::Reply"- blob_spans = []- for index, (field, element) in enumerate(out_blobs):- if index == 0:- offset = f"WebGLCommandList::first_inline_data_offset(sizeof({reply_type}))"- else:- offset = f"WebGLCommandList::next_inline_data_offset({out_blobs[index - 1][0]}_span)"- lines.append(- f" WebGLDataSpan {field}_span {{ {offset}, static_cast<u32>({field}.size() * sizeof({element})) }};"- )- blob_spans.append(field)-- initializers = []- for _, field_name, arg in sync_reply_fields(function):- if arg is not None and "payload" in arg:- initializers.append(f".{field_name} = {field_name}_span")- else:- initializers.append(f".{field_name} = {field_name}")- lines.append(f" {reply_type} reply {{ {', '.join(initializers)} }};")-- blob_arguments = "".join(- f", ReadonlyBytes {{ {field}.data(), {field}.size() * sizeof({element}) }}" for field, element in out_blobs- )- lines.append(f" return WebGLSyncCall::encode_reply(reply{blob_arguments});")-- out.write("\n".join(lines) + "\n")- return payload_used, objects_used---def sync_signature(function: dict, payload_used: bool, objects_used: bool) -> str:- name = command_name(function)- request = "const& request" if function["args"] else "const&"- objects = "WebGLObjectMap& objects" if objects_used else "WebGLObjectMap&"- payload = "ReadonlyBytes payload" if payload_used else "ReadonlyBytes"- return (- # The dispatcher invokes these through a templated callback. Some compilers do not- # count that dependent call as a reference for -Wunused-function, even though the- # overload is required at runtime for its sync-call type. Keep the generated local- # handlers and make that intent explicit.- f"[[maybe_unused]] static ByteBuffer handle_one(OpenGLContext& gl, {objects}, SyncCalls::{name}::Request {request}, {payload})"- )---def write_header_file(out: TextIO, functions: list) -> None:- out.write("""#pragma once--#include <AK/Error.h>-#include <Compositor/WebGLObjectMap.h>-#include <Compositor/OpenGLContext.h>-#include <LibCompositing/WebGL/WebGLCommandList.h>--namespace Compositor {-""")- for function in functions:- if function["category"] not in ("command", "gen"):- continue- out.write(- f"ErrorOr<void> replay_webgl_command(OpenGLContext&, WebGLObjectMap&, "- f"Compositing::WebGL::Commands::{command_name(function)} const&, ReadonlyBytes);\n"- )- out.write("""-// Wire-specified ops; defined manually in HostWebGLContext.cpp. Builtin commands carry-// host-level semantics (presenting, resizing) and are dispatched by the host itself-// rather than through replay_webgl_command.-""")- for function in functions:- if function["category"] == "custom" and is_wire_command(function):- out.write(- f"ErrorOr<void> replay_webgl_command(OpenGLContext&, WebGLObjectMap&, "- f"Compositing::WebGL::Commands::{command_name(function)} const&, ReadonlyBytes);\n"- )- for function in functions:- if is_wire_sync(function):- out.write(- f"ErrorOr<ByteBuffer> handle_one(OpenGLContext&, WebGLObjectMap&, "- f"Compositing::WebGL::SyncCalls::{command_name(function)}::Request const&, ReadonlyBytes);\n"- )- out.write("""-ErrorOr<ByteBuffer> handle_webgl_sync_call(OpenGLContext&, WebGLObjectMap&, ReadonlyBytes request);--}-""")---def write_implementation_file(out: TextIO, functions: list) -> None:- out.write("""#include <AK/Assertions.h>-#include <AK/Vector.h>-#include <Compositor/WebGLCommandReplayer.h>--namespace Compositor {--using namespace Compositing::WebGL;--""")- for function in functions:- if function["category"] not in ("command", "gen"):- continue- body = StringIO()- if function["category"] == "gen":- payload_used = emit_gen_body(body, function)- else:- payload_used = emit_command_body(body, function)- out.write(f"{signature(function, payload_used)}\n{{\n")- out.write(body.getvalue())- out.write(" return {};\n}\n\n")-- for function in functions:- if function["category"] != "sync":- continue- body = StringIO()- payload_used, objects_used = emit_sync_body(body, function)- out.write(f"{sync_signature(function, payload_used, objects_used)}\n{{\n")- out.write(body.getvalue())- out.write("}\n\n")-- out.write("""ErrorOr<ByteBuffer> handle_webgl_sync_call(OpenGLContext& gl, WebGLObjectMap& objects, ReadonlyBytes request)-{- return WebGLSyncCall::dispatch_request(request, [&]<typename Call>(typename Call::Request const& call_request, ReadonlyBytes payload) -> ErrorOr<ByteBuffer> {- return handle_one(gl, objects, call_request, payload);- });-}--}-""")---if __name__ == "__main__":- run_generator("Generate the Compositor WebGL command replayer", write_header_file, write_implementation_file)diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txtindex 3c3780d70c8..c6cf63e0d5e 100644--- a/Services/Compositor/CMakeLists.txt+++ b/Services/Compositor/CMakeLists.txt@@ -15,7 +15,6 @@ set(SOURCESConnectionFromClient.cppConnectionFromPresentation.cppConnectionFromWebContent.cpp- HostWebGLContext.cppOpenGLContext.cppPaintingSurface.cppPresentableSurface.cpp@@ -25,20 +24,9 @@ set(SOURCESVideoFrameHolds.cppVideoFrameSkia.cppVSyncScheduler.cpp- WebGLObjectMap.cppWindowServer.cpp)-invoke_py_generator(- "WebGLCommandReplayer.cpp"- "generate_compositor_webgl_replayer.py"- "${LADYBIRD_SOURCE_DIR}/Libraries/LibCompositing/WebGL/GLFunctions.json"- "WebGLCommandReplayer.h"- "WebGLCommandReplayer.cpp"- arguments -j "${LADYBIRD_SOURCE_DIR}/Libraries/LibCompositing/WebGL/GLFunctions.json"- dependencies "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_webgl.py"-)-set(GENERATED_SOURCESCompositorControlClientEndpoint.hCompositorControlServerEndpoint.h@@ -49,7 +37,6 @@ set(GENERATED_SOURCESRenderClockClientEndpoint.hRenderClockServerEndpoint.h${CMAKE_BINARY_DIR}/Libraries/LibCompositing/WebGL/GLFunctions.cpp- WebGLCommandReplayer.cpp)import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME compositor_core FEATURES allocator FFI_HEADER CompositorCoreRustFFI.h)diff --git a/Services/Compositor/CanvasHost.cpp b/Services/Compositor/CanvasHost.cppindex 23f1505b762..b5848771c32 100644--- a/Services/Compositor/CanvasHost.cpp+++ b/Services/Compositor/CanvasHost.cpp@@ -4,10 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <Compositor/BitmapExport.h>#include <Compositor/Canvas2DCommandPlayer.h>#include <Compositor/CanvasHost.h>#include <Compositor/CanvasSurfaceRegistry.h>-#include <Compositor/HostWebGLContext.h>+#include <Compositor/OpenGLContext.h>#include <Compositor/PaintingSurface.h>#include <Compositor/SkiaBackendContext.h>#include <Compositor/VideoFrameHolds.h>@@ -123,13 +124,6 @@ static ErrorOr<NonnullRefPtr<PresentableSurface>> present_into_surface_of_pool(Preturn surface;}-HostWebGLContext& CanvasHost::as_webgl(Context& context)-{- auto* webgl_context = context.get_pointer<WebGLContext>();- VERIFY(webgl_context);- return **webgl_context;-}-bool CanvasHost::create_2d_context(Compositing::CanvasId canvas_id, Gfx::IntSize size, bool alpha, bool will_read_frequently, Gfx::ColorSpace const& color_space){auto command_player = create_2d_command_player(size, alpha, will_read_frequently, color_space);@@ -155,16 +149,14 @@ bool CanvasHost::create_2d_context(Compositing::CanvasId canvas_id, Gfx::IntSizereturn true;}-CanvasHost::CreateWebGLContextResult CanvasHost::create_webgl_context(Compositing::WebGL::WebGLVersion version, Gfx::IntSize size, bool depth, bool stencil, bool antialias)+bool CanvasHost::create_webgl_context(Compositing::CanvasId canvas_id, OpenGLContext::WebGLVersion version, OpenGLContext::DrawingBufferOptions options, Gfx::IntSize size){- auto context = HostWebGLContext::create(m_skia_backend_context, version, { .depth = depth, .stencil = stencil, .antialias = antialias }, size);- if (!context)- return {};-- auto canvas_id = m_canvas_surface_registry.allocate_canvas_id();- auto supported_extensions = context->gl_context().get_supported_opengl_extensions();- m_contexts.set(canvas_id, context.release_nonnull());- return { .success = true, .canvas_id = canvas_id, .supported_extensions = move(supported_extensions) };+ auto gl_context = OpenGLContext::create(m_skia_backend_context, version, options);+ if (!gl_context)+ return false;+ gl_context->set_size(size);+ m_contexts.set(canvas_id, gl_context.release_nonnull());+ return true;}void CanvasHost::destroy_2d_context(Compositing::CanvasId canvas_id)@@ -279,98 +271,100 @@ void CanvasHost::forget_video_sink(Media::VideoSinkHandle handle)m_video_frame_images.remove(handle);}-Vector<HostWebGLContext::UploadSource> CanvasHost::resolve_webgl_upload_sources(Vector<Compositing::WebGL::ImageSourceFrame> const& frames) const-{- Vector<HostWebGLContext::UploadSource> sources;- sources.ensure_capacity(frames.size());- for (auto const& frame : frames) {- frame.visit(- [&](Gfx::DecodedImageFrame const& decoded_frame) {- sources.unchecked_append(decoded_frame);- },- [&](Compositing::CapturedVideoFrame const& captured_frame) {- if (auto video_frame = m_video_frame_holds.held_frame(captured_frame.sink_handle, captured_frame.generation)) {- sources.unchecked_append(video_frame.release_nonnull());- return;- }- sources.unchecked_append(HostWebGLContext::MissingVideoFrame {});- });- }- return sources;-}--void CanvasHost::execute_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)+OpenGLContext& CanvasHost::webgl_context(Compositing::CanvasId canvas_id){auto* context = this->context(canvas_id);VERIFY(context);- MUST(as_webgl(*context).execute_commands(commands, resolve_webgl_upload_sources(frames)));+ return *context->get<WebGLContext>();}-void CanvasHost::set_webgl_shared_command_buffer(Compositing::CanvasId canvas_id, Compositing::WebGL::WebGLSharedCommandBuffer shared_command_buffer)+CanvasHost::WebGLPresentOutcome CanvasHost::present_webgl_context(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer, bool show_presented_frame){- auto* context = this->context(canvas_id);- VERIFY(context);- as_webgl(*context).set_shared_command_buffer(move(shared_command_buffer));-}--bool CanvasHost::execute_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)-{- auto* context = this->context(canvas_id);- VERIFY(context);- auto& webgl_context = as_webgl(*context);-- auto commands = webgl_context.shared_command_buffer_range(offset, size_in_bytes);- if (!commands.has_value())- return false;-- // WebContent can rewrite shared bytes while they execute, so a malformed stream is- // a misbehaving peer rather than a Compositor bug; report instead of crashing.- if (webgl_context.execute_commands(*commands, resolve_webgl_upload_sources(frames)).is_error())- return false;- webgl_context.store_executed_flush_sequence_number(flush_sequence_number);- return true;+ auto& gl_context = webgl_context(canvas_id);+ auto outcome = WebGLPresentOutcome::ShowedPresentedFrame;+ auto surface = show_presented_frame ? gl_context.presented_surface() : nullptr;+ if (!surface) {+ gl_context.present_drawing_buffer(preserve_drawing_buffer);+ surface = gl_context.presented_surface();+ if (!surface)+ return WebGLPresentOutcome::NoDrawingBuffer;+ outcome = WebGLPresentOutcome::Presented;+ }+ if (auto presentable_surface = gl_context.presented_presentable_surface(); presentable_surface && &presentable_surface->painting_surface() == surface.ptr())+ m_canvas_surface_registry.set_canvas_surface(m_canvas_surface_owner_id, canvas_id, *presentable_surface);+ else+ m_canvas_surface_registry.set_canvas_surface(m_canvas_surface_owner_id, canvas_id, surface.release_nonnull());+ return outcome;}-ErrorOr<ByteBuffer> CanvasHost::execute_webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request)+Optional<Gfx::IntSize> CanvasHost::read_back_webgl_drawing_buffer(Compositing::CanvasId canvas_id, bool from_presented_frame, Gfx::IntRect rect, Bytes pixels){- auto* context = this->context(canvas_id);- VERIFY(context);- return as_webgl(*context).execute_sync_call(request);-}+ auto& gl_context = webgl_context(canvas_id);+ gl_context.make_current();+ gl_context.flush_drawing_buffer();+ auto surface = from_presented_frame ? gl_context.presented_surface() : gl_context.drawing_buffer_surface();+ if (!surface)+ return {};-Compositing::WebGL::ReadPixelsResult CanvasHost::webgl_read_pixels_robust_angle(Compositing::CanvasId canvas_id, Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer pixels)-{- auto* context = this->context(canvas_id);- VERIFY(context);- return as_webgl(*context).read_pixels_robust_angle(x, y, width, height, format, type, buf_size, move(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 {};-bool CanvasHost::webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data)-{- auto* context = this->context(canvas_id);- VERIFY(context);- return as_webgl(*context).read_buffer_sub_data(target, offset, size, move(data));+ 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();}-void CanvasHost::present_webgl_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer)+RefPtr<Media::VideoFrame> CanvasHost::held_video_frame(Media::VideoSinkHandle handle, u64 generation) const{- auto* context = this->context(canvas_id);- VERIFY(context);-- auto& webgl_context = as_webgl(*context);- auto surface = MUST(webgl_context.prepare_for_compositing(preserve_drawing_buffer));- if (auto presentable_surface = webgl_context.presented_presentable_surface(); presentable_surface && &presentable_surface->painting_surface() == surface.ptr())- m_canvas_surface_registry.set_canvas_surface(m_canvas_surface_owner_id, canvas_id, *presentable_surface);- else- m_canvas_surface_registry.set_canvas_surface(m_canvas_surface_owner_id, canvas_id, move(surface));+ return m_video_frame_holds.held_frame(handle, generation);}-void CanvasHost::clear_webgl_drawing_buffer(Compositing::CanvasId canvas_id)+CanvasHost::WebGLImageConversion CanvasHost::convert_image_for_webgl_upload(WebGLImageSource source, Compositing::RegisteredImageFrames const& registered_image_frames, Gfx::ExportFormat format, int export_flags, Optional<Gfx::IntSize> target_size, Gfx::BitmapExportResult& out_pixels) const{- auto* context = this->context(canvas_id);- if (!context || !context->has<WebGLContext>())- return;- as_webgl(*context).clear_drawing_buffer();+ Optional<BitmapInColorSpace> bitmap;+ auto conversion = source.visit(+ [&](Compositing::ImageFrameResourceId id) {+ auto image_frame = registered_image_frames.image_frame(id);+ if (!image_frame)+ return WebGLImageConversion::UnknownImageFrame;+ bitmap = BitmapInColorSpace { image_frame->frame().bitmap_sharing_pixels(), image_frame->frame().color_space() };+ return WebGLImageConversion::Converted;+ },+ [&](HeldVideoFrame held_video_frame) {+ if (auto video_frame = this->held_video_frame(held_video_frame.sink_handle, held_video_frame.generation)) {+ auto video_bitmap = bitmap_from_video_frame(*video_frame, m_skia_backend_context);+ if (video_bitmap.is_error())+ return WebGLImageConversion::Failed;+ bitmap = video_bitmap.release_value();+ return WebGLImageConversion::Converted;+ }+ auto missing_frame_bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 1, 1 });+ if (missing_frame_bitmap.is_error())+ return WebGLImageConversion::Failed;+ bitmap = BitmapInColorSpace { missing_frame_bitmap.release_value(), {} };+ return WebGLImageConversion::Converted;+ });+ if (conversion != WebGLImageConversion::Converted)+ return conversion;++ Optional<int> target_width;+ Optional<int> target_height;+ if (target_size.has_value()) {+ target_width = target_size->width();+ target_height = target_size->height();+ }+ auto pixels = Gfx::export_bitmap_to_byte_buffer(*bitmap->bitmap, bitmap->color_space, format, export_flags, target_width, target_height);+ if (pixels.is_error())+ return WebGLImageConversion::Failed;+ out_pixels = pixels.release_value();+ return WebGLImageConversion::Converted;}Gfx::ShareableBitmap CanvasHost::read_back_surface(Gfx::PaintingSurface& surface, Gfx::IntRect rect, Gfx::AlphaType alpha_type, Gfx::ColorSpace const& color_space)@@ -402,8 +396,8 @@ RefPtr<Gfx::PaintingSurface> CanvasHost::presented_surface(Compositing::CanvasId[](Canvas2DContext& canvas_context) -> RefPtr<Gfx::PaintingSurface> {return canvas_context.presented_surface;},- [](WebGLContext& webgl_context) -> RefPtr<Gfx::PaintingSurface> {- return webgl_context->presented_surface();+ [](WebGLContext& gl_context) -> RefPtr<Gfx::PaintingSurface> {+ return gl_context->presented_surface();});}@@ -417,11 +411,8 @@ Gfx::ShareableBitmap CanvasHost::read_back_pixels(Compositing::CanvasId canvas_i[rect, alpha_type, &color_space](Canvas2DContext& canvas_context) {return read_back_surface(canvas_context.command_player->surface(), rect, alpha_type, color_space);},- [rect, alpha_type, &color_space](WebGLContext& webgl_context) -> Gfx::ShareableBitmap {- // NB: The drawing buffer of a WebGL context is sRGB.- if (alpha_type != Gfx::AlphaType::Premultiplied || !color_space.data().has<Empty>())- return {};- return webgl_context->read_back_drawing_buffer(rect);+ [](WebGLContext&) -> Gfx::ShareableBitmap {+ return {};});}diff --git a/Services/Compositor/CanvasHost.h b/Services/Compositor/CanvasHost.hindex b393044cb4c..6bb8ce2d485 100644--- a/Services/Compositor/CanvasHost.h+++ b/Services/Compositor/CanvasHost.h@@ -19,16 +19,15 @@#include <AK/String.h>#include <AK/Variant.h>#include <AK/Vector.h>+#include <Compositor/BitmapExport.h>#include <Compositor/DrawnResources.h>#include <Compositor/Forward.h>-#include <Compositor/HostWebGLContext.h>+#include <Compositor/OpenGLContext.h>#include <Compositor/PresentableSurface.h>#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Forward.h>#include <LibCompositing/Types.h>-#include <LibCompositing/WebGL/ImageSourceFrame.h>#include <LibCompositing/WebGL/Types.h>-#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Forward.h>#include <LibGfx/ShareableBitmap.h>@@ -53,17 +52,29 @@ class VideoFrameHolds;class CanvasHost {public:- struct CreateWebGLContextResult {- bool success { false };- Compositing::CanvasId canvas_id { 0 };- Vector<String> supported_extensions;+ struct HeldVideoFrame {+ Media::VideoSinkHandle sink_handle;+ u64 generation { 0 };+ };+ using WebGLImageSource = Variant<Compositing::ImageFrameResourceId, HeldVideoFrame>;++ enum class WebGLPresentOutcome {+ Presented,+ ShowedPresentedFrame,+ NoDrawingBuffer,+ };++ enum class WebGLImageConversion {+ Converted,+ UnknownImageFrame,+ Failed,};CanvasHost(RefPtr<Gfx::SkiaBackendContext>, CanvasSurfaceRegistry&, VideoFrameHolds const&);~CanvasHost();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);+ bool create_webgl_context(Compositing::CanvasId, OpenGLContext::WebGLVersion, OpenGLContext::DrawingBufferOptions, Gfx::IntSize);void destroy_2d_context(Compositing::CanvasId);void destroy_webgl_context(Compositing::CanvasId);@@ -72,17 +83,14 @@ public: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&);- ErrorOr<ByteBuffer> execute_webgl_sync_call(Compositing::CanvasId, ByteBuffer request);- Compositing::WebGL::ReadPixelsResult webgl_read_pixels_robust_angle(Compositing::CanvasId, Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer pixels);- bool webgl_read_buffer_sub_data(Compositing::CanvasId, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data);Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const { return m_canvas_surface_owner_id; }- void present_webgl_canvas(Compositing::CanvasId, bool preserve_drawing_buffer);- void clear_webgl_drawing_buffer(Compositing::CanvasId);+ OpenGLContext& webgl_context(Compositing::CanvasId);+ WebGLPresentOutcome present_webgl_context(Compositing::CanvasId, bool preserve_drawing_buffer, bool show_presented_frame);+ Optional<Gfx::IntSize> read_back_webgl_drawing_buffer(Compositing::CanvasId, bool from_presented_frame, Gfx::IntRect, Bytes pixels);+ 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& = {});RefPtr<Gfx::PaintingSurface> presented_surface(Compositing::CanvasId);@@ -97,15 +105,13 @@ private:PresentableSurfacePool presented_surfaces;NonnullRefPtr<Gfx::PaintingSurface> presented_surface;};- using WebGLContext = NonnullOwnPtr<HostWebGLContext>;+ using WebGLContext = NonnullOwnPtr<OpenGLContext>;using Context = Variant<Canvas2DContext, WebGLContext>;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&);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;RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;CanvasSurfaceRegistry& m_canvas_surface_registry;diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cppindex a8511f1f00f..59e4552d836 100644--- a/Services/Compositor/CompositorState.cpp+++ b/Services/Compositor/CompositorState.cpp@@ -12,7 +12,9 @@#include <Compositor/Canvas2DCommandPlayer.h>#include <Compositor/CanvasHost.h>#include <Compositor/CompositorState.h>+#include <Compositor/OpenGLContext.h>#include <Compositor/SkiaUtils.h>+#include <Compositor/VideoFrameSkia.h>#include <LibCompositing/CanvasColorSpace.h>#include <LibCompositing/DisplayList/DisplayListCommand.h>#include <LibCompositing/DisplayList/RegisteredImageFrames.h>@@ -21,7 +23,9 @@#include <LibCore/StatsLog.h>#include <LibCore/Timer.h>#include <LibGfx/Bitmap.h>+#include <LibGfx/ExportFormat.h>#include <LibMedia/Sinks/DisplayingVideoSink.h>+#include <LibMediaCodecs/VideoFrame.h>#include <LibMediaCodecs/VideoSurface.h>#include <core/SkCanvas.h>#include <core/SkImage.h>@@ -1386,6 +1390,28 @@ VSyncScheduler& CompositorState::vsync_scheduler_for_display(Optional<u64> displnamespace {+struct VideoFrameForRust {+ AK_ALLOC_WITH_KMALLOC;++ NonnullRefPtr<Media::VideoFrame> frame;+};++struct VideoFrameImageForRust {+ AK_ALLOC_WITH_KMALLOC;++ sk_sp<SkImage> image;+};++struct ConvertedPixelsForRust {+ AK_ALLOC_WITH_KMALLOC;++ ByteBuffer buffer;+};++// NB: `ExportFormat` of libcompositing_rust lists the formats in this order.+static_assert(to_underlying(Gfx::ExportFormat::Luminance8) == 0);+static_assert(to_underlying(Gfx::ExportFormat::RGBA8888) == 7);+struct SharedMemoryMapping {AK_ALLOC_WITH_KMALLOC;@@ -1560,6 +1586,84 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state).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); },+ .gl_proc_address = [](void*, char const* name) { return OpenGLContext::address_of_function(name); },+ .create_webgl_context = [](void* host, u64 client, Compositing::CanvasId canvas_id, RustFFI::ContextOptions options) {+ auto version = options.webgl2 ? Compositing::WebGL::WebGLVersion::WebGL2 : Compositing::WebGL::WebGLVersion::WebGL1;+ return state_of(host).canvas_host_of(WebContentClientId { client }).create_webgl_context(canvas_id, version, { .depth = options.depth, .stencil = options.stencil, .antialias = options.antialias }, options.size); },+ .destroy_webgl_context = [](void* host, u64 client, Compositing::CanvasId canvas_id) { state_of(host).canvas_host_of(WebContentClientId { client }).destroy_webgl_context(canvas_id); },+ .make_webgl_context_current = [](void* host, u64 client, Compositing::CanvasId canvas_id, RustFFI::DefaultBuffers* defaults) {+ auto& gl_context = state_of(host).canvas_host_of(WebContentClientId { client }).webgl_context(canvas_id);+ gl_context.make_current();+ *defaults = { .framebuffer = gl_context.default_framebuffer(), .renderbuffer = gl_context.default_renderbuffer() }; },+ .set_webgl_drawing_buffer_size = [](void* host, u64 client, Compositing::CanvasId canvas_id, Gfx::IntSize size) { state_of(host).canvas_host_of(WebContentClientId { client }).webgl_context(canvas_id).set_size(size); },+ .present_webgl_context = [](void* host, u64 client, Compositing::CanvasId canvas_id, bool preserve_drawing_buffer, bool show_presented_frame) {+ switch (state_of(host).canvas_host_of(WebContentClientId { client }).present_webgl_context(canvas_id, preserve_drawing_buffer, show_presented_frame)) {+ case CanvasHost::WebGLPresentOutcome::Presented:+ return RustFFI::PresentOutcome::Presented;+ case CanvasHost::WebGLPresentOutcome::ShowedPresentedFrame:+ return RustFFI::PresentOutcome::ShowedPresentedFrame;+ case CanvasHost::WebGLPresentOutcome::NoDrawingBuffer:+ return RustFFI::PresentOutcome::NoDrawingBuffer;+ }+ VERIFY_NOT_REACHED(); },+ .read_back_webgl_drawing_buffer = [](void* host, u64 client, Compositing::CanvasId canvas_id, bool from_presented_frame, Gfx::IntRect rect, u8* pixels, size_t pixels_size, Gfx::IntSize* size) {+ auto read_size = state_of(host).canvas_host_of(WebContentClientId { client }).read_back_webgl_drawing_buffer(canvas_id, from_presented_frame, rect, { pixels, pixels_size });+ if (!read_size.has_value())+ return false;+ *size = *read_size;+ return true; },+ .webgl_can_copy_images_into_textures = [](void* host, u64 client, Compositing::CanvasId canvas_id) { return state_of(host).canvas_host_of(WebContentClientId { client }).webgl_context(canvas_id).can_copy_images_into_textures(); },+ .held_video_frame = [](void* host, u64 client, u64 sink_handle, u64 generation, RustFFI::FfiCppObject* frame, Gfx::IntSize* size) {+ auto held_frame = state_of(host).canvas_host_of(WebContentClientId { client }).held_video_frame(Media::VideoSinkHandle { sink_handle }, generation);+ if (!held_frame)+ return false;+ *size = held_frame->size().to_type<int>();+ frame->object = make<VideoFrameForRust>(held_frame.release_nonnull()).leak_ptr();+ frame->destroy = [](void* object) { delete static_cast<VideoFrameForRust*>(object); };+ return true; },+ .video_frame_image = [](void* host, void* frame, RustFFI::FfiCppObject* image) {+ auto sk_image = sk_image_from_video_frame(*static_cast<VideoFrameForRust*>(frame)->frame, state_of(host).m_skia_backend_context);+ if (!sk_image)+ return;+ image->object = make<VideoFrameImageForRust>(move(sk_image)).leak_ptr();+ image->destroy = [](void* object) { delete static_cast<VideoFrameImageForRust*>(object); }; },+ .copy_video_frame_image_into_bound_texture = [](void* host, u64 client, Compositing::CanvasId canvas_id, void* image, RustFFI::VideoFrameCopy copy) {+ auto& gl_context = state_of(host).canvas_host_of(WebContentClientId { client }).webgl_context(canvas_id);+ return gl_context.copy_image_into_bound_texture(*static_cast<VideoFrameImageForRust*>(image)->image, copy.source_size, copy.size, copy.target, copy.level, copy.xoffset, copy.yoffset, copy.flip_y, copy.premultiply_alpha); },+ .convert_image_source_for_webgl = [](void* host, u64 client_id, RustFFI::FfiImageSource source, RustFFI::FfiImageConversion conversion, RustFFI::FfiConvertedPixels* converted) {+ auto* client = state_of(host).web_content_client_if_present(WebContentClientId { client_id });+ VERIFY(client);+ VERIFY(conversion.export_format <= to_underlying(Gfx::ExportFormat::RGBA8888));+ auto image_source = source.is_held_video_frame+ ? CanvasHost::WebGLImageSource { CanvasHost::HeldVideoFrame { Media::VideoSinkHandle { source.id }, source.generation } }+ : CanvasHost::WebGLImageSource { Compositing::ImageFrameResourceId { source.id } };+ int export_flags = 0;+ if (conversion.flip_y)+ export_flags |= Gfx::ExportFlags::FlipY;+ if (conversion.premultiply_alpha)+ export_flags |= Gfx::ExportFlags::PremultiplyAlpha;+ Optional<Gfx::IntSize> target_size;+ if (conversion.has_target_size)+ target_size = conversion.target_size;+ Gfx::BitmapExportResult pixels;+ switch (client->canvas_host().convert_image_for_webgl_upload(image_source, client->registered_image_frames(), static_cast<Gfx::ExportFormat>(conversion.export_format), export_flags, target_size, pixels)) {+ case CanvasHost::WebGLImageConversion::UnknownImageFrame:+ return RustFFI::FfiImageConversionOutcome::UnknownImageFrame;+ case CanvasHost::WebGLImageConversion::Failed:+ return RustFFI::FfiImageConversionOutcome::Failed;+ case CanvasHost::WebGLImageConversion::Converted:+ break;+ }+ auto owned_pixels = make<ConvertedPixelsForRust>(move(pixels.buffer));+ *converted = {+ .pixels = { .object = owned_pixels.ptr(), .destroy = [](void* object) { delete static_cast<ConvertedPixelsForRust*>(object); } },+ .data = owned_pixels->buffer.data(),+ .size = owned_pixels->buffer.size(),+ .width = pixels.width,+ .height = pixels.height,+ };+ (void)owned_pixels.leak_ptr();+ return RustFFI::FfiImageConversionOutcome::Converted; },};}diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipcindex b420bc1c9ed..5e4f386d5d1 100644--- a/Services/Compositor/CompositorWebContentServer.ipc+++ b/Services/Compositor/CompositorWebContentServer.ipc@@ -5,8 +5,6 @@#include <LibCompositing/Forward.h>#include <LibCompositing/Types.h>#include <LibCompositing/Video/VideoFramePresentationPage.h>-#include <LibCompositing/WebGL/ImageSourceFrame.h>-#include <LibCompositing/WebGL/Types.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/DecodedImageFrame.h>@@ -81,17 +79,21 @@ endpoint CompositorWebContentServerstage_rasterization(u64 token, Vector<Compositing::DisplayListFontDescription> fonts, Vector<Compositing::ImageFrameResourceId> image_frame_ids, Gfx::ShareableBitmap target_bitmap) =|[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) => ()- webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames) =|- webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer) =|- webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id) =|- webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) => (ByteBuffer reply)- webgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels) => (i32 length, i32 columns, i32 rows)- webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data) => (bool success)+ // Only Rust sends and receives the messages of WebGL contexts. The commands of a context name the images that they+ // upload by their position among the image sources sent with them.+ [RustReceiver, RustSender] 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)+ [RustReceiver, RustSender] destroy_webgl_context(Compositing::CanvasId canvas_id) =|+ [RustReceiver, RustSender] webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) =|+ [RustReceiver, RustSender] webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSource> image_sources) =|+ [RustReceiver, RustSender] webgl_drain_command_buffer(Compositing::CanvasId canvas_id) => ()+ [RustReceiver, RustSender] webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSource> image_sources) =|+ [RustReceiver, RustSender] webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer) =|+ [RustReceiver, RustSender] webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id) =|+ [RustReceiver, RustSender] webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) => (ByteBuffer reply)+ [RustReceiver, RustSender] webgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels) => (i32 length, i32 columns, i32 rows)+ [RustReceiver, RustSender] webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data) => (bool success)+ // The pixels of the drawing buffer that the rect covers, as premultiplied BGRA8888 rows of the size answered.+ [RustReceiver, RustSender] webgl_read_back_drawing_buffer(Compositing::CanvasId canvas_id, Gfx::IntRect rect, Core::AnonymousBuffer pixels) => (Gfx::IntSize size)[RustReceiver] invalidate_wheel_event_listener_state(Web::CompositorContextId context_id, u64 generation) =|[RustReceiver] invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation) => ()diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cppindex 431fbb615b9..c01492ab407 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/WebGL/WebGLSharedCommandBuffer.h>#include <LibGfx/ColorSpace.h>#include <LibWebCommon/Page/InputEvent.h>@@ -375,86 +374,6 @@ void ConnectionFromWebContent::placeholder_canvas_committed(Compositing::CanvasIasync_placeholder_canvas_committed(canvas_id, size, origin_clean);}-Messages::CompositorWebContentServer::CreateWebglContextResponse ConnectionFromWebContent::create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias)-{- auto result = m_canvas_host.create_webgl_context(webgl_version, size, depth, stencil, antialias);- return { 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));- if (!shared_command_buffer.has_value()) {- did_misbehave("WebContent sent an invalid WebGL shared command buffer");- return;- }-- m_canvas_host.set_webgl_shared_command_buffer(canvas_id, shared_command_buffer.release_value());-}--void ConnectionFromWebContent::webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames)-{- if (!m_canvas_host.execute_webgl_commands_from_shared_buffer(canvas_id, offset, size_in_bytes, flush_sequence_number, frames))- did_misbehave("WebContent published an invalid WebGL shared command buffer range");-}--void ConnectionFromWebContent::webgl_drain_command_buffer(Compositing::CanvasId)-{- // The empty reply is the point: it proves every earlier message on this connection,- // including all published command ranges, has already been processed.-}--void ConnectionFromWebContent::webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames)-{- if (!commands.is_valid()) {- did_misbehave("WebContent sent an invalid WebGL command buffer");- return;- }-- m_canvas_host.execute_webgl_commands(canvas_id, commands.bytes(), frames);-}--void ConnectionFromWebContent::webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer)-{- m_canvas_host.present_webgl_canvas(canvas_id, preserve_drawing_buffer);-}--void ConnectionFromWebContent::webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id)-{- m_canvas_host.clear_webgl_drawing_buffer(canvas_id);-}--Messages::CompositorWebContentServer::WebglSyncCallResponse ConnectionFromWebContent::webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request)-{- return MUST(m_canvas_host.execute_webgl_sync_call(canvas_id, move(request)));-}--Messages::CompositorWebContentServer::WebglReadPixelsResponse ConnectionFromWebContent::webgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels)-{- if (buf_size < 0 || (buf_size > 0 && (!pixels.is_valid() || pixels.size() < static_cast<size_t>(buf_size)))) {- did_misbehave("WebContent sent an invalid WebGL readPixels buffer");- return { 0, 0, 0 };- }-- auto result = m_canvas_host.webgl_read_pixels_robust_angle(canvas_id, x, y, width, height, format, type, buf_size, move(pixels));- return { result.length, result.columns, result.rows };-}--Messages::CompositorWebContentServer::WebglReadBufferSubDataResponse ConnectionFromWebContent::webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data)-{- if (size < 0 || (size > 0 && (!data.is_valid() || data.size() < static_cast<size_t>(size)))) {- did_misbehave("WebContent sent an invalid WebGL buffer readback target");- return { false };- }-- return { m_canvas_host.webgl_read_buffer_sub_data(canvas_id, target, offset, size, move(data)) };-}-void ConnectionFromWebContent::viewport_size_updated(Web::CompositorContextId context_id, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress window_resize_in_progress){if (!context_is_owned_by_this_connection(context_id))diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.hindex 55f06fa94f1..d762a0f760c 100644--- a/Services/Compositor/ConnectionFromWebContent.h+++ b/Services/Compositor/ConnectionFromWebContent.h@@ -18,7 +18,6 @@#include <LibCompositing/DisplayList/DisplayListResources.h>#include <LibCompositing/DisplayList/RegisteredImageFrames.h>#include <LibCompositing/DisplayList/RegisteredTypefaces.h>-#include <LibCompositing/WebGL/Types.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Size.h>#include <LibIPC/ConnectionFromClient.h>@@ -72,17 +71,6 @@ private:virtual Messages::CompositorWebContentServer::GetPlaceholderCanvasPixelsResponse get_placeholder_canvas_pixels(Compositing::CanvasId, Gfx::IntRect) override;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;- virtual void webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames) override;- virtual void webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer) override;- virtual void webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id) override;- virtual Messages::CompositorWebContentServer::WebglSyncCallResponse webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) override;- virtual Messages::CompositorWebContentServer::WebglReadPixelsResponse webgl_read_pixels(Compositing::CanvasId canvas_id, i32 x, i32 y, i32 width, i32 height, u32 format, u32 type, i32 buf_size, Core::AnonymousBuffer pixels) override;- virtual Messages::CompositorWebContentServer::WebglReadBufferSubDataResponse webgl_read_buffer_sub_data(Compositing::CanvasId canvas_id, u32 target, i64 offset, i64 size, Core::AnonymousBuffer data) override;virtual void synchronize_for_testing() override { }virtual void viewport_size_updated(Web::CompositorContextId, Gfx::IntSize viewport_size, double device_pixel_ratio, Compositing::WindowResizingInProgress) override;virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) override;diff --git a/Services/Compositor/HostWebGLContext.cpp b/Services/Compositor/HostWebGLContext.cppdeleted file mode 100644index 87dd35c8ff7..00000000000--- a/Services/Compositor/HostWebGLContext.cpp+++ /dev/null@@ -1,537 +0,0 @@-/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <GLES3/gl3.h>--#include <AK/Vector.h>-#include <Compositor/BitmapExport.h>-#include <Compositor/HostWebGLContext.h>-#include <Compositor/PaintingSurface.h>-#include <Compositor/SkiaBackendContext.h>-#include <Compositor/VideoFrameSkia.h>-#include <Compositor/WebGLCommandReplayer.h>-#include <LibCompositing/WebGL/TextureUpload.h>-#include <LibCompositing/WebGL/WebGLCommandList.h>-#include <LibGfx/Bitmap.h>-#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/ShareableBitmap.h>-#include <LibMediaCodecs/VideoFrame.h>--#include <core/SkImage.h>--namespace Compositor {--using namespace Compositing::WebGL;--static constexpr GLsizei max_webgl_string_list_entries = 16384;--// The pixels of a bitmap converted for upload are tightly packed, row after row and image after image. So while they're-// uploaded, the unpack parameters that the page set for its own data are reset, and afterward restored.-class PackedBitmapUnpackState {- AK_MAKE_NONCOPYABLE(PackedBitmapUnpackState);- AK_MAKE_NONMOVABLE(PackedBitmapUnpackState);--public:- explicit PackedBitmapUnpackState(OpenGLContext const& gl_context)- {- reset(GL_UNPACK_ALIGNMENT, 1);- if (gl_context.supports_unpack_subimage_parameters()) {- reset(GL_UNPACK_ROW_LENGTH, 0);- reset(GL_UNPACK_SKIP_PIXELS, 0);- reset(GL_UNPACK_SKIP_ROWS, 0);- }- if (gl_context.webgl_version() == WebGLVersion::WebGL2) {- reset(GL_UNPACK_IMAGE_HEIGHT, 0);- reset(GL_UNPACK_SKIP_IMAGES, 0);- }- }-- ~PackedBitmapUnpackState()- {- for (auto const& saved : m_saved_parameters)- glPixelStorei(saved.parameter, saved.value);- }--private:- void reset(GLenum parameter, GLint value)- {- GLint saved_value = 0;- glGetIntegerv(parameter, &saved_value);- m_saved_parameters.append({ parameter, saved_value });- glPixelStorei(parameter, value);- }-- struct SavedParameter {- GLenum parameter;- GLint value;- };- Vector<SavedParameter, 6> m_saved_parameters;-};--HostWebGLContext::HostWebGLContext(NonnullOwnPtr<OpenGLContext> gl_context, RefPtr<Gfx::SkiaBackendContext> skia_backend_context)- : m_gl_context(move(gl_context))- , m_skia_backend_context(move(skia_backend_context))-{-}--OwnPtr<HostWebGLContext> HostWebGLContext::create(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, OpenGLContext::WebGLVersion version, OpenGLContext::DrawingBufferOptions options, Gfx::IntSize initial_size)-{- if (initial_size.width() < 1 || initial_size.width() > max_webgl_drawing_buffer_dimension- || initial_size.height() < 1 || initial_size.height() > max_webgl_drawing_buffer_dimension)- return {};- auto gl_context = OpenGLContext::create(skia_backend_context, version, options);- if (!gl_context)- return {};- gl_context->set_size(initial_size);- return adopt_own(*new HostWebGLContext(gl_context.release_nonnull(), move(skia_backend_context)));-}--Optional<ReadonlyBytes> HostWebGLContext::shared_command_buffer_range(u64 offset, u64 size_in_bytes) const-{- if (!m_shared_command_buffer.is_valid())- return {};- auto data_region = m_shared_command_buffer.data_region();- if (offset % WebGLCommandList::command_alignment != 0)- return {};- if (offset > data_region.size() || size_in_bytes > data_region.size() - offset)- return {};- return data_region.slice(offset, size_in_bytes);-}--ErrorOr<void> HostWebGLContext::execute_commands(ReadonlyBytes bytes, Vector<UploadSource> const& sources)-{- m_gl_context->make_current();- clear_drawing_buffer_if_needed();-- return WebGLCommandList::for_each_command(bytes, [&]<typename Command>(Command const& command, [[maybe_unused]] ReadonlyBytes payload) -> ErrorOr<void> {- if constexpr (IsSame<Command, Commands::SetDrawingBufferSize>) {- return set_drawing_buffer_size(command.width, command.height);- } else if constexpr (IsSame<Command, Commands::ReadPixelsIntoPixelPackBuffer>) {- m_gl_context->read_pixels_robust_angle(command.x, command.y, command.width, command.height, command.format, command.type, 0, nullptr, nullptr, nullptr, reinterpret_cast<void*>(static_cast<uintptr_t>(command.offset)));- return {};- } else if constexpr (IsSame<Command, Commands::TexImage2DFromBitmap>) {- return tex_image2d_from_bitmap(command, sources);- } else if constexpr (IsSame<Command, Commands::TexSubImage2DFromBitmap>) {- return tex_sub_image2d_from_bitmap(command, sources);- } else if constexpr (IsSame<Command, Commands::TexImage3DFromBitmap>) {- return tex_image3d_from_bitmap(command, sources);- } else if constexpr (IsSame<Command, Commands::TexSubImage3DFromBitmap>) {- return tex_sub_image3d_from_bitmap(command, sources);- } else {- return replay_webgl_command(*m_gl_context, m_objects, command, payload);- }- });-}--static ErrorOr<HostWebGLContext::UploadSource const*> upload_source_at(Vector<HostWebGLContext::UploadSource> const& sources, u32 index)-{- if (index >= sources.size())- return Error::from_string_literal("WebGL image upload references an out-of-range bitmap");- return &sources[index];-}--static ErrorOr<BitmapInColorSpace> bitmap_for_upload(HostWebGLContext::UploadSource const& source, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)-{- return source.visit(- [](Gfx::DecodedImageFrame const& frame) -> ErrorOr<BitmapInColorSpace> {- return BitmapInColorSpace { frame.bitmap_sharing_pixels(), frame.color_space() };- },- [&](NonnullRefPtr<Media::VideoFrame> const& video_frame) -> ErrorOr<BitmapInColorSpace> {- return bitmap_from_video_frame(*video_frame, skia_backend_context);- },- [](HostWebGLContext::MissingVideoFrame) -> ErrorOr<BitmapInColorSpace> {- return BitmapInColorSpace { TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 1, 1 })), {} };- });-}--static ErrorOr<Gfx::BitmapExportResult> convert_bitmap_for_upload(Vector<HostWebGLContext::UploadSource> const& sources, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, u32 bitmap_index, GLenum format, GLenum type, bool has_explicit_destination_size, GLsizei destination_width, GLsizei destination_height, bool flip_y, bool premultiply_alpha)-{- auto const& source = *TRY(upload_source_at(sources, bitmap_index));-- auto export_format = texture_export_format(format, type);- if (!export_format.has_value())- return Error::from_string_literal("WebGL image upload has an unsupported format+type combination");-- int export_flags = 0;- if (flip_y)- export_flags |= Gfx::ExportFlags::FlipY;- if (premultiply_alpha)- export_flags |= Gfx::ExportFlags::PremultiplyAlpha;-- Optional<int> target_width;- Optional<int> target_height;- if (has_explicit_destination_size) {- if (destination_width < 0 || destination_height < 0) {- return Gfx::BitmapExportResult {- .buffer = {},- .width = destination_width,- .height = destination_height,- };- }- target_width = destination_width;- target_height = destination_height;- }-- auto [bitmap, color_space] = TRY(bitmap_for_upload(source, skia_backend_context));- return Gfx::export_bitmap_to_byte_buffer(*bitmap, color_space, export_format.value(), export_flags, target_width, target_height);-}--static bool copy_can_write_internal_format(GLint internalformat)-{- switch (internalformat) {- case GL_ALPHA:- case GL_LUMINANCE:- case GL_LUMINANCE_ALPHA:- case GL_RGB:- case GL_RGBA:- case GL_SRGB_EXT:- case GL_SRGB_ALPHA_EXT:- case GL_R8:- case GL_RG8:- case GL_RGB8:- case GL_RGBA8:- case GL_SRGB8:- case GL_SRGB8_ALPHA8:- case GL_RGB565:- case GL_RGBA4:- case GL_RGB5_A1:- case GL_RGB10_A2:- case GL_RGB9_E5:- case GL_R11F_G11F_B10F:- case GL_R16F:- case GL_RG16F:- case GL_RGB16F:- case GL_RGBA16F:- case GL_R32F:- case GL_RG32F:- case GL_RGB32F:- case GL_RGBA32F:- return true;- default:- return false;- }-}--static bool format_is_integer(GLenum format)-{- return format == GL_RED_INTEGER || format == GL_RG_INTEGER || format == GL_RGB_INTEGER || format == GL_RGBA_INTEGER;-}--static Optional<Gfx::IntSize> upload_size(Media::VideoFrame const& frame, bool has_explicit_destination_size, GLsizei destination_width, GLsizei destination_height)-{- if (!has_explicit_destination_size)- return Gfx::IntSize { static_cast<int>(frame.width()), static_cast<int>(frame.height()) };- if (destination_width < 0 || destination_height < 0)- return {};- return Gfx::IntSize { destination_width, destination_height };-}--class PixelUnpackBufferUnbinder {-public:- explicit PixelUnpackBufferUnbinder(OpenGLContext& gl_context)- : m_gl_context(gl_context)- , m_has_pixel_buffer_objects(gl_context.supports_pixel_buffer_objects())- {- if (!m_has_pixel_buffer_objects)- return;- m_gl_context.get_integerv_robust_angle(GL_PIXEL_UNPACK_BUFFER_BINDING, 1, nullptr, &m_bound_buffer);- m_gl_context.bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);- }-- ~PixelUnpackBufferUnbinder()- {- if (m_has_pixel_buffer_objects)- m_gl_context.bind_buffer(GL_PIXEL_UNPACK_BUFFER, m_bound_buffer);- }--private:- OpenGLContext& m_gl_context;- bool m_has_pixel_buffer_objects { false };- GLint m_bound_buffer { 0 };-};--// The level is defined by the same call that an upload of pixels would make, so that WebGL sees the same errors.-bool HostWebGLContext::define_texture_image_from_video_frame(Commands::TexImage2DFromBitmap const& command, Media::VideoFrame const& frame)-{- if (!m_gl_context->can_copy_images_into_textures() || !copy_can_write_internal_format(command.internalformat))- return false;- auto size = upload_size(frame, command.has_explicit_destination_size, command.destination_width, command.destination_height);- if (!size.has_value())- return false;- auto image = sk_image_from_video_frame(frame, m_skia_backend_context);- if (!image)- return false;-- m_gl_context->stash_errors();- {- PixelUnpackBufferUnbinder unbinder { *m_gl_context };- m_gl_context->tex_image2d_robust_angle(command.target, command.level, command.internalformat, size->width(), size->height(), 0, command.format, command.type, 0, nullptr);- }- if (m_gl_context->stash_errors() || size->is_empty())- return true;- if (!m_gl_context->copy_image_into_bound_texture(*image, frame.size().to_type<int>(), *size, command.target, command.level, 0, 0, command.flip_y, command.premultiply_alpha))- return false;- m_gl_context->discard_errors();- return true;-}--bool HostWebGLContext::update_texture_image_from_video_frame(Commands::TexSubImage2DFromBitmap const& command, Media::VideoFrame const& frame)-{- if (!m_gl_context->can_copy_images_into_textures() || format_is_integer(command.format))- return false;- auto size = upload_size(frame, command.has_explicit_destination_size, command.destination_width, command.destination_height);- if (!size.has_value())- return false;- auto image = sk_image_from_video_frame(frame, m_skia_backend_context);- if (!image)- return false;-- m_gl_context->stash_errors();- {- PixelUnpackBufferUnbinder unbinder { *m_gl_context };- m_gl_context->tex_sub_image2d_robust_angle(command.target, command.level, command.xoffset, command.yoffset, 0, 0, command.format, command.type, 0, nullptr);- }- if (m_gl_context->stash_errors() || size->is_empty())- return true;- if (!m_gl_context->copy_image_into_bound_texture(*image, frame.size().to_type<int>(), *size, command.target, command.level, command.xoffset, command.yoffset, command.flip_y, command.premultiply_alpha))- return false;- // A region beyond the level is the caller's error, as it would be for an upload of pixels.- m_gl_context->stash_errors();- return true;-}--ErrorOr<void> HostWebGLContext::tex_image2d_from_bitmap(Commands::TexImage2DFromBitmap const& command, Vector<UploadSource> const& sources)-{- if (auto const* video_frame = TRY(upload_source_at(sources, command.bitmap_index))->get_pointer<NonnullRefPtr<Media::VideoFrame>>(); video_frame && define_texture_image_from_video_frame(command, **video_frame))- return {};- auto converted = TRY(convert_bitmap_for_upload(sources, m_skia_backend_context, command.bitmap_index, command.format, command.type, command.has_explicit_destination_size, command.destination_width, command.destination_height, command.flip_y, command.premultiply_alpha));- PackedBitmapUnpackState packed_bitmap_unpack_state { *m_gl_context };- m_gl_context->tex_image2d_robust_angle(command.target, command.level, command.internalformat, converted.width, converted.height, 0, command.format, command.type, converted.buffer.size(), converted.buffer.data());- return {};-}--ErrorOr<void> HostWebGLContext::tex_sub_image2d_from_bitmap(Commands::TexSubImage2DFromBitmap const& command, Vector<UploadSource> const& sources)-{- if (auto const* video_frame = TRY(upload_source_at(sources, command.bitmap_index))->get_pointer<NonnullRefPtr<Media::VideoFrame>>(); video_frame && update_texture_image_from_video_frame(command, **video_frame))- return {};- auto converted = TRY(convert_bitmap_for_upload(sources, m_skia_backend_context, command.bitmap_index, command.format, command.type, command.has_explicit_destination_size, command.destination_width, command.destination_height, command.flip_y, command.premultiply_alpha));- PackedBitmapUnpackState packed_bitmap_unpack_state { *m_gl_context };- m_gl_context->tex_sub_image2d_robust_angle(command.target, command.level, command.xoffset, command.yoffset, converted.width, converted.height, command.format, command.type, converted.buffer.size(), converted.buffer.data());- return {};-}--ErrorOr<void> HostWebGLContext::tex_image3d_from_bitmap(Commands::TexImage3DFromBitmap const& command, Vector<UploadSource> const& sources)-{- auto converted = TRY(convert_bitmap_for_upload(sources, m_skia_backend_context, command.bitmap_index, command.format, command.type, command.has_explicit_destination_size, command.destination_width, command.destination_height, command.flip_y, command.premultiply_alpha));- PackedBitmapUnpackState packed_bitmap_unpack_state { *m_gl_context };- m_gl_context->tex_image3d_robust_angle(command.target, command.level, command.internalformat, converted.width, converted.height, command.depth, 0, command.format, command.type, converted.buffer.size(), converted.buffer.data());- return {};-}--ErrorOr<void> HostWebGLContext::tex_sub_image3d_from_bitmap(Commands::TexSubImage3DFromBitmap const& command, Vector<UploadSource> const& sources)-{- auto converted = TRY(convert_bitmap_for_upload(sources, m_skia_backend_context, command.bitmap_index, command.format, command.type, command.has_explicit_destination_size, command.destination_width, command.destination_height, command.flip_y, command.premultiply_alpha));- PackedBitmapUnpackState packed_bitmap_unpack_state { *m_gl_context };- m_gl_context->tex_sub_image3d_robust_angle(command.target, command.level, command.xoffset, command.yoffset, command.zoffset, converted.width, converted.height, command.depth, command.format, command.type, converted.buffer.size(), converted.buffer.data());- return {};-}--// A non-preserving context's drawing buffer is cleared after being prepared for-// compositing, but the clear is deferred until the next GL command or read. Until-// then the presented frame is still the canvas content, so readbacks take it.-void HostWebGLContext::clear_drawing_buffer_if_needed()-{- if (!m_needs_clear_before_next_frame)- return;- m_gl_context->clear_buffer_to_default_values();- m_needs_clear_before_next_frame = false;-}--ErrorOr<ByteBuffer> HostWebGLContext::execute_sync_call(ReadonlyBytes request)-{- m_gl_context->make_current();- clear_drawing_buffer_if_needed();- return handle_webgl_sync_call(*m_gl_context, m_objects, request);-}--ErrorOr<NonnullRefPtr<Gfx::PaintingSurface>> HostWebGLContext::prepare_for_compositing(bool preserve_drawing_buffer)-{- // Nothing ran since the last present, so that frame is still the canvas content. The drawing buffer holds- // whatever an earlier frame left in it until the deferred clear.- if (m_needs_clear_before_next_frame) {- if (auto presented_surface = m_gl_context->presented_surface())- return presented_surface.release_nonnull();- }-- m_gl_context->present_drawing_buffer(preserve_drawing_buffer);-- auto presented_surface = m_gl_context->presented_surface();- if (!presented_surface)- return Error::from_string_literal("WebGL context has no drawing buffer");-- if (!preserve_drawing_buffer)- m_needs_clear_before_next_frame = true;-- return presented_surface.release_nonnull();-}--void HostWebGLContext::clear_drawing_buffer()-{- m_gl_context->make_current();- m_gl_context->clear_buffer_to_default_values();- m_needs_clear_before_next_frame = false;-}--RefPtr<Gfx::PaintingSurface> HostWebGLContext::presented_surface()-{- return m_gl_context->presented_surface();-}--Gfx::ShareableBitmap HostWebGLContext::read_back_drawing_buffer(Gfx::IntRect rect)-{- m_gl_context->make_current();- m_gl_context->flush_drawing_buffer();- auto surface = m_needs_clear_before_next_frame ? m_gl_context->presented_surface() : m_gl_context->drawing_buffer_surface();- if (!surface)- return {};-- auto clipped_rect = rect.intersected(surface->rect());- if (clipped_rect.is_empty())- return {};-- auto bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, clipped_rect.size());- if (bitmap_or_error.is_error())- return {};- auto bitmap = bitmap_or_error.release_value();- surface->flush();- surface->read_into_bitmap(*bitmap, clipped_rect.location());- return Gfx::ShareableBitmap { move(bitmap), Gfx::ShareableBitmap::ConstructWithKnownGoodBitmap };-}--ReadPixelsResult HostWebGLContext::read_pixels_robust_angle(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei buf_size, Core::AnonymousBuffer pixels)-{- VERIFY(buf_size >= 0);- VERIFY(static_cast<size_t>(buf_size) <= pixels.size());-- m_gl_context->make_current();- clear_drawing_buffer_if_needed();-- GLsizei length = 0;- GLsizei columns = 0;- GLsizei rows = 0;- m_gl_context->read_pixels_robust_angle(x, y, width, height, format, type, buf_size, &length, &columns, &rows, pixels.data<void>());- return {- .length = length,- .columns = columns,- .rows = rows,- };-}--bool HostWebGLContext::read_buffer_sub_data(GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data)-{- VERIFY(size >= 0);- VERIFY(static_cast<size_t>(size) <= data.size());-- m_gl_context->make_current();-- if (auto* mapped = m_gl_context->map_buffer_range(target, offset, size, GL_MAP_READ_BIT)) {- __builtin_memcpy(data.data<void>(), mapped, static_cast<size_t>(size));- m_gl_context->unmap_buffer(target);- return true;- }- return false;-}--ErrorOr<void> HostWebGLContext::set_drawing_buffer_size(int width, int height)-{- VERIFY(width >= 1);- VERIFY(width <= max_webgl_drawing_buffer_dimension);- VERIFY(height >= 1);- VERIFY(height <= max_webgl_drawing_buffer_dimension);- m_gl_context->set_size({ width, height });- m_gl_context->make_current();- return {};-}--ErrorOr<void> replay_webgl_command(OpenGLContext& gl, WebGLObjectMap& objects, Commands::ShaderSource const& command, ReadonlyBytes payload)-{- auto source_bytes = WebGLCommandList::resolve_string_span(payload, command.source);- auto shader = objects.lookup(command.shader);- GLchar const* source = reinterpret_cast<GLchar const*>(source_bytes.data());- GLint length = static_cast<GLint>(source_bytes.size() - 1);- gl.shader_source(shader, 1, &source, &length);- return {};-}--// Splits a payload of `count` packed NUL-terminated strings into pointers.-static ErrorOr<Vector<GLchar const*>> split_packed_strings(ReadonlyBytes bytes, GLsizei count)-{- if (count < 0 || count > max_webgl_string_list_entries)- return Error::from_string_literal("WebGL string list is too long");- Vector<GLchar const*> strings;- strings.ensure_capacity(count);- size_t cursor = 0;- for (GLsizei i = 0; i < count; ++i) {- auto start = cursor;- while (cursor < bytes.size() && bytes[cursor] != 0)- ++cursor;- if (cursor >= bytes.size())- return Error::from_string_literal("WebGL string is not NUL-terminated");- strings.unchecked_append(reinterpret_cast<GLchar const*>(bytes.data() + start));- ++cursor;- }- return strings;-}--ErrorOr<void> replay_webgl_command(OpenGLContext& gl, WebGLObjectMap& objects, Commands::TransformFeedbackVaryings const& command, ReadonlyBytes payload)-{- auto varyings_bytes = WebGLCommandList::resolve_data_span(payload, command.varyings);- auto varyings = TRY(split_packed_strings(varyings_bytes, command.count));- auto program = objects.lookup(command.program);- gl.transform_feedback_varyings(program, command.count, varyings.data(), command.buffer_mode);- return {};-}--ErrorOr<ByteBuffer> handle_one(OpenGLContext& gl, WebGLObjectMap&, SyncCalls::GetString::Request const& request, ReadonlyBytes)-{- auto const* value = gl.get_string(request.name);- static constexpr u8 empty_string[] { 0 };- auto value_bytes = value- ? ReadonlyBytes { value, __builtin_strlen(reinterpret_cast<char const*>(value)) + 1 }- : ReadonlyBytes { empty_string, sizeof(empty_string) };- SyncCalls::GetString::Reply reply {- .value = { WebGLCommandList::first_inline_data_offset(sizeof(SyncCalls::GetString::Reply)), static_cast<u32>(value_bytes.size()) },- };- return WebGLSyncCall::encode_reply(reply, value_bytes);-}--ErrorOr<ByteBuffer> handle_one(OpenGLContext& gl, WebGLObjectMap&, SyncCalls::GetVertexAttribPointervRobustANGLE::Request const& request, ReadonlyBytes)-{- void* pointer = nullptr;- GLsizei length = 0;- gl.get_vertex_attrib_pointerv_robust_angle(request.index, request.pname, 1, &length, &pointer);- SyncCalls::GetVertexAttribPointervRobustANGLE::Reply reply {- .pointer = static_cast<Compositing::WebGL::GLintptr>(reinterpret_cast<uintptr_t>(pointer)),- };- return WebGLSyncCall::encode_reply(reply);-}--ErrorOr<ByteBuffer> handle_one(OpenGLContext& gl, WebGLObjectMap& objects, SyncCalls::GetUniformIndices::Request const& request, ReadonlyBytes payload)-{- auto names_bytes = WebGLCommandList::resolve_data_span(payload, request.uniform_names);- auto names = TRY(split_packed_strings(names_bytes, request.uniform_count));- auto program = objects.lookup(request.program);- Vector<GLuint> indices;- indices.resize(request.uniform_count);- gl.get_uniform_indices(program, request.uniform_count, names.data(), indices.data());- ReadonlyBytes indices_bytes { indices.data(), indices.size() * sizeof(GLuint) };- SyncCalls::GetUniformIndices::Reply reply {- .uniform_indices = { WebGLCommandList::first_inline_data_offset(sizeof(SyncCalls::GetUniformIndices::Reply)), static_cast<u32>(indices_bytes.size()) },- };- return WebGLSyncCall::encode_reply(reply, indices_bytes);-}--}diff --git a/Services/Compositor/HostWebGLContext.h b/Services/Compositor/HostWebGLContext.hdeleted file mode 100644index 41d3bc1334a..00000000000--- a/Services/Compositor/HostWebGLContext.h+++ /dev/null@@ -1,82 +0,0 @@-/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <AK/HashMap.h>-#include <AK/NonnullOwnPtr.h>-#include <AK/OwnPtr.h>-#include <AK/RefPtr.h>-#include <AK/Variant.h>-#include <Compositor/Forward.h>-#include <Compositor/OpenGLContext.h>-#include <Compositor/WebGLObjectMap.h>-#include <LibCompositing/DisplayList/DisplayListResourceIds.h>-#include <LibCompositing/WebGL/Types.h>-#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>-#include <LibCore/AnonymousBuffer.h>-#include <LibGfx/DecodedImageFrame.h>-#include <LibGfx/Forward.h>-#include <LibGfx/Size.h>-#include <LibMediaCodecs/Forward.h>--namespace Compositing::WebGL::Commands {--struct TexImage2DFromBitmap;-struct TexSubImage2DFromBitmap;-struct TexImage3DFromBitmap;-struct TexSubImage3DFromBitmap;--}--namespace Compositor {--class HostWebGLContext {-public:- AK_ALLOC_WITH_KMALLOC;-- static OwnPtr<HostWebGLContext> create(RefPtr<Gfx::SkiaBackendContext>, OpenGLContext::WebGLVersion, OpenGLContext::DrawingBufferOptions, Gfx::IntSize initial_size);-- struct MissingVideoFrame { };- using UploadSource = Variant<Gfx::DecodedImageFrame, NonnullRefPtr<Media::VideoFrame>, MissingVideoFrame>;- ErrorOr<void> execute_commands(ReadonlyBytes, Vector<UploadSource> const&);-- void set_shared_command_buffer(Compositing::WebGL::WebGLSharedCommandBuffer shared_command_buffer) { m_shared_command_buffer = move(shared_command_buffer); }- Optional<ReadonlyBytes> shared_command_buffer_range(u64 offset, u64 size_in_bytes) const;- void store_executed_flush_sequence_number(u64 flush_sequence_number) { m_shared_command_buffer.store_executed_flush_sequence_number(flush_sequence_number); }- ErrorOr<ByteBuffer> execute_sync_call(ReadonlyBytes request);- Gfx::ShareableBitmap read_back_drawing_buffer(Gfx::IntRect);- Compositing::WebGL::ReadPixelsResult read_pixels_robust_angle(Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer pixels);- bool read_buffer_sub_data(Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data);- ErrorOr<NonnullRefPtr<Gfx::PaintingSurface>> prepare_for_compositing(bool preserve_drawing_buffer);- void clear_drawing_buffer();- RefPtr<Gfx::PaintingSurface> presented_surface();- RefPtr<PresentableSurface> presented_presentable_surface() { return m_gl_context->presented_presentable_surface(); }-- OpenGLContext& gl_context() { return *m_gl_context; }--private:- HostWebGLContext(NonnullOwnPtr<OpenGLContext>, RefPtr<Gfx::SkiaBackendContext>);-- ErrorOr<void> set_drawing_buffer_size(int width, int height);- void clear_drawing_buffer_if_needed();- ErrorOr<void> tex_image2d_from_bitmap(Compositing::WebGL::Commands::TexImage2DFromBitmap const&, Vector<UploadSource> const&);- ErrorOr<void> tex_sub_image2d_from_bitmap(Compositing::WebGL::Commands::TexSubImage2DFromBitmap const&, Vector<UploadSource> const&);- ErrorOr<void> tex_image3d_from_bitmap(Compositing::WebGL::Commands::TexImage3DFromBitmap const&, Vector<UploadSource> const&);- ErrorOr<void> tex_sub_image3d_from_bitmap(Compositing::WebGL::Commands::TexSubImage3DFromBitmap const&, Vector<UploadSource> const&);-- bool define_texture_image_from_video_frame(Compositing::WebGL::Commands::TexImage2DFromBitmap const&, Media::VideoFrame const&);- bool update_texture_image_from_video_frame(Compositing::WebGL::Commands::TexSubImage2DFromBitmap const&, Media::VideoFrame const&);-- NonnullOwnPtr<OpenGLContext> m_gl_context;- RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;- WebGLObjectMap m_objects;- Compositing::WebGL::WebGLSharedCommandBuffer m_shared_command_buffer;- bool m_needs_clear_before_next_frame { false };-};--}diff --git a/Services/Compositor/OpenGLContext.cpp b/Services/Compositor/OpenGLContext.cppindex 3aa92e3e105..e4162fcf8bf 100644--- a/Services/Compositor/OpenGLContext.cpp+++ b/Services/Compositor/OpenGLContext.cpp@@ -233,6 +233,15 @@ static Microsoft::WRL::ComPtr<ID3D11Device1> get_d3d11_device(EGLDisplay display}#endif+void const* OpenGLContext::address_of_function([[maybe_unused]] char const* name)+{+#ifdef ENABLE_WEBGL+ return reinterpret_cast<void const*>(eglGetProcAddress(name));+#else+ return nullptr;+#endif+}+OwnPtr<OpenGLContext> OpenGLContext::create(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, WebGLVersion webgl_version, [[maybe_unused]] DrawingBufferOptions drawing_buffer_options){#ifdef ENABLE_WEBGL@@ -382,53 +391,6 @@ OwnPtr<OpenGLContext> OpenGLContext::create(RefPtr<Gfx::SkiaBackendContext> skia#endif}-void OpenGLContext::clear_buffer_to_default_values()-{-#ifdef ENABLE_WEBGL- GLint original_framebuffer;- GLint original_renderbuffer;- GLenum framebuffer_target = GL_FRAMEBUFFER;- GLenum framebuffer_binding = GL_FRAMEBUFFER_BINDING;- if (m_webgl_version == WebGLVersion::WebGL2) {- framebuffer_target = GL_DRAW_FRAMEBUFFER;- framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;- }- glGetIntegerv(framebuffer_binding, &original_framebuffer);- glGetIntegerv(GL_RENDERBUFFER_BINDING, &original_renderbuffer);-- glBindFramebuffer(framebuffer_target, default_framebuffer());- glBindRenderbuffer(GL_RENDERBUFFER, default_renderbuffer());-- Array<GLfloat, 4> current_clear_color;- glGetFloatv(GL_COLOR_CLEAR_VALUE, current_clear_color.data());-- GLfloat current_clear_depth;- glGetFloatv(GL_DEPTH_CLEAR_VALUE, ¤t_clear_depth);-- GLint current_clear_stencil;- glGetIntegerv(GL_STENCIL_CLEAR_VALUE, ¤t_clear_stencil);-- // The implicit clear value for the color buffer is (0, 0, 0, 0)- glClearColor(0, 0, 0, 0);-- // The implicit clear value for the depth buffer is 1.0.- glClearDepthf(1.0f);-- // The implicit clear value for the stencil buffer is 0.- glClearStencil(0);-- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);-- // Restore the clear values.- glClearColor(current_clear_color[0], current_clear_color[1], current_clear_color[2], current_clear_color[3]);- glClearDepthf(current_clear_depth);- glClearStencil(current_clear_stencil);-- glBindFramebuffer(framebuffer_target, original_framebuffer);- glBindRenderbuffer(GL_RENDERBUFFER, original_renderbuffer);-#endif-}-#ifdef ENABLE_WEBGLu32 OpenGLContext::color_buffer_texture_target() const{@@ -944,35 +906,6 @@ bool OpenGLContext::supports_pack_subimage_parameters() constreturn is_webgl2_or_has_enabled_extension("GL_NV_pack_subimage"sv);}-bool OpenGLContext::supports_unpack_subimage_parameters() const-{- return is_webgl2_or_has_enabled_extension("GL_EXT_unpack_subimage"sv);-}--GLenum OpenGLContext::get_error()-{- if (!m_stashed_errors.is_empty())- return m_stashed_errors.take_first();- return GLFunctions::get_error();-}--bool OpenGLContext::stash_errors()-{- auto stashed_any_errors = false;- for (auto error = GLFunctions::get_error(); error != GL_NO_ERROR; error = GLFunctions::get_error()) {- if (!m_stashed_errors.contains_slow(error))- m_stashed_errors.append(error);- stashed_any_errors = true;- }- return stashed_any_errors;-}--void OpenGLContext::discard_errors()-{- for (auto error = GLFunctions::get_error(); error != GL_NO_ERROR; error = GLFunctions::get_error())- dbgln("Compositor: Discarding GL error {:#x} raised by the Compositor's own work", error);-}-bool OpenGLContext::can_copy_images_into_textures(){#if defined(AK_OS_MACOS) || defined(USE_VULKAN_DMABUF_IMAGES)@@ -1071,30 +1004,4 @@ u32 OpenGLContext::default_framebuffer() constreturn m_impl->framebuffer;}-Vector<String> OpenGLContext::get_supported_opengl_extensions()-{-#ifdef ENABLE_WEBGL- make_current();-- Vector<String> extensions;-- if (auto const* extensions_string = reinterpret_cast<char const*>(glGetString(GL_EXTENSIONS))) {- StringView extensions_view(extensions_string, strlen(extensions_string));- for (auto extension : extensions_view.split_view(' '))- extensions.append(MUST(String::from_utf8(extension)));- }-- if (auto const* requestable_extensions_string = reinterpret_cast<char const*>(glGetString(GL_REQUESTABLE_EXTENSIONS_ANGLE))) {- StringView requestable_extensions_view(requestable_extensions_string, strlen(requestable_extensions_string));- for (auto extension : requestable_extensions_view.split_view(' '))- extensions.append(MUST(String::from_utf8(extension)));- }-- return extensions;-#else- (void)m_webgl_version;- return {};-#endif-}-}diff --git a/Services/Compositor/OpenGLContext.h b/Services/Compositor/OpenGLContext.hindex dd4f64f3970..da592032170 100644--- a/Services/Compositor/OpenGLContext.h+++ b/Services/Compositor/OpenGLContext.h@@ -39,8 +39,8 @@ public:};static OwnPtr<OpenGLContext> create(RefPtr<Gfx::SkiaBackendContext>, WebGLVersion, DrawingBufferOptions);+ static void const* address_of_function(char const* name);- void clear_buffer_to_default_values();void allocate_painting_surface_if_needed();struct Impl;@@ -66,17 +66,9 @@ public:u32 default_framebuffer() const;u32 default_renderbuffer() const;- Vector<String> get_supported_opengl_extensions();-- // Keeps the errors WebGL has yet to collect apart from those of the Compositor's own GL work.- GLenum get_error();- bool stash_errors();- void discard_errors();-WebGLVersion webgl_version() const { return m_webgl_version; }bool supports_pixel_buffer_objects() const;bool supports_pack_subimage_parameters() const;- bool supports_unpack_subimage_parameters() const;bool can_copy_images_into_textures();// The source size is the part of the image to copy, which can be smaller than the image.bool copy_image_into_bound_texture(SkImage const&, Gfx::IntSize source_size, Gfx::IntSize, GLenum target, GLint level, GLint xoffset, GLint yoffset, bool flip_y, bool premultiply_alpha);@@ -90,7 +82,6 @@ private:NonnullOwnPtr<Impl> m_impl;WebGLVersion m_webgl_version;[[maybe_unused]] DrawingBufferOptions m_drawing_buffer_options;- Vector<GLenum> m_stashed_errors;void free_surface_resources();void free_color_buffer(ColorBuffer&);diff --git a/Services/Compositor/Rust/build.rs b/Services/Compositor/Rust/build.rsindex d4950f2ad94..67fe0582899 100644--- a/Services/Compositor/Rust/build.rs+++ b/Services/Compositor/Rust/build.rs@@ -122,6 +122,7 @@ fn main() -> Result<(), Box<dyn Error>> {"src/cpp_object.rs","src/surfaces/painting_surface.rs","src/surfaces/presentable_surface.rs",+ "src/webgl/host.rs",] {println!("cargo:rerun-if-changed={source}");builder = builder.with_src(manifest_dir.join(source));diff --git a/Services/Compositor/Rust/src/core/messages.rs b/Services/Compositor/Rust/src/core/messages.rsindex 3da3f48b866..af4ca77fdd0 100644--- a/Services/Compositor/Rust/src/core/messages.rs+++ b/Services/Compositor/Rust/src/core/messages.rs@@ -11,6 +11,9 @@ 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 crate::raster_host::SharedMemory;+use crate::webgl::host::{ContextOptions, MappedMemory};+use crate::webgl::replay::ReplayError;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;@@ -27,19 +30,23 @@ use libcompositing_rust::ipc_types::compositor_web_content_client::messages::Diduse libcompositing_rust::ipc_types::compositor_web_content_server::messages::{ApplyScrollRequests, BeginInputTraceForTesting, BeginInputTraceForTestingResponse,ClearPerTestInputStateForTesting, ClearPerTestInputStateForTestingResponse, CreateCanvas2dContext,- DestroyCanvas2dContext, InvalidateKeyboardScrollState, InvalidateKeyboardScrollStateResponse,- InvalidateWheelEventListenerState, RasterizeDisplayList, ReserveCanvasIds, ReserveCanvasIdsResponse,- RouteFirstWheelStepForTesting, RouteFirstWheelStepForTestingResponse, ScrollStateForTesting,- ScrollStateForTestingResponse, TakeInputTraceForTesting, TakeInputTraceForTestingResponse,- TakePendingAsyncScrollUpdates, TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread,- TakeWheelEventFromMainThreadResponse, UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState,- UpdateVisualContextTree, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,+ CreateWebglContext, CreateWebglContextResponse, DestroyCanvas2dContext, DestroyWebglContext,+ InvalidateKeyboardScrollState, InvalidateKeyboardScrollStateResponse, InvalidateWheelEventListenerState,+ RasterizeDisplayList, ReserveCanvasIds, ReserveCanvasIdsResponse, RouteFirstWheelStepForTesting,+ RouteFirstWheelStepForTestingResponse, ScrollStateForTesting, ScrollStateForTestingResponse,+ TakeInputTraceForTesting, TakeInputTraceForTestingResponse, TakePendingAsyncScrollUpdates,+ TakePendingAsyncScrollUpdatesResponse, TakeWheelEventFromMainThread, TakeWheelEventFromMainThreadResponse,+ UpdateCanvas2dStream, UpdateDisplayList, UpdateScrollState, UpdateVisualContextTree, WebglClearDrawingBuffer,+ WebglCommands, WebglCommandsFromSharedBuffer, WebglDrainCommandBuffer, WebglDrainCommandBufferResponse,+ WebglPresentCanvas, WebglReadBackDrawingBuffer, WebglReadBackDrawingBufferResponse, WebglReadBufferSubData,+ WebglReadBufferSubDataResponse, WebglReadPixels, WebglReadPixelsResponse, WebglSetCommandBuffer, WebglSyncCall,+ WebglSyncCallResponse, WheelEventCanceled, WheelEventLetThrough, WheelEventLetThroughResponse,};use libcompositing_rust::ipc_types::{- Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind,+ Compositing_RemoteLayerHostHandle, Compositing_RemoteLayerHostKind, Compositing_WebGL_WebGLVersion,Compositing_WheelEventAnswer as WheelEventAnswer, Compositing_WheelStepLetThrough as WheelStepLetThrough,- LayerPlanOnWire, SharedDisplayList, compositor_control_server, compositor_presentation_server,- compositor_web_content_server,+ Core_AnonymousBuffer, LayerPlanOnWire, SharedDisplayList, compositor_control_server,+ compositor_presentation_server, compositor_web_content_server,};use libcompositing_rust::scrolling::async_scrolling_state::AsyncScrollOperationID;use libcompositing_rust::scrolling::{AccumulatedVisualContextTree, DisplayList};@@ -48,7 +55,7 @@ use libcompositing_rust::scrolling::{PinchEvent, ScrollRequest,};use libcompositing_rust::time::MonotonicTime;-use libgfx_rust::{FloatPoint, IntSize};+use libgfx_rust::{FloatPoint, IntRect, IntSize};use libipc_rust::Misbehavior;use std::io::Write;use std::rc::Rc;@@ -285,6 +292,18 @@ impl MessagesFromWebContent<'_> {}}+fn misbehavior(error: ReplayError) -> Misbehavior {+ Misbehavior(error.0)+}++impl MessagesFromWebContent<'_> {+ fn map_shared_memory(&self, buffer: Core_AnonymousBuffer) -> Result<Option<SharedMemory>, Misbehavior> {+ self.core.raster().map_shared_memory(buffer).ok_or(Misbehavior(+ "WebContent sent shared memory that does not hold as much as it claims",+ ))+ }+}+impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {fn reserve_canvas_ids(&mut self, _: ReserveCanvasIds) -> Result<ReserveCanvasIdsResponse, Misbehavior> {let reserved_ids = self@@ -326,6 +345,184 @@ impl compositor_web_content_server::Stub for MessagesFromWebContent<'_> {Ok(())}+ fn create_webgl_context(&mut self, message: CreateWebglContext) -> Result<CreateWebglContextResponse, Misbehavior> {+ let options = ContextOptions {+ webgl2: message.webgl_version == Compositing_WebGL_WebGLVersion::WebGL2,+ depth: message.depth,+ stencil: message.stencil,+ antialias: message.antialias,+ size: message.size,+ };+ let created = self+ .core+ .webgl_contexts()+ .create(self.core.raster(), self.client_id, options);+ Ok(match created {+ Some(created) => CreateWebglContextResponse {+ success: true,+ canvas_id: created.canvas_id,+ supported_extensions: created.supported_extensions.into_iter().map(Into::into).collect(),+ },+ None => CreateWebglContextResponse {+ success: false,+ canvas_id: CanvasId(0),+ supported_extensions: Vec::new(),+ },+ })+ }++ fn destroy_webgl_context(&mut self, message: DestroyWebglContext) -> Result<(), Misbehavior> {+ self.core+ .webgl_contexts()+ .destroy(self.core.raster(), self.client_id, message.canvas_id);+ Ok(())+ }++ fn webgl_set_command_buffer(&mut self, message: WebglSetCommandBuffer) -> Result<(), Misbehavior> {+ let command_buffer = self.map_shared_memory(message.command_buffer)?;+ self.core+ .webgl_contexts()+ .set_command_buffer(+ self.client_id,+ message.canvas_id,+ command_buffer.map(|memory| Box::new(memory) as Box<dyn MappedMemory>),+ )+ .map_err(misbehavior)+ }++ fn webgl_commands_from_shared_buffer(&mut self, message: WebglCommandsFromSharedBuffer) -> Result<(), Misbehavior> {+ self.core+ .webgl_contexts()+ .execute_commands_from_shared_buffer(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ message.offset,+ message.size_in_bytes,+ message.flush_sequence_number,+ &message.image_sources,+ )+ .map_err(misbehavior)+ }++ fn webgl_drain_command_buffer(+ &mut self,+ _: WebglDrainCommandBuffer,+ ) -> Result<WebglDrainCommandBufferResponse, Misbehavior> {+ Ok(WebglDrainCommandBufferResponse)+ }++ fn webgl_commands(&mut self, message: WebglCommands) -> Result<(), Misbehavior> {+ let commands = self.map_shared_memory(message.commands)?;+ self.core+ .webgl_contexts()+ .execute_commands(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ commands.as_ref().map(|memory| memory as &dyn MappedMemory),+ &message.image_sources,+ )+ .map_err(misbehavior)+ }++ fn webgl_present_canvas(&mut self, message: WebglPresentCanvas) -> Result<(), Misbehavior> {+ self.core+ .webgl_contexts()+ .present(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ message.preserve_drawing_buffer,+ )+ .map_err(misbehavior)+ }++ fn webgl_clear_drawing_buffer(&mut self, message: WebglClearDrawingBuffer) -> Result<(), Misbehavior> {+ self.core+ .webgl_contexts()+ .clear_drawing_buffer(self.core.raster(), self.client_id, message.canvas_id);+ Ok(())+ }++ fn webgl_sync_call(&mut self, message: WebglSyncCall) -> Result<WebglSyncCallResponse, Misbehavior> {+ let reply = self+ .core+ .webgl_contexts()+ .execute_sync_call(self.core.raster(), self.client_id, message.canvas_id, &message.request)+ .map_err(misbehavior)?;+ Ok(WebglSyncCallResponse { reply })+ }++ fn webgl_read_pixels(&mut self, message: WebglReadPixels) -> Result<WebglReadPixelsResponse, Misbehavior> {+ let pixels = self.map_shared_memory(message.pixels)?;+ let rect = IntRect {+ x: message.x,+ y: message.y,+ width: message.width,+ height: message.height,+ };+ let result = self+ .core+ .webgl_contexts()+ .read_pixels(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ rect,+ message.format,+ message.r#type,+ message.buf_size,+ pixels.as_ref().map(|memory| memory as &dyn MappedMemory),+ )+ .map_err(misbehavior)?;+ Ok(WebglReadPixelsResponse {+ length: result.length,+ columns: result.columns,+ rows: result.rows,+ })+ }++ fn webgl_read_buffer_sub_data(+ &mut self,+ message: WebglReadBufferSubData,+ ) -> Result<WebglReadBufferSubDataResponse, Misbehavior> {+ let data = self.map_shared_memory(message.data)?;+ let success = self+ .core+ .webgl_contexts()+ .read_buffer_sub_data(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ message.target,+ message.offset,+ message.size,+ data.as_ref().map(|memory| memory as &dyn MappedMemory),+ )+ .map_err(misbehavior)?;+ Ok(WebglReadBufferSubDataResponse { success })+ }++ fn webgl_read_back_drawing_buffer(+ &mut self,+ message: WebglReadBackDrawingBuffer,+ ) -> Result<WebglReadBackDrawingBufferResponse, Misbehavior> {+ let pixels = self.map_shared_memory(message.pixels)?;+ let size = self+ .core+ .webgl_contexts()+ .read_back_drawing_buffer(+ self.core.raster(),+ self.client_id,+ message.canvas_id,+ message.rect,+ pixels.as_ref().map(|memory| memory as &dyn MappedMemory),+ )+ .map_err(misbehavior)?;+ Ok(WebglReadBackDrawingBufferResponse { size })+ }+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 c97264acd3c..b66e0c99123 100644--- a/Services/Compositor/Rust/src/core/mod.rs+++ b/Services/Compositor/Rust/src/core/mod.rs@@ -52,6 +52,7 @@ pub struct CompositorCore {display_list_chunk_stores: RefCell<crate::display_list_chunk_stores::DisplayListChunkStores>,remote_layers: RefCell<RemoteLayers>,canvas_2d_contexts: RefCell<crate::canvas_2d_contexts::Canvas2DContexts>,+ webgl_contexts: RefCell<crate::webgl::WebGLContexts>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -126,6 +127,7 @@ impl CompositorCore {display_list_chunk_stores: RefCell::default(),remote_layers: RefCell::default(),canvas_2d_contexts: RefCell::default(),+ webgl_contexts: RefCell::default(),}}@@ -152,6 +154,10 @@ impl CompositorCore {self.canvas_2d_contexts.borrow_mut()}+ pub fn webgl_contexts(&self) -> std::cell::RefMut<'_, crate::webgl::WebGLContexts> {+ self.webgl_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 1ef7d31bc4c..8c1c866c45d 100644--- a/Services/Compositor/Rust/src/ffi.rs+++ b/Services/Compositor/Rust/src/ffi.rs@@ -613,8 +613,9 @@ 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));+ let client = WebContentClientId(web_content_client_id);+ core.canvas_2d_contexts().forget_client(client);+ core.webgl_contexts().forget_client(client);}#[unsafe(no_mangle)]diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rsindex 515ea674197..f4388c8bb88 100644--- a/Services/Compositor/Rust/src/raster_host.rs+++ b/Services/Compositor/Rust/src/raster_host.rs@@ -9,10 +9,15 @@//! submission, and the display ticks. None of these calls comes back into the core before it returns.use crate::backing_stores::{FfiNewStore, NewStore, Publication, SharedImageToPublish, StoreKind};-use crate::cpp_object::FfiCppObject;+use crate::cpp_object::{CppObject, FfiCppObject};+use crate::host::WebContentClientId;use crate::remote_layers::{RemoteLayerHost, RemoteLayerObject, WindowServerObject};use crate::surfaces::painting_surface::PaintingSurface;use crate::surfaces::presentable_surface::PresentableSurface;+use crate::webgl::host::{+ ContextOptions, DefaultBuffers, ImageConversion, ImageConversionOutcome, PresentOutcome, VideoFrameCopy, WebGLHost,+};+use libcompositing_rust::display_list::commands::VideoSinkHandle;use libcompositing_rust::display_list::commands::{CanvasId, CompositorContextId, DisplayListCommandType};use libcompositing_rust::display_list::storage::{ListChunk, PackedChunkSize, receive_packed_chunks_from_shared_memory,@@ -23,9 +28,10 @@ use libcompositing_rust::ipc_types::{Web_Bindings_PredefinedColorSpace,};use libcompositing_rust::time::MonotonicTime;+use libcompositing_rust::webgl::ImageSource;use libgfx_rust::{Color, FloatRect, IntRect, IntSize, ScalingMode};use std::collections::HashMap;-use std::ffi::c_void;+use std::ffi::{CStr, c_char, c_void};use std::ptr::NonNull;use std::rc::Rc;@@ -325,6 +331,87 @@ pub struct FfiRasterHost {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>),++ /// Answers the address of the GL function of the name, or null.+ pub gl_proc_address: unsafe extern "C" fn(*mut c_void, *const c_char) -> *const c_void,+ /// Arguments: the client, the canvas, and what its context is made with. Answers whether a GL context with a+ /// drawing buffer could be made.+ pub create_webgl_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId, ContextOptions) -> bool,+ pub destroy_webgl_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId),+ /// Makes the GL context of the client's canvas current, and writes its default framebuffer and renderbuffer.+ pub make_webgl_context_current: unsafe extern "C" fn(*mut c_void, u64, CanvasId, *mut DefaultBuffers),+ pub set_webgl_drawing_buffer_size: unsafe extern "C" fn(*mut c_void, u64, CanvasId, IntSize),+ /// Arguments: the client, the canvas, whether the drawing buffer is preserved, and whether the frame presented last+ /// goes on being shown where there is one.+ pub present_webgl_context: unsafe extern "C" fn(*mut c_void, u64, CanvasId, bool, bool) -> PresentOutcome,+ /// Arguments: the client, the canvas, whether the frame presented last is read rather than the drawing buffer, the+ /// rect, where the pixels go, how many bytes fit there, and where the size of what was read is written.+ pub read_back_webgl_drawing_buffer:+ unsafe extern "C" fn(*mut c_void, u64, CanvasId, bool, IntRect, *mut u8, usize, *mut IntSize) -> bool,+ pub webgl_can_copy_images_into_textures: unsafe extern "C" fn(*mut c_void, u64, CanvasId) -> bool,+ /// Arguments: the client, the sink of the video, the generation of its frame, and where the frame and its size are+ /// written. Answers whether the client holds that frame.+ pub held_video_frame: unsafe extern "C" fn(*mut c_void, u64, u64, u64, *mut FfiCppObject, *mut IntSize) -> bool,+ /// Writes an image of the frame on the GPU, which is null where there cannot be one.+ pub video_frame_image: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut FfiCppObject),+ pub copy_video_frame_image_into_bound_texture:+ unsafe extern "C" fn(*mut c_void, u64, CanvasId, *mut c_void, VideoFrameCopy) -> bool,+ pub convert_image_source_for_webgl: unsafe extern "C" fn(+ *mut c_void,+ u64,+ FfiImageSource,+ FfiImageConversion,+ *mut FfiConvertedPixels,+ ) -> FfiImageConversionOutcome,+}++#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiImageSource {+ pub is_held_video_frame: bool,+ pub id: u64,+ pub generation: u64,+}++#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiImageConversion {+ /// A `Gfx::ExportFormat`.+ pub export_format: u8,+ pub flip_y: bool,+ pub premultiply_alpha: bool,+ pub has_target_size: bool,+ pub target_size: IntSize,+}++#[repr(C)]+pub struct FfiConvertedPixels {+ pub pixels: FfiCppObject,+ pub data: *const u8,+ pub size: usize,+ pub width: i32,+ pub height: i32,+}++#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum FfiImageConversionOutcome {+ Converted,+ UnknownImageFrame,+ Failed,+}++pub struct ConvertedPixels {+ _owner: CppObject,+ data: *const u8,+ size: usize,+}++impl AsRef<[u8]> for ConvertedPixels {+ fn as_ref(&self) -> &[u8] {+ // SAFETY: The owner keeps the bytes for as long as this lives, and nothing writes them.+ unsafe { ak::slice_from_raw_parts(self.data, self.size) }+ }}/// Shared memory that WebContent sent, mapped until this is dropped.@@ -887,6 +974,198 @@ impl RasterHost {}}+impl WebGLHost for RasterHost {+ type Pixels = ConvertedPixels;+ type VideoFrame = CppObject;+ type VideoFrameImage = CppObject;++ fn gl_proc_address(&self, name: &CStr) -> *const c_void {+ // SAFETY: The host outlives this, and reads the name during the call.+ unsafe { (self.0.gl_proc_address)(self.host(), name.as_ptr()) }+ }++ fn allocate_canvas_id(&self) -> CanvasId {+ CanvasId(self.reserve_canvas_ids(1))+ }++ fn create_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId, options: ContextOptions) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.create_webgl_context)(self.host(), client.0, canvas_id, options) }+ }++ fn destroy_webgl_context(&self, client: WebContentClientId, canvas_id: CanvasId) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.destroy_webgl_context)(self.host(), client.0, canvas_id) };+ }++ fn make_webgl_context_current(&self, client: WebContentClientId, canvas_id: CanvasId) -> DefaultBuffers {+ let mut defaults = DefaultBuffers::default();+ // SAFETY: The host outlives this, and writes the default buffers.+ unsafe { (self.0.make_webgl_context_current)(self.host(), client.0, canvas_id, &raw mut defaults) };+ defaults+ }++ fn set_webgl_drawing_buffer_size(&self, client: WebContentClientId, canvas_id: CanvasId, size: IntSize) {+ // SAFETY: The host outlives this.+ unsafe { (self.0.set_webgl_drawing_buffer_size)(self.host(), client.0, canvas_id, size) };+ }++ fn present_webgl_context(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ preserve_drawing_buffer: bool,+ show_presented_frame: bool,+ ) -> PresentOutcome {+ // SAFETY: The host outlives this.+ unsafe {+ (self.0.present_webgl_context)(+ self.host(),+ client.0,+ canvas_id,+ preserve_drawing_buffer,+ show_presented_frame,+ )+ }+ }++ unsafe fn read_back_webgl_drawing_buffer(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ from_presented_frame: bool,+ rect: IntRect,+ pixels: *mut u8,+ pixels_size: usize,+ ) -> Option<IntSize> {+ let mut size = IntSize::default();+ // SAFETY: The host outlives this, the caller passes as many writable bytes, and the host writes the size.+ unsafe {+ (self.0.read_back_webgl_drawing_buffer)(+ self.host(),+ client.0,+ canvas_id,+ from_presented_frame,+ rect,+ pixels,+ pixels_size,+ &raw mut size,+ )+ }+ .then_some(size)+ }++ fn webgl_can_copy_images_into_textures(&self, client: WebContentClientId, canvas_id: CanvasId) -> bool {+ // SAFETY: The host outlives this.+ unsafe { (self.0.webgl_can_copy_images_into_textures)(self.host(), client.0, canvas_id) }+ }++ fn held_video_frame(+ &self,+ client: WebContentClientId,+ sink_handle: VideoSinkHandle,+ generation: u64,+ ) -> Option<(CppObject, IntSize)> {+ let mut frame = FfiCppObject::default();+ let mut size = IntSize::default();+ // SAFETY: The host outlives this, and writes the frame and its size where it answers true.+ let held = unsafe {+ (self.0.held_video_frame)(+ self.host(),+ client.0,+ sink_handle.0,+ generation,+ &raw mut frame,+ &raw mut size,+ )+ };+ if !held {+ return None;+ }+ // SAFETY: The host handed the frame over.+ unsafe { CppObject::adopt(frame) }.map(|frame| (frame, size))+ }++ fn video_frame_image(&self, frame: &CppObject) -> Option<CppObject> {+ let mut image = FfiCppObject::default();+ // SAFETY: The host outlives this, the frame is one it made, and it writes an image or null.+ unsafe { (self.0.video_frame_image)(self.host(), frame.as_ptr(), &raw mut image) };+ // SAFETY: The host handed the image over, if there is one.+ unsafe { CppObject::adopt(image) }+ }++ fn copy_video_frame_image_into_bound_texture(+ &self,+ client: WebContentClientId,+ canvas_id: CanvasId,+ image: &CppObject,+ copy: VideoFrameCopy,+ ) -> bool {+ // SAFETY: The host outlives this, and the image is one it made.+ unsafe {+ (self.0.copy_video_frame_image_into_bound_texture)(self.host(), client.0, canvas_id, image.as_ptr(), copy)+ }+ }++ fn convert_image_source(+ &self,+ client: WebContentClientId,+ source: ImageSource,+ conversion: ImageConversion,+ ) -> ImageConversionOutcome<ConvertedPixels> {+ let source = match source {+ ImageSource::RegisteredImageFrame(id) => FfiImageSource {+ is_held_video_frame: false,+ id: id.0,+ generation: 0,+ },+ ImageSource::HeldVideoFrame {+ sink_handle,+ generation,+ } => FfiImageSource {+ is_held_video_frame: true,+ id: sink_handle.0,+ generation,+ },+ };+ let conversion = FfiImageConversion {+ export_format: conversion.export_format as u8,+ flip_y: conversion.flip_y,+ premultiply_alpha: conversion.premultiply_alpha,+ has_target_size: conversion.target_size.is_some(),+ target_size: conversion.target_size.unwrap_or_default(),+ };+ let mut converted = FfiConvertedPixels {+ pixels: FfiCppObject::default(),+ data: std::ptr::null(),+ size: 0,+ width: 0,+ height: 0,+ };+ // SAFETY: The host outlives this, and writes the converted pixels where it answers that it converted them.+ let outcome = unsafe {+ (self.0.convert_image_source_for_webgl)(self.host(), client.0, source, conversion, &raw mut converted)+ };+ match outcome {+ FfiImageConversionOutcome::Converted => {+ // SAFETY: The host handed the pixels over.+ let owner = unsafe { CppObject::adopt(converted.pixels) }.expect("converted pixels have an owner");+ ImageConversionOutcome::Converted {+ pixels: ConvertedPixels {+ _owner: owner,+ data: converted.data,+ size: converted.size,+ },+ width: converted.width,+ height: converted.height,+ }+ }+ FfiImageConversionOutcome::UnknownImageFrame => ImageConversionOutcome::UnknownImageFrame,+ FfiImageConversionOutcome::Failed => ImageConversionOutcome::Failed,+ }+ }+}+pub struct Canvas2DPainting<'a> {raster: &'a RasterHost,painter: FfiCanvas2DPainter,diff --git a/Services/Compositor/Rust/src/webgl/host.rs b/Services/Compositor/Rust/src/webgl/host.rsindex 9cf224c2341..616a5b64cae 100644--- a/Services/Compositor/Rust/src/webgl/host.rs+++ b/Services/Compositor/Rust/src/webgl/host.rs@@ -57,6 +57,7 @@ pub enum ImageConversionOutcome<P> {}#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(C)]pub struct VideoFrameCopy {/// The part of the frame to copy, from its top left.pub source_size: IntSize,diff --git a/Services/Compositor/WebGLObjectMap.cpp b/Services/Compositor/WebGLObjectMap.cppdeleted file mode 100644index 56f755e6b87..00000000000--- a/Services/Compositor/WebGLObjectMap.cpp+++ /dev/null@@ -1,64 +0,0 @@-/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <Compositor/WebGLObjectMap.h>--namespace Compositor {--template<typename Value>-static Value lookup_or_default(HashMap<Compositing::WebGL::WebGLObjectId, Value> const& map, Compositing::WebGL::WebGLObjectId id)-{- return map.get(id).value_or(Value {});-}--template<typename Value>-static Value take_or_default(HashMap<Compositing::WebGL::WebGLObjectId, Value>& map, Compositing::WebGL::WebGLObjectId id)-{- return map.take(id).value_or(Value {});-}--template<typename Value>-static ErrorOr<void> add_unique(HashMap<Compositing::WebGL::WebGLObjectId, Value>& map, Compositing::WebGL::WebGLObjectId id, Value value)-{- if (id == 0)- return Error::from_string_literal("WebGL object id 0 is reserved");- if (map.contains(id))- return Error::from_string_literal("WebGL object id is already in use");- map.set(id, value);- return {};-}--GLuint WebGLObjectMap::lookup(Compositing::WebGL::WebGLObjectId id) const-{- return lookup_or_default(m_objects, id);-}--GLuint WebGLObjectMap::take(Compositing::WebGL::WebGLObjectId id)-{- return take_or_default(m_objects, id);-}--ErrorOr<void> WebGLObjectMap::add(Compositing::WebGL::WebGLObjectId id, GLuint name)-{- return add_unique(m_objects, id, name);-}--GLsync WebGLObjectMap::lookup_sync(Compositing::WebGL::WebGLObjectId id) const-{- return lookup_or_default(m_syncs, id);-}--GLsync WebGLObjectMap::take_sync(Compositing::WebGL::WebGLObjectId id)-{- return take_or_default(m_syncs, id);-}--ErrorOr<void> WebGLObjectMap::add_sync(Compositing::WebGL::WebGLObjectId id, GLsync sync)-{- return add_unique(m_syncs, id, sync);-}--}diff --git a/Services/Compositor/WebGLObjectMap.h b/Services/Compositor/WebGLObjectMap.hdeleted file mode 100644index 8d18ea3e04b..00000000000--- a/Services/Compositor/WebGLObjectMap.h+++ /dev/null@@ -1,31 +0,0 @@-/*- * Copyright (c) 2026, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <AK/HashMap.h>-#include <LibCompositing/WebGL/GLFunctions.h>-#include <LibCompositing/WebGL/Types.h>--namespace Compositor {--class WebGLObjectMap {-public:- GLuint lookup(Compositing::WebGL::WebGLObjectId) const;- GLuint take(Compositing::WebGL::WebGLObjectId);- ErrorOr<void> add(Compositing::WebGL::WebGLObjectId, GLuint);-- GLsync lookup_sync(Compositing::WebGL::WebGLObjectId) const;- GLsync take_sync(Compositing::WebGL::WebGLObjectId);- ErrorOr<void> add_sync(Compositing::WebGL::WebGLObjectId, GLsync);--private:- HashMap<Compositing::WebGL::WebGLObjectId, GLuint> m_objects;- HashMap<Compositing::WebGL::WebGLObjectId, GLsync> m_syncs;-};--}diff --git a/Tests/LibWeb/Text/expected/WebGL/tex-image-2d-animated-image-uploads-first-frame.txt b/Tests/LibWeb/Text/expected/WebGL/tex-image-2d-animated-image-uploads-first-frame.txtnew file mode 100644index 00000000000..ea7e7363b7f--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebGL/tex-image-2d-animated-image-uploads-first-frame.txt@@ -0,0 +1 @@+uploaded pixel: 0,255,0,255diff --git a/Tests/LibWeb/Text/input/WebGL/tex-image-2d-animated-image-uploads-first-frame.html b/Tests/LibWeb/Text/input/WebGL/tex-image-2d-animated-image-uploads-first-frame.htmlnew file mode 100644index 00000000000..bdd733cc80f--- /dev/null+++ b/Tests/LibWeb/Text/input/WebGL/tex-image-2d-animated-image-uploads-first-frame.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<!-- The first frame of the animated image is green, and the next one is red. -->+<img id="image" src="data:image/gif;base64,R0lGODlhZAAyAPAAAAD/AAAAACH5BAABAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAZAAyAAACTYSPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5LL5bCsAACH5BAAQJwAALAAAAABkADIAgP8AAAAAAAJNhI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvlsKwAAOw==">+<script>+ promiseTest(async () => {+ const image = document.getElementById("image");+ await waitForImageAnimationState(image.src, state => state.shownFrameIndex > 0);++ const gl = document.createElement("canvas").getContext("webgl");+ gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);+ gl.bindFramebuffer(gl.FRAMEBUFFER, gl.createFramebuffer());+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, gl.getParameter(gl.TEXTURE_BINDING_2D), 0);+ const pixel = new Uint8Array(4);+ gl.readPixels(50, 25, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);+ println(`uploaded pixel: ${Array.from(pixel).join(",")}`);+ });+</script>