Skip to content

Truly independent web browser

LibWeb: Implement CustomEvent in Rust

Shannon Booth93c92f4043a0
diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/custom_event.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/custom_event.rs
new file mode 100644
index 00000000000..cb9e3d746da
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/custom_event.rs
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2021, Luke Wilde <[email protected]>
+ * Copyright (c) 2022, Andreas Kling <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CustomEvent, https://dom.spec.whatwg.org/#interface-customevent
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::{Utf16FlyString, Utf16String};
+use libjs_rust::api::{Gc, GcRefCell, Realm, Trace, Value, Vm};
+
+use crate::bindings::event_target::CppEvent;
+use crate::bindings::interface::{Ref, Wrappable, allocate, realm_arguments};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::dom::event::EventInit;
+
+/// The dictionary CustomEventInit of DOM/CustomEvent.idl.
+pub(crate) struct CustomEventInit {
+ pub(crate) parent: EventInit,
+ pub(crate) detail: Value,
+}
+
+// https://dom.spec.whatwg.org/#customevent
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CustomEvent {
+ event: CppEvent,
+ // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent-type-bubbles-cancelable-detail-detail
+ detail: GcRefCell<Value>,
+}
+
+impl Wrappable for CustomEvent {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event.as_cpp_parent()
+ }
+}
+
+impl CustomEvent {
+ pub(crate) fn create(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ event_name: &Utf16String,
+ event_init: CustomEventInit,
+ ) -> Ref<CustomEvent> {
+ let event = CppEvent::create_for_owner(
+ realm,
+ event_name,
+ event_init.parent.bubbles,
+ event_init.parent.cancelable,
+ event_init.parent.composed,
+ );
+ let object = allocate(vm, |_| CustomEvent {
+ event,
+ detail: GcRefCell::new(event_init.detail),
+ });
+ object.event.set_owner(object);
+ object
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ r#type: Utf16String,
+ event_init_dict: CustomEventInit,
+ ) -> WebIdlResult<Ref<CustomEvent>> {
+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))
+ }
+
+ pub(crate) fn event(&self) -> &CppEvent {
+ &self.event
+ }
+
+ // https://dom.spec.whatwg.org/#dom-customevent-detail
+ pub(crate) fn detail(&self, _: &mut CallContext) -> WebIdlResult<Value> {
+ Ok(*self.detail.borrow())
+ }
+
+ // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
+ pub(crate) fn init_custom_event(
+ &self,
+ cx: &mut CallContext,
+ r#type: Utf16String,
+ bubbles: bool,
+ cancelable: bool,
+ detail: Value,
+ ) -> WebIdlResult<()> {
+ // 1. If this’s dispatch flag is set, then return.
+ if self.event.dispatched() {
+ return Ok(());
+ }
+
+ // 2. Initialize this with type, bubbles, and cancelable.
+ self.event.initialize_event(&r#type, bubbles, cancelable);
+
+ // 3. Set this’s detail attribute to detail.
+ *self.detail.borrow_mut(cx.vm()) = detail;
+ Ok(())
+ }
+}
+
+/// The Event of a new CustomEvent in the realm, for the implementation to fire.
+///
+/// # Safety
+///
+/// The VM, the realm and the detail must be live. The type is lent for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_custom_event_create(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ r#type: usize,
+ detail: u64,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let event_init = CustomEventInit {
+ parent: EventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ },
+ // SAFETY: The caller passes a live detail.
+ detail: unsafe { Value::from_raw(detail) },
+ };
+ // SAFETY: The caller lends the type for the call.
+ let r#type: Utf16String = unsafe { Utf16FlyString::from_raw_borrowed(r#type) }.into();
+ CustomEvent::create(vm, realm, &r#type, event_init).event().as_ptr()
+}
+
+/// The Event of a new CustomEvent in the realm whose type is the empty string, for createEvent().
+///
+/// # Safety
+///
+/// The VM and the realm must be live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_custom_event_create_for_create_event(
+ vm: *mut c_void,
+ realm: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let event_init = CustomEventInit {
+ parent: EventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ },
+ detail: Value::NULL,
+ };
+ CustomEvent::create(vm, realm, &Utf16String::from_utf8(""), event_init)
+ .event()
+ .as_ptr()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs
index 863f7bc6f6c..160e567fbbc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs
@@ -11,6 +11,8 @@ pub(crate) mod abort_controller;
#[cfg(not(test))]
pub(crate) mod abort_signal;
#[cfg(not(test))]
+pub(crate) mod custom_event;
+#[cfg(not(test))]
pub(crate) mod document;
#[cfg(not(test))]
pub(crate) mod dom_token_list;
diff --git a/Libraries/LibWeb/DOM/CustomEvent.cpp b/Libraries/LibWeb/DOM/CustomEvent.cpp
index ced10c7649c..7d9bfbb1e16 100644
--- a/Libraries/LibWeb/DOM/CustomEvent.cpp
+++ b/Libraries/LibWeb/DOM/CustomEvent.cpp
@@ -1,59 +1,32 @@
/*
* Copyright (c) 2021, Luke Wilde <[email protected]>
* Copyright (c) 2022, Andreas Kling <[email protected]>
+ * 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/DOM/CustomEvent.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/DOM/Event.h>
namespace Web::DOM {
-GC_DEFINE_ALLOCATOR(CustomEvent);
-
-GC::Ref<CustomEvent> CustomEvent::create(JS::Object const& relevant_global_object, FlyString const& event_name, CustomEventInit const& event_init)
-{
- return create(event_name, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object));
-}
-
-GC::Ref<CustomEvent> CustomEvent::create(FlyString const& event_name, CustomEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
-{
- return GC::Heap::the().allocate<CustomEvent>(event_name, event_init, time_stamp);
-}
-
-GC::Ref<CustomEvent> CustomEvent::create_for_constructor(Utf16String const& event_name, CustomEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
-{
- return create(FlyString { event_name.to_utf8() }, event_init, time_stamp);
+extern "C" {
+// Defined in Bindings/Rust/src/dom/custom_event.rs.
+Event* web_rust_custom_event_create(JSVM*, void* realm, FlatPtr type, JSValue detail);
+Event* web_rust_custom_event_create_for_create_event(JSVM*, void* realm);
}
-CustomEvent::CustomEvent(FlyString const& event_name, CustomEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
- : Event(event_name, event_init, time_stamp)
- , m_detail(event_init.detail)
+GC::Ref<Event> create_custom_event(JS::Realm& realm, Utf16FlyString const& type, JS::Value detail)
{
+ return *web_rust_custom_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.raw_identity(), JS::HostABI::value_to_abi(detail));
}
-CustomEvent::~CustomEvent() = default;
-
-void CustomEvent::visit_edges(GC::Cell::Visitor& visitor)
+GC::Ref<Event> create_custom_event(JS::Realm& realm)
{
- Base::visit_edges(visitor);
- visitor.visit(m_detail);
-}
-
-// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
-void CustomEvent::init_custom_event(Utf16FlyString const& type, bool bubbles, bool cancelable, JS::Value detail)
-{
- // 1. If this’s dispatch flag is set, then return.
- if (dispatched())
- return;
-
- // 2. Initialize this with type, bubbles, and cancelable.
- initialize_event(type, bubbles, cancelable);
-
- // 3. Set this’s detail attribute to detail.
- m_detail = detail;
+ return *web_rust_custom_event_create_for_create_event(JS::HostABI::vm_to_abi(realm.vm()), &realm);
}
}
diff --git a/Libraries/LibWeb/DOM/CustomEvent.h b/Libraries/LibWeb/DOM/CustomEvent.h
index f7bf2c3a54d..12fd4f624c4 100644
--- a/Libraries/LibWeb/DOM/CustomEvent.h
+++ b/Libraries/LibWeb/DOM/CustomEvent.h
@@ -1,46 +1,24 @@
/*
* Copyright (c) 2021, Luke Wilde <[email protected]>
* Copyright (c) 2022, Andreas Kling <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-#include <AK/FlyString.h>
+#include <AK/Utf16FlyString.h>
+#include <LibGC/Ptr.h>
+#include <LibJS/Forward.h>
#include <LibJS/Runtime/Value.h>
-#include <LibWeb/Bindings/CustomEvent.h>
-#include <LibWeb/DOM/Event.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
namespace Web::DOM {
-using CustomEventInit = Bindings::CustomEventInit;
+WEB_API GC::Ref<Event> create_custom_event(JS::Realm&, Utf16FlyString const& type, JS::Value detail);
-// https://dom.spec.whatwg.org/#customevent
-class WEB_API CustomEvent : public Event {
- WEB_WRAPPABLE(CustomEvent, Event);
- GC_DECLARE_ALLOCATOR(CustomEvent);
-
-public:
- [[nodiscard]] static GC::Ref<CustomEvent> create(JS::Object const& relevant_global_object, FlyString const& event_name, CustomEventInit const& = {});
- [[nodiscard]] static GC::Ref<CustomEvent> create(FlyString const& event_name, CustomEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
- [[nodiscard]] static GC::Ref<CustomEvent> create_for_constructor(Utf16String const& event_name, CustomEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
-
- virtual ~CustomEvent() override;
-
- // https://dom.spec.whatwg.org/#dom-customevent-detail
- JS::Value const& detail() const { return m_detail; }
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- void init_custom_event(Utf16FlyString const& type, bool bubbles, bool cancelable, JS::Value detail);
-
-private:
- CustomEvent(FlyString const& event_name, CustomEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);
-
- // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent-type-bubbles-cancelable-detail-detail
- JS::Value m_detail { JS::js_null() };
-};
+GC::Ref<Event> create_custom_event(JS::Realm&);
}
diff --git a/Libraries/LibWeb/DOM/CustomEvent.idl b/Libraries/LibWeb/DOM/CustomEvent.idl
index 86b6633b987..00e41540a61 100644
--- a/Libraries/LibWeb/DOM/CustomEvent.idl
+++ b/Libraries/LibWeb/DOM/CustomEvent.idl
@@ -1,11 +1,11 @@
// https://dom.spec.whatwg.org/#interface-customevent
-[Exposed=*]
+[Exposed=*, ImplementedIn=Rust]
interface CustomEvent : Event {
constructor(DOMString type, optional CustomEventInit eventInitDict = {});
readonly attribute any detail;
- undefined initCustomEvent([FlyString] DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // legacy
+ undefined initCustomEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any detail = null); // legacy
};
dictionary CustomEventInit : EventInit {
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 1e7b391528e..45468ff9136 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -3909,7 +3909,7 @@ WebIDL::ExceptionOr<GC::Ref<Event>> Document::create_event(Utf16FlyString const&
} else if (interface.equals_ignoring_ascii_case("compositionevent"sv)) {
event = UIEvents::CompositionEvent::create(String {}, {}, time_stamp);
} else if (interface.equals_ignoring_ascii_case("customevent"sv)) {
- event = CustomEvent::create(FlyString {}, {}, time_stamp);
+ event = create_custom_event(realm);
} else if (interface.equals_ignoring_ascii_case("devicemotionevent"sv)) {
event = Event::create(FlyString {}, time_stamp); // FIXME: Create DeviceMotionEvent
} else if (interface.equals_ignoring_ascii_case("deviceorientationevent"sv)) {
diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cpp
index 181b474f5c9..256fe80e92a 100644
--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp
@@ -43,7 +43,6 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/SharedResourceRequest.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/GeneratedPagesLoader.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
@@ -61,10 +60,9 @@ static void add_pdf_viewer_ready_listener(DOM::Document& document, GC::Ref<Fetch
auto listener_function = JS::NativeFunction::create(
realm, GC::create_function(GC::Heap::the(), GC::captures(document, js_response), [](DOM::Document& document, GC::Ref<Fetch::Response>& js_response, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {
- DOM::CustomEventInit init;
auto& realm = document.relevant_settings_object().realm();
- init.detail = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { js_response });
- document.dispatch_event(*DOM::CustomEvent::create("ladybirdpdf"_fly_string, init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(document))));
+ auto detail = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { js_response });
+ document.dispatch_event(*DOM::create_custom_event(realm, "ladybirdpdf"_utf16_fly_string, detail));
return JS::js_undefined();
}),
0, Utf16FlyString {}, &realm);
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index a5fa6a95993..bc332d21a74 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -462,7 +462,6 @@ class CaretPosition;
class CharacterData;
class Comment;
class CommitMessages;
-class CustomEvent;
class Document;
class DocumentFragment;
class DocumentLoadEventDelayer;
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 97adda8df2d..204fab22538 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -50,9 +50,10 @@ ALLOWED_REALM_MENTIONS = {
"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),
"CookieStore": (2, 3, "the C++ facade creates the Rust CookieStore in a given realm"),
"DOM": (
- 9,
- 30,
- "The AbortSignal and AbortController facades and node helpers use callback/materialization realms",
+ 11,
+ 35,
+ "The AbortSignal and AbortController facades and node helpers use callback/materialization realms; "
+ "the C++ glue of the Rust CustomEvent creates it in a given realm",
),
"Fetch": (
22,
diff --git a/Services/WebContent/WebUIConnection.cpp b/Services/WebContent/WebUIConnection.cpp
index 2b85f8df740..ec1942b7c3d 100644
--- a/Services/WebContent/WebUIConnection.cpp
+++ b/Services/WebContent/WebUIConnection.cpp
@@ -34,9 +34,9 @@ static Utf16FlyString const& web_ui_loaded_event()
return *event;
}
-static FlyString const& web_ui_message_event()
+static Utf16FlyString const& web_ui_message_event()
{
- static NeverDestroyed<FlyString> event { "WebUIMessage"_fly_string };
+ static NeverDestroyed<Utf16FlyString> event { "WebUIMessage"_utf16_fly_string };
return *event;
}
@@ -90,10 +90,7 @@ void WebUIConnection::send_message(String name, JsonValue data)
return;
}
- Web::DOM::CustomEventInit event_init {};
- event_init.detail = serialized_detail.value();
-
- m_document->dispatch_event(Web::DOM::CustomEvent::create(realm.global_object(), web_ui_message_event(), event_init));
+ m_document->dispatch_event(Web::DOM::create_custom_event(realm, web_ui_message_event(), serialized_detail.value()));
}
void WebUIConnection::received_message_from_web_ui(Utf16String const& name, JS::Value data)