Truly independent web browser
LibWeb: Implement MessageEvent in Rust
Shannon Booth703bef747366
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex acfa09f912f..d640997afed 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -57,7 +57,6 @@#include <LibWeb/HTML/HTMLFormElement.h>#include <LibWeb/HTML/HTMLSlotElement.h>#include <LibWeb/HTML/Location.h>-#include <LibWeb/HTML/MessageEvent.h>#include <LibWeb/HTML/PromiseRejectionEvent.h>#include <LibWeb/HTML/Scripting/ClassicScript.h>#include <LibWeb/HTML/Scripting/Environments.h>@@ -865,7 +864,6 @@ void shut_down_agent()// What the agent keeps outside its heap refers to cells in it, so that goes while the heap is alive.Platform::discard_thread_pool_completions();Fetch::Fetching::disarm_all_body_stream_wakes();- HTML::clear_message_event_ports_caches();ServiceWorker::clear_service_worker_container_ready_promise_caches();FileAPI::forget_blob_url_store_of_this_agent();Fetch::Fetching::clear_http_memory_cache();diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rsindex 90bfcd24b9a..d02fa9a6bdc 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs@@ -13,9 +13,7 @@ use core::ffi::c_void;use core::ptr::NonNull;use ak::{Utf16FlyString, Utf16String};-use libjs_rust::api::{FunctionObject, Gc, Object, Realm, Trace, Value};-use liburl_rust::FfiOrigin;-use liburl_rust::origin::Origin;+use libjs_rust::api::{FunctionObject, Gc, Realm, Trace, Value};use crate::bindings::CallContext;use crate::bindings::callback::CallbackInterface;@@ -68,17 +66,6 @@ unsafe extern "C" {cancelable: bool,composed: bool,) -> *mut c_void;- fn web_bindings_create_message_event(- realm: *mut c_void,- r#type: ak::Span<'_, u8>,- data: u64,- ports: *const *mut c_void,- count: usize,- origin: *const FfiOrigin,- last_event_id: ak::Span<'_, u8>,- source: *mut c_void,- ) -> *mut c_void;- fn web_bindings_message_event_data(event: u64) -> u64;fn web_bindings_set_has_pending_activity(realm: *mut c_void, event_target: *mut c_void, has_pending_activity: bool);fn web_bindings_set_event_owner(event: *mut c_void, interface_name: u16, owner: *mut c_void);fn web_bindings_event_set_is_trusted(event: *mut c_void, is_trusted: bool);@@ -281,39 +268,6 @@ impl CppEvent {})}- /// A MessageEvent in the realm, https://html.spec.whatwg.org/multipage/comms.html#messageevent- pub(crate) fn create_message_event(- realm: Gc<Realm>,- r#type: &str,- data: Value,- ports: &[Gc<Object>],- origin: Option<&Origin>,- last_event_id: &str,- source: Option<&CppCell>,- ) -> Self {- let ports: Vec<*mut c_void> = ports.iter().map(|port| port.as_ptr().cast()).collect();- let create = |origin: *const FfiOrigin| {- // SAFETY: The realm, the data, the ports and the source are live, the type, the ports, the origin and the- // last event ID are lent for the call, and LibWeb returns a live event.- Self(unsafe {- CppCell::from_raw(web_bindings_create_message_event(- realm.as_ptr().cast(),- ak::Span::new(r#type.as_bytes()),- data.to_raw(),- ports.as_ptr(),- ports.len(),- origin,- ak::Span::new(last_event_id.as_bytes()),- source.map_or(core::ptr::null_mut(), CppCell::as_ptr),- ))- })- };- match origin {- Some(origin) => FfiOrigin::with_origin(origin, |origin| create(origin)),- None => create(core::ptr::null()),- }- }-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)) };@@ -372,12 +326,6 @@ impl CppEvent {}}-/// The data attribute of a MessageEvent, which the value is a wrapper of.-pub(crate) fn message_event_data(event: Value) -> Value {- // SAFETY: The event is live, and LibWeb returns its data, which is live.- unsafe { Value::from_raw(web_bindings_message_event_data(event.to_raw())) }-}-fn event_target_of(object: &impl Wrappable) -> *mut c_void {object.cpp_parent()diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rsindex 630f6c91f8f..6e4b3bfceeb 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs@@ -57,6 +57,11 @@ impl<T> WorldEntries<T> {entries}+ /// Forgets the collection of each world.+ pub(crate) fn clear(&self) {+ self.entries.borrow_mut().clear();+ }+/// Calls back with each live collection, for the caller to update when the object changes. The collections stay/// alive through the walk, as updating one can allocate and nothing else holds the rest.pub(crate) fn for_each_live(&self, vm: &Vm, mut callback: impl FnMut(Gc<T>)) {diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rsindex 8395d30d70e..252767002db 100644--- a/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs@@ -17,6 +17,7 @@ use crate::bindings::conversions::to_dom_string;use crate::bindings::interface::{Interface, Ref, Wrappable, allocate, implementation_of};use crate::bindings::services::web_bindings_extract_an_origin;use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::message_event::MessageEvent;#[derive(Trace)]#[gc(crate = libjs_rust)]@@ -102,6 +103,9 @@ fn extract_an_origin(value: Value) -> Option<OriginValue> {if is_host_instance_of(&object, URL::wrapper_class()) {return Some(implementation_of::<URL>(object).extract_an_origin());}+ if is_host_instance_of(&object, MessageEvent::wrapper_class()) {+ return implementation_of::<MessageEvent>(object).extract_an_origin();+ }unsafe extern "C" fn on_origin(ctx: *mut core::ffi::c_void, ffi_origin: *const FfiOrigin) {// SAFETY: ctx is the result below, and LibWeb lends the origin for the call.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rsindex f7219066fea..e765b7f402f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs@@ -18,13 +18,14 @@ use liburl_rust::FfiOrigin;use liburl_rust::origin::Origin;use crate::bindings::environment_settings_object::relevant_settings_object;-use crate::bindings::event_target::{CppEvent, CppEventTarget, EventListenerListChanged, GetTheParent};+use crate::bindings::event_target::{CppEventTarget, EventListenerListChanged, GetTheParent};use crate::bindings::global_object::{relevant_global_object, window_from_global_object, worker_global_scope_from_global_object,};use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate};use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::message_event::{MessageEvent, MessageEventInit};use crate::html::structured_serialize::message_record::MessageRecord;use crate::html::structured_serialize::{structured_deserialize_message, structured_serialize_for_message};use crate::storage_api::storage_key::{StorageKey, obtain_a_storage_key_for_non_storage_purposes};@@ -333,33 +334,31 @@ impl BroadcastChannel {let Ok(data) = data else {// If this throws an exception, catch it, fire an event named messageerror at destination, using MessageEvent, with its// origin initialized to sourceOrigin, and then abort these steps.- let event = CppEvent::create_message_event(+ let event = MessageEvent::create(+ vm,target_realm,- "messageerror",- Value::NULL,- &[],- Some(&message.source_origin),- "",- None,+ &Utf16String::from_utf8("messageerror"),+ MessageEventInit::new(vm),+ Some(message.source_origin.clone()),);- event.set_is_trusted(true);- destination.event_target.dispatch_event(&event);+ event.event().set_is_trusted(true);+ destination.event_target.dispatch_event(event.event());return;};// 4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and// its origin initialized to sourceOrigin.- let event = CppEvent::create_message_event(+ let mut event_init = MessageEventInit::new(vm);+ event_init.data = data;+ let event = MessageEvent::create(+ vm,target_realm,- "message",- data,- &[],- Some(&message.source_origin),- "",- None,+ &Utf16String::from_utf8("message"),+ event_init,+ Some(message.source_origin.clone()),);- event.set_is_trusted(true);- destination.event_target.dispatch_event(&event);+ event.event().set_is_trusted(true);+ destination.event_target.dispatch_event(event.event());}// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-closediff --git a/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs b/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rsindex a8d1e5339a2..ba6fb2aec43 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs@@ -28,6 +28,7 @@ use crate::domurl::url_input;use crate::fetch::infrastructure::fetch_controller::CppFetchController;use crate::fetch::infrastructure::http::requests::CppRequest;use crate::fetch::infrastructure::http::response_view::CppResponseView;+use crate::html::message_event::{MessageEvent, MessageEventInit};use crate::platform::timer::CppTimer;unsafe extern "C" {@@ -673,16 +674,17 @@ impl EventSource {let origin = origin.as_ref().expect("Interpreting the event stream follows its response");- let event = CppEvent::create_message_event(+ let mut event_init = MessageEventInit::new(vm);+ event_init.data = Value::from_string(PrimitiveString::create(vm, Utf16String::from_utf8(data_buffer)));+ event_init.last_event_id = Utf16String::from_utf8(&last_event_id);+ let event = MessageEvent::create(+ vm,this.realm,- r#type,- Value::from_string(PrimitiveString::create(vm, Utf16String::from_utf8(data_buffer))),- &[],- Some(origin),- &last_event_id,- None,+ &Utf16String::from_utf8(r#type),+ event_init,+ Some(origin.clone()),);- event.set_is_trusted(true);+ event.event().set_is_trusted(true);// 7. Set the data buffer and the event type buffer to the empty string.event_type.clear();@@ -692,7 +694,7 @@ impl EventSource {// event at the EventSource object.queue_a_task(vm, TaskSource::RemoteEvent, (this, event), |_, (this, event)| {if this.ready_state.get() != ReadyState::Closed {- this.event_target.dispatch_event(&event);+ this.event_target.dispatch_event(event.event());}});}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex eacd8426b2d..1897dee252c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -14,7 +14,7 @@use core::ffi::{c_int, c_void};use core::ptr::NonNull;-use ak::Utf16String;+use ak::{Utf16FlyString, Utf16String};use libgfx_rust::image_frame::ImageFrameHandle;use libjs_rust::api::{Gc, JSVM, MarkedVec, Object, RawNativeFunctionResult, Value, Vm, vm_from_abi};use liburl_rust::FfiOrigin;@@ -24,6 +24,7 @@ use super::event_source::EventSource;use super::image_bitmap::ImageBitmap;use super::image_bitmap_rendering_context::ImageBitmapRenderingContext;use super::image_data::ImageData;+use super::message_event::{MessageEvent, MessageEventInit, MessageEventSource};use super::message_port::MessagePort;use super::storage::{Storage, StorageType};use super::storage_event::{StorageEvent, StorageEventInit};@@ -604,6 +605,64 @@ pub unsafe extern "C" fn web_rust_html_create_storage_event(vm: *mut c_void, rea.as_ptr()}+/// The Event of a new MessageEvent in the realm, for C++ to fire. Its origin is the origin if there is one, and the+/// empty string otherwise.+///+/// # Safety+///+/// The VM, the realm, the data and each port must be live, and so must the source if it is not null. The type, the+/// port array and the origin are lent for the call.+#[allow(clippy::too_many_arguments, reason = "C++ passes each member of the dictionary")]+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_html_create_message_event(+ vm: *mut c_void,+ realm: *mut c_void,+ r#type: usize,+ data: u64,+ ports: *const *mut c_void,+ count: usize,+ source: *mut c_void,+ origin: *const FfiOrigin,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ let mut event_init = MessageEventInit::new(vm);+ // SAFETY: The caller passes live data.+ event_init.data = unsafe { Value::from_raw(data) };+ // SAFETY: The caller lends the ports for the call.+ for &port in unsafe { ak::slice_from_raw_parts(ports, count) } {+ // SAFETY: Each port is a live MessagePort.+ event_init.ports.push(unsafe { cell_from_abi::<MessagePort>(port) });+ }+ if !source.is_null() {+ // SAFETY: A source that is not null is a live MessagePort.+ let source = unsafe { cell_from_abi::<MessagePort>(source) };+ event_init.source = Some(MessageEventSource::MessagePort(source));+ }+ // SAFETY: An origin that is not null is lent for the call.+ let origin = (!origin.is_null()).then(|| unsafe { (*origin).to_origin() });+ // SAFETY: The caller lends the type for the call.+ let r#type: Utf16String = unsafe { Utf16FlyString::from_raw_borrowed(r#type) }.into();+ MessageEvent::create(vm, realm, &r#type, event_init, origin)+ .event()+ .as_ptr()+}++/// The Event of a new MessageEvent 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_html_create_message_event_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) };+ MessageEvent::create_for_create_event(vm, realm).event().as_ptr()+}+/// # Safety////// The VM, the realm, the target and the transferred objects must be live, and the target must be a Window if remotediff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_event.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_event.rsnew file mode 100644index 00000000000..d8eb804cefe--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_event.rs@@ -0,0 +1,276 @@+/*+ * Copyright (c) 2021, Dex♪ <[email protected]>+ * Copyright (c) 2022, Andreas Kling <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2026, Sam Atkins <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! MessageEvent, https://html.spec.whatwg.org/multipage/comms.html#messageevent++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Must, Object, Realm, Trace, Value, Vm};+use liburl_rust::origin::Origin;++use crate::bindings::conversions::{CppInterface, UsvString, frozen_array_to_js, rooted_sequence_to_js};+use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate, wrap};+use crate::bindings::setlike::WorldEntries;+use crate::bindings::{CallContext, WebIdlResult};+use crate::dom::event::EventInit;+use crate::html::message_port::MessagePort;++/// The union MessageEventSource of HTML/MessageEvent.idl, whose members the bindings convert.+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum MessageEventSource {+ WindowProxy(CppInterface),+ MessagePort(Ref<MessagePort>),+}++/// The dictionary MessageEventInit of HTML/MessageEvent.idl, whose members the bindings convert.+pub(crate) struct MessageEventInit<'vm> {+ pub(crate) parent: EventInit,+ pub(crate) data: Value,+ pub(crate) origin: UsvString,+ pub(crate) last_event_id: Utf16String,+ pub(crate) source: Option<MessageEventSource>,+ pub(crate) ports: MarkedVec<'vm, Ref<MessagePort>>,+}++impl<'vm> MessageEventInit<'vm> {+ /// The dictionary with the default value of each member.+ pub(crate) fn new(vm: &'vm Vm) -> Self {+ Self {+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ data: Value::NULL,+ origin: UsvString::from_utf8(""),+ last_event_id: Utf16String::from_utf8(""),+ source: None,+ ports: MarkedVec::new(vm),+ }+ }+}++// https://html.spec.whatwg.org/multipage/comms.html#concept-messageevent-origin+// Each MessageEvent has an origin (an origin, a string, or null), initially null.+enum MessageEventOrigin {+ Origin(Origin),+ String(UsvString),+ Null,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct MessageEventState {+ data: Value,+ #[gc(untraced)]+ origin: MessageEventOrigin,+ #[gc(untraced)]+ last_event_id: Utf16String,+ source: Option<MessageEventSource>,+ ports: Vec<Ref<MessagePort>>,+}++// https://html.spec.whatwg.org/multipage/comms.html#messageevent+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct MessageEvent {+ event: CppEvent,+ state: GcRefCell<MessageEventState>,+ ports_arrays: WorldEntries<Object>,+}++impl Wrappable for MessageEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++impl MessageEvent {+ /// A new MessageEvent in the realm, whose origin is the origin if there is one, and the origin member of the+ /// dictionary otherwise.+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: MessageEventInit<'_>,+ origin: Option<Origin>,+ ) -> Ref<MessageEvent> {+ let origin = match origin {+ Some(origin) => MessageEventOrigin::Origin(origin),+ None => MessageEventOrigin::String(event_init.origin),+ };+ Self::create_with_origin(+ vm,+ realm,+ event_name,+ event_init.parent,+ event_init.data,+ origin,+ event_init.last_event_id,+ event_init.source,+ &event_init.ports,+ )+ }++ /// A new MessageEvent in the realm whose type is the empty string, for createEvent().+ pub(crate) fn create_for_create_event(vm: &Vm, realm: Gc<Realm>) -> Ref<MessageEvent> {+ let event_init = MessageEventInit::new(vm);+ Self::create_with_origin(+ vm,+ realm,+ &Utf16String::from_utf8(""),+ event_init.parent,+ event_init.data,+ MessageEventOrigin::Null,+ event_init.last_event_id,+ event_init.source,+ &event_init.ports,+ )+ }++ #[allow(clippy::too_many_arguments, reason = "the event has these attributes")]+ fn create_with_origin(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: EventInit,+ data: Value,+ origin: MessageEventOrigin,+ last_event_id: Utf16String,+ source: Option<MessageEventSource>,+ ports: &MarkedVec<'_, Ref<MessagePort>>,+ ) -> Ref<MessageEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.bubbles,+ event_init.cancelable,+ event_init.composed,+ );+ let object = allocate(vm, |_| MessageEvent {+ event,+ state: GcRefCell::new(MessageEventState {+ data,+ origin,+ last_event_id,+ source,+ ports: ports.to_vec(),+ }),+ ports_arrays: WorldEntries::default(),+ });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: MessageEventInit<'_>,+ ) -> WebIdlResult<Ref<MessageEvent>> {+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict, None))+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ /// The data attribute, for the implementation.+ pub(crate) fn data_value(&self) -> Value {+ self.state.borrow().data+ }++ pub(crate) fn data(&self, _: &mut CallContext) -> WebIdlResult<Value> {+ Ok(self.data_value())+ }++ // https://html.spec.whatwg.org/multipage/comms.html#dom-messageevent-origin+ pub(crate) fn origin(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ Ok(match &self.state.borrow().origin {+ // 1. If this's origin is an origin, then return the serialization of this's origin.+ MessageEventOrigin::Origin(origin) => UsvString::from_utf8(&origin.serialize()),+ // 2. If this's origin is null, then return the empty string.+ MessageEventOrigin::Null => UsvString::from_utf8(""),+ // 3. Return this's origin.+ MessageEventOrigin::String(origin) => origin.clone(),+ })+ }++ pub(crate) fn last_event_id(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.state.borrow().last_event_id.clone())+ }++ pub(crate) fn source(&self, _: &mut CallContext) -> WebIdlResult<Option<MessageEventSource>> {+ Ok(self.state.borrow().source)+ }++ pub(crate) fn ports(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ let ports = self.ports_arrays.get_or_create(cx, || {+ let ports = MarkedVec::new(cx.vm());+ for port in &self.state.borrow().ports {+ ports.push(*port);+ }+ let array = rooted_sequence_to_js(cx, ports, |port| Ok(Value::from_object(wrap(cx, *port))));+ frozen_array_to_js(cx, array).must().as_object()+ });+ Ok(Value::from_object(ports))+ }++ // https://html.spec.whatwg.org/multipage/comms.html#dom-messageevent-initmessageevent+ #[allow(clippy::too_many_arguments, reason = "the operation has these arguments")]+ pub(crate) fn init_message_event(+ &self,+ cx: &mut CallContext,+ r#type: Utf16String,+ bubbles: bool,+ cancelable: bool,+ data: Value,+ origin: UsvString,+ last_event_id: Utf16String,+ source: Option<MessageEventSource>,+ ports: MarkedVec<'_, Ref<MessagePort>>,+ ) -> WebIdlResult<()> {+ // The initMessageEvent(type, bubbles, cancelable, data, origin, lastEventId, source, ports) method must+ // initialize the event in a manner analogous to the similarly-named initEvent() method.++ // https://dom.spec.whatwg.org/#dom-event-initevent+ // 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);++ *self.state.borrow_mut(cx.vm()) = MessageEventState {+ data,+ origin: MessageEventOrigin::String(origin),+ last_event_id,+ source,+ ports: ports.to_vec(),+ };++ self.ports_arrays.clear();+ Ok(())+ }++ // https://html.spec.whatwg.org/multipage/comms.html#the-messageevent-interface:extract-an-origin+ pub(crate) fn extract_an_origin(&self) -> Option<Origin> {+ // Objects implementing the MessageEvent interface's extract an origin steps are to return this's origin if it+ // is an origin; otherwise null.+ match &self.state.borrow().origin {+ MessageEventOrigin::Origin(origin) => Some(origin.clone()),+ MessageEventOrigin::String(_) | MessageEventOrigin::Null => None,+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rsindex 006e9ec4f35..9875126b746 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs@@ -24,13 +24,15 @@ use libjs_rust::api::{is_host_instance_of,};-use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent, set_event_handler_attribute};+use crate::bindings::event_target::{CppEventTarget, GetTheParent, set_event_handler_attribute};use crate::bindings::interface::{- Interface, Ref, Wrappable, Wrapped, allocate, implementation_if_wrapper, with_temporary_execution_context,+ Interface, Ref, Wrappable, Wrapped, allocate, implementation_if_wrapper, implementation_of,+ with_temporary_execution_context,};use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::message_event::{MessageEvent, MessageEventInit};use crate::html::port_channel::{PeerState, PortChannelEnd};use crate::html::structured_serialize::transfer_data_holder::{RawAttachment, ReceivePayload, TransferPayload, append_attachments,@@ -516,9 +518,15 @@ impl MessagePort {TransferRecord::discard(serialize_with_transfer_result);let Ok(deserialize_record) = deserialize_record else {// If this throws an exception, catch it, fire an event named messageerror at messageEventTarget, using MessageEvent, and then return.- let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], None, "", None);- event.set_is_trusted(true);- message_event_target.dispatch_event(&event);+ let event = MessageEvent::create(+ vm,+ target_realm,+ &Utf16String::from_utf8("messageerror"),+ MessageEventInit::new(vm),+ None,+ );+ event.event().set_is_trusted(true);+ message_event_target.dispatch_event(event.event());return;};@@ -530,22 +538,17 @@ impl MessagePort {let new_ports = MarkedVec::new(vm);for value in deserialize_record.transferred_values.values().iter() {if is_host_instance_of(value, Self::wrapper_class()) {- new_ports.push(*value);+ new_ports.push(implementation_of::<Self>(*value));}}// 7. Fire an event named message at messageEventTarget, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.- let event = CppEvent::create_message_event(- target_realm,- "message",- message_clone,- &new_ports.values(),- None,- "",- None,- );- event.set_is_trusted(true);- message_event_target.dispatch_event(&event);+ let mut event_init = MessageEventInit::new(vm);+ event_init.data = message_clone;+ event_init.ports = new_ports;+ let event = MessageEvent::create(vm, target_realm, &Utf16String::from_utf8("message"), event_init, None);+ event.event().set_is_trusted(true);+ message_event_target.dispatch_event(event.event());}pub(crate) fn enable(this: Ref<Self>, vm: &Vm) {diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex f0fb1a55a79..5e52137bb2f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -72,6 +72,8 @@ pub(crate) mod image_data;#[cfg(not(test))]pub(crate) mod message_channel;#[cfg(not(test))]+pub(crate) mod message_event;+#[cfg(not(test))]pub(crate) mod message_port;#[cfg(not(test))]pub(crate) mod navigable;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/window.rs b/Libraries/LibWeb/Bindings/Rust/src/html/window.rsindex 58c3c7251cc..d00d5d88e21 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/window.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/window.rs@@ -20,11 +20,13 @@ use libjs_rust::api::{use liburl_rust::FfiOrigin;use liburl_rust::origin::Origin;+use crate::bindings::conversions::window_proxy_from_object;use crate::bindings::cpp_cell::CppCell;-use crate::bindings::event_target::{CppEvent, CppEventTarget};-use crate::bindings::interface::{Interface, with_temporary_execution_context_and_callbacks};+use crate::bindings::event_target::CppEventTarget;+use crate::bindings::interface::{Interface, implementation_of, with_temporary_execution_context_and_callbacks};use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::message_event::{MessageEvent, MessageEventInit, MessageEventSource};use crate::html::message_port::MessagePort;use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};use crate::html::structured_serialize::{structured_deserialize_with_transfer, structured_serialize_with_transfer};@@ -35,6 +37,7 @@ unsafe extern "C" {fn web_window_post_message_incumbent_settings() -> *mut c_void;fn web_window_post_message_settings_origin(settings: *mut c_void, context: *mut c_void, receive: ReceiveOrigin);fn web_window_post_message_source(settings: *mut c_void) -> *mut c_void;+ fn web_window_post_message_source_object(source: *mut c_void) -> *mut c_void;fn web_window_post_message_parse_target_origin(target: usize, context: *mut c_void, receive: ReceiveOrigin);fn web_window_post_message_realm(window: *mut c_void) -> *mut c_void;fn web_window_post_message_document_origin(window: *mut c_void, context: *mut c_void, receive: ReceiveOrigin);@@ -223,7 +226,14 @@ fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMess// 3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).// NB: Both were snapshotted before the task was queued.let origin = &posted_message.origin;- let source = posted_message.source.as_ref();+ let source = posted_message.source.as_ref().map(|source| {+ // SAFETY: The source is a live WindowProxy, and C++ returns its live object.+ let object = unsafe { web_window_post_message_source_object(source.as_ptr()) };+ let object = NonNull::new(object.cast()).expect("a WindowProxy has an object");+ // SAFETY: The object is live.+ let object = unsafe { Gc::<Object>::from_non_null(object) };+ MessageEventSource::WindowProxy(window_proxy_from_object(object).expect("the source is a WindowProxy"))+ });// 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).// NB: The execution context must not stay on the stack while the event is dispatched, so that a microtask@@ -240,10 +250,17 @@ fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMess// If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent,// with its origin initialized to origin and the source attribute initialized to source, and then return.let Ok(deserialize_record) = deserialize_record else {- let event =- CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], Some(origin), "", source);- event.set_is_trusted(true);- target_window.dispatch_event(&event);+ let mut event_init = MessageEventInit::new(vm);+ event_init.source = source;+ let event = MessageEvent::create(+ vm,+ target_realm,+ &Utf16String::from_utf8("messageerror"),+ event_init,+ Some(origin.clone()),+ );+ event.event().set_is_trusted(true);+ target_window.dispatch_event(event.event());return;};@@ -256,22 +273,24 @@ fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMesslet new_ports = MarkedVec::new(vm);for &value in deserialize_record.transferred_values.values().iter() {if is_host_instance_of(&value, MessagePort::wrapper_class()) {- new_ports.push(value);+ new_ports.push(implementation_of::<MessagePort>(value));}}// 7. Fire an event named message at targetWindow, using MessageEvent, with its origin initialized to origin,// the source attribute initialized to source, the data attribute initialized to messageClone, and the ports// attribute initialized to newPorts.- let event = CppEvent::create_message_event(+ let mut event_init = MessageEventInit::new(vm);+ event_init.data = message_clone;+ event_init.source = source;+ event_init.ports = new_ports;+ let event = MessageEvent::create(+ vm,target_realm,- "message",- message_clone,- &new_ports.values(),- Some(origin),- "",- source,+ &Utf16String::from_utf8("message"),+ event_init,+ Some(origin.clone()),);- event.set_is_trusted(true);- target_window.dispatch_event(&event);+ event.event().set_is_trusted(true);+ target_window.dispatch_event(event.event());}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rsindex 891b3253f2f..c6cb92d6950 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs@@ -13,7 +13,6 @@ use libjs_rust::api::{Trace, Value, Vm,};-use crate::bindings::event_target::message_event_data;use crate::bindings::interface::{Ref, allocate, implementation_of, wrap};use crate::bindings::promise::{NativeSteps, WebIdlPromise, create_promise, create_rejected_promise_from_exception, create_resolved_promise,@@ -21,6 +20,7 @@ use crate::bindings::promise::{};use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter};use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::html::message_event::MessageEvent;use crate::html::message_port::MessagePort;use crate::streams::algorithms::{AbortAlgorithm, CancelAlgorithm, CloseAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm,@@ -61,7 +61,7 @@ fn add_handlers<C: Trace + Copy + 'static>(|vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageSteps<C>>| {let (state, realm) = function.captures;// NB: The port's message event handler is called with a MessageEvent.- let data = message_event_data(vm.argument(0));+ let data = implementation_of::<MessageEvent>(vm.argument(0).as_object()).data_value();(function.steps)(&CallContext::new(vm, realm), state, data);Ok(Value::UNDEFINED)},diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cppindex 6d85ab13e50..9df1b841bd6 100644--- a/Libraries/LibWeb/Bindings/RustEventTarget.cpp+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp@@ -7,15 +7,11 @@#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>-#include <LibURL/RustIntegration.h>#include <LibWeb/Bindings/RustEventTarget.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/EventDispatcher.h>#include <LibWeb/DOM/IDLEventListener.h>-#include <LibWeb/HTML/MessageEvent.h>-#include <LibWeb/HTML/MessagePort.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowProxy.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/WebIDL/CallbackType.h>@@ -119,8 +115,6 @@ void web_bindings_add_event_listener_without_options(DOM::EventTarget*, Readonlyvoid web_bindings_remove_event_listener_without_options(DOM::EventTarget*, ReadonlyBytes type, WebIDL::CallbackType*);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);-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, ReadonlyBytes last_event_id, HTML::WindowProxy* source);-JSValue web_bindings_message_event_data(JSValue event);void web_bindings_set_event_owner(RustEvent*, u16 interface_name, RustInterfaceCell* owner);void web_bindings_event_set_is_trusted(DOM::Event*, bool is_trusted);bool web_bindings_dispatch_event(DOM::EventTarget*, DOM::Event*);@@ -212,32 +206,6 @@ RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubblereturn RustEvent::create(Utf16FlyString::from_utf16(type_string.utf16_view()), event_init, HighResolutionTime::current_high_resolution_time(js_realm.global_object())).ptr();}-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, ReadonlyBytes last_event_id, HTML::WindowProxy* source)-{- auto& js_realm = *static_cast<JS::Realm*>(realm);- HTML::MessageEventInit event_init;- event_init.data = JS::HostABI::value_from_abi(data);- event_init.last_event_id = Utf16String::from_utf8_without_validation(last_event_id);- if (source)- event_init.source = GC::Ref { *source };- for (size_t i = 0; i < count; ++i) {- auto* port = impl_from<HTML::MessagePort>(JS::HostABI::object_from_abi(ports[i]));- VERIFY(port);- event_init.ports.append(*port);- }- auto event_type = Utf16FlyString::from_utf8_without_validation(type);- if (!origin)- return HTML::MessageEvent::create(js_realm.global_object(), event_type, event_init).ptr();- return HTML::MessageEvent::create(js_realm.global_object(), event_type, event_init, URL::RustIntegration::origin_from_ffi(*origin)).ptr();-}--JSValue web_bindings_message_event_data(JSValue event)-{- auto* message_event = impl_from<HTML::MessageEvent>(&JS::HostABI::value_from_abi(event).as_object());- VERIFY(message_event);- return JS::HostABI::value_to_abi(message_event->data());-}-void web_bindings_set_event_owner(RustEvent* event, u16 interface_name, RustInterfaceCell* owner){event->set_owner(static_cast<InterfaceName>(interface_name), *owner);diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 10f0f18afca..cde9660900d 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -3928,7 +3928,7 @@ WebIDL::ExceptionOr<GC::Ref<Event>> Document::create_event(Utf16FlyString const&} else if (interface.equals_ignoring_ascii_case("keyboardevent"sv)) {event = UIEvents::KeyboardEvent::create(Utf16FlyString {}, {}, time_stamp);} else if (interface.equals_ignoring_ascii_case("messageevent"sv)) {- event = HTML::MessageEvent::create(FlyString {}, time_stamp);+ event = HTML::create_message_event(realm);} else if (interface.equals_ignoring_ascii_case("mouseevent"sv)|| interface.equals_ignoring_ascii_case("mouseevents"sv)) {event = UIEvents::MouseEvent::create(FlyString {}, UIEvents::MouseEventOptions {}, 0, 0, 0, 0, time_stamp);diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex aa9869de6f3..a5fa6a95993 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -776,7 +776,6 @@ class LocalTraversableNavigable;class Location;class MediaError;class MediaStreamPlayback;-class MessageEvent;class MessagePort;class MimeType;class MimeTypeArray;diff --git a/Libraries/LibWeb/HTML/MessageEvent.cpp b/Libraries/LibWeb/HTML/MessageEvent.cppindex acb21eabc03..76a6e07fd28 100644--- a/Libraries/LibWeb/HTML/MessageEvent.cpp+++ b/Libraries/LibWeb/HTML/MessageEvent.cpp@@ -6,268 +6,44 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Array.h>-#include <LibWeb/Bindings/MessagePort.h>-#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibURL/RustIntegration.h>+#include <LibWeb/DOM/Event.h>#include <LibWeb/HTML/MessageEvent.h>#include <LibWeb/HTML/MessagePort.h>-#include <LibWeb/HTML/WindowProxy.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/Infra/SerializedURL.h>namespace Web::HTML {-GC_DEFINE_ALLOCATOR(MessageEvent);--static Bindings::WrapperWorldWeakValueCacheMap<MessageEvent, JS::Array>& message_event_ports_caches()-{- static thread_local NeverDestroyed<Bindings::WrapperWorldWeakValueCacheMap<MessageEvent, JS::Array>> caches;- return *caches;-}--void clear_message_event_ports_caches()-{- message_event_ports_caches().clear();-}--static void clear_ports_cache(MessageEvent& event)-{- message_event_ports_caches().cache_for(event).clear();-}--static Bindings::WrapperWorldWeakValueCache<JS::Array>& ports_cache_for(MessageEvent& event)-{- return message_event_ports_caches().cache_for(event);-}--static MessageEventInit message_event_init_from_bindings(Bindings::MessageEventInit const& event_init)-{- return {- {- .bubbles = event_init.bubbles,- .cancelable = event_init.cancelable,- .composed = event_init.composed,- },- event_init.data,- event_init.last_event_id,- event_init.origin,- event_init.ports,- event_init.source,- };-}--WebIDL::ExceptionOr<GC::Ref<MessageEvent>> MessageEvent::create_for_constructor(Utf16String const& event_name, Bindings::MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return MessageEvent::create(Utf16FlyString::from_utf16(event_name.utf16_view()), message_event_init_from_bindings(event_init), time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(JS::Object const& relevant_global_object, FlyString const& event_name, MessageEventInit const& event_init)-{- return create(event_name, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object));-}--GC::Ref<MessageEvent> MessageEvent::create(JS::Object const& relevant_global_object, FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin)-{- return create(event_name, event_init, origin, HighResolutionTime::current_high_resolution_time(relevant_global_object));-}--GC::Ref<MessageEvent> MessageEvent::create(JS::Object const& relevant_global_object, Utf16FlyString const& event_name, MessageEventInit const& event_init)-{- return create(event_name, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object));-}--GC::Ref<MessageEvent> MessageEvent::create(JS::Object const& relevant_global_object, Utf16FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin)-{- return create(event_name, event_init, origin, HighResolutionTime::current_high_resolution_time(relevant_global_object));-}--GC::Ref<MessageEvent> MessageEvent::create(FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, event_init, time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, event_init, origin, time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(Utf16FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, event_init, time_stamp);-}--GC::Ref<MessageEvent> MessageEvent::create(Utf16FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<MessageEvent>(event_name, event_init, origin, time_stamp);+extern "C" {+// Defined in Bindings/Rust/src/html/exports.rs.+DOM::Event* web_rust_html_create_message_event(JSVM*, void* realm, FlatPtr type, JSValue data, MessagePort* const* ports, size_t count, MessagePort* source, URL::FFI::FfiOrigin const* origin);+DOM::Event* web_rust_html_create_message_event_for_create_event(JSVM*, void* realm);}-MessageEvent::MessageEvent(FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, time_stamp)- , m_data(JS::js_null())- , m_origin(Utf16String {})+GC::Ref<DOM::Event> create_message_event(JS::Realm& realm, Utf16FlyString const& type, MessageEventInit const& event_init, Optional<URL::Origin> const& origin){-}--MessageEvent::MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : MessageEvent(event_name, event_init, Utf16String { event_init.origin }, time_stamp)-{-}--MessageEvent::MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : MessageEvent(event_name, event_init, Variant<URL::Origin, Utf16String, Empty> { origin }, time_stamp)-{-}--MessageEvent::MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, Variant<URL::Origin, Utf16String, Empty> origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_data(event_init.data)- , m_origin(move(origin))- , m_last_event_id(event_init.last_event_id)- , m_source(event_init.source)--{- m_ports.ensure_capacity(event_init.ports.size());- for (auto const& port : event_init.ports) {- m_ports.unchecked_append(port);- }-}--MessageEvent::MessageEvent(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, time_stamp)- , m_data(JS::js_null())- , m_origin(Empty {})-{-}--MessageEvent::MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : MessageEvent(event_name, event_init, Variant<URL::Origin, Utf16String, Empty> { event_init.origin }, time_stamp)-{-}--MessageEvent::MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const& origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : MessageEvent(event_name, event_init, Variant<URL::Origin, Utf16String, Empty> { origin }, time_stamp)-{-}--MessageEvent::MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, Variant<URL::Origin, Utf16String, Empty> origin, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_data(event_init.data)- , m_origin(move(origin))- , m_last_event_id(event_init.last_event_id)- , m_source(event_init.source)-{- m_ports.ensure_capacity(event_init.ports.size());+ GC::RootVector<MessagePort*> ports;+ ports.ensure_capacity(event_init.ports.size());for (auto const& port : event_init.ports)- m_ports.unchecked_append(port);-}--MessageEvent::~MessageEvent() = default;+ ports.unchecked_append(port.ptr());-void MessageEvent::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_data);- visitor.visit(m_ports);- visitor.visit(m_source);-}--// https://html.spec.whatwg.org/multipage/comms.html#dom-messageevent-origin-Utf16String MessageEvent::origin() const-{- return m_origin.visit(- // 1. If this's origin is an origin, then return the serialization of this's origin.- [](URL::Origin const& origin) {- return utf16_string_from_url_ascii(origin.serialize());- },- // 2. If this's origin is null, then return the empty string.- [](Empty) {- return Utf16String {};- },- // 3. Return this's origin.- [](Utf16String const& origin) {- return origin;- });-}--NullableMessageEventSource MessageEvent::source() const-{- return m_source;-}--JS::Value MessageEvent::ports(JS::Realm& realm)-{- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto& ports_cache = ports_cache_for(*this);-- if (auto ports_array = ports_cache.get(wrapper_world))- return JS::Value(ports_array);-- GC::RootVector<JS::Value> port_vector;- for (auto const& port : message_ports())- port_vector.append(Bindings::wrap(wrapper_world, realm, port));-- auto ports_array = JS::Array::create_from(realm, port_vector);- MUST(ports_array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));-- ports_cache.set(wrapper_world, ports_array);-- return JS::Value(ports_array);-}--// https://html.spec.whatwg.org/multipage/comms.html#dom-messageevent-initmessageevent-void MessageEvent::init_message_event(Utf16FlyString const& type, bool bubbles, bool cancelable, JS::Value data, Utf16View origin, Utf16View last_event_id, NullableMessageEventSource source, GC::RootVector<GC::Ref<MessagePort>> const& ports)-{- auto was_dispatched = dispatched();-- // The initMessageEvent(type, bubbles, cancelable, data, origin, lastEventId, source, ports) method must initialize the event in a- // manner analogous to the similarly-named initEvent() method.-- // 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);-- // Implementation Defined: Initialise other values.- m_data = data;- m_origin = Utf16String::from_utf16(origin);- m_last_event_id = Utf16String::from_utf16(last_event_id);- m_source = source;-- m_ports.clear();- m_ports.ensure_capacity(ports.size());- for (auto const& port : ports) {- m_ports.unchecked_append(port);- }+ auto create = [&](URL::FFI::FfiOrigin const* ffi_origin) {+ return web_rust_html_create_message_event(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.raw_identity(), JS::HostABI::value_to_abi(event_init.data), ports.data(), ports.size(), event_init.source.ptr(), ffi_origin);+ };+ if (!origin.has_value())+ return *create(nullptr);- if (!was_dispatched)- clear_ports_cache(*this);+ DOM::Event* event = nullptr;+ URL::RustIntegration::lend_origin_to_ffi(*origin, [&](URL::FFI::FfiOrigin const& ffi_origin) {+ event = create(&ffi_origin);+ });+ return *event;}-// https://html.spec.whatwg.org/multipage/comms.html#the-messageevent-interface:extract-an-origin-Optional<URL::Origin> MessageEvent::extract_an_origin() const+GC::Ref<DOM::Event> create_message_event(JS::Realm& realm){- // Objects implementing the MessageEvent interface's extract an origin steps are to return this's origin if it is an origin; otherwise null.- return m_origin.visit(- [](URL::Origin const& origin) -> Optional<URL::Origin> {- return origin;- },- [](auto const&) -> Optional<URL::Origin> {- return {};- });+ return *web_rust_html_create_message_event_for_create_event(JS::HostABI::vm_to_abi(realm.vm()), &realm);}}diff --git a/Libraries/LibWeb/HTML/MessageEvent.h b/Libraries/LibWeb/HTML/MessageEvent.hindex 386c5ffca93..5179b92bf2b 100644--- a/Libraries/LibWeb/HTML/MessageEvent.h+++ b/Libraries/LibWeb/HTML/MessageEvent.h@@ -8,87 +8,29 @@#pragma once+#include <AK/Optional.h>#include <AK/Utf16FlyString.h>-#include <AK/Utf16String.h>-#include <AK/Utf16View.h>+#include <LibGC/Ptr.h>#include <LibGC/RootVector.h>#include <LibJS/Forward.h>-#include <LibWeb/Bindings/MessageEvent.h>-#include <LibWeb/DOM/Event.h>+#include <LibJS/Runtime/Value.h>+#include <LibURL/Origin.h>#include <LibWeb/Export.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>+#include <LibWeb/Forward.h>namespace Web::HTML {-// FIXME: Include ServiceWorker-// https://html.spec.whatwg.org/multipage/comms.html#messageeventsource-using MessageEventSource = Variant<GC::Ref<WindowProxy>, GC::Ref<MessagePort>>;-using NullableMessageEventSource = Variant<GC::Ref<WindowProxy>, GC::Ref<MessagePort>, Empty>;--struct MessageEventInit : DOM::EventInit {+struct MessageEventInit {JS::Value data { JS::js_null() };- Utf16String last_event_id {};- Utf16String origin {};GC::RootVector<GC::Ref<MessagePort>> ports {};- NullableMessageEventSource source { Empty {} };+ GC::Ptr<MessagePort> source;};-// https://html.spec.whatwg.org/multipage/comms.html#messageevent-class WEB_API MessageEvent : public DOM::Event {- WEB_WRAPPABLE(MessageEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(MessageEvent);--public:- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<MessageEvent>> create_for_constructor(Utf16String const& event_name, Bindings::MessageEventInit const&, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(JS::Object const& relevant_global_object, FlyString const& event_name, MessageEventInit const&);- [[nodiscard]] static GC::Ref<MessageEvent> create(JS::Object const& relevant_global_object, FlyString const& event_name, MessageEventInit const&, URL::Origin const&);- [[nodiscard]] static GC::Ref<MessageEvent> create(JS::Object const& relevant_global_object, Utf16FlyString const& event_name, MessageEventInit const&);- [[nodiscard]] static GC::Ref<MessageEvent> create(JS::Object const& relevant_global_object, Utf16FlyString const& event_name, MessageEventInit const&, URL::Origin const&);- [[nodiscard]] static GC::Ref<MessageEvent> create(FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(FlyString const& event_name, MessageEventInit const&, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(FlyString const& event_name, MessageEventInit const&, URL::Origin const&, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(Utf16FlyString const& event_name, MessageEventInit const&, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<MessageEvent> create(Utf16FlyString const& event_name, MessageEventInit const&, URL::Origin const&, HighResolutionTime::DOMHighResTimeStamp);-- virtual ~MessageEvent() override;-- JS::Value const& data() const { return m_data; }- Utf16String origin() const;- Utf16String const& last_event_id() const { return m_last_event_id; }- Vector<GC::Ref<MessagePort>> const& message_ports() const { return m_ports; }- JS::Value ports(JS::Realm&);-- NullableMessageEventSource source() const;-- virtual Optional<URL::Origin> extract_an_origin() const override;-- void init_message_event(Utf16FlyString const& type, bool bubbles, bool cancelable, JS::Value data, Utf16View origin, Utf16View last_event_id, NullableMessageEventSource source, GC::RootVector<GC::Ref<MessagePort>> const& ports);--private:- virtual void visit_edges(GC::Cell::Visitor&) override;-- MessageEvent(FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const&, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(FlyString const& event_name, MessageEventInit const& event_init, Variant<URL::Origin, Utf16String, Empty>, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, URL::Origin const&, HighResolutionTime::DOMHighResTimeStamp);- MessageEvent(Utf16FlyString const& event_name, MessageEventInit const& event_init, Variant<URL::Origin, Utf16String, Empty>, HighResolutionTime::DOMHighResTimeStamp);-- JS::Value m_data;-- // https://html.spec.whatwg.org/multipage/comms.html#concept-messageevent-origin- // Each MessageEvent has an origin (an origin, a string, or null), initially null.- Variant<URL::Origin, Utf16String, Empty> m_origin;-- Utf16String m_last_event_id;- NullableMessageEventSource m_source;- Vector<GC::Ref<MessagePort>> m_ports;-};+// The Event of a new MessageEvent in the realm, whose origin is the origin if there is one, and the empty string+// otherwise.+WEB_API GC::Ref<DOM::Event> create_message_event(JS::Realm&, Utf16FlyString const& type, MessageEventInit const&, Optional<URL::Origin> const& origin = {});-// For an agent that goes away, whose weak references the cache would keep beyond the end of its heap.-void clear_message_event_ports_caches();+// The Event of a new MessageEvent in the realm whose type is the empty string, for createEvent().+GC::Ref<DOM::Event> create_message_event(JS::Realm&);}diff --git a/Libraries/LibWeb/HTML/MessageEvent.idl b/Libraries/LibWeb/HTML/MessageEvent.idlindex 10f18e67505..e5e99103d05 100644--- a/Libraries/LibWeb/HTML/MessageEvent.idl+++ b/Libraries/LibWeb/HTML/MessageEvent.idl@@ -2,7 +2,7 @@typedef (WindowProxy or MessagePort) MessageEventSource;// https://html.spec.whatwg.org/multipage/comms.html#messageevent-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface MessageEvent : Event {constructor(DOMString type, optional MessageEventInit eventInitDict = {});diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cppindex abe83bf0d6c..8e1d3e20828 100644--- a/Libraries/LibWeb/HTML/Window.cpp+++ b/Libraries/LibWeb/HTML/Window.cpp@@ -1678,6 +1678,7 @@ void web_window_queue_posted_message(JSVM*, Window*, SerializedTransferRecord*,EnvironmentSettingsObject* web_window_post_message_incumbent_settings();void web_window_post_message_settings_origin(EnvironmentSettingsObject*, void*, void (*)(void*, URL::FFI::FfiOrigin const*));WindowProxy* web_window_post_message_source(EnvironmentSettingsObject*);+JSObject* web_window_post_message_source_object(WindowProxy*);void web_window_post_message_parse_target_origin(FlatPtr, void*, void (*)(void*, URL::FFI::FfiOrigin const*));void* web_window_post_message_realm(Window*);void web_window_post_message_document_origin(Window*, void*, void (*)(void*, URL::FFI::FfiOrigin const*));@@ -1698,6 +1699,11 @@ WindowProxy* web_window_post_message_source(EnvironmentSettingsObject* settings)return window_proxy_from_global_this_value(settings->realm().global_environment().global_this_value()).ptr();}+JSObject* web_window_post_message_source_object(WindowProxy* source)+{+ return JS::HostABI::object_to_abi(&source->object());+}+void web_window_post_message_parse_target_origin(FlatPtr raw_target_origin, void* context, void (*receive)(void*, URL::FFI::FfiOrigin const*)){// DOMURL parsing also resolves blob URL entries, whose stored origin takes precedence over parsing their path.diff --git a/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp b/Libraries/LibWeb/WebRTC/WebRTCAgent.cppindex 55b3aff77a0..f8f4a3c3e19 100644--- a/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp+++ b/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp@@ -198,7 +198,7 @@ void WebRTCAgent::wire_event_handlers()HTML::TemporaryExecutionContext context(realm);HTML::MessageEventInit init;init.data = JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(text));- (*channel)->dispatch_event(HTML::MessageEvent::create((*channel)->relevant_global_object(), HTML::EventNames::message, init));+ (*channel)->dispatch_event(HTML::create_message_event(realm, HTML::EventNames::message, init));}};m_client->on_data_channel_message_binary_event = [this](u64 channel_id, ByteBuffer bytes) {@@ -210,7 +210,7 @@ void WebRTCAgent::wire_event_handlers()init.data = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, FileAPI::Blob::create(move(bytes), String {}));elseinit.data = JS::ArrayBuffer::create(realm, bytes);- (*channel)->dispatch_event(HTML::MessageEvent::create((*channel)->relevant_global_object(), HTML::EventNames::message, init));+ (*channel)->dispatch_event(HTML::create_message_event(realm, HTML::EventNames::message, init));}};}diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cppindex a36fec55577..5afac8c45b9 100644--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp@@ -494,7 +494,7 @@ void WebSocket::on_message(ByteBuffer message, bool is_text)HTML::MessageEventInit event_init;event_init.data = data_for_event;- self.dispatch_event(HTML::MessageEvent::create(realm.global_object(), HTML::EventNames::message, event_init, self.m_url.origin()));+ self.dispatch_event(HTML::create_message_event(realm, HTML::EventNames::message, event_init, self.m_url.origin()));}));}diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 32f16f18734..c27dbfbab52 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -65,10 +65,10 @@ ALLOWED_REALM_MENTIONS = {"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (63,- 167,+ 170,"HTML algorithms still contain structured serialization, including canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; window postMessage glue supplies principal realms and routes remote messages; ""the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; "- "the C++ glue of the Rust Storage and StorageEvent creates them in a given realm",+ "the C++ glue of the Rust Storage, StorageEvent and MessageEvent creates them in a given realm",),"IndexedDB": (4,diff --git a/Services/WebContent/Worker/WorkerHost.cpp b/Services/WebContent/Worker/WorkerHost.cppindex 075ccaafa13..e3e9f79055f 100644--- a/Services/WebContent/Worker/WorkerHost.cpp+++ b/Services/WebContent/Worker/WorkerHost.cpp@@ -420,9 +420,9 @@ void WorkerHost::connect_shared_worker_impl(Web::HTML::TransferDataEncoder messaWeb::HTML::MessageEventInit event_init {};event_init.data = GC::Ref { vm.empty_string() };event_init.ports.append(inside_port);- event_init.source = Web::HTML::NullableMessageEventSource { inside_port };+ event_init.source = inside_port;- auto message_event = Web::HTML::MessageEvent::create(realm.global_object(), Web::HTML::EventNames::connect, event_init);+ auto message_event = Web::HTML::create_message_event(realm, Web::HTML::EventNames::connect, event_init);worker_global_scope->dispatch_event(message_event);}));diff --git a/Tests/LibWeb/TestWindowProxyWorld.cpp b/Tests/LibWeb/TestWindowProxyWorld.cppindex a1a4d287de9..b4370a83dc1 100644--- a/Tests/LibWeb/TestWindowProxyWorld.cpp+++ b/Tests/LibWeb/TestWindowProxyWorld.cpp@@ -18,6 +18,7 @@#include <LibWeb/Bindings/PrincipalHostDefined.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/DOM/BindingsGlue.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/DOM/IDLEventListener.h>#include <LibWeb/HTML/BrowsingContext.h>@@ -197,6 +198,34 @@ TEST_CASE(per_world_windowproxy_and_window_wrapper)EXPECT(window->dispatch_event(*event));EXPECT(listener_was_called->value);+ auto source_listener_was_called = make_ref_counted<ListenerCall>();+ auto source_callback_function = JS::NativeFunction::create(+ extension_realm,+ GC::create_function(GC::Heap::the(), GC::captures(extension_proxy, source_listener_was_called), [](auto& extension_proxy, auto& source_listener_was_called, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ source_listener_was_called->value = true;++ auto event_value = vm.argument(0);+ EXPECT(event_value.is_object());+ auto source = TRY(event_value.as_object().internal_get(JS::PropertyKey { "source"_utf16_fly_string }, event_value));+ EXPECT(source.is_object());+ EXPECT(&source.as_object() == &extension_proxy->object());++ return JS::js_undefined();+ }),+ 1);+ auto source_callback = GC::Heap::the().allocate<Web::WebIDL::CallbackType>(*source_callback_function, principal_settings);+ window->add_event_listener_without_options("windowproxy-source-test"_utf16_fly_string, *Web::DOM::IDLEventListener::create(*source_callback));++ auto message_event_value = run_script(window->principal_realm(), "new MessageEvent('windowproxy-source-test', { source: window });"_utf16);+ auto main_world_source = MUST(message_event_value.as_object().internal_get(JS::PropertyKey { "source"_utf16_fly_string }, message_event_value));+ EXPECT(main_world_source.is_object());+ EXPECT(&main_world_source.as_object() == &main_proxy->object());++ auto* message_event = Web::Bindings::event_from_value(message_event_value);+ EXPECT(message_event);+ EXPECT(window->dispatch_event(*message_event));+ EXPECT(source_listener_was_called->value);+auto* popped_extension_execution_context = vm.pop_execution_context();EXPECT(popped_extension_execution_context == extension_execution_context.ptr());