Truly independent web browser
LibWeb: Fire WebGL context events from Rust
Aliaksandr Kalenikdaadd2e2231a
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex a4c9afc028f..eeb31397675 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -91,6 +91,7 @@ pub(crate) enum TaskSource {Permissions = 18,FontLoading = 19,Gamepad = 25,+ WebGL = 26,Crypto = 27,Storage = 29,}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 6178f694599..7556a442342 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -469,6 +469,7 @@ pub unsafe extern "C" fn web_rust_shut_down_agent(vm: *mut c_void) {let vm = unsafe { &*vm.cast::<Vm>() };MessagePort::shut_down_ports_of_agent(vm);crate::html::broadcast_channel::forget_broadcast_channels_of_agent();+ crate::web_gl::context_loss::forget_contexts_of_agent();crate::web_assembly::Agent::shut_down();crate::indexed_db::internal::storage::shut_down_storage();crate::permissions_api::permission_store::forget_statuses_of_this_agent();diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rsindex 437c514acd6..e3472588631 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs@@ -14,6 +14,7 @@ use libgfx_rust::image_frame::ImageFrameHandle;use libjs_rust::api::{Gc, Object, Realm};use crate::bindings::conversions::CppInterface;+use crate::bindings::event_target::CppEventTarget;use crate::canvas_2d::host::TransportAbi;use crate::compositor_connection::CompositorConnection;@@ -28,6 +29,8 @@ pub(crate) enum TexImageSourceKind {unsafe extern "C" {fn web_webgl_canvas_did_change_content(canvas_host: *mut c_void);+ fn web_webgl_canvas_did_create_backing_storage(canvas_host: *mut c_void);+ fn web_webgl_canvas_event_target(canvas_host: *mut c_void) -> *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;@@ -51,6 +54,15 @@ impl Canvas {unsafe { web_webgl_canvas_did_change_content(self.host.as_ptr()) };}+ pub(crate) fn did_create_backing_storage(self) {+ unsafe { web_webgl_canvas_did_create_backing_storage(self.host.as_ptr()) };+ }++ pub(crate) fn event_target(self) -> CppEventTarget {+ // SAFETY: The event target of a canvas is the canvas.+ unsafe { CppEventTarget::from_raw(web_webgl_canvas_event_target(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.diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rsnew file mode 100644index 00000000000..1880ab2919f--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/context_loss.rs@@ -0,0 +1,140 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::cell::RefCell;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, GcWeak, MarkedVec, Vm};++use super::canvas::Canvas;+use super::exports::create_remote_context;+use super::state::{ContextRef, RenderingContext, WebGL1, WebGL2};+use super::web_gl_context_event::{WebGLContextEvent, WebGLContextEventInit};+use crate::bindings::interface::Wrapped;+use crate::bindings::promise::{TaskSource, queue_a_task};+use crate::dom::event::EventInit;++#[derive(Clone)]+enum WeakContext {+ WebGL1(GcWeak<EmbedderCell<Wrapped<RenderingContext<WebGL1>>>>),+ WebGL2(GcWeak<EmbedderCell<Wrapped<RenderingContext<WebGL2>>>>),+}++impl WeakContext {+ fn get(&self) -> Option<ContextRef> {+ match self {+ Self::WebGL1(context) => context.get().map(ContextRef::WebGL1),+ Self::WebGL2(context) => context.get().map(ContextRef::WebGL2),+ }+ }+}++struct ContextsOfThisThread {+ contexts: Vec<WeakContext>,+ live_after_pruning: usize,+}++impl ContextsOfThisThread {+ const CONTEXTS_BEFORE_FIRST_PRUNING: usize = 128;++ fn add(&mut self, vm: &Vm, context: ContextRef) {+ if self.contexts.len() >= (2 * self.live_after_pruning).max(Self::CONTEXTS_BEFORE_FIRST_PRUNING) {+ self.contexts.retain(|context| context.get().is_some());+ self.live_after_pruning = self.contexts.len();+ }+ self.contexts.push(match context {+ ContextRef::WebGL1(context) => WeakContext::WebGL1(GcWeak::new(vm.heap(), context)),+ ContextRef::WebGL2(context) => WeakContext::WebGL2(GcWeak::new(vm.heap(), context)),+ });+ }+}++thread_local! {+ static CONTEXTS_OF_THIS_THREAD: RefCell<ContextsOfThisThread> = const {+ RefCell::new(ContextsOfThisThread {+ contexts: Vec::new(),+ live_after_pruning: 0,+ })+ };+}++pub(crate) fn register_context(vm: &Vm, context: ContextRef) {+ CONTEXTS_OF_THIS_THREAD.with_borrow_mut(|contexts| contexts.add(vm, context));+}++pub(crate) fn forget_contexts_of_agent() {+ CONTEXTS_OF_THIS_THREAD.with_borrow_mut(|contexts| {+ contexts.contexts.clear();+ contexts.live_after_pruning = 0;+ });+}++fn live_contexts_of_this_thread(vm: &Vm) -> MarkedVec<'_, ContextRef> {+ let live_contexts = MarkedVec::new(vm);+ CONTEXTS_OF_THIS_THREAD.with_borrow(|contexts| {+ for context in contexts.contexts.iter().filter_map(WeakContext::get) {+ live_contexts.push(context);+ }+ });+ live_contexts+}++// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-event+pub(crate) fn fire_webgl_context_event(vm: &Vm, canvas: Canvas, event_type: &str) -> bool {+ let Some(realm) = canvas.relevant_realm() else {+ return true;+ };+ // To fire a WebGL context event named e means that an event using the WebGLContextEvent interface, with its type attribute [DOM4] initialized to e, its cancelable attribute initialized to true, and its isTrusted attribute [DOM4] initialized to true, is to be dispatched at the given object.+ // FIXME: Consider setting a status message.+ let event_init = WebGLContextEventInit {+ parent: EventInit {+ bubbles: false,+ cancelable: true,+ composed: false,+ },+ status_message: Utf16String::from_utf8(""),+ };+ let event = WebGLContextEvent::create(vm, realm, &Utf16String::from_utf8(event_type), &event_init);+ event.event().set_is_trusted(true);+ canvas.event_target().dispatch_event(event.event())+}++pub(crate) fn lose_contexts_of_this_thread(vm: &Vm) {+ let contexts = live_contexts_of_this_thread(vm);+ for index in 0..contexts.len() {+ let context = contexts.get(index).expect("the index is in bounds");+ let state = context.state();+ if !state.mark_lost() {+ continue;+ }+ queue_a_task(vm, state.realm(), TaskSource::WebGL, context, |vm, context| {+ let state = context.state();+ let page_wants_context_restored = !fire_webgl_context_event(vm, state.canvas(), "webglcontextlost");+ state.set_context_restore_requested(page_wants_context_restored);+ });+ }+}++pub(crate) fn restore_contexts_of_this_thread(vm: &Vm) {+ let contexts = live_contexts_of_this_thread(vm);+ for index in 0..contexts.len() {+ let context = contexts.get(index).expect("the index is in bounds");+ let state = context.state();+ if !state.wants_restoring() {+ continue;+ }+ let Some((remote_context, supported_opengl_extensions)) =+ create_remote_context(state.canvas(), state.is_webgl2(), &state.actual_context_parameters)+ else {+ continue;+ };+ state.restore(remote_context, supported_opengl_extensions);+ state.canvas().did_create_backing_storage();+ queue_a_task(vm, state.realm(), TaskSource::WebGL, context, |vm, context| {+ fire_webgl_context_event(vm, context.state().canvas(), "webglcontextrestored");+ });+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rsindex cc7fde0a8fd..229138c5e9e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/exports.rs@@ -11,9 +11,12 @@ use core::ffi::c_void;use core::marker::PhantomData;use core::ptr::NonNull;-use ak::Utf16String;+use libjs_rust::api::Vm;use super::canvas::Canvas;+use super::context_loss::{+ fire_webgl_context_event, lose_contexts_of_this_thread, register_context, restore_contexts_of_this_thread,+};use super::fingerprint::verify_that_rust_and_cpp_agree_on_layouts_and_constants;use super::host::{ContextCreation, RemoteContext};use super::proxy::recorder::Proxy;@@ -21,11 +24,9 @@ use super::state::{ContextParameters, ContextRef, ContextState, RenderingContext, WebGL1, WebGL2, WebGLVersion,drawing_buffer_dimension,};-use super::web_gl_context_event::{WebGLContextEvent, WebGLContextEventInit};use super::web_gl_rendering_context::WebGLPowerPreference;use super::web_gl_rendering_context_base::WebGLContextAttributes;use crate::bindings::interface::{Interface, allocate, cell_into_abi, realm_arguments};-use crate::dom::event::EventInit;/// Mirrors `Web::WebGL::ContextAttributes`.#[derive(Clone, Copy)]@@ -95,7 +96,7 @@ pub struct ContextCreationArguments {context_attributes: ContextAttributes,}-fn create_remote_context(+pub(super) fn create_remote_context(canvas: Canvas,webgl2: bool,context_attributes: &WebGLContextAttributes,@@ -166,6 +167,9 @@ pub unsafe extern "C" fn web_webgl_context_create(let Some((remote_context, supported_opengl_extensions)) =create_remote_context(canvas, version == WebGLVersion::WebGL2, &context_attributes)else {+ // https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-creation-error+ // 1. Fire a WebGL context event named "webglcontextcreationerror" at canvas, optionally with its statusMessage attribute set to a platform dependent string about the nature of the failure.+ fire_webgl_context_event(vm, canvas, "webglcontextcreationerror");return core::ptr::null_mut();};let parameters = ContextParameters {@@ -176,12 +180,16 @@ pub unsafe extern "C" fn web_webgl_context_create(context_attributes,supported_opengl_extensions,};+ // 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_backing_storage();match version {WebGLVersion::WebGL1 => {let context = allocate(vm, |defer_gc| {RenderingContext::<WebGL1>::new(defer_gc, ContextState::new(defer_gc, parameters))});context.set_context_ref(ContextRef::WebGL1(context));+ register_context(vm, ContextRef::WebGL1(context));cell_into_abi(context)}WebGLVersion::WebGL2 => {@@ -189,16 +197,12 @@ pub unsafe extern "C" fn web_webgl_context_create(RenderingContext::<WebGL2>::new(defer_gc, ContextState::new(defer_gc, parameters))});context.set_context_ref(ContextRef::WebGL2(context));+ register_context(vm, ContextRef::WebGL2(context));cell_into_abi(context)}}}-#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_canvas_host(context: &ContextCell) -> *mut c_void {- with_context(context, |context| context.canvas().host.as_ptr())-}-#[unsafe(no_mangle)]pub extern "C" fn web_webgl_context_is_lost(context: &ContextCell) -> bool {with_context(context, ContextState::is_context_lost)@@ -250,35 +254,22 @@ pub extern "C" fn web_webgl_context_read_back_drawing_buffer(frame.map_or(core::ptr::null_mut(), |frame| frame.hand_over_copy())}-/// False when the context was lost already.-#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_mark_lost(context: &ContextCell) -> bool {- with_context(context, ContextState::mark_lost)-}--#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_set_restore_requested(context: &ContextCell, requested: bool) {- with_context(context, |context| context.set_context_restore_requested(requested));-}-+/// # Safety+///+/// `vm` must be the live VM of the thread.#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_wants_restoring(context: &ContextCell) -> bool {- with_context(context, ContextState::wants_restoring)+pub unsafe extern "C" fn web_webgl_lose_contexts_of_this_thread(vm: *mut c_void) {+ // SAFETY: The caller passes the live VM.+ lose_contexts_of_this_thread(unsafe { &*vm.cast::<Vm>() });}+/// # Safety+///+/// `vm` must be the live VM of the thread.#[unsafe(no_mangle)]-pub extern "C" fn web_webgl_context_restore(context: &ContextCell) -> bool {- with_context(context, |context| {- 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- })+pub unsafe extern "C" fn web_webgl_restore_contexts_of_this_thread(vm: *mut c_void) {+ // SAFETY: The caller passes the live VM.+ restore_contexts_of_this_thread(unsafe { &*vm.cast::<Vm>() });}/// Converts the options of getContext() to the dictionary, and answers true with the exception that the conversion@@ -315,29 +306,3 @@ pub unsafe extern "C" fn web_webgl_context_attributes_from_value(}}}--/// # Safety-///-/// `vm` must be the live VM, `realm` a live realm, and `type` a raw AK::Utf16String that the call takes over.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_webgl_context_event_create(- vm: *mut c_void,- realm: *mut c_void,- r#type: usize,-) -> *mut c_void {- // SAFETY: The caller passes the live VM and a live realm.- let (vm, realm) = unsafe { realm_arguments(vm, realm) };- // SAFETY: The caller hands over the type.- let r#type = unsafe { Utf16String::from_raw_owned(r#type) };- let event_init = WebGLContextEventInit {- parent: EventInit {- bubbles: false,- cancelable: true,- composed: false,- },- status_message: Utf16String::from_utf8(""),- };- let event = WebGLContextEvent::create(vm, realm, &r#type, &event_init);- event.event().set_is_trusted(true);- event.event().as_ptr()-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rsindex 178e608aa1d..8afb6968e0f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/mod.rs@@ -21,6 +21,8 @@ pub(crate) mod buffer_source;#[cfg(not(test))]pub(crate) mod canvas;#[cfg(not(test))]+pub(crate) mod context_loss;+#[cfg(not(test))]pub(crate) mod exports;#[cfg(not(test))]pub(crate) mod extensions;diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 6cd0eb8302e..3b2fa50248d 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -548,6 +548,7 @@ static_assert(to_underlying(HTML::Task::Source::FileReading) == 13);static_assert(to_underlying(HTML::Task::Source::PerformanceTimeline) == 15);static_assert(to_underlying(HTML::Task::Source::Clipboard) == 17);static_assert(to_underlying(HTML::Task::Source::Permissions) == 18);+static_assert(to_underlying(HTML::Task::Source::WebGL) == 26);static_assert(to_underlying(HTML::Task::Source::Crypto) == 27);static_assert(to_underlying(HTML::Task::Source::Storage) == 29);diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 373dc5f1477..607fa9cfc12 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -902,7 +902,6 @@ set(SOURCESWebDriver/JSON.cppWebDriver/Screenshot.cppWebDriver/UserPrompt.cpp- WebGL/EventNames.cppWebGL/RemoteWebGLTransportFFI.cppWebGL/WebGLRenderingContextBase.cppWebIDL/AbstractOperations.cppdiff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cppindex 0bfa53ace31..80173da347c 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp@@ -555,12 +555,6 @@ Optional<Compositing::CanvasId> HTMLCanvasElement::canvas_id() constreturn {};}-void HTMLCanvasElement::notify_compositor_connection_lost()-{- if (auto* webgl_context = canvas_webgl_context())- webgl_context->lose_context_from_compositor_loss();-}-void HTMLCanvasElement::set_canvas_content_dirty(){m_canvas_content_dirty = true;@@ -600,10 +594,6 @@ void HTMLCanvasElement::prepare_for_compositing()void HTMLCanvasElement::notify_compositor_backing_storage_lost(){- if (auto* webgl_context = canvas_webgl_context()) {- webgl_context->restore_context_after_compositor_reconnect();- return;- }if (auto context_2d = canvas_rendering_context_2d())context_2d->notify_backing_storage_lost();}diff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.h b/Libraries/LibWeb/HTML/HTMLCanvasElement.hindex eaa613f55f5..7bc1df84359 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.h+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.h@@ -86,8 +86,6 @@ public:void ensure_backing_storage();- void notify_compositor_connection_lost();-private:HTMLCanvasElement(DOM::Document&, DOM::QualifiedName);diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex 643d1f466ac..35db83a231b 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -15,6 +15,7 @@#include <LibGfx/Bitmap.h>#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>+#include <LibJS/HostClassBuilder.h>#include <LibWeb/Bindings/CSS.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/CSS/StyleEngineInput.h>@@ -67,6 +68,13 @@#include <LibWebCommon/HTML/SelectedFile.h>#include <LibWebCommon/Loader/ContentBlocking.h>+extern "C" {++// Defined in Bindings/Rust/src/web_gl/exports.rs.+void web_webgl_lose_contexts_of_this_thread(JSVM*);+void web_webgl_restore_contexts_of_this_thread(JSVM*);+}+namespace Web {GC_DEFINE_ALLOCATOR(Page);@@ -2031,6 +2039,7 @@ void Page::prepare_canvas_contexts_for_compositing()void Page::notify_all_canvas_elements_of_lost_backing_storage(){+ web_webgl_restore_contexts_of_this_thread(JS::HostABI::vm_to_abi(JS::VM::the()));for_each_canvas_element([](auto& canvas_element) {canvas_element.notify_compositor_backing_storage_lost();});@@ -2038,9 +2047,7 @@ void Page::notify_all_canvas_elements_of_lost_backing_storage()void Page::notify_all_webgl_contexts_lost(){- for_each_canvas_element([](auto& canvas_element) {- canvas_element.notify_compositor_connection_lost();- });+ web_webgl_lose_contexts_of_this_thread(JS::HostABI::vm_to_abi(JS::VM::the()));}void Page::record_context_menu_request(Badge<EventHandler>, ContextMenuRequest request)diff --git a/Libraries/LibWeb/WebGL/EventNames.cpp b/Libraries/LibWeb/WebGL/EventNames.cppdeleted file mode 100644index e4b6d20c29d..00000000000--- a/Libraries/LibWeb/WebGL/EventNames.cpp+++ /dev/null@@ -1,16 +0,0 @@-/*- * Copyright (c) 2023, Kenneth Myhra <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/WebGL/EventNames.h>--namespace Web::WebGL::EventNames {--#define __ENUMERATE_GL_EVENT(name) \- Utf16FlyString const& name = *new Utf16FlyString(#name##_utf16_fly_string);-ENUMERATE_GL_EVENTS-#undef __ENUMERATE_GL_EVENT--}diff --git a/Libraries/LibWeb/WebGL/EventNames.h b/Libraries/LibWeb/WebGL/EventNames.hdeleted file mode 100644index 11e3b4247d3..00000000000--- a/Libraries/LibWeb/WebGL/EventNames.h+++ /dev/null@@ -1,22 +0,0 @@-/*- * Copyright (c) 2023, Kenneth Myhra <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Utf16FlyString.h>--namespace Web::WebGL::EventNames {--#define ENUMERATE_GL_EVENTS \- __ENUMERATE_GL_EVENT(webglcontextcreationerror) \- __ENUMERATE_GL_EVENT(webglcontextlost) \- __ENUMERATE_GL_EVENT(webglcontextrestored)--#define __ENUMERATE_GL_EVENT(name) extern Utf16FlyString const& name;-ENUMERATE_GL_EVENTS-#undef __ENUMERATE_GL_EVENT--}diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cppindex b478e5e7ce9..d3e797e734d 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp@@ -7,7 +7,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Utf16FlyString.h>#include <AK/Vector.h>#include <LibGfx/Bitmap.h>#include <LibGfx/DecodedImageFrame.h>@@ -16,16 +15,13 @@#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/WrapperWorld.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/OffscreenCanvas.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/WebGL/EventNames.h>#include <LibWeb/WebGL/WebGL2RenderingContext.h>#include <LibWeb/WebGL/WebGLRenderingContext.h>#include <LibWeb/WebGL/WebGLRenderingContextBase.h>@@ -57,22 +53,18 @@ 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_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);void web_webgl_context_present_for_compositing(void* context);void web_webgl_context_clear_drawing_buffer(void* context);void* web_webgl_context_read_back_drawing_buffer(void* context, i32 x, i32 y, i32 width, i32 height);-bool 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);-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);// What the Rust implementation asks of LibWeb, declared in Bindings/Rust/src/web_gl/canvas.rs.void web_webgl_canvas_did_change_content(void* canvas_host);+void web_webgl_canvas_did_create_backing_storage(void* canvas_host);+DOM::EventTarget* web_webgl_canvas_event_target(void* canvas_host);void web_webgl_canvas_bitmap_size(void* canvas_host, i32* out_width, i32* out_height);void* web_webgl_canvas_wrapper(void* canvas, bool canvas_is_offscreen, void* realm);void* web_webgl_canvas_relevant_realm(void* canvas_host);@@ -99,24 +91,6 @@ HTML::CanvasHost& canvas_host_for(CanvasOwner const& canvas)return canvas.visit([](auto const& canvas) -> HTML::CanvasHost& { return *canvas; });}-// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-event-// Returns false if the event was canceled (the page called preventDefault), which is how-// webglcontextlost signals that the page wants the context restored.-static bool fire_webgl_context_event(HTML::CanvasHost& canvas, Utf16FlyString const& type)-{- // To fire a WebGL context event named e means that an event using the WebGLContextEvent interface, with its type attribute [DOM4] initialized to e, its cancelable attribute initialized to true, and its isTrusted attribute [DOM4] initialized to true, is to be dispatched at the given object.- // FIXME: Consider setting a status message.- auto& event = *static_cast<DOM::Event*>(web_webgl_context_event_create(JS::HostABI::vm_to_abi(JS::VM::the()), web_webgl_canvas_relevant_realm(&canvas), type.to_utf16_string().into_raw()));- return canvas.canvas_event_target().dispatch_event(event);-}--// https://www.khronos.org/registry/webgl/specs/latest/1.0/#fire-a-webgl-context-creation-error-static void fire_webgl_context_creation_error(HTML::CanvasHost& canvas)-{- // 1. Fire a WebGL context event named "webglcontextcreationerror" at canvas, optionally with its statusMessage attribute set to a platform dependent string about the nature of the failure.- fire_webgl_context_event(canvas, EventNames::webglcontextcreationerror);-}-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.@@ -129,16 +103,7 @@ WebGLRenderingContextBase* WebGLRenderingContextBase::create(JS::Realm& realm, C.canvas_is_offscreen = canvas.has<GC::Ref<HTML::OffscreenCanvas>>(),.context_attributes = context_attributes,};- 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;+ return static_cast<WebGLRenderingContextBase*>(web_webgl_context_create(JS::HostABI::vm_to_abi(realm.vm()), &arguments));}GC::Ptr<WebGLRenderingContext> WebGLRenderingContext::create(JS::Realm& realm, CanvasOwner canvas, ContextAttributes const& context_attributes)@@ -151,11 +116,6 @@ GC::Ptr<WebGL2RenderingContext> WebGL2RenderingContext::create(JS::Realm& realm,return static_cast<WebGL2RenderingContext*>(WebGLRenderingContextBase::create(realm, canvas, context_attributes, WebGLVersion::WebGL2));}-HTML::CanvasHost& WebGLRenderingContextBase::canvas_host() const-{- return *static_cast<HTML::CanvasHost*>(web_webgl_context_canvas_host(cell_of(*this)));-}-bool WebGLRenderingContextBase::is_context_lost() const{return web_webgl_context_is_lost(cell_of(*this));@@ -192,37 +152,19 @@ Optional<Gfx::DecodedImageFrame> WebGLRenderingContextBase::read_back_drawing_bureturn move(*frame);}-void WebGLRenderingContextBase::lose_context_from_compositor_loss()+void web_webgl_canvas_did_change_content(void* canvas_host){- if (!web_webgl_context_mark_lost(this))- return;-- HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](WebGLRenderingContextBase& self) {- // webglcontextlost is cancelable; preventDefault() means the page wants the context- // restored once a compositor is available again.- web_webgl_context_set_restore_requested(&self, !fire_webgl_context_event(self.canvas_host(), EventNames::webglcontextlost));- }));+ static_cast<HTML::CanvasHost*>(canvas_host)->did_change_canvas_content();}-void WebGLRenderingContextBase::restore_context_after_compositor_reconnect()+void web_webgl_canvas_did_create_backing_storage(void* canvas_host){- if (!web_webgl_context_wants_restoring(this))- return;-- // A fresh host context starts with no GL objects; per the spec the page re-creates them- // in its webglcontextrestored handler.- if (!web_webgl_context_restore(this))- return;- 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);- }));+ static_cast<HTML::CanvasHost*>(canvas_host)->did_create_canvas_backing_storage();}-void web_webgl_canvas_did_change_content(void* canvas_host)+DOM::EventTarget* web_webgl_canvas_event_target(void* canvas_host){- static_cast<HTML::CanvasHost*>(canvas_host)->did_change_canvas_content();+ return &static_cast<HTML::CanvasHost*>(canvas_host)->canvas_event_target();}void web_webgl_canvas_bitmap_size(void* canvas_host, i32* out_width, i32* out_height)diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.hindex 713d67b3cb5..3341dfcbfa6 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.h@@ -49,8 +49,6 @@ JS::ThrowCompletionOr<ContextAttributes> convert_to_context_attributes(JS::VM&,// (Libraries/LibWeb/Bindings/Rust/src/web_gl): what the rest of LibWeb calls, and what the Rust code calls back.class WEB_API WebGLRenderingContextBase : public Bindings::RustInterfaceCell {public:- HTML::CanvasHost& canvas_host() const;-bool is_context_lost() const;Optional<Compositing::CanvasId> canvas_id() const;@@ -60,16 +58,6 @@ public:void clear_drawing_buffer();Optional<Gfx::DecodedImageFrame> read_back_drawing_buffer(Gfx::IntRect const&);- // https://registry.khronos.org/webgl/specs/latest/1.0/#CONTEXT_LOST- // The compositor process (and with it the GL state) went away: set the context lost- // flag, stop talking to the dead host, and fire webglcontextlost at the canvas.- void lose_context_from_compositor_loss();-- // The compositor came back. If the page asked for restoration (called preventDefault on- // webglcontextlost), build a fresh remote context and fire webglcontextrestored so the- // page can re-create its now-lost GL resources.- void restore_context_after_compositor_reconnect();-protected:static WebGLRenderingContextBase* create(JS::Realm&, CanvasOwner, ContextAttributes const&, WebGLVersion);};diff --git a/Tests/LibWebView/test-webdriver-compositor-reconnect.py b/Tests/LibWebView/test-webdriver-compositor-reconnect.pyindex d814f5d3470..8b28d22da69 100755--- a/Tests/LibWebView/test-webdriver-compositor-reconnect.py+++ b/Tests/LibWebView/test-webdriver-compositor-reconnect.py@@ -6,7 +6,8 @@# When the Compositor dies, the browser connects a new one, and the page's next rendering update# has to bring the new Compositor up to date: its first frame carries the whole display list again,-# not only what changed since the old Compositor's last frame.+# not only what changed since the old Compositor's last frame. Every WebGL context of the page, of a+# canvas element or of an OffscreenCanvas, is lost with the Compositor.import argparseimport base64@@ -26,7 +27,21 @@ webdriver_helpers = importlib.import_module("test-webdriver-delete-session")PAGE = "data:text/html," + urllib.parse.quote("""<style>#box { width: 100px; height: 100px; background: blue; }-</style><div id=box></div>"""+</style><div id=box></div><canvas id=canvas style="display: none"></canvas><script>+window.webglContextEvents = [];+function createWebGLContextThatRecordsItsEvents(name, canvas) {+ canvas.addEventListener("webglcontextlost", event => {+ event.preventDefault();+ webglContextEvents.push(`${name} lost`);+ });+ return canvas.getContext("webgl") !== null;+}+function createWebGLContexts() {+ window.offscreenCanvas = new OffscreenCanvas(16, 16);+ return createWebGLContextThatRecordsItsEvents("canvas element", document.getElementById("canvas"))+ && createWebGLContextThatRecordsItsEvents("OffscreenCanvas", offscreenCanvas);+}+</script>""")@@ -82,6 +97,7 @@ def run_test(webdriver_binary):status, _, body = webdriver_helpers.request(port, "POST", f"/session/{session}/url", {"url": PAGE})assert status == 200, bodywebdriver_helpers.wait_for_compositor(port, session)+ assert execute(port, session, "return createWebGLContexts();"), "WebGL contexts could not be created"first = take_screenshot(port, session)compositors = descendants_named(webdriver.pid, "Compositor")@@ -101,6 +117,16 @@ def run_test(webdriver_binary):assert take_screenshot(port, session) == firstexecute(port, session, "document.getElementById('box').style.background = 'green';")assert take_screenshot(port, session) != first++ expected_webgl_context_events = ["OffscreenCanvas lost", "canvas element lost"]+ deadline = time.monotonic() + webdriver_helpers.EVENT_TIMEOUT_SECONDS+ while True:+ webgl_context_events = execute(port, session, "return webglContextEvents.toSorted();")+ if webgl_context_events == expected_webgl_context_events:+ break+ if time.monotonic() >= deadline:+ raise AssertionError(f"WebGL context events: {webgl_context_events}")+ time.sleep(0.05)webdriver_helpers.request(port, "DELETE", f"/session/{session}")finally:webdriver.terminate()