Truly independent web browser
LibWeb: Let Rust interfaces inherit from EventTarget and Event
Shannon Boothf5603990be0b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex 71e15d59a91..12bbb436e93 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -1010,6 +1010,13 @@ impl ToJs for WebIdlPromise {}}+/// https://webidl.spec.whatwg.org/#js-short+impl ToJs for i16 {+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {+ Ok(Value::from_i32(i32::from(self)))+ }+}+/// https://webidl.spec.whatwg.org/#js-longimpl ToJs for i32 {fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {@@ -1092,6 +1099,12 @@ impl<T: Interface> ToJs for Ref<T> {}}+/// (DOMString or sequence<DOMString>), which more than one interface's IDL names without a typedef.+pub(crate) enum DOMStringOrDOMStringSequence {+ DOMString(Utf16String),+ Sequence(Vec<Utf16String>),+}+/// An object of an interface that LibWeb implements in C++, as its wrapper. Only the C++ code knows the object/// behind the wrapper, so an implementation hands the wrapper to a service of LibWeb to have something done with it.#[derive(Clone, Copy, Trace)]diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rsnew file mode 100644index 00000000000..0a02f2bc437--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs@@ -0,0 +1,200 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The EventTarget or Event that an object of an interface implemented in Rust owns when its interface inherits from+//! one of them, which LibWeb implements in C++ (Libraries/LibWeb/Bindings/RustEventTarget.h). The object's wrappers+//! hold it as their wrappable, so that the C++ bindings of EventTarget and Event run on it, and its wrappers are the+//! object's.++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Value};++use crate::bindings::cpp_cell::CppCell;+use crate::bindings::interface::{Interface, Ref, Wrappable, cell_from_abi, cell_into_abi};++unsafe extern "C" {+ fn web_bindings_create_event_target() -> *mut c_void;+ fn web_bindings_set_event_target_owner(+ event_target: *mut c_void,+ interface_name: u16,+ owner: *mut c_void,+ get_the_parent: unsafe extern "C" fn(*mut c_void) -> *mut c_void,+ );+ fn web_bindings_event_handler_attribute(event_target: *mut c_void, name: ak::Span<'_, u8>) -> u64;+ fn web_bindings_set_event_handler_attribute(event_target: *mut c_void, name: ak::Span<'_, u8>, value: u64);+ fn web_bindings_create_event(+ realm: *mut c_void,+ r#type: ak::Span<'_, u8>,+ bubbles: bool,+ cancelable: bool,+ composed: bool,+ ) -> *mut c_void;+ fn web_bindings_create_rust_event(+ realm: *mut c_void,+ r#type: usize,+ bubbles: bool,+ cancelable: bool,+ composed: bool,+ ) -> *mut c_void;+ fn web_bindings_set_event_owner(event: *mut c_void, interface_name: u16, owner: *mut c_void);+ fn web_bindings_dispatch_event(target: *mut c_void, event: *mut c_void) -> bool;+ fn web_bindings_dispatch_event_with_legacy_output_did_listeners_throw_flag(+ target: *mut c_void,+ event: *mut c_void,+ ) -> bool;+ fn web_bindings_event_canceled(event: *mut c_void) -> bool;+}++/// The EventTarget that an object owns.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppEventTarget(CppCell);++/// https://dom.spec.whatwg.org/#get-the-parent+pub(crate) trait GetTheParent: Interface {+ fn get_the_parent(&self) -> Option<CppEventTarget>;+}++impl CppEventTarget {+ pub(crate) fn new() -> Self {+ // SAFETY: LibWeb returns a new, live EventTarget.+ Self(unsafe { CppCell::from_raw(web_bindings_create_event_target()) })+ }++ pub(crate) fn set_owner<T: GetTheParent>(&self, owner: Ref<T>) {+ unsafe extern "C" fn get_the_parent<T: GetTheParent>(owner: *mut c_void) -> *mut c_void {+ // SAFETY: LibWeb passes the owner that set_owner() gave it, which is the live cell of an object of T.+ let owner = unsafe { cell_from_abi::<T>(owner) };+ owner+ .get_the_parent()+ .map_or(core::ptr::null_mut(), |parent| parent.as_ptr())+ }+ // SAFETY: The EventTarget and the owner are live, and the owner keeps the EventTarget alive.+ unsafe {+ web_bindings_set_event_target_owner(+ self.as_ptr(),+ T::INTERFACE_NAME,+ cell_into_abi(owner),+ get_the_parent::<T>,+ );+ }+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://dom.spec.whatwg.org/#concept-event-dispatch+ pub(crate) fn dispatch_event(&self, event: &CppEvent) -> bool {+ // SAFETY: The EventTarget and the event are live.+ unsafe { web_bindings_dispatch_event(self.as_ptr(), event.as_ptr()) }+ }++ /// Returns the legacyOutputDidListenersThrowFlag.+ pub(crate) fn dispatch_event_with_legacy_output_did_listeners_throw_flag(&self, event: &CppEvent) -> bool {+ // SAFETY: The EventTarget and the event are live.+ unsafe {+ web_bindings_dispatch_event_with_legacy_output_did_listeners_throw_flag(self.as_ptr(), event.as_ptr())+ }+ }+}++/// An Event: a plain one, or the one that an object owns.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppEvent(CppCell);++impl CppEvent {+ pub(crate) fn create(realm: Gc<Realm>, r#type: &str, bubbles: bool, cancelable: bool, composed: bool) -> Self {+ // SAFETY: The realm is live, the type is lent for the call, and LibWeb returns a live event.+ Self(unsafe {+ CppCell::from_raw(web_bindings_create_event(+ realm.as_ptr().cast(),+ ak::Span::new(r#type.as_bytes()),+ bubbles,+ cancelable,+ composed,+ ))+ })+ }++ pub(crate) fn create_for_owner(+ realm: Gc<Realm>,+ r#type: &Utf16String,+ bubbles: bool,+ cancelable: bool,+ composed: bool,+ ) -> Self {+ // SAFETY: The realm is live, the type is lent for the call, and LibWeb returns a live event.+ Self(unsafe {+ CppCell::from_raw(web_bindings_create_rust_event(+ realm.as_ptr().cast(),+ r#type.raw_identity(),+ bubbles,+ cancelable,+ composed,+ ))+ })+ }++ pub(crate) fn set_owner<T: Interface>(&self, owner: Ref<T>) {+ // SAFETY: The event and the owner are live, and the owner keeps the event alive.+ unsafe { web_bindings_set_event_owner(self.as_ptr(), T::INTERFACE_NAME, cell_into_abi(owner)) };+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://dom.spec.whatwg.org/#canceled-flag+ pub(crate) fn canceled(&self) -> bool {+ // SAFETY: The event is live.+ unsafe { web_bindings_event_canceled(self.as_ptr()) }+ }+}++fn event_target_of(object: &impl Wrappable) -> *mut c_void {+ object+ .cpp_parent()+ .expect("an object with event handler IDL attributes owns an EventTarget")+ .as_ptr()+}++/// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes+pub(crate) fn event_handler_attribute(object: &impl Wrappable, event_type: &str) -> Value {+ // SAFETY: The EventTarget is live, and the name is lent for the call.+ let value =+ unsafe { web_bindings_event_handler_attribute(event_target_of(object), ak::Span::new(event_type.as_bytes())) };+ // SAFETY: LibWeb returns a live value.+ unsafe { Value::from_raw(value) }+}++/// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes+pub(crate) fn set_event_handler_attribute(object: &impl Wrappable, event_type: &str, value: Value) {+ // SAFETY: The EventTarget and the value are live, and the name is lent for the call.+ unsafe {+ web_bindings_set_event_handler_attribute(+ event_target_of(object),+ ak::Span::new(event_type.as_bytes()),+ value.to_raw(),+ );+ }+}++impl CppEventTarget {+ pub(crate) fn as_cpp_parent(&self) -> Option<NonNull<c_void>> {+ NonNull::new(self.as_ptr())+ }+}++impl CppEvent {+ pub(crate) fn as_cpp_parent(&self) -> Option<NonNull<c_void>> {+ NonNull::new(self.as_ptr())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 22e9f8602db..64aaf003d2a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -67,6 +67,12 @@ pub(crate) trait Wrappable {Self: Trace + Sized,{}++ /// The C++ EventTarget or Event that the object owns, which its wrappers hold as their wrappable+ /// (bindings::event_target).+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ None+ }}/// The value of the cell of an object of an interface: its implementation, and its wrapper in the main world.@@ -315,16 +321,16 @@ fn register_wrapper_outside_main_world<T: Interface>(realm: Gc<Realm>, object: R}}-/// A new wrapper of the object in the realm, whose host data is the cell of the object.fn create_wrapper<T: Interface>(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>, object: Ref<T>) -> Gc<HostObject> {- // SAFETY: The wrapper class's hooks expect no wrappable, and the host data is a live cell.+ // SAFETY: The wrapper class's hooks expect a wrappable exactly for an interface that inherits from an interface+ // implemented in C++, whose objects own one, and the wrappable and the host data are live cells.unsafe {HostObject::create(vm,realm,T::wrapper_class(),Some(prototype),- None,+ object.cpp_parent(),Some(object.as_non_null().cast()),)}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rsindex 097b352b006..7b2cbee4341 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs@@ -22,6 +22,7 @@ pub(crate) mod async_iterable;pub(crate) mod callback;pub(crate) mod conversions;pub(crate) mod cpp_cell;+pub(crate) mod event_target;#[cfg(web_idl_bindings)]pub(crate) mod generated;pub(crate) mod interface;diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/event.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/event.rsnew file mode 100644index 00000000000..179005e27f2--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/event.rs@@ -0,0 +1,12 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++/// https://dom.spec.whatwg.org/#dictdef-eventinit+pub(crate) struct EventInit {+ pub(crate) bubbles: bool,+ pub(crate) cancelable: bool,+ pub(crate) composed: bool,+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rsnew file mode 100644index 00000000000..0513ae3bd99--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs@@ -0,0 +1,9 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The IDL definitions of DOM that the interfaces implemented in Rust use.++pub(crate) mod event;diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex ce44de48cd4..360d35459f3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -49,6 +49,11 @@ pub(crate) mod canvas_2d;reason = "the bindings call every attribute and operation as one that can throw")]pub(crate) mod compression;+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the dictionaries")+)]+pub(crate) mod dom;#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 4b6e6f8b333..f7921508873 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -56,11 +56,12 @@ RustInterfaceCell* rust_interface_cell_of_wrapper(JS::Object& object, JSHostClasbool rust_interface_object_implements_interface(JS::Object const& object, StringView interface_name){- if (!JS::is_host_instance_of(object, web_bindings_rust_interface_wrapper_host_class))+ auto const* wrapper = as_if<JS::HostObject>(object);+ if (!wrapper || !JS::host_data_of(object))return false;- // NB: The class of the wrappers of an interface has the name of the interface, and the class of the wrappers of- // the interface that it inherits from as its parent.- for (auto const* host_class = &as<JS::HostObject>(object).host_class(); host_class != &web_bindings_rust_interface_wrapper_host_class; host_class = host_class->parent) {+ // NB: The host class of an interface's wrappers is named after it, and chains through the parent interfaces'+ // classes up to the class of every Rust interface, or else to that of a C++ interface it inherits from.+ for (auto const* host_class = &wrapper->host_class(); host_class && host_class != &web_bindings_rust_interface_wrapper_host_class; host_class = host_class->parent) {if (StringView { host_class->name, host_class->name_length } == interface_name)return true;}diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cppnew file mode 100644index 00000000000..a5a2797ba66--- /dev/null+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp@@ -0,0 +1,176 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/RustEventTarget.h>+#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/DOM/EventDispatcher.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/WebIDL/CallbackType.h>++// Defined by the generated Rust bindings.+extern "C" JSObject* web_rust_bindings_wrap(JSVM*, void* realm, u16 interface_name, void* cell);++namespace Web::Bindings {++GC_DEFINE_ALLOCATOR(RustEventTarget);+GC_DEFINE_ALLOCATOR(RustEvent);++static GC::Ref<JS::HostObject> wrapper_of_owner(JS::Realm& realm, InterfaceName interface_name, RustInterfaceCell& owner)+{+ auto* wrapper = web_rust_bindings_wrap(JS::HostABI::vm_to_abi(realm.vm()), &realm, to_underlying(interface_name), &owner);+ return as<JS::HostObject>(*JS::HostABI::object_from_abi(wrapper));+}++GC::Ref<RustEventTarget> RustEventTarget::create()+{+ return GC::Heap::the().allocate<RustEventTarget>();+}++void RustEventTarget::set_owner(InterfaceName interface_name, RustInterfaceCell& owner, GetTheParent get_the_parent)+{+ VERIFY(!m_owner);+ m_owner_interface_name = interface_name;+ m_owner = owner;+ m_get_the_parent = get_the_parent;+}++DOM::EventTarget* RustEventTarget::get_parent(DOM::Event const&)+{+ VERIFY(m_owner);+ return m_get_the_parent(m_owner.ptr());+}++GC::Ref<JS::HostObject> RustEventTarget::create_wrapper(JS::Realm& realm)+{+ VERIFY(m_owner);+ return wrapper_of_owner(realm, m_owner_interface_name, *m_owner);+}++void RustEventTarget::visit_edges(Visitor& visitor)+{+ Base::visit_edges(visitor);+ visitor.visit(m_owner);+}++GC::Ref<RustEvent> RustEvent::create(Utf16FlyString const& type, DOM::EventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)+{+ return GC::Heap::the().allocate<RustEvent>(type, event_init, time_stamp);+}++RustEvent::RustEvent(Utf16FlyString const& type, DOM::EventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)+ : DOM::Event(type, event_init, time_stamp)+{+}++void RustEvent::set_owner(InterfaceName interface_name, RustInterfaceCell& owner)+{+ VERIFY(!m_owner);+ m_owner_interface_name = interface_name;+ m_owner = owner;+}++GC::Ref<JS::HostObject> RustEvent::create_wrapper(JS::Realm& realm)+{+ VERIFY(m_owner);+ return wrapper_of_owner(realm, m_owner_interface_name, *m_owner);+}++void RustEvent::visit_edges(Visitor& visitor)+{+ Base::visit_edges(visitor);+ visitor.visit(m_owner);+}++}++using namespace Web;+using namespace Web::Bindings;++// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs.+extern "C" {++RustEventTarget* web_bindings_create_event_target();+void web_bindings_set_event_target_owner(RustEventTarget*, u16 interface_name, RustInterfaceCell* owner, RustEventTarget::GetTheParent);+JSValue web_bindings_event_handler_attribute(RustEventTarget*, ReadonlyBytes name);+void web_bindings_set_event_handler_attribute(RustEventTarget*, ReadonlyBytes name, JSValue);+DOM::Event* web_bindings_create_event(void* realm, ReadonlyBytes type, bool bubbles, bool cancelable, bool composed);+RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubbles, bool cancelable, bool composed);+void web_bindings_set_event_owner(RustEvent*, u16 interface_name, RustInterfaceCell* owner);+bool web_bindings_dispatch_event(DOM::EventTarget*, DOM::Event*);+bool web_bindings_dispatch_event_with_legacy_output_did_listeners_throw_flag(DOM::EventTarget*, DOM::Event*);+bool web_bindings_event_canceled(DOM::Event*);+}++RustEventTarget* web_bindings_create_event_target()+{+ return RustEventTarget::create().ptr();+}++void web_bindings_set_event_target_owner(RustEventTarget* event_target, u16 interface_name, RustInterfaceCell* owner, RustEventTarget::GetTheParent get_the_parent)+{+ event_target->set_owner(static_cast<InterfaceName>(interface_name), *owner, get_the_parent);+}++// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes+JSValue web_bindings_event_handler_attribute(RustEventTarget* event_target, ReadonlyBytes name)+{+ auto* callback = event_target->event_handler_attribute(Utf16FlyString::from_utf8_without_validation(name));+ if (!callback)+ return JS::HostABI::value_to_abi(JS::js_null());+ return JS::HostABI::value_to_abi(callback->callback);+}++// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes+void web_bindings_set_event_handler_attribute(RustEventTarget* event_target, ReadonlyBytes name, JSValue raw_value)+{+ // NB: EventHandler is [LegacyTreatNonObjectAsNull], so a value that is not an object sets the handler to null.+ auto value = JS::HostABI::value_from_abi(raw_value);+ GC::Ptr<WebIDL::CallbackType> callback;+ if (value.is_object())+ callback = GC::Heap::the().allocate<WebIDL::CallbackType>(value.as_object(), HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);+ event_target->set_event_handler_attribute(Utf16FlyString::from_utf8_without_validation(name), callback);+}++DOM::Event* web_bindings_create_event(void* realm, ReadonlyBytes type, bool bubbles, bool cancelable, bool composed)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ DOM::EventInit event_init { .bubbles = bubbles, .cancelable = cancelable, .composed = composed };+ return DOM::Event::create(Utf16FlyString::from_utf8_without_validation(type), event_init, HighResolutionTime::current_high_resolution_time(js_realm.global_object())).ptr();+}++RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubbles, bool cancelable, bool composed)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ DOM::EventInit event_init { .bubbles = bubbles, .cancelable = cancelable, .composed = composed };+ auto type_string = Utf16String::from_raw(type);+ return RustEvent::create(Utf16FlyString::from_utf16(type_string.utf16_view()), event_init, HighResolutionTime::current_high_resolution_time(js_realm.global_object())).ptr();+}++void web_bindings_set_event_owner(RustEvent* event, u16 interface_name, RustInterfaceCell* owner)+{+ event->set_owner(static_cast<InterfaceName>(interface_name), *owner);+}++bool web_bindings_dispatch_event(DOM::EventTarget* target, DOM::Event* event)+{+ return target->dispatch_event(*event);+}++bool web_bindings_dispatch_event_with_legacy_output_did_listeners_throw_flag(DOM::EventTarget* target, DOM::Event* event)+{+ bool legacy_output_did_listeners_throw_flag = false;+ DOM::EventDispatcher::dispatch(*target, *event, false, legacy_output_did_listeners_throw_flag);+ return legacy_output_did_listeners_throw_flag;+}++bool web_bindings_event_canceled(DOM::Event* event)+{+ return event->cancelled();+}diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.h b/Libraries/LibWeb/Bindings/RustEventTarget.hnew file mode 100644index 00000000000..5c44b5d9e2a--- /dev/null+++ b/Libraries/LibWeb/Bindings/RustEventTarget.h@@ -0,0 +1,63 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/DOM/Event.h>+#include <LibWeb/DOM/EventTarget.h>++namespace Web::Bindings {++// The EventTarget that an object of an interface implemented in Rust owns, whose wrappers are the object's+// (Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs).+class RustEventTarget final : public DOM::EventTarget {+ WEB_NON_IDL_WRAPPABLE(RustEventTarget, DOM::EventTarget);+ GC_DECLARE_ALLOCATOR(RustEventTarget);++public:+ // https://dom.spec.whatwg.org/#get-the-parent+ using GetTheParent = RustEventTarget* (*)(RustInterfaceCell * owner);++ static GC::Ref<RustEventTarget> create();++ void set_owner(InterfaceName, RustInterfaceCell&, GetTheParent);++private:+ RustEventTarget() = default;++ virtual EventTarget* get_parent(DOM::Event const&) override;+ virtual bool is_owned_by_rust_interface_object() const override { return true; }+ virtual GC::Ref<JS::HostObject> create_wrapper(JS::Realm&) override;+ virtual void visit_edges(Visitor&) override;++ InterfaceName m_owner_interface_name { InterfaceName::Unknown };+ GC::Ptr<RustInterfaceCell> m_owner;+ GetTheParent m_get_the_parent { nullptr };+};++// The Event that an object of an interface implemented in Rust owns, whose wrappers are the object's.+class RustEvent final : public DOM::Event {+ WEB_NON_IDL_WRAPPABLE(RustEvent, DOM::Event);+ GC_DECLARE_ALLOCATOR(RustEvent);++public:+ static GC::Ref<RustEvent> create(Utf16FlyString const& type, DOM::EventInit const&, HighResolutionTime::DOMHighResTimeStamp);++ void set_owner(InterfaceName, RustInterfaceCell&);++private:+ RustEvent(Utf16FlyString const& type, DOM::EventInit const&, HighResolutionTime::DOMHighResTimeStamp);++ virtual bool is_owned_by_rust_interface_object() const override { return true; }+ virtual GC::Ref<JS::HostObject> create_wrapper(JS::Realm&) override;+ virtual void visit_edges(Visitor&) override;++ InterfaceName m_owner_interface_name { InterfaceName::Unknown };+ GC::Ptr<RustInterfaceCell> m_owner;+};++}diff --git a/Libraries/LibWeb/Bindings/Wrappable.cpp b/Libraries/LibWeb/Bindings/Wrappable.cppindex 8b8b00f6e9f..c51b5f26558 100644--- a/Libraries/LibWeb/Bindings/Wrappable.cpp+++ b/Libraries/LibWeb/Bindings/Wrappable.cpp@@ -242,6 +242,10 @@ JS::ThrowCompletionOr<void> set_prototype_of_cached_main_world_wrapper(Wrappablevoid preserve_wrapper(Wrappable& wrappable, JS::HostObject& wrapper){+ // An object of an interface implemented in Rust keeps its wrappers alive itself, as wrapper_is_preserved() says.+ if (wrappable.is_owned_by_rust_interface_object())+ return;+auto& gc_allocated_wrappable = as<GCAllocatedWrappable>(wrappable);auto& world = host_defined_wrapper_world(wrapper.shape().realm());@@ -278,6 +282,11 @@ bool wrapper_is_preserved(JS::HostObject const& wrapper)auto const* wrappable = wrappable_impl_from(&wrapper);if (!wrappable)return false;++ // NB: The wrappers of a Rust object that inherits from a C++ interface hold the C++ object it owns as their+ // wrappable.+ if (wrappable->is_owned_by_rust_interface_object())+ return host_defined_wrapper_world(wrapper.shape().realm()).is_main_world();auto const& gc_allocated_wrappable = as<GCAllocatedWrappable>(*wrappable);auto& world = host_defined_wrapper_world(wrapper.shape().realm());diff --git a/Libraries/LibWeb/Bindings/Wrappable.h b/Libraries/LibWeb/Bindings/Wrappable.hindex dcd6905453a..20617f707a5 100644--- a/Libraries/LibWeb/Bindings/Wrappable.h+++ b/Libraries/LibWeb/Bindings/Wrappable.h@@ -116,6 +116,10 @@ public:[[nodiscard]] virtual bool implements_interface(Bindings::InterfaceName) const { return false; }[[nodiscard]] virtual bool implements_interface(String const&) const { return false; }+ // Whether an object of an interface implemented in Rust owns this object, so that its wrappers are the Rust+ // object's (Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs).+ [[nodiscard]] virtual bool is_owned_by_rust_interface_object() const { return false; }+template<typename T>requires(IsBaseOf<Wrappable, T> && requires { T::s_interface_name; })bool fast_is() constdiff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 618ea3f391f..ac12248c790 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -29,6 +29,7 @@ set(SOURCESBindings/OptionConstructor.cppBindings/PlatformObject.cppBindings/RustBindingsServices.cpp+ Bindings/RustEventTarget.cppBindings/StylePropertyMapReadOnlyIterator.cppBindings/PrincipalHostDefined.cppBindings/Wrappable.cppdiff --git a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp b/Libraries/LibWeb/WebIDL/OverloadResolution.cppindex 11f79b19b87..181d4206665 100644--- a/Libraries/LibWeb/WebIDL/OverloadResolution.cpp+++ b/Libraries/LibWeb/WebIDL/OverloadResolution.cpp@@ -25,9 +25,14 @@ static bool is_platform_object(JS::Value value)static bool platform_object_implements_interface(JS::Value value, StringView interface_name){+ // NB: The wrappers of a Rust object that inherits from a C++ interface hold the C++ object it owns as their+ // wrappable, which implements only the C++ interface.+ if (Bindings::rust_interface_object_implements_interface(value.as_object(), interface_name))+ return true;+auto const* wrappable = Bindings::wrappable_impl_from(&value.as_object());if (!wrappable)- return Bindings::rust_interface_object_implements_interface(value.as_object(), interface_name);+ return false;return wrappable->implements_interface(MUST(String::from_utf8(interface_name)));}diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 6e960fe8178..862ce9025fd 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -47,7 +47,9 @@ from Generators.libweb_bindings.rust_to_js_value import rust_to_js_valuefrom Generators.libweb_bindings.rust_to_js_value import write_dictionary_to_jsfrom Generators.libweb_bindings.rust_to_js_value import write_enumeration_to_jsfrom Generators.libweb_bindings.rust_to_js_value import write_union_to_js+from Generators.libweb_bindings.rust_types import CPP_PARENT_INTERFACESfrom Generators.libweb_bindings.rust_types import UnsupportedByRustBindings+from Generators.libweb_bindings.rust_types import cpp_ancestorfrom Generators.libweb_bindings.rust_types import cpp_interface_name_constantfrom Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import inheriting_interfaces@@ -57,6 +59,7 @@ from Generators.libweb_bindings.rust_types import rust_interface_pathfrom Generators.libweb_bindings.rust_types import rust_parameter_typefrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_usage import DefinitionUsage+from Generators.libweb_bindings.wrappers import wrapper_host_class_namefrom Generators.libweb_bindings.wrappers import wrapper_namefrom Utils.utils import title_case_to_snake_casefrom Utils.webidl_parser import Interface@@ -137,8 +140,15 @@ def check_interface_is_supported(interface: Interface, module: Module, context:fail(f"the Rust bindings do not handle its extended attributes {sorted(unsupported_attributes)}")if interface.is_callback_interface:fail("it is a callback interface")- if interface.parent_name and not is_implemented_in_rust(context.interfaces.get(interface.parent_name)):- fail(f"it inherits from {interface.parent_name}, which is not implemented in Rust")+ parent = context.interfaces.get(interface.parent_name)+ if (+ interface.parent_name+ and not is_implemented_in_rust(parent)+ and interface.parent_name not in CPP_PARENT_INTERFACES+ ):+ fail(+ f"it inherits from {interface.parent_name}, which is neither implemented in Rust nor one of {CPP_PARENT_INTERFACES}"+ )if module.callback_functions:fail("its module defines callback functions")@@ -240,9 +250,14 @@ void {interface.namespace_class}::initialize(JS::Realm& realm, JS::Object& objecparent = context.interfaces.get(interface.parent_name)if parent is not None:includes.add_binding(parent.implemented_name)- parent_host_class = wrapper_host_class_symbol(parent)+ parent_host_class = (+ wrapper_host_class_symbol(parent) if is_implemented_in_rust(parent) else wrapper_host_class_name(parent)+ )else:parent_host_class = "web_bindings_rust_interface_wrapper_host_class"+ has_cpp_ancestor = cpp_ancestor(interface, context) is not None+ if has_cpp_ancestor:+ includes.add("LibWeb/Bindings/PlatformObject.h")initialize_prototype = rust_entry_point_name(interface, "initialize_prototype")initialize_constructor = rust_entry_point_name(interface, "initialize_constructor")@@ -268,7 +283,23 @@ void {initialize_constructor}(JSVM*, void* realm, JSObject* constructor);)if interface.constructors:out.write(f"JSCompletion {construct}(JSVM*, JSObject* constructor, JSObject* new_target);\n")- if not supports_indexed_properties:+ if has_cpp_ancestor:+ if supports_indexed_properties:+ raise UnsupportedByRustBindings(+ f"{interface.path}: {interface.name} supports indexed properties and inherits from an interface "+ "implemented in C++, which the Rust bindings do not handle yet"+ )+ out.write(+ f"""+}}++// The wrappers hold the cell of their object as host data and, for an interface that inherits from one implemented in+// C++, the C++ object it owns as their wrappable, which the hooks keep alive.+constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,+ &{parent_host_class}, &platform_object_hooks, nullptr, platform_object_host_class_flags);+"""+ )+ elif not supports_indexed_properties:out.write(f"""}}@@ -382,6 +413,14 @@ def write_ensure_web_prototype_implementation(out: TextIO, intrinsics: List[Interust_interfaces = [interface for interface in intrinsics if is_implemented_in_rust(interface) and not interface.is_namespace]+ # NB: The interface prototype object and the interface object of an interface implemented in Rust have those of the+ # interface it inherits from as their prototype, which can be an interface implemented in C++.+ cpp_parent_names = {+ interface.parent_name for interface in rust_interfaces if interface.parent_name in CPP_PARENT_INTERFACES+ }+ prototype_interfaces = rust_interfaces + [+ interface for interface in intrinsics if interface.name in cpp_parent_names+ ]def write_switch(function: str, interfaces: List[Interface], object_of: Callable[[Interface], str]) -> None:out.write(@@ -408,14 +447,14 @@ JSObject* {function}(void* realm, u16 interface_name)write_switch("web_bindings_ensure_web_prototype",- rust_interfaces,+ prototype_interfaces,lambda interface: (f'ensure_web_prototype<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'),)write_switch("web_bindings_ensure_web_constructor",- rust_interfaces,+ prototype_interfaces,lambda interface: (f'ensure_web_constructor<{interface.prototype_class}>(js_realm, "{interface.namespaced_name}"_utf16_fly_string)'),@@ -534,6 +573,8 @@ def implementation_method_signatures()for attribute in members.attributes:what = f"{interface.name}.{attribute.attribute.name}"+ if attribute.event_type is not None:+ continueif not attribute.attribute.inherit:result_type = rust_type(attribute.attribute.type, context, what, is_result=True)signatures.append(@@ -774,6 +815,7 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]values,};use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};+ use crate::bindings::event_target::{event_handler_attribute, set_event_handler_attribute};use crate::bindings::promise::WebIdlPromise;use crate::bindings::structured_data;use crate::bindings::{CallContext, WebIdlResult};@@ -826,7 +868,12 @@ def write_rust_interface(implementation = rust_interface_path(interface)members = rust_members(interface)parent = context.interfaces.get(interface.parent_name)- inherited_interface_name = "None" if parent is None else f"Some(super::{rust_module_name(parent)}::INTERFACE_NAME)"+ if parent is None:+ inherited_interface_name = "None"+ elif is_implemented_in_rust(parent):+ inherited_interface_name = f"Some(super::{rust_module_name(parent)}::INTERFACE_NAME)"+ else:+ inherited_interface_name = f"Some({cpp_interface_name_constant(parent)})"method_documentation = "".join(f"/// - `{signature}`\n" for signature in implementation_method_signatures(context, interface, members))@@ -877,6 +924,9 @@ def write_rust_interface(for attribute in members.attributes:name = attribute.attribute.name+ if attribute.event_type is not None:+ write_rust_event_handler_attribute(out, attribute)+ continueconversion = rust_to_js_value(attribute.attribute.type, "result", "&cx", context, f"{interface.name}.{name}")call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"if attribute.attribute.inherit:@@ -1526,6 +1576,28 @@ def write_this_implementation(out: TextIO, context: GenerationContext, interface)+def write_rust_event_handler_attribute(out: TextIO, attribute: RustAttribute) -> None:+ """The getter and the setter of an event handler IDL attribute, which get and set the event handler of the C+++ EventTarget that the object owns, https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes"""+ out.write(+ f"""+ pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ let (implementation, _) = this_implementation(vm)?;+ let object: &Implementation = &implementation;+ Ok(event_handler_attribute(object, "{attribute.event_type}"))+ }}++ fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ let value = vm.argument(0);+ let (implementation, _) = this_implementation(vm)?;+ let object: &Implementation = &implementation;+ set_event_handler_attribute(object, "{attribute.event_type}", value);+ Ok(Value::UNDEFINED)+ }}+"""+ )++def inherited_attribute_getter_call(context: GenerationContext, interface: Interface, attribute: RustAttribute) -> str:"""The call of the getter of an attribute that the interface redeclares with inherit, whose getter is that of theinterface it inherits the attribute from, https://webidl.spec.whatwg.org/#dfn-inherit-getter. The implementation@@ -1788,7 +1860,13 @@ def write_rust_wrap_for_cpp(out: TextIO, context: GenerationContext, usage: Defi/// The pointers must be the VM, a live realm, and the live cell of an object of the interface.#[unsafe(no_mangle)]"""- if not usage.rust_interfaces_named_by_cpp:+ # NB: The C++ object that such an object owns is wrapped by the object's interface too.+ wrapped_interfaces = dict(usage.rust_interfaces_named_by_cpp)+ for interface in context.interfaces.values():+ if is_implemented_in_rust(interface) and cpp_ancestor(interface, context) is not None:+ wrapped_interfaces[interface.name] = interface++ if not wrapped_interfaces:out.write(f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(_vm: *mut core::ffi::c_void,@@ -1825,7 +1903,7 @@ def write_rust_wrap_for_cpp(out: TextIO, context: GenerationContext, usage: Defi}}"""- arms = "".join(arm(interface) for _, interface in sorted(usage.rust_interfaces_named_by_cpp.items()))+ arms = "".join(arm(interface) for _, interface in sorted(wrapped_interfaces.items()))out.write(f"""{documentation}pub unsafe extern "C" fn web_rust_bindings_wrap(vm: *mut core::ffi::c_void,diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.pyindex b410beeb341..8cec842cf39 100644--- a/Meta/Generators/libweb_bindings/rust_members.py+++ b/Meta/Generators/libweb_bindings/rust_members.py@@ -71,6 +71,9 @@ class RustAttribute:getter_method: str# The method of the implementation that the setter calls, for an attribute that is not read only.setter_method: Optional[str]+ # The event type of an event handler IDL attribute, whose getter and setter work on the C++ EventTarget that the+ # object owns: https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributes+ event_type: Optional[str] = None@propertydef is_cached(self) -> bool:@@ -382,7 +385,12 @@ def rust_members(interface: Interface) -> RustMembers:fail(f"its attribute {attribute.name} is [CachedAccessor] and not read only")getter_method = method_of(attribute.name, attribute.extended_attributes)setter_method = None if attribute.readonly else f"set_{generated_function_stem(getter_method)}"- rust_attribute = RustAttribute(attribute, getter_method, setter_method)+ event_type = None+ if attribute.type.name in ("EventHandler", "EventHandlerNonNull"):+ if attribute.readonly or not attribute.name.startswith("on") or attribute.extended_attributes:+ fail(f"its event handler IDL attribute {attribute.name} is not a plain attribute named on<event type>")+ event_type = attribute.name.removeprefix("on")+ rust_attribute = RustAttribute(attribute, getter_method, setter_method, event_type)members.attributes.append(rust_attribute)members.attributes_in_order.append(rust_attribute)@@ -439,8 +447,12 @@ def rust_members(interface: Interface) -> RustMembers:else:members.constants.append(RustConstant(constant.name, value))- methods = [attribute.getter_method for attribute in members.attributes]- methods.extend(attribute.setter_method for attribute in members.attributes if attribute.setter_method is not None)+ methods = [attribute.getter_method for attribute in members.attributes if attribute.event_type is None]+ methods.extend(+ attribute.setter_method+ for attribute in members.attributes+ if attribute.setter_method is not None and attribute.event_type is None+ )methods.extend(overload.methodfor operation_set in members.operation_sets + members.static_operation_setsdiff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex e6284eead54..40307237a79 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -304,6 +304,8 @@ def rust_default_value(return numeric_literalif member.type.nullable and default_value == "null":return "None"+ if name == "any" and default_value in ("null", "undefined"):+ return "Value::NULL" if default_value == "null" else "Value::UNDEFINED"if isinstance(member.type, IDLParameterizedType) and name == "sequence" and default_value == "[]":return "Vec::new()"dictionary = resolved_dictionary(member.type, context)diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 6be83350aea..0cca9e50e1a 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -50,7 +50,7 @@ SUPPORTED_TYPE_EXTENDED_ATTRIBUTES = {}# The integer types, with the Rust type of their values.-INTEGER_TYPES = {"long": "i32", "unsigned long": "u32", "long long": "i64", "unsigned long long": "u64"}+INTEGER_TYPES = {"short": "i16", "long": "i32", "unsigned long": "u32", "long long": "i64", "unsigned long long": "u64"}# The floating point types, with the Rust type of their values.FLOATING_POINT_TYPES = {"float": "f32", "unrestricted float": "f32", "double": "f64", "unrestricted double": "f64"}@@ -69,6 +69,10 @@ PLAIN_DATA_TYPES = {# The unions that the bindings runtime has a type for, by the name of the typedef that names the union.RUNTIME_UNION_TYPES = {"ArrayBufferView": "ArrayBufferView", "BufferSource": "BufferSource"}+# The unions that no typedef names and more than one interface's IDL uses, whose enums the bindings runtime defines,+# by their type name.+SHARED_UNNAMED_UNIONS = {"DOMStringOrDOMStringSequence": "crate::bindings::conversions"}+DECIMAL_LITERAL = re.compile(r"-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?")# https://webidl.spec.whatwg.org/#prod-integer@@ -113,6 +117,20 @@ def is_implemented_in_rust(interface: Optional[Interface]) -> bool:return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"+# The interfaces implemented in C++ that an interface implemented in Rust can inherit from+# (Libraries/LibWeb/Bindings/RustEventTarget.h).+CPP_PARENT_INTERFACES = ("EventTarget", "Event")+++def cpp_ancestor(interface: Interface, context: GenerationContext) -> Optional[Interface]:+ """The interface implemented in C++ that the interface inherits from, through any number of interfaces+ implemented in Rust, if any."""+ ancestor = context.interfaces.get(interface.parent_name)+ while ancestor is not None and is_implemented_in_rust(ancestor):+ ancestor = context.interfaces.get(ancestor.parent_name)+ return ancestor++def resolved_dictionary(idl_type: IDLType, context: GenerationContext) -> Optional[Dictionary]:return context.dictionaries.get(idl_type.name)@@ -356,8 +374,11 @@ def rust_union_path(idl_type: IDLUnionType, context: GenerationContext, what: stif len(names) > 1:raise UnsupportedByRustBindings(f"{what} has the union type {idl_type}, which the typedefs {names} all name")if not names:+ type_name = idl_type_name(idl_type.without_nullable(), what)+ if type_name in SHARED_UNNAMED_UNIONS:+ return f"{SHARED_UNNAMED_UNIONS[type_name]}::{type_name}"idl_path = unnamed_union_idl_path(idl_type, context, what)- return f"{rust_module_path(idl_path)}::{idl_type_name(idl_type.without_nullable(), what)}"+ return f"{rust_module_path(idl_path)}::{type_name}"name = names[0]for module in context.modules:if any(typedef.name == name for typedef in module.typedefs):diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex 81cd157d995..ee84a8f9d0d 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -112,7 +112,14 @@ class DefinitionUsage:if interface is None or not is_implemented_in_rust(interface):continuemembers = rust_members(interface)+ parent = self.context.interfaces.get(interface.parent_name)+ if parent is not None and not is_implemented_in_rust(parent):+ # NB: The bindings of the interface name the interface implemented in C++ it inherits from, whose+ # interface prototype object and interface object are the prototypes of its own.+ self.cpp_interfaces_named_by_rust[parent.name] = parentfor attribute in members.attributes:+ if attribute.event_type is not None:+ continuehas_setter = attribute.setter_method is not Noneself._name_for_rust(attribute.attribute.type, from_js=has_setter, to_js=True)operations = [