Skip to content

Truly independent web browser

LibWeb: Implement the performance timeline in Rust

Shannon Boothf22a5e702ce0
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
index 660dff4d857..4c961355d00 100644
--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp
+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
@@ -73,7 +73,6 @@
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserver.h>
#include <LibWeb/PermissionsAPI/PermissionStore.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
@@ -796,7 +795,6 @@ void shut_down_agent()
Platform::discard_thread_pool_completions();
Fetch::Fetching::disarm_all_body_stream_wakes();
HTML::clear_message_event_ports_caches();
- PerformanceTimeline::clear_supported_entry_types_caches();
ServiceWorker::clear_service_worker_container_ready_promise_caches();
PermissionsAPI::PermissionStore::forget_statuses_of_this_agent();
FileAPI::forget_blob_url_store_of_this_agent();
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
index fcda287d151..92ad10b59c9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
@@ -11,7 +11,7 @@ use core::ffi::c_void;
use core::ptr::NonNull;
use ak::Utf16String;
-use libjs_rust::api::{Gc, Object, Trace};
+use libjs_rust::api::{Gc, Object, Realm, Trace};
use liburl_rust::{RustUrl, Url};
use crate::bindings::cpp_cell::CppCell;
@@ -19,6 +19,7 @@ use crate::bindings::cpp_cell::CppCell;
unsafe extern "C" {
fn web_bindings_relevant_settings_object(global_object: *mut c_void) -> *mut c_void;
fn web_bindings_environment_settings_object_global_object(settings_object: *mut c_void) -> *mut c_void;
+ fn web_bindings_environment_settings_object_realm(settings_object: *mut c_void) -> *mut c_void;
fn web_bindings_environment_settings_object_id(
settings_object: *mut c_void,
id: *mut c_void,
@@ -76,6 +77,14 @@ impl CppEnvironmentSettingsObject {
unsafe { Gc::from_non_null(NonNull::new(global_object.cast()).expect("a settings object has a global object")) }
}
+ /// https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object's-realm
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ // SAFETY: The settings object is live, and LibWeb returns its live realm.
+ let realm = unsafe { web_bindings_environment_settings_object_realm(self.as_ptr()) };
+ // SAFETY: The realm is live.
+ unsafe { Gc::from_non_null(NonNull::new(realm.cast()).expect("a settings object has a realm")) }
+ }
+
/// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#encoding-parsing-a-url
pub(crate) fn encoding_parse_url(&self, url: &Utf16String) -> Option<Url> {
let mut parsed_url = None;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 6b230d34799..5051ac43818 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -33,7 +33,8 @@ use crate::bindings::realm_data::wrapper_world_of;
use crate::bindings::services::{
web_bindings_define_unforgeable_attributes, web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype,
web_bindings_perform_a_security_check, web_bindings_realm_is_secure_context, web_bindings_realm_is_window,
- web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper, web_bindings_with_temporary_execution_context,
+ web_bindings_report_an_exception, web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper,
+ web_bindings_with_temporary_execution_context,
};
/// What an implementation can tell the bindings about its objects, as a C++ implementation object does by overriding
@@ -458,6 +459,12 @@ pub(crate) fn realm_is_secure_context(realm: Gc<Realm>) -> bool {
unsafe { web_bindings_realm_is_secure_context(realm.as_ptr().cast()) }
}
+/// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception
+pub(crate) fn report_an_exception(realm: Gc<Realm>, exception: Value) {
+ // SAFETY: The realm and the exception are live.
+ unsafe { web_bindings_report_an_exception(realm.as_ptr().cast(), exception.to_raw()) }
+}
+
/// Runs the steps while an execution context of the realm is on the stack, for steps that can run script but that do not
/// run on behalf of script, as an HTML::TemporaryExecutionContext does for C++.
pub(crate) fn with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Realm>, steps: F) -> R {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index e184f9c9a3e..9a1df63abe7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -73,6 +73,7 @@ pub(crate) enum TaskSource {
Networking = 3,
PostedMessage = 6,
FileReading = 13,
+ PerformanceTimeline = 15,
FontLoading = 19,
Crypto = 27,
Storage = 29,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
index 0dbef0af3c8..cb63b6cccd7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
@@ -17,6 +17,7 @@ use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, FunctionObject
use crate::bindings::interface::Ref;
use crate::bindings::services::web_bindings_wrapper_world;
+use crate::performance_timeline::performance_timeline::PerformanceTimelineRef;
use crate::web_assembly::tag::Tag;
/// The wrapper world of a realm, Web::Bindings::WrapperWorld, which the realm keeps alive.
@@ -47,6 +48,10 @@ pub(crate) struct RealmData {
pub(crate) webassembly_error_constructors: [Cell<Option<Gc<Object>>>; 3],
/// The Tag object of the JavaScript exception tag, https://webassembly.github.io/spec/js-api/#javascript-exception-tag
pub(crate) webassembly_js_tag: Cell<Option<Ref<Tag>>>,
+ /// https://w3c.github.io/performance-timeline/#performance-timeline
+ pub(crate) performance_timeline: Cell<Option<PerformanceTimelineRef>>,
+ /// https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute
+ pub(crate) performance_observer_supported_entry_types: Cell<Option<Gc<Object>>>,
}
static REALM_DATA_CLASS: EmbedderClass<RealmData> = EmbedderClass::new("RealmData");
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index 25b0cf72278..4f3582681f2 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -49,6 +49,8 @@ unsafe extern "C" {
pub(crate) fn web_bindings_realm_is_window(realm: *mut c_void) -> bool;
pub(crate) fn web_bindings_realm_is_secure_context(realm: *mut c_void) -> bool;
+ pub(crate) fn web_bindings_report_an_exception(realm: *mut c_void, exception: u64);
+
/// Runs the steps with the context while an execution context of the realm is on the stack, as an
/// HTML::TemporaryExecutionContext puts it there, with callbacks enabled if `callbacks_enabled`.
pub(crate) fn web_bindings_with_temporary_execution_context(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/mod.rs
new file mode 100644
index 00000000000..1200558de10
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! High Resolution Time, https://w3c.github.io/hr-time/
+
+pub(crate) mod performance;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/performance.rs b/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/performance.rs
new file mode 100644
index 00000000000..65bc10f3d2f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/high_resolution_time/performance.rs
@@ -0,0 +1,515 @@
+/*
+ * Copyright (c) 2020, Andreas Kling <[email protected]>
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Performance, https://w3c.github.io/hr-time/#sec-performance
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Realm, Trace, Value, Vm, utf16_formatted};
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::global_object::{CppWindow, window_from_global_object};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::css::css_rule::wrap_cpp_cell;
+use crate::html::window_or_worker_global_scope::structured_clone;
+use crate::performance_timeline::performance_entry::wrap_entries;
+use crate::performance_timeline::performance_timeline::{PerformanceTimeline, PerformanceTimelineRef};
+use crate::user_timing::performance_mark::{PerformanceMarkOptions, run_the_performance_mark_constructor};
+use crate::user_timing::performance_measure::{
+ DOMStringOrDouble, PerformanceMeasureOptions, create_performance_measure,
+};
+
+unsafe extern "C" {
+ fn web_high_resolution_time_current_high_resolution_time(global_object: *mut c_void) -> f64;
+ fn web_high_resolution_time_get_time_origin_timestamp(global_object: *mut c_void) -> f64;
+ fn web_navigation_timing_performance_timing_create(window: *mut c_void) -> *mut c_void;
+ fn web_navigation_timing_performance_navigation_create(window: *mut c_void) -> *mut c_void;
+ fn web_navigation_timing_is_performance_timing_attribute(name: usize) -> bool;
+ fn web_navigation_timing_performance_timing_attribute(timing: *mut c_void, name: usize) -> u64;
+ fn web_event_timing_event_counts(window: *mut c_void) -> *mut c_void;
+ fn web_event_timing_interaction_count(window: *mut c_void) -> u64;
+}
+
+pub(crate) enum DOMStringOrPerformanceMeasureOptions {
+ DOMString(Utf16String),
+ PerformanceMeasureOptions(PerformanceMeasureOptions),
+}
+
+// https://w3c.github.io/hr-time/#sec-performance
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Performance {
+ event_target: CppEventTarget,
+ realm: Gc<Realm>,
+ timing: GcRefCell<Option<CppCell>>,
+ navigation: GcRefCell<Option<CppCell>>,
+}
+
+impl Wrappable for Performance {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event_target.as_cpp_parent()
+ }
+}
+
+impl GetTheParent for Performance {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+fn is_performance_timing_attribute(name: &Utf16String) -> bool {
+ // SAFETY: The name is lent for the call.
+ unsafe { web_navigation_timing_is_performance_timing_attribute(name.raw_identity()) }
+}
+
+impl Performance {
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {
+ let performance = allocate(vm, |_| Self {
+ event_target: CppEventTarget::new(),
+ realm,
+ timing: GcRefCell::default(),
+ navigation: GcRefCell::default(),
+ });
+ performance.event_target.set_owner(performance);
+ performance
+ }
+
+ pub(crate) fn event_target(&self) -> &CppEventTarget {
+ &self.event_target
+ }
+
+ fn performance_timeline(&self, vm: &Vm) -> PerformanceTimelineRef {
+ PerformanceTimeline::of(vm, self.realm)
+ }
+
+ fn window(&self) -> Option<CppWindow> {
+ window_from_global_object(self.realm.global_object())
+ }
+
+ fn timing_cell(&self, vm: &Vm) -> CppCell {
+ if let Some(timing) = self.timing.borrow().as_ref() {
+ return timing.clone();
+ }
+ let window = self.window().expect("only a Window has a PerformanceTiming");
+ // SAFETY: The Window is live, and LibWeb returns a new, live PerformanceTiming.
+ let timing = unsafe { CppCell::from_raw(web_navigation_timing_performance_timing_create(window.as_ptr())) };
+ *self.timing.borrow_mut(vm) = Some(timing.clone());
+ timing
+ }
+
+ // https://w3c.github.io/navigation-timing/#dom-performance-timing
+ pub(crate) fn timing(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(wrap_cpp_cell(cx, &self.timing_cell(cx.vm())))
+ }
+
+ // https://w3c.github.io/navigation-timing/#dom-performance-navigation
+ pub(crate) fn navigation(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ if let Some(navigation) = self.navigation.borrow().as_ref() {
+ return Ok(wrap_cpp_cell(cx, navigation));
+ }
+ let window = self.window().expect("only a Window has a PerformanceNavigation");
+ // SAFETY: The Window is live, and LibWeb returns a new, live PerformanceNavigation.
+ let navigation =
+ unsafe { CppCell::from_raw(web_navigation_timing_performance_navigation_create(window.as_ptr())) };
+ *self.navigation.borrow_mut(cx.vm()) = Some(navigation.clone());
+ Ok(wrap_cpp_cell(cx, &navigation))
+ }
+
+ // https://w3c.github.io/event-timing/#dom-performance-eventcounts
+ pub(crate) fn event_counts(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The eventCounts attribute's getter returns this's relevant global object's eventCounts.
+ let window = self.window().expect("only a Window has eventCounts");
+ // SAFETY: The Window is live, and LibWeb returns its live EventCounts.
+ let event_counts = unsafe { CppCell::from_raw(web_event_timing_event_counts(window.as_ptr())) };
+ Ok(wrap_cpp_cell(cx, &event_counts))
+ }
+
+ // https://w3c.github.io/event-timing/#dom-performance-interactioncount
+ pub(crate) fn interaction_count(&self, _: &mut CallContext) -> WebIdlResult<u64> {
+ // The interactionCount attribute's getter returns this's relevant global object's interactionCount.
+ let window = self.window().expect("only a Window has an interactionCount");
+ // SAFETY: The Window is live.
+ Ok(unsafe { web_event_timing_interaction_count(window.as_ptr()) })
+ }
+
+ // https://w3c.github.io/hr-time/#timeorigin-attribute
+ pub(crate) fn time_origin(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ // The timeOrigin attribute MUST return the number of milliseconds in the duration returned by get time origin timestamp for the relevant global object of this.
+ // SAFETY: The global object is live.
+ Ok(unsafe { web_high_resolution_time_get_time_origin_timestamp(self.realm.global_object().as_ptr().cast()) })
+ }
+
+ // https://w3c.github.io/hr-time/#now-method
+ pub(crate) fn now(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ // The now() method MUST return the number of milliseconds in the current high resolution time given this's relevant global object (a duration).
+ // SAFETY: The global object is live.
+ Ok(
+ unsafe {
+ web_high_resolution_time_current_high_resolution_time(self.realm.global_object().as_ptr().cast())
+ },
+ )
+ }
+
+ // https://w3c.github.io/user-timing/#mark-method
+ pub(crate) fn mark(
+ &self,
+ cx: &mut CallContext,
+ mark_name: Utf16String,
+ mark_options: PerformanceMarkOptions,
+ ) -> WebIdlResult<CppInterface> {
+ let vm = cx.vm();
+
+ // 1. Run the PerformanceMark constructor and let entry be the newly created object.
+ let entry = run_the_performance_mark_constructor(self.realm, &mark_name, &mark_options)?;
+
+ // 2. Queue entry.
+ let timeline = self.performance_timeline(vm);
+ timeline.queue_performance_entry(vm, &entry);
+
+ // 3. Add entry to the performance entry buffer.
+ timeline.add_performance_entry(vm, &entry, false);
+
+ // 4. Return entry.
+ Ok(entry.wrap(cx))
+ }
+
+ pub(crate) fn clear_marks(&self, cx: &mut CallContext, mark_name: Option<Utf16String>) -> WebIdlResult<()> {
+ let vm = cx.vm();
+ let timeline = self.performance_timeline(vm);
+ let entry_type = Utf16String::from_utf8("mark");
+
+ // 1. If markName is omitted, remove all PerformanceMark objects from the performance entry buffer.
+ let Some(mark_name) = mark_name else {
+ timeline.clear_performance_entry_buffer(vm, &entry_type);
+ return Ok(());
+ };
+
+ // 2. Otherwise, remove all PerformanceMark objects listed in the performance entry buffer whose name is markName.
+ timeline.remove_entries_from_performance_entry_buffer(vm, &entry_type, &mark_name);
+
+ // 3. Return undefined.
+ Ok(())
+ }
+
+ fn convert_name_to_timestamp(&self, vm: &Vm, name: &Utf16String) -> WebIdlResult<f64> {
+ // 1. If the global object is not a Window object, throw a TypeError.
+ if self.window().is_none() {
+ return Err(Exception::TypeError(utf16_formatted(
+ "'{}' is an attribute in the PerformanceTiming interface and thus can only be used in a Window context",
+ &[name],
+ )));
+ }
+
+ // 2. If name is navigationStart, return 0.
+ if *name == Utf16String::from_utf8("navigationStart") {
+ return Ok(0.0);
+ }
+
+ let timing = self.timing_cell(vm);
+
+ // 3. Let startTime be the value of navigationStart in the PerformanceTiming interface.
+ // SAFETY: The PerformanceTiming is live, and the name is lent for the call.
+ let start_time = unsafe {
+ web_navigation_timing_performance_timing_attribute(
+ timing.as_ptr(),
+ Utf16String::from_utf8("navigationStart").raw_identity(),
+ )
+ };
+
+ // 4. Let endTime be the value of name in the PerformanceTiming interface.
+ // SAFETY: The PerformanceTiming is live, and the name is lent for the call.
+ let end_time =
+ unsafe { web_navigation_timing_performance_timing_attribute(timing.as_ptr(), name.raw_identity()) };
+
+ // 5. If endTime is 0, throw an InvalidAccessError.
+ if end_time == 0 {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ utf16_formatted(
+ "The '{}' entry in the PerformanceTiming interface is equal to 0, meaning it hasn't happened yet",
+ &[name],
+ ),
+ ));
+ }
+
+ // 6. Return result of subtracting startTime from endTime.
+ Ok(end_time.wrapping_sub(start_time) as f64)
+ }
+
+ // https://w3c.github.io/user-timing/#dfn-convert-a-mark-to-a-timestamp
+ fn convert_mark_to_timestamp(&self, cx: &CallContext, mark: &DOMStringOrDouble) -> WebIdlResult<f64> {
+ let mark_time_stamp = match mark {
+ DOMStringOrDouble::DOMString(mark_string) => {
+ // 1. If mark is a DOMString and it has the same name as a read only attribute in the PerformanceTiming interface, let end
+ // time be the value returned by running the convert a name to a timestamp algorithm with name set to the value of mark.
+ if is_performance_timing_attribute(mark_string) {
+ return self.convert_name_to_timestamp(cx.vm(), mark_string);
+ }
+
+ // 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime attribute from the most recent occurrence
+ // of a PerformanceMark object in the performance entry buffer whose name is mark. If no matching entry is found, throw a
+ // SyntaxError.
+ let start_time = self
+ .performance_timeline(cx.vm())
+ .with_relevant_performance_entry_tuple(&Utf16String::from_utf8("mark"), |tuple| {
+ tuple
+ .performance_entry_buffer
+ .iter()
+ .rev()
+ .find(|entry| entry.name() == *mark_string)
+ .map(|entry| entry.start_time())
+ });
+
+ return start_time.ok_or_else(|| {
+ Exception::syntax_error(utf16_formatted(
+ "No PerformanceMark object with name '{}' found in the performance timeline",
+ &[mark_string],
+ ))
+ });
+ }
+ // 3. Otherwise, if mark is a DOMHighResTimeStamp:
+ DOMStringOrDouble::Double(mark_time_stamp) => *mark_time_stamp,
+ };
+
+ // 1. If mark is negative, throw a TypeError.
+ if mark_time_stamp < 0.0 {
+ return Err(Exception::type_error(
+ "Cannot have negative time values in PerformanceMark",
+ ));
+ }
+
+ // 2. Otherwise, let end time be mark.
+ Ok(mark_time_stamp)
+ }
+
+ // https://w3c.github.io/user-timing/#dom-performance-measure
+ pub(crate) fn measure(
+ &self,
+ cx: &mut CallContext,
+ measure_name: Utf16String,
+ start_or_measure_options: DOMStringOrPerformanceMeasureOptions,
+ end_mark: Option<Utf16String>,
+ ) -> WebIdlResult<CppInterface> {
+ let vm = cx.vm();
+
+ // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start, end, duration, and detail
+ // are present, run the following checks:
+ let options = match &start_or_measure_options {
+ DOMStringOrPerformanceMeasureOptions::PerformanceMeasureOptions(options) => Some(options),
+ DOMStringOrPerformanceMeasureOptions::DOMString(_) => None,
+ };
+ if let Some(options) = options
+ && (options.start.is_some()
+ || options.end.is_some()
+ || options.duration.is_some()
+ || options.detail.is_some())
+ {
+ // 1. If endMark is given, throw a TypeError.
+ if end_mark.is_some() {
+ return Err(Exception::type_error(
+ "Cannot provide PerformanceMeasureOptions and endMark at the same time",
+ ));
+ }
+
+ // 2. If startOrMeasureOptions's start and end members are both omitted, throw a TypeError.
+ if options.start.is_none() && options.end.is_none() {
+ return Err(Exception::type_error(
+ "PerformanceMeasureOptions must contain one or both of 'start' and 'end'",
+ ));
+ }
+
+ // 3. If startOrMeasureOptions's start, duration, and end members are all present, throw a TypeError.
+ if options.start.is_some() && options.end.is_some() && options.duration.is_some() {
+ return Err(Exception::type_error(
+ "PerformanceMeasureOptions cannot contain 'start', 'duration' and 'end' properties all at once",
+ ));
+ }
+ }
+
+ // 2. Compute end time as follows:
+ // 1. If endMark is given, let end time be the value returned by running the convert a mark to a timestamp algorithm passing
+ // in endMark.
+ let end_time = if let Some(end_mark) = end_mark {
+ self.convert_mark_to_timestamp(cx, &DOMStringOrDouble::DOMString(end_mark))?
+ }
+ // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its end member is present, let end
+ // time be the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's end.
+ else if let Some(end) = options.and_then(|options| options.end.as_ref()) {
+ self.convert_mark_to_timestamp(cx, end)?
+ }
+ // 3. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start and duration members are
+ // both present:
+ else if let Some((start, duration)) =
+ options.and_then(|options| Some((options.start.as_ref()?, options.duration?)))
+ {
+ // 1. Let start be the value returned by running the convert a mark to a timestamp algorithm passing in start.
+ let start = self.convert_mark_to_timestamp(cx, start)?;
+
+ // 2. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
+ let duration = self.convert_mark_to_timestamp(cx, &DOMStringOrDouble::Double(duration))?;
+
+ // 3. Let end time be start plus duration.
+ start + duration
+ }
+ // 4. Otherwise, let end time be the value that would be returned by the Performance object's now() method.
+ else {
+ self.now(cx)?
+ };
+
+ // 3. Compute start time as follows:
+ // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start member is present, let start time be
+ // the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's start.
+ let start_time = if let Some(start) = options.and_then(|options| options.start.as_ref()) {
+ self.convert_mark_to_timestamp(cx, start)?
+ }
+ // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its duration and end members are
+ // both present:
+ else if let Some((duration, end)) =
+ options.and_then(|options| Some((options.duration?, options.end.as_ref()?)))
+ {
+ // 1. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
+ let duration = self.convert_mark_to_timestamp(cx, &DOMStringOrDouble::Double(duration))?;
+
+ // 2. Let end be the value returned by running the convert a mark to a timestamp algorithm passing in end.
+ let end = self.convert_mark_to_timestamp(cx, end)?;
+
+ // 3. Let start time be end minus duration.
+ end - duration
+ }
+ // 3. Otherwise, if startOrMeasureOptions is a DOMString, let start time be the value returned by running the convert a mark
+ // to a timestamp algorithm passing in startOrMeasureOptions.
+ else if let DOMStringOrPerformanceMeasureOptions::DOMString(start) = &start_or_measure_options {
+ self.convert_mark_to_timestamp(cx, &DOMStringOrDouble::DOMString(start.clone()))?
+ }
+ // 4. Otherwise, let start time be 0.
+ else {
+ 0.0
+ };
+
+ // NOTE: Step 4 (creating the entry) is done after determining values, as we set the values once during creation and never
+ // change them after.
+
+ // 5. Set entry's name attribute to measureName.
+ // NOTE: Will be done during construction.
+
+ // 6. Set entry's entryType attribute to DOMString "measure".
+ // NOTE: Already done via the `entry_type` virtual function.
+
+ // 7. Set entry's startTime attribute to start time.
+ // NOTE: Will be done during construction.
+
+ // 8. Set entry's duration attribute to the duration from start time to end time. The resulting duration value MAY be negative.
+ let duration = end_time - start_time;
+
+ // 4. Create a new PerformanceMeasure object (entry).
+ let mut detail = Value::NULL;
+ if let Some(options_detail) = options.and_then(|options| options.detail)
+ && !options_detail.is_null()
+ {
+ detail = structured_clone(&CallContext::new(vm, self.realm), options_detail, &[])?;
+ }
+ let entry = create_performance_measure(&measure_name, start_time, duration, detail);
+
+ // 10. Queue entry.
+ let timeline = self.performance_timeline(vm);
+ timeline.queue_performance_entry(vm, &entry);
+
+ // 11. Add entry to the performance entry buffer.
+ timeline.add_performance_entry(vm, &entry, false);
+
+ // 12. Return entry.
+ Ok(entry.wrap(cx))
+ }
+
+ // https://w3c.github.io/user-timing/#dom-performance-clearmeasures
+ pub(crate) fn clear_measures(&self, cx: &mut CallContext, measure_name: Option<Utf16String>) -> WebIdlResult<()> {
+ let vm = cx.vm();
+ let timeline = self.performance_timeline(vm);
+ let entry_type = Utf16String::from_utf8("measure");
+
+ // 1. If measureName is omitted, remove all PerformanceMeasure objects in the performance entry buffer.
+ let Some(measure_name) = measure_name else {
+ timeline.clear_performance_entry_buffer(vm, &entry_type);
+ return Ok(());
+ };
+
+ // 2. Otherwise remove all PerformanceMeasure objects listed in the performance entry buffer whose name is measureName.
+ timeline.remove_entries_from_performance_entry_buffer(vm, &entry_type, &measure_name);
+
+ // 3. Return undefined.
+ Ok(())
+ }
+
+ // https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings
+ pub(crate) fn clear_resource_timings(&self, cx: &mut CallContext) -> WebIdlResult<()> {
+ // 1. Remove all PerformanceResourceTiming objects in the performance entry buffer.
+ // 2. Set resource timing buffer current size to 0.
+ self.performance_timeline(cx.vm())
+ .clear_performance_entry_buffer(cx.vm(), &Utf16String::from_utf8("resource"));
+ Ok(())
+ }
+
+ // https://w3c.github.io/resource-timing/#dom-performance-setresourcetimingbuffersize
+ pub(crate) fn set_resource_timing_buffer_size(&self, cx: &mut CallContext, max_size: u32) -> WebIdlResult<()> {
+ // 1. Set resource timing buffer size limit to the maxSize parameter. If the maxSize parameter is less than
+ // resource timing buffer current size, no PerformanceResourceTiming objects are to be removed from the
+ // performance entry buffer.
+ self.performance_timeline(cx.vm())
+ .set_resource_timing_buffer_size_limit(max_size);
+ Ok(())
+ }
+
+ // https://w3c.github.io/performance-timeline/#getentries-method
+ pub(crate) fn get_entries<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by the filter buffer map by name and type algorithm with name and
+ // type set to null.
+ let entries = self
+ .performance_timeline(cx.vm())
+ .filter_buffer_map_by_name_and_type(cx, None, None);
+ Ok(wrap_entries(cx, &entries))
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performance-getentriesbytype
+ pub(crate) fn get_entries_by_type<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ r#type: Utf16String,
+ ) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to null,
+ // and type set to the method's input type parameter.
+ let entries = self
+ .performance_timeline(cx.vm())
+ .filter_buffer_map_by_name_and_type(cx, None, Some(&r#type));
+ Ok(wrap_entries(cx, &entries))
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performance-getentriesbyname
+ pub(crate) fn get_entries_by_name<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ name: Utf16String,
+ r#type: Option<Utf16String>,
+ ) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to the
+ // method input name parameter, and type set to null if optional entryType is omitted, or set to the method's input type
+ // parameter otherwise.
+ let entries =
+ self.performance_timeline(cx.vm())
+ .filter_buffer_map_by_name_and_type(cx, Some(&name), r#type.as_ref());
+ Ok(wrap_entries(cx, &entries))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 4c11720ce0c..59bba580266 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -106,6 +106,16 @@ pub(crate) mod file_api;
reason = "the bindings call every attribute and operation as one that can throw"
)]
pub(crate) mod geometry;
+#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod high_resolution_time;
#[cfg_attr(
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the interfaces")
@@ -131,6 +141,16 @@ pub(crate) mod indexed_db;
)]
pub(crate) mod notifications_api;
#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod performance_timeline;
+#[cfg(not(test))]
pub(crate) mod platform;
#[cfg_attr(
not(web_idl_bindings),
@@ -178,6 +198,16 @@ pub(crate) mod url_pattern;
clippy::unnecessary_wraps,
reason = "the bindings call every attribute and operation as one that can throw"
)]
+pub(crate) mod user_timing;
+#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
pub(crate) mod web_assembly;
#[cfg_attr(
not(web_idl_bindings),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/entry_types.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/entry_types.rs
new file mode 100644
index 00000000000..fc415cc9dd4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/entry_types.rs
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timing entry types registry, https://w3c.github.io/timing-entrytypes-registry/#registry
+
+pub(crate) struct SupportedEntryType {
+ pub(crate) entry_type: &'static str,
+ pub(crate) window_only: bool,
+ /// https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
+ pub(crate) available_from_timeline: bool,
+ /// https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
+ // NB: None is an infinite size.
+ pub(crate) max_buffer_size: Option<u64>,
+}
+
+// NB: In alphabetical order of their entry type, which supportedEntryTypes lists them in.
+pub(crate) const SUPPORTED_ENTRY_TYPES: &[SupportedEntryType] = &[
+ SupportedEntryType {
+ entry_type: "event",
+ window_only: true,
+ available_from_timeline: false,
+ max_buffer_size: Some(150),
+ },
+ SupportedEntryType {
+ entry_type: "first-input",
+ window_only: true,
+ available_from_timeline: true,
+ max_buffer_size: Some(1),
+ },
+ SupportedEntryType {
+ entry_type: "largest-contentful-paint",
+ window_only: true,
+ available_from_timeline: false,
+ max_buffer_size: Some(150),
+ },
+ SupportedEntryType {
+ entry_type: "mark",
+ window_only: false,
+ available_from_timeline: true,
+ max_buffer_size: None,
+ },
+ SupportedEntryType {
+ entry_type: "measure",
+ window_only: false,
+ available_from_timeline: true,
+ max_buffer_size: None,
+ },
+ SupportedEntryType {
+ entry_type: "navigation",
+ window_only: true,
+ available_from_timeline: true,
+ max_buffer_size: None,
+ },
+ SupportedEntryType {
+ entry_type: "paint",
+ window_only: true,
+ available_from_timeline: true,
+ max_buffer_size: Some(2),
+ },
+ SupportedEntryType {
+ entry_type: "resource",
+ window_only: false,
+ available_from_timeline: true,
+ max_buffer_size: Some(250),
+ },
+ SupportedEntryType {
+ entry_type: "visibility-state",
+ window_only: true,
+ available_from_timeline: true,
+ max_buffer_size: Some(50),
+ },
+];
+
+pub(crate) fn supported_entry_types(global_is_window: bool) -> impl Iterator<Item = &'static SupportedEntryType> {
+ SUPPORTED_ENTRY_TYPES
+ .iter()
+ .filter(move |entry_type| global_is_window || !entry_type.window_only)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/exports.rs
new file mode 100644
index 00000000000..e3993ab379e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/exports.rs
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which LibWeb's C++ reaches the performance timeline of a global object.
+
+use core::ffi::c_void;
+
+use crate::bindings::interface::{cell_into_abi, realm_arguments};
+use crate::performance_timeline::performance_entry::CppPerformanceEntry;
+use crate::performance_timeline::performance_timeline::PerformanceTimeline;
+
+/// https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `realm` the live realm of a Window or a WorkerGlobalScope.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_performance_timeline_performance(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) };
+ cell_into_abi(PerformanceTimeline::of(vm, realm).performance(vm))
+}
+
+/// https://w3c.github.io/performance-timeline/#dfn-queue-a-performanceentry
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `realm` the live realm of a Window or a WorkerGlobalScope, and `entry` a live
+/// PerformanceEntry whose relevant global object is that of the realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_performance_timeline_queue_performance_entry(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ entry: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, a live realm and a live entry.
+ let ((vm, realm), entry) = unsafe { (realm_arguments(vm, realm), CppPerformanceEntry::from_raw(entry)) };
+ PerformanceTimeline::of(vm, realm).queue_performance_entry(vm, &entry);
+}
+
+/// https://w3c.github.io/performance-timeline/#dfn-queue-a-performanceentry
+///
+/// # Safety
+///
+/// As for web_rust_performance_timeline_queue_performance_entry().
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_performance_timeline_add_performance_entry(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ entry: *mut c_void,
+ check_if_performance_buffer_is_full: bool,
+) {
+ // SAFETY: The caller passes the live VM, a live realm and a live entry.
+ let ((vm, realm), entry) = unsafe { (realm_arguments(vm, realm), CppPerformanceEntry::from_raw(entry)) };
+ PerformanceTimeline::of(vm, realm).add_performance_entry(vm, &entry, check_if_performance_buffer_is_full);
+}
+
+/// https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry
+///
+/// # Safety
+///
+/// As for web_rust_performance_timeline_queue_performance_entry(), with a PerformanceResourceTiming.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_performance_timeline_add_resource_timing_entry(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ entry: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, a live realm and a live entry.
+ let ((vm, realm), entry) = unsafe { (realm_arguments(vm, realm), CppPerformanceEntry::from_raw(entry)) };
+ PerformanceTimeline::of(vm, realm).add_resource_timing_entry(vm, &entry);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/mod.rs
new file mode 100644
index 00000000000..de8d8ad5d0c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/mod.rs
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Performance Timeline, https://w3c.github.io/performance-timeline/
+
+pub(crate) mod entry_types;
+pub(crate) mod exports;
+pub(crate) mod performance_entry;
+pub(crate) mod performance_entry_tuple;
+pub(crate) mod performance_observer;
+pub(crate) mod performance_observer_entry_list;
+#[allow(
+ clippy::module_inception,
+ reason = "the module mirrors the specification's performance timeline, which the crate module is named after"
+)]
+pub(crate) mod performance_timeline;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry.rs
new file mode 100644
index 00000000000..f75931b0295
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry.rs
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceEntry, https://w3c.github.io/performance-timeline/#the-performanceentry-interface
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace};
+
+use crate::bindings::CallContext;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::css::css_rule::wrap_cpp_cell;
+use crate::performance_timeline::performance_observer::PerformanceObserverInit;
+
+unsafe extern "C" {
+ fn web_performance_timeline_entry_name(entry: *mut c_void) -> usize;
+ fn web_performance_timeline_entry_entry_type(entry: *mut c_void) -> usize;
+ fn web_performance_timeline_entry_start_time(entry: *mut c_void) -> f64;
+ fn web_performance_timeline_entry_should_add_entry(
+ entry: *mut c_void,
+ has_options: bool,
+ has_duration_threshold: bool,
+ duration_threshold: f64,
+ ) -> bool;
+}
+
+/// https://w3c.github.io/performance-timeline/#dom-performanceentry
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CppPerformanceEntry(CppCell);
+
+impl CppPerformanceEntry {
+ /// # Safety
+ ///
+ /// `entry` must be a live PerformanceEntry.
+ pub(crate) unsafe fn from_raw(entry: *mut c_void) -> Self {
+ // SAFETY: The caller passes a live PerformanceEntry.
+ Self(unsafe { CppCell::from_raw(entry) })
+ }
+
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+
+ /// https://w3c.github.io/performance-timeline/#dom-performanceentry-name
+ pub(crate) fn name(&self) -> Utf16String {
+ // SAFETY: The entry is live, and LibWeb hands over a copy of its name.
+ unsafe { Utf16String::from_raw_owned(web_performance_timeline_entry_name(self.as_ptr())) }
+ }
+
+ /// https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype
+ pub(crate) fn entry_type(&self) -> Utf16String {
+ // SAFETY: The entry is live, and LibWeb hands over a copy of its entry type.
+ unsafe { Utf16String::from_raw_owned(web_performance_timeline_entry_entry_type(self.as_ptr())) }
+ }
+
+ /// https://w3c.github.io/performance-timeline/#dom-performanceentry-starttime
+ pub(crate) fn start_time(&self) -> f64 {
+ // SAFETY: The entry is live.
+ unsafe { web_performance_timeline_entry_start_time(self.as_ptr()) }
+ }
+
+ /// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
+ pub(crate) fn should_add_entry(&self, options: Option<&PerformanceObserverInit>) -> bool {
+ let duration_threshold = options.and_then(|options| options.duration_threshold);
+ // SAFETY: The entry is live.
+ unsafe {
+ web_performance_timeline_entry_should_add_entry(
+ self.as_ptr(),
+ options.is_some(),
+ duration_threshold.is_some(),
+ duration_threshold.unwrap_or_default(),
+ )
+ }
+ }
+
+ pub(crate) fn wrap(&self, cx: &CallContext) -> CppInterface {
+ wrap_cpp_cell(cx, &self.0)
+ }
+}
+
+pub(crate) fn wrap_entries<'vm>(
+ cx: &CallContext<'vm>,
+ entries: &MarkedVec<'_, CppPerformanceEntry>,
+) -> MarkedVec<'vm, CppInterface> {
+ let wrappers = MarkedVec::with_capacity(cx.vm(), entries.len());
+ for entry in entries.values().iter() {
+ wrappers.push(entry.wrap(cx));
+ }
+ wrappers
+}
+
+pub(crate) fn sort_in_chronological_order(entries: &MarkedVec<'_, CppPerformanceEntry>) {
+ entries
+ .values_mut()
+ .sort_by(|left, right| left.start_time().total_cmp(&right.start_time()));
+}
+
+// https://w3c.github.io/performance-timeline/#dfn-filter-buffer-by-name-and-type
+pub(crate) fn filter_buffer_by_name_and_type<'vm>(
+ cx: &CallContext<'vm>,
+ buffer: &[CppPerformanceEntry],
+ name: Option<&Utf16String>,
+ r#type: Option<&Utf16String>,
+) -> MarkedVec<'vm, CppPerformanceEntry> {
+ // 1. Let result be an initially empty list.
+ let result = MarkedVec::new(cx.vm());
+
+ // 2. For each PerformanceEntry entry in buffer, run the following steps:
+ for entry in buffer {
+ // 1. If type is not null and if type is not identical to entry's entryType attribute, continue to next entry.
+ if r#type.is_some_and(|r#type| *r#type != entry.entry_type()) {
+ continue;
+ }
+
+ // 2. If name is not null and if name is not identical to entry's name attribute, continue to next entry.
+ if name.is_some_and(|name| *name != entry.name()) {
+ continue;
+ }
+
+ // 3. append entry to result.
+ result.push(entry.clone());
+ }
+
+ // 3. Sort results's entries in chronological order with respect to startTime
+ sort_in_chronological_order(&result);
+
+ // 4. Return result.
+ result
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry_tuple.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry_tuple.rs
new file mode 100644
index 00000000000..1a7e3213ece
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_entry_tuple.rs
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use ak::Utf16String;
+use libjs_rust::api::{DeferGc, Trace};
+
+use crate::performance_timeline::entry_types::SupportedEntryType;
+use crate::performance_timeline::performance_entry::CppPerformanceEntry;
+
+// https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer-map
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PerformanceEntryTuple {
+ /// The key of the tuple in the map.
+ #[gc(untraced)]
+ pub(crate) entry_type: Utf16String,
+
+ // https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer
+ // A performance entry buffer to store PerformanceEntry objects, that is initially empty.
+ pub(crate) performance_entry_buffer: Vec<CppPerformanceEntry>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-maxbuffersize
+ // An integer maxBufferSize, initialized to the registry value for this entry type.
+ // NB: None is an infinite size.
+ #[gc(untraced)]
+ pub(crate) max_buffer_size: Option<u64>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-availablefromtimeline
+ // A boolean availableFromTimeline, initialized to the registry value for this entry type.
+ pub(crate) available_from_timeline: bool,
+
+ // https://w3c.github.io/performance-timeline/#dfn-dropped-entries-count
+ // An integer dropped entries count that is initially 0.
+ pub(crate) dropped_entries_count: u64,
+}
+
+impl PerformanceEntryTuple {
+ pub(crate) fn new(_: &DeferGc<'_>, supported_entry_type: &SupportedEntryType) -> Self {
+ Self {
+ entry_type: Utf16String::from_utf8(supported_entry_type.entry_type),
+ performance_entry_buffer: Vec::new(),
+ max_buffer_size: supported_entry_type.max_buffer_size,
+ available_from_timeline: supported_entry_type.available_from_timeline,
+ dropped_entries_count: 0,
+ }
+ }
+
+ // https://w3c.github.io/performance-timeline/#dfn-determine-if-a-performance-entry-buffer-is-full
+ pub(crate) fn is_full(&mut self) -> bool {
+ // 1. Let num current entries be the size of tuple's performance entry buffer.
+ let num_current_entries = self.performance_entry_buffer.len() as u64;
+
+ // 2. If num current entries is less than tuples's maxBufferSize, return false.
+ if self
+ .max_buffer_size
+ .is_none_or(|max_buffer_size| num_current_entries < max_buffer_size)
+ {
+ return false;
+ }
+
+ // 3. Increase tuple's dropped entries count by 1.
+ self.dropped_entries_count += 1;
+
+ // 4. Return true.
+ true
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer.rs
new file mode 100644
index 00000000000..2cbb08894cf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer.rs
@@ -0,0 +1,356 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceObserver, https://w3c.github.io/performance-timeline/#the-performanceobserver-interface
+
+use core::cell::{Cell, RefCell};
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, PropertyKey, Realm, ThrowCompletionOr, Trace, Value, Vm};
+
+use crate::bindings::callback::CallbackFunction;
+use crate::bindings::conversions::{CppInterface, ToJs, frozen_array_to_js, sequence_to_js};
+use crate::bindings::interface::{Ref, Wrappable, allocate, create_dictionary_object, realm_is_window, wrap};
+use crate::bindings::realm_data::realm_data;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::performance_timeline::entry_types::supported_entry_types;
+use crate::performance_timeline::performance_entry::{CppPerformanceEntry, wrap_entries};
+use crate::performance_timeline::performance_observer_entry_list::PerformanceObserverEntryList;
+use crate::performance_timeline::performance_timeline::PerformanceTimeline;
+
+// https://w3c.github.io/performance-timeline/#dom-performanceobserverinit
+#[derive(Clone, Default)]
+pub(crate) struct PerformanceObserverInit {
+ pub(crate) entry_types: Option<Vec<Utf16String>>,
+ pub(crate) r#type: Option<Utf16String>,
+ pub(crate) buffered: Option<bool>,
+ // https://w3c.github.io/event-timing/#sec-modifications-perf-timeline
+ pub(crate) duration_threshold: Option<f64>,
+}
+
+// https://w3c.github.io/performance-timeline/#dfn-observer-type
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ObserverType {
+ Undefined,
+ Single,
+ Multiple,
+}
+
+// https://w3c.github.io/performance-timeline/#dom-performanceobserver
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PerformanceObserver {
+ realm: Gc<Realm>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-observer-callback
+ // A PerformanceObserverCallback observer callback set on creation.
+ callback: CallbackFunction,
+
+ // https://w3c.github.io/performance-timeline/#dfn-observer-buffer
+ // A PerformanceEntryList object called the observer buffer that is initially empty.
+ observer_buffer: GcRefCell<Vec<CppPerformanceEntry>>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-observer-type
+ // A DOMString observer type which is initially "undefined".
+ #[gc(untraced)]
+ observer_type: Cell<ObserverType>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-requires-dropped-entries
+ // A boolean requires dropped entries which is initially set to false.
+ requires_dropped_entries: Cell<bool>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-options-list
+ // A registered performance observer is a struct consisting of an observer member (a PerformanceObserver object)
+ // and an options list member (a list of PerformanceObserverInit objects).
+ // NOTE: This doesn't use a separate struct as methods such as disconnect() assume it can access an options list from `this`: a PerformanceObserver.
+ #[gc(untraced)]
+ options_list: RefCell<Vec<PerformanceObserverInit>>,
+}
+
+impl Wrappable for PerformanceObserver {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+fn is_supported_entry_type(global_is_window: bool, r#type: &Utf16String) -> bool {
+ supported_entry_types(global_is_window).any(|supported| *r#type == Utf16String::from_utf8(supported.entry_type))
+}
+
+impl PerformanceObserver {
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserver-constructor
+ pub(crate) fn construct(cx: &mut CallContext, callback: CallbackFunction) -> WebIdlResult<Ref<Self>> {
+ Ok(allocate(cx.vm(), |_| Self {
+ realm: cx.realm(),
+ callback,
+ observer_buffer: GcRefCell::default(),
+ observer_type: Cell::new(ObserverType::Undefined),
+ requires_dropped_entries: Cell::new(false),
+ options_list: RefCell::default(),
+ }))
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserver-observe
+ pub(crate) fn observe(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ options: PerformanceObserverInit,
+ ) -> WebIdlResult<()> {
+ let vm = cx.vm();
+
+ // 1. Let relevantGlobal be this's relevant global object.
+ let relevant_global = PerformanceTimeline::of(vm, this.realm);
+
+ // 2. If options's entryTypes and type members are both omitted, then throw a "TypeError".
+ if options.entry_types.is_none() && options.r#type.is_none() {
+ return Err(Exception::type_error("Must specify one of entryTypes or type"));
+ }
+
+ // 3. If options's entryTypes is present and any other member is also present, then throw a "TypeError".
+ if options.entry_types.is_some() && (options.r#type.is_some() || options.buffered.is_some()) {
+ return Err(Exception::type_error(
+ "Cannot specify type or buffered if entryTypes is specified",
+ ));
+ }
+
+ // 4. Update or check this's observer type by running these steps:
+ match this.observer_type.get() {
+ // 1. If this's observer type is "undefined":
+ ObserverType::Undefined => {
+ // 1. If options's entryTypes member is present, then set this's observer type to "multiple".
+ if options.entry_types.is_some() {
+ this.observer_type.set(ObserverType::Multiple);
+ }
+
+ // 2. If options's type member is present, then set this's observer type to "single".
+ if options.r#type.is_some() {
+ this.observer_type.set(ObserverType::Single);
+ }
+ }
+ // 2. If this's observer type is "single" and options's entryTypes member is present, then throw an
+ // "InvalidModificationError".
+ ObserverType::Single => {
+ if options.entry_types.is_some() {
+ return Err(Exception::Dom(
+ "InvalidModificationError",
+ Utf16String::from_utf8(
+ "Cannot change a PerformanceObserver from observing a single type to observing multiple types",
+ ),
+ ));
+ }
+ }
+ // 3. If this's observer type is "multiple" and options's type member is present, then throw an
+ // "InvalidModificationError".
+ ObserverType::Multiple => {
+ if options.r#type.is_some() {
+ return Err(Exception::Dom(
+ "InvalidModificationError",
+ Utf16String::from_utf8(
+ "Cannot change a PerformanceObserver from observing multiple types to observing a single type",
+ ),
+ ));
+ }
+ }
+ }
+
+ // 5. Set this's requires dropped entries to true.
+ this.requires_dropped_entries.set(true);
+
+ let global_is_window = realm_is_window(this.realm);
+
+ // 6. If this's observer type is "multiple", run the following steps:
+ if this.observer_type.get() == ObserverType::Multiple {
+ // 1. Let entry types be options's entryTypes sequence.
+ let mut options = options;
+ let entry_types = options
+ .entry_types
+ .as_mut()
+ .expect("an observer of multiple types observes entryTypes");
+
+ // 2. Remove all types from entry types that are not contained in relevantGlobal's frozen array of supported
+ // entry types. The user agent SHOULD notify developers if entry types is modified. For example, a console
+ // warning listing removed types might be appropriate.
+ entry_types.retain(|r#type| is_supported_entry_type(global_is_window, r#type));
+
+ // 3. If the resulting entry types sequence is an empty sequence, abort these steps.
+ // The user agent SHOULD notify developers when the steps are aborted to notify that registration has been
+ // aborted. For example, a console warning might be appropriate.
+ if entry_types.is_empty() {
+ return Ok(());
+ }
+
+ // 4. If the list of registered performance observer objects of relevantGlobal contains a registered
+ // performance observer whose observer is this, replace its options list with a list containing options as
+ // its only item.
+ // 5. Otherwise, create and append a registered performance observer object to the list of registered
+ // performance observer objects of relevantGlobal, with observer set to this and options list set to a list
+ // containing options as its only item.
+ *this.options_list.borrow_mut() = vec![options];
+ relevant_global.register_performance_observer(vm, *this);
+ return Ok(());
+ }
+
+ // 7. Otherwise, run the following steps:
+ // 1. Assert that this's observer type is "single".
+ assert!(this.observer_type.get() == ObserverType::Single);
+
+ // 2. If options's type is not contained in the relevantGlobal's frozen array of supported entry types, abort
+ // these steps. The user agent SHOULD notify developers when this happens, for instance via a console warning.
+ let r#type = options
+ .r#type
+ .clone()
+ .expect("an observer of a single type observes type");
+ if !is_supported_entry_type(global_is_window, &r#type) {
+ return Ok(());
+ }
+
+ // 3. If the list of registered performance observer objects of relevantGlobal contains a registered performance
+ // observer obs whose observer is this:
+ if relevant_global.has_registered_performance_observer(*this) {
+ // 1. If obs's options list contains a PerformanceObserverInit item currentOptions whose type is equal to
+ // options's type, replace currentOptions with options in obs's options list.
+ let mut options_list = this.options_list.borrow_mut();
+ if let Some(current_options) = options_list
+ .iter_mut()
+ .find(|current_options| current_options.r#type == options.r#type)
+ {
+ *current_options = options.clone();
+ }
+ // 2. Otherwise, append options to obs's options list.
+ else {
+ options_list.push(options.clone());
+ }
+ }
+ // 4. Otherwise, create and append a registered performance observer object to the list of registered performance
+ // observer objects of relevantGlobal, with observer set to the this and options list set to a list containing
+ // options as its only item.
+ else {
+ *this.options_list.borrow_mut() = vec![options.clone()];
+ relevant_global.register_performance_observer(vm, *this);
+ }
+
+ // 5. If options's buffered flag is set:
+ if options.buffered == Some(true) {
+ // 1. Let tuple be the relevant performance entry tuple of options's type and relevantGlobal.
+ relevant_global.with_relevant_performance_entry_tuple(&r#type, |tuple| {
+ // 2. For each entry in tuple's performance entry buffer:
+ let mut observer_buffer = this.observer_buffer.borrow_mut(vm);
+ for entry in &tuple.performance_entry_buffer {
+ // 1. If should add entry with entry and options as parameters returns true, append entry to the
+ // observer buffer.
+ if entry.should_add_entry(Some(&options)) {
+ observer_buffer.push(entry.clone());
+ }
+ }
+ });
+
+ // 3. Queue the PerformanceObserver task with relevantGlobal as input.
+ relevant_global.queue_the_performance_observer_task(vm);
+ }
+
+ Ok(())
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserver-disconnect
+ pub(crate) fn disconnect(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {
+ let vm = cx.vm();
+
+ // 1. Remove this from the list of registered performance observer objects of relevant global object.
+ PerformanceTimeline::of(vm, this.realm).unregister_performance_observer(vm, *this);
+
+ // 2. Empty this's observer buffer.
+ this.observer_buffer.borrow_mut(vm).clear();
+
+ // 3. Empty this's options list.
+ this.options_list.borrow_mut().clear();
+ Ok(())
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserver-takerecords
+ pub(crate) fn take_records<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // The takeRecords() method must return a copy of this's observer buffer, and also empty this's observer buffer.
+ let records = self.take_observer_buffer(cx.vm());
+ Ok(wrap_entries(cx, &records))
+ }
+
+ pub(crate) fn take_observer_buffer<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, CppPerformanceEntry> {
+ let records = MarkedVec::new(vm);
+ let mut buffer = self.observer_buffer.borrow_mut(vm);
+ records.extend_from_slice(&buffer);
+ buffer.clear();
+ drop(buffer);
+ records
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserver-supportedentrytypes
+ pub(crate) fn supported_entry_types(cx: &mut CallContext) -> WebIdlResult<Value> {
+ // When supportedEntryTypes’s attribute getter is called, run the following steps:
+ // 1. Let globalObject be the environment settings object’s global object.
+ // 2. Return globalObject’s frozen array of supported entry types.
+ let data = realm_data(cx.vm(), cx.realm());
+ if let Some(array) = data.performance_observer_supported_entry_types.get() {
+ return Ok(Value::from_object(array));
+ }
+ let global_is_window = realm_is_window(cx.realm());
+ let types: Vec<Utf16String> = supported_entry_types(global_is_window)
+ .map(|supported| Utf16String::from_utf8(supported.entry_type))
+ .collect();
+ let array = frozen_array_to_js(cx, sequence_to_js(cx, types, |r#type| r#type.to_js(cx)))?;
+ data.performance_observer_supported_entry_types
+ .set(Some(array.as_object()));
+ Ok(array)
+ }
+
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ self.realm
+ }
+
+ pub(crate) fn requires_dropped_entries(&self) -> bool {
+ self.requires_dropped_entries.get()
+ }
+
+ pub(crate) fn unset_requires_dropped_entries(&self) {
+ self.requires_dropped_entries.set(false);
+ }
+
+ pub(crate) fn options_list(&self) -> core::cell::Ref<'_, Vec<PerformanceObserverInit>> {
+ self.options_list.borrow()
+ }
+
+ pub(crate) fn append_to_observer_buffer(&self, vm: &Vm, entry: CppPerformanceEntry) {
+ self.observer_buffer.borrow_mut(vm).push(entry);
+ }
+
+ pub(crate) fn invoke_callback(
+ this: Ref<Self>,
+ vm: &Vm,
+ observer_entry_list: Ref<PerformanceObserverEntryList>,
+ dropped_entries_count: Option<u64>,
+ ) -> ThrowCompletionOr<()> {
+ let cx = &CallContext::new(vm, this.realm);
+ let callback_options = create_dictionary_object(cx);
+ if let Some(dropped_entries_count) = dropped_entries_count {
+ callback_options.create_data_property(
+ vm,
+ &PropertyKey::from_utf8("droppedEntriesCount"),
+ dropped_entries_count.to_js(cx)?,
+ None,
+ None,
+ )?;
+ }
+ let observer = Value::from_object(wrap(cx, this));
+ this.callback.invoke(
+ Some(observer),
+ &[
+ Value::from_object(wrap(cx, observer_entry_list)),
+ observer,
+ Value::from_object(callback_options),
+ ],
+ )?;
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer_entry_list.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer_entry_list.rs
new file mode 100644
index 00000000000..77073b56b38
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_observer_entry_list.rs
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceObserverEntryList, https://w3c.github.io/performance-timeline/#performanceobserverentrylist-interface
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, MarkedVec, Realm, Trace, Vm};
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::performance_timeline::performance_entry::{
+ CppPerformanceEntry, filter_buffer_by_name_and_type, wrap_entries,
+};
+
+// https://w3c.github.io/performance-timeline/#performanceobserverentrylist-interface
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PerformanceObserverEntryList {
+ realm: Gc<Realm>,
+ // https://w3c.github.io/performance-timeline/#dfn-entry-list
+ entry_list: Vec<CppPerformanceEntry>,
+}
+
+impl Wrappable for PerformanceObserverEntryList {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+impl PerformanceObserverEntryList {
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, entry_list: &MarkedVec<'_, CppPerformanceEntry>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ realm,
+ entry_list: entry_list.to_vec(),
+ })
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentries
+ pub(crate) fn get_entries<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
+ // name and type set to null.
+ let entries = filter_buffer_by_name_and_type(cx, &self.entry_list, None, None);
+ Ok(wrap_entries(cx, &entries))
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentriesbytype
+ pub(crate) fn get_entries_by_type<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ r#type: Utf16String,
+ ) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
+ // name set to null, and type set to the method's input type parameter.
+ let entries = filter_buffer_by_name_and_type(cx, &self.entry_list, None, Some(&r#type));
+ Ok(wrap_entries(cx, &entries))
+ }
+
+ // https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentriesbyname
+ pub(crate) fn get_entries_by_name<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ name: Utf16String,
+ r#type: Option<Utf16String>,
+ ) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {
+ // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
+ // name set to the method input name parameter, and type set to null if optional entryType is omitted, or set to the
+ // method's input type parameter otherwise.
+ let entries = filter_buffer_by_name_and_type(cx, &self.entry_list, Some(&name), r#type.as_ref());
+ Ok(wrap_entries(cx, &entries))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs
new file mode 100644
index 00000000000..6aecce99b71
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/performance_timeline/performance_timeline.rs
@@ -0,0 +1,514 @@
+/*
+ * Copyright (c) 2022, Andrew Kaster <[email protected]>
+ * Copyright (c) 2023, Linus Groh <[email protected]>
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2025-2026, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The performance timeline, https://w3c.github.io/performance-timeline/#performance-timeline
+
+use core::cell::Cell;
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, Realm, Trace, Vm};
+
+use crate::bindings::CallContext;
+use crate::bindings::environment_settings_object::relevant_settings_object;
+use crate::bindings::event_target::CppEvent;
+use crate::bindings::interface::{
+ Ref, realm_is_window, report_an_exception, with_temporary_execution_context_and_callbacks,
+};
+use crate::bindings::promise::{TaskSource, queue_a_global_task, queue_a_task};
+use crate::bindings::realm_data::realm_data;
+use crate::high_resolution_time::performance::Performance;
+use crate::performance_timeline::entry_types::supported_entry_types;
+use crate::performance_timeline::performance_entry::{
+ CppPerformanceEntry, filter_buffer_by_name_and_type, sort_in_chronological_order,
+};
+use crate::performance_timeline::performance_entry_tuple::PerformanceEntryTuple;
+use crate::performance_timeline::performance_observer::PerformanceObserver;
+use crate::performance_timeline::performance_observer_entry_list::PerformanceObserverEntryList;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PerformanceTimeline {
+ realm: Gc<Realm>,
+
+ // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
+ performance: Cell<Option<Ref<Performance>>>,
+
+ // https://w3c.github.io/performance-timeline/#performance-timeline
+ // Each global object has:
+ // - a performance observer task queued flag
+ performance_observer_task_queued: Cell<bool>,
+
+ // - a list of registered performance observer objects that is initially empty
+ registered_performance_observer_objects: GcRefCell<Vec<Ref<PerformanceObserver>>>,
+
+ // https://w3c.github.io/performance-timeline/#dfn-performance-entry-buffer-map
+ // a performance entry buffer map map, keyed on a DOMString, representing the entry type to which the buffer belongs. The map's value is the following tuple:
+ performance_entry_buffer_map: GcRefCell<Vec<PerformanceEntryTuple>>,
+
+ // https://w3c.github.io/resource-timing/#sec-extensions-performance-interface
+ // Each ECMAScript global environment has:
+ // https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-size-limit
+ // A resource timing buffer size limit which should initially be 250 or greater.
+ // The recommended minimum number of PerformanceResourceTiming objects is 250, though this may be changed by the
+ // user agent. setResourceTimingBufferSize can be called to request a change to this limit.
+ resource_timing_buffer_size_limit: Cell<u32>,
+
+ // https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-full-event-pending-flag
+ // A resource timing buffer full event pending flag which is initially false.
+ resource_timing_buffer_full_event_pending: Cell<bool>,
+
+ // https://w3c.github.io/resource-timing/#dfn-resource-timing-secondary-buffer-current-size
+ // A resource timing secondary buffer current size which is initially 0.
+ // https://w3c.github.io/resource-timing/#dfn-resource-timing-secondary-buffer
+ // A resource timing secondary buffer to store PerformanceResourceTiming objects that is initially empty.
+ resource_timing_secondary_buffer: GcRefCell<Vec<CppPerformanceEntry>>,
+}
+
+static PERFORMANCE_TIMELINE_CLASS: EmbedderClass<PerformanceTimeline> = EmbedderClass::new("PerformanceTimeline");
+
+impl EmbedderValue for PerformanceTimeline {
+ const CLASS: &'static EmbedderClass<Self> = &PERFORMANCE_TIMELINE_CLASS;
+}
+
+pub(crate) type PerformanceTimelineRef = Gc<EmbedderCell<PerformanceTimeline>>;
+
+impl PerformanceTimeline {
+ /// Every world of the global object shares its timeline.
+ pub(crate) fn of(vm: &Vm, realm: Gc<Realm>) -> PerformanceTimelineRef {
+ let realm = relevant_settings_object(realm.global_object()).realm();
+ let data = realm_data(vm, realm);
+ if let Some(timeline) = data.performance_timeline.get() {
+ return timeline;
+ }
+ let timeline = PERFORMANCE_TIMELINE_CLASS.allocate(vm, |defer_gc| Self {
+ realm,
+ performance: Cell::new(None),
+ performance_observer_task_queued: Cell::new(false),
+ registered_performance_observer_objects: GcRefCell::default(),
+ performance_entry_buffer_map: GcRefCell::new(
+ supported_entry_types(realm_is_window(realm))
+ .map(|supported_entry_type| PerformanceEntryTuple::new(defer_gc, supported_entry_type))
+ .collect(),
+ ),
+ resource_timing_buffer_size_limit: Cell::new(250),
+ resource_timing_buffer_full_event_pending: Cell::new(false),
+ resource_timing_secondary_buffer: GcRefCell::default(),
+ });
+ data.performance_timeline.set(Some(timeline));
+ timeline
+ }
+
+ // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
+ pub(crate) fn performance(&self, vm: &Vm) -> Ref<Performance> {
+ if let Some(performance) = self.performance.get() {
+ return performance;
+ }
+ let performance = Performance::create(vm, self.realm);
+ self.performance.set(Some(performance));
+ performance
+ }
+
+ /// https://w3c.github.io/performance-timeline/#dfn-relevant-performance-entry-tuple
+ pub(crate) fn with_relevant_performance_entry_tuple<R>(
+ &self,
+ entry_type: &Utf16String,
+ steps: impl FnOnce(&PerformanceEntryTuple) -> R,
+ ) -> R {
+ // 1. Let map be the performance entry buffer map associated with globalObject.
+ // 2. Return the result of getting the value of an entry from map, given entryType as the key.
+ let map = self.performance_entry_buffer_map.borrow();
+ steps(Self::tuple_of(&map, entry_type))
+ }
+
+ fn with_relevant_performance_entry_tuple_mut<R>(
+ &self,
+ vm: &Vm,
+ entry_type: &Utf16String,
+ steps: impl FnOnce(&mut PerformanceEntryTuple) -> R,
+ ) -> R {
+ let mut map = self.performance_entry_buffer_map.borrow_mut(vm);
+ let tuple = map
+ .iter_mut()
+ .find(|tuple| tuple.entry_type == *entry_type)
+ .expect("the entry type is a supported entry type");
+ steps(tuple)
+ }
+
+ fn tuple_of<'a>(map: &'a [PerformanceEntryTuple], entry_type: &Utf16String) -> &'a PerformanceEntryTuple {
+ map.iter()
+ .find(|tuple| tuple.entry_type == *entry_type)
+ .expect("the entry type is a supported entry type")
+ }
+
+ // https://w3c.github.io/performance-timeline/#dfn-queue-a-performanceentry
+ pub(crate) fn queue_performance_entry(&self, vm: &Vm, new_entry: &CppPerformanceEntry) {
+ // 1. Let interested observers be an initially empty set of PerformanceObserver objects.
+ let interested_observers = MarkedVec::new(vm);
+
+ // 2. Let entryType be newEntry’s entryType value.
+ let entry_type = new_entry.entry_type();
+
+ // 3. Let relevantGlobal be newEntry's relevant global object.
+ // NB: Already is `self`.
+
+ // 4. For each registered performance observer regObs in relevantGlobal's list of registered performance observer
+ // objects:
+ for registered_observer in self.registered_performance_observer_objects.borrow().iter() {
+ // 1. If regObs's options list contains a PerformanceObserverInit options whose entryTypes member includes entryType
+ // or whose type member equals to entryType:
+ let options_list = registered_observer.options_list();
+ let options = options_list.iter().find(|options| match &options.entry_types {
+ Some(entry_types) => entry_types.contains(&entry_type),
+ None => options.r#type.as_ref() == Some(&entry_type),
+ });
+
+ if let Some(options) = options {
+ // 1. If should add entry with newEntry and options returns true, append regObs's observer to interested observers.
+ if new_entry.should_add_entry(Some(options)) {
+ interested_observers.push(*registered_observer);
+ }
+ }
+ }
+
+ // 5. For each observer in interested observers:
+ for observer in interested_observers.values().iter() {
+ // 1. Append newEntry to observer's observer buffer.
+ observer.append_to_observer_buffer(vm, new_entry.clone());
+ }
+
+ // AD-HOC: Steps 6-9 are not here because other engines do not add to the performance entry buffer when queuing
+ // the performance observer task. The users of the Performance Timeline specification also do not expect
+ // this function to add to the entry buffer, instead queuing the observer task, then adding to the entry
+ // buffer separately.
+
+ // OPTIMIZATION: The PerformanceObserver task delivers only what observers have buffered. An entry that no observer
+ // is interested in buffers nothing, so it doesn't queue the task. A document's initial visibility
+ // state entry, e.g., then doesn't queue a task for every new document.
+ if interested_observers.is_empty() {
+ return;
+ }
+
+ // 10. Queue the PerformanceObserver task with relevantGlobal as input.
+ self.queue_the_performance_observer_task(vm);
+ }
+
+ // https://w3c.github.io/performance-timeline/#dfn-queue-a-performanceentry
+ // AD-HOC: This is a separate function because the users of this specification queues PerformanceObserver tasks and add
+ // to the entry buffer separately.
+ pub(crate) fn add_performance_entry(
+ &self,
+ vm: &Vm,
+ new_entry: &CppPerformanceEntry,
+ check_if_performance_buffer_is_full: bool,
+ ) {
+ // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal.
+ self.with_relevant_performance_entry_tuple_mut(vm, &new_entry.entry_type(), |tuple| {
+ // AD-HOC: We have a custom flag to always append to the buffer by default, as other performance specs do this by default
+ // (either they don't have a limit, or they check the limit themselves). This flag allows compatibility for specs
+ // that rely do and don't rely on this.
+ let mut is_buffer_full = false;
+ let mut should_add = true;
+
+ if check_if_performance_buffer_is_full {
+ // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple
+ // as input.
+ is_buffer_full = tuple.is_full();
+
+ // 8. Let shouldAdd be the result of should add entry with newEntry as input.
+ should_add = new_entry.should_add_entry(None);
+ }
+
+ // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer.
+ if !is_buffer_full && should_add {
+ tuple.performance_entry_buffer.push(new_entry.clone());
+ }
+ });
+ }
+
+ pub(crate) fn clear_performance_entry_buffer(&self, vm: &Vm, entry_type: &Utf16String) {
+ self.with_relevant_performance_entry_tuple_mut(vm, entry_type, |tuple| tuple.performance_entry_buffer.clear());
+ }
+
+ pub(crate) fn remove_entries_from_performance_entry_buffer(
+ &self,
+ vm: &Vm,
+ entry_type: &Utf16String,
+ entry_name: &Utf16String,
+ ) {
+ self.with_relevant_performance_entry_tuple_mut(vm, entry_type, |tuple| {
+ tuple
+ .performance_entry_buffer
+ .retain(|entry| entry.name() != *entry_name);
+ });
+ }
+
+ // https://w3c.github.io/performance-timeline/#dfn-filter-buffer-map-by-name-and-type
+ pub(crate) fn filter_buffer_map_by_name_and_type<'vm>(
+ &self,
+ cx: &CallContext<'vm>,
+ name: Option<&Utf16String>,
+ r#type: Option<&Utf16String>,
+ ) -> MarkedVec<'vm, CppPerformanceEntry> {
+ // 1. Let result be an initially empty list.
+ let result = MarkedVec::new(cx.vm());
+
+ // 2. Let map be the performance entry buffer map associated with the relevant global object of this.
+ let map = self.performance_entry_buffer_map.borrow();
+
+ // 3. Let tuple list be an empty list.
+ // 4. If type is not null, append the result of getting the value of entry on map given type as key to tuple list.
+ // Otherwise, assign the result of get the values on map to tuple list.
+ let tuple_list = map
+ .iter()
+ .filter(|tuple| r#type.is_none_or(|r#type| tuple.entry_type == *r#type));
+
+ // 5. For each tuple in tuple list, run the following steps:
+ for tuple in tuple_list {
+ // 1. Let buffer be tuple's performance entry buffer.
+ let buffer = &tuple.performance_entry_buffer;
+
+ // 2. If tuple's availableFromTimeline is false, continue to the next tuple.
+ if !tuple.available_from_timeline {
+ continue;
+ }
+
+ // 3. Let entries be the result of running filter buffer by name and type with buffer, name and type as inputs.
+ let entries = filter_buffer_by_name_and_type(cx, buffer, name, r#type);
+
+ // 4. For each entry in entries, append entry to result.
+ result.extend_from_slice(&entries.values());
+ }
+
+ // 6. Sort results's entries in chronological order with respect to startTime
+ sort_in_chronological_order(&result);
+
+ // 7. Return result.
+ result
+ }
+
+ pub(crate) fn register_performance_observer(&self, vm: &Vm, observer: Ref<PerformanceObserver>) {
+ if !self.has_registered_performance_observer(observer) {
+ self.registered_performance_observer_objects
+ .borrow_mut(vm)
+ .push(observer);
+ }
+ }
+
+ pub(crate) fn unregister_performance_observer(&self, vm: &Vm, observer: Ref<PerformanceObserver>) {
+ self.registered_performance_observer_objects
+ .borrow_mut(vm)
+ .retain(|registered_observer| *registered_observer != observer);
+ }
+
+ pub(crate) fn has_registered_performance_observer(&self, observer: Ref<PerformanceObserver>) -> bool {
+ self.registered_performance_observer_objects
+ .borrow()
+ .contains(&observer)
+ }
+
+ // https://w3c.github.io/performance-timeline/#dfn-queue-the-performanceobserver-task
+ pub(crate) fn queue_the_performance_observer_task(&self, vm: &Vm) {
+ // 1. If relevantGlobal's performance observer task queued flag is set, terminate these steps.
+ if self.performance_observer_task_queued.get() {
+ return;
+ }
+
+ // 2. Set relevantGlobal's performance observer task queued flag.
+ self.performance_observer_task_queued.set(true);
+
+ // 3. Queue a task that consists of running the following substeps. The task source for the queued task is the performance
+ // timeline task source.
+ queue_a_global_task(
+ vm,
+ self.realm.global_object(),
+ TaskSource::PerformanceTimeline,
+ self.realm,
+ |vm, realm| {
+ with_temporary_execution_context_and_callbacks(realm, || {
+ Self::of(vm, realm).run_performance_observer_task(vm);
+ });
+ },
+ );
+ }
+
+ fn run_performance_observer_task(&self, vm: &Vm) {
+ // 1. Unset performance observer task queued flag of relevantGlobal.
+ self.performance_observer_task_queued.set(false);
+
+ // 2. Let notifyList be a copy of relevantGlobal's list of registered performance observer objects.
+ let notify_list = MarkedVec::new(vm);
+ notify_list.extend_from_slice(&self.registered_performance_observer_objects.borrow());
+
+ // 3. For each registered performance observer object registeredObserver in notifyList, run these steps:
+ for registered_observer in notify_list.values().iter() {
+ // 1. Let po be registeredObserver's observer.
+ // 2. Let entries be a copy of po’s observer buffer.
+ // 4. Empty po’s observer buffer.
+ let entries = registered_observer.take_observer_buffer(vm);
+
+ // 3. If entries is empty, return.
+ // FIXME: Do they mean `continue`?
+ if entries.is_empty() {
+ continue;
+ }
+
+ // 5. Let observerEntryList be a new PerformanceObserverEntryList, with its entry list set to entries.
+ let observer_entry_list = PerformanceObserverEntryList::create(vm, registered_observer.realm(), &entries);
+
+ // 6. Let droppedEntriesCount be null.
+ let mut dropped_entries_count = None;
+
+ // 7. If po's requires dropped entries is set, perform the following steps:
+ if registered_observer.requires_dropped_entries() {
+ // 1. Set droppedEntriesCount to 0.
+ let mut count = 0;
+
+ // 2. For each PerformanceObserverInit item in registeredObserver's options list:
+ let map = self.performance_entry_buffer_map.borrow();
+ for item in registered_observer.options_list().iter() {
+ // 1. For each DOMString entryType that appears either as item's type or in item's entryTypes:
+ for r#type in item.r#type.iter().chain(item.entry_types.iter().flatten()) {
+ // 1. Let map be relevantGlobal's performance entry buffer map.
+ // 2. Let tuple be the result of getting the value of entry on map given entryType as key.
+ let tuple = Self::tuple_of(&map, r#type);
+
+ // 3. Increase droppedEntriesCount by tuple's dropped entries count.
+ count += tuple.dropped_entries_count;
+ }
+ }
+ dropped_entries_count = Some(count);
+
+ // 3. Set po's requires dropped entries to false.
+ registered_observer.unset_requires_dropped_entries();
+ }
+
+ // 8. Let callbackOptions be a PerformanceObserverCallbackOptions with its droppedEntriesCount set to
+ // droppedEntriesCount if droppedEntriesCount is not null, otherwise unset.
+ // 9. Call po’s observer callback with observerEntryList as the first argument, with po as the second
+ // argument and as callback this value, and with callbackOptions as the third argument.
+ // If this throws an exception, report the exception.
+ if let Err(throw) = PerformanceObserver::invoke_callback(
+ *registered_observer,
+ vm,
+ observer_entry_list,
+ dropped_entries_count,
+ ) {
+ report_an_exception(self.realm, throw.value());
+ }
+ }
+ }
+
+ pub(crate) fn set_resource_timing_buffer_size_limit(&self, value: u32) {
+ self.resource_timing_buffer_size_limit.set(value);
+ }
+
+ // https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry
+ pub(crate) fn add_resource_timing_entry(&self, vm: &Vm, new_entry: &CppPerformanceEntry) {
+ // 1. If can add resource timing entry returns true and resource timing buffer full event pending flag is false,
+ // run the following substeps:
+ if self.can_add_resource_timing_entry() && !self.resource_timing_buffer_full_event_pending.get() {
+ // a. Add new entry to the performance entry buffer.
+ // b. Increase resource timing buffer current size by 1.
+ self.add_performance_entry(vm, new_entry, false);
+
+ // c. Return.
+ return;
+ }
+
+ // 2. If resource timing buffer full event pending flag is false, run the following substeps:
+ if !self.resource_timing_buffer_full_event_pending.get() {
+ // a. Set resource timing buffer full event pending flag to true.
+ self.resource_timing_buffer_full_event_pending.set(true);
+
+ // b. Queue a task on the performance timeline task source to run fire a buffer full event.
+ queue_a_task(
+ vm,
+ self.realm,
+ TaskSource::PerformanceTimeline,
+ self.realm,
+ |vm, realm| {
+ Self::of(vm, realm).fire_resource_timing_buffer_full_event(vm);
+ },
+ );
+ }
+
+ // 3. Add new entry to the resource timing secondary buffer.
+ // 4. Increase resource timing secondary buffer current size by 1.
+ self.resource_timing_secondary_buffer
+ .borrow_mut(vm)
+ .push(new_entry.clone());
+ }
+
+ // https://w3c.github.io/resource-timing/#dfn-can-add-resource-timing-entry
+ fn can_add_resource_timing_entry(&self) -> bool {
+ // 1. If resource timing buffer current size is smaller than resource timing buffer size limit, return true.
+ // 2. Return false.
+ self.resource_timing_buffer_current_size() < self.resource_timing_buffer_size_limit.get() as usize
+ }
+
+ // https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-current-size
+ fn resource_timing_buffer_current_size(&self) -> usize {
+ // A resource timing buffer current size which is initially 0.
+ self.with_relevant_performance_entry_tuple(&Utf16String::from_utf8("resource"), |tuple| {
+ tuple.performance_entry_buffer.len()
+ })
+ }
+
+ // https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event
+ fn fire_resource_timing_buffer_full_event(&self, vm: &Vm) {
+ // 1. While resource timing secondary buffer is not empty, run the following substeps:
+ while !self.resource_timing_secondary_buffer.borrow().is_empty() {
+ // 1. Let number of excess entries before be resource timing secondary buffer current size.
+ let number_of_excess_entries_before = self.resource_timing_secondary_buffer.borrow().len();
+
+ // 2. If can add resource timing entry returns false, then fire an event named resourcetimingbufferfull at the Performance object.
+ if !self.can_add_resource_timing_entry() {
+ let full_event = CppEvent::create(self.realm, "resourcetimingbufferfull", false, false, false);
+ full_event.set_is_trusted(true);
+ self.performance(vm).event_target().dispatch_event(&full_event);
+ }
+
+ // 3. Run copy secondary buffer.
+ self.copy_resource_timing_secondary_buffer(vm);
+
+ // 4. Let number of excess entries after be resource timing secondary buffer current size.
+ let number_of_excess_entries_after = self.resource_timing_secondary_buffer.borrow().len();
+
+ // 5. If number of excess entries before is lower than or equals number of excess entries after, then remove
+ // all entries from resource timing secondary buffer, set resource timing secondary buffer current size to
+ // 0, and abort these steps.
+ if number_of_excess_entries_before <= number_of_excess_entries_after {
+ self.resource_timing_secondary_buffer.borrow_mut(vm).clear();
+ break;
+ }
+ }
+
+ // 2. Set resource timing buffer full event pending flag to false.
+ self.resource_timing_buffer_full_event_pending.set(false);
+ }
+
+ // https://w3c.github.io/resource-timing/#dfn-copy-secondary-buffer
+ fn copy_resource_timing_secondary_buffer(&self, vm: &Vm) {
+ // 1. While resource timing secondary buffer is not empty and can add resource timing entry returns true,
+ // run the following substeps:
+ while !self.resource_timing_secondary_buffer.borrow().is_empty() && self.can_add_resource_timing_entry() {
+ // 1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
+ // 2. Add entry to the end of performance entry buffer.
+ // 3. Increment resource timing buffer current size by 1.
+ // 4. Remove entry from resource timing secondary buffer.
+ // 5. Decrement resource timing secondary buffer current size by 1.
+ let mut secondary_buffer = self.resource_timing_secondary_buffer.borrow_mut(vm);
+ let entry = secondary_buffer.remove(0);
+ self.with_relevant_performance_entry_tuple_mut(vm, &Utf16String::from_utf8("resource"), |tuple| {
+ tuple.performance_entry_buffer.push(entry);
+ });
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/user_timing/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/user_timing/mod.rs
new file mode 100644
index 00000000000..ba780108b91
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/user_timing/mod.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! User Timing, https://w3c.github.io/user-timing/
+
+pub(crate) mod performance_mark;
+pub(crate) mod performance_measure;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_mark.rs b/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_mark.rs
new file mode 100644
index 00000000000..ca35d14ecba
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_mark.rs
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceMark, https://w3c.github.io/user-timing/#performancemark
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Value};
+
+use crate::bindings::WebIdlResult;
+use crate::performance_timeline::performance_entry::CppPerformanceEntry;
+
+unsafe extern "C" {
+ fn web_user_timing_performance_mark_create(
+ global_object: *mut c_void,
+ mark_name: usize,
+ has_detail: bool,
+ detail: u64,
+ has_start_time: bool,
+ start_time: f64,
+ entry: *mut *mut c_void,
+ ) -> RawNativeFunctionResult;
+}
+
+// https://w3c.github.io/user-timing/#ref-for-dom-performancemarkoptions-1
+pub(crate) struct PerformanceMarkOptions {
+ pub(crate) detail: Option<Value>,
+ pub(crate) start_time: Option<f64>,
+}
+
+/// https://w3c.github.io/user-timing/#dfn-performancemark-constructor
+pub(crate) fn run_the_performance_mark_constructor(
+ realm: Gc<Realm>,
+ mark_name: &Utf16String,
+ mark_options: &PerformanceMarkOptions,
+) -> WebIdlResult<CppPerformanceEntry> {
+ let mut entry = core::ptr::null_mut();
+ // SAFETY: The global object and the detail are live, the name is lent for the call, and LibWeb writes a live entry.
+ unsafe {
+ web_user_timing_performance_mark_create(
+ realm.global_object().as_ptr().cast(),
+ mark_name.raw_identity(),
+ mark_options.detail.is_some(),
+ mark_options.detail.unwrap_or(Value::UNDEFINED).to_raw(),
+ mark_options.start_time.is_some(),
+ mark_options.start_time.unwrap_or_default(),
+ &raw mut entry,
+ )
+ }
+ .into_completion()?;
+ // SAFETY: LibWeb wrote the live entry that it created.
+ Ok(unsafe { CppPerformanceEntry::from_raw(entry) })
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_measure.rs b/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_measure.rs
new file mode 100644
index 00000000000..4960217223f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/user_timing/performance_measure.rs
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceMeasure, https://w3c.github.io/user-timing/#performancemeasure
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::Value;
+
+use crate::performance_timeline::performance_entry::CppPerformanceEntry;
+
+unsafe extern "C" {
+ fn web_user_timing_performance_measure_create(
+ measure_name: usize,
+ start_time: f64,
+ duration: f64,
+ detail: u64,
+ ) -> *mut c_void;
+}
+
+// https://w3c.github.io/user-timing/#extensions-performance-interface
+#[derive(Default)]
+pub(crate) struct PerformanceMeasureOptions {
+ pub(crate) detail: Option<Value>,
+ pub(crate) start: Option<DOMStringOrDouble>,
+ pub(crate) duration: Option<f64>,
+ pub(crate) end: Option<DOMStringOrDouble>,
+}
+
+/// (DOMString or DOMHighResTimeStamp)
+pub(crate) enum DOMStringOrDouble {
+ DOMString(Utf16String),
+ Double(f64),
+}
+
+pub(crate) fn create_performance_measure(
+ measure_name: &Utf16String,
+ start_time: f64,
+ duration: f64,
+ detail: Value,
+) -> CppPerformanceEntry {
+ // SAFETY: The detail is live, the name is lent for the call, and LibWeb returns a live entry.
+ unsafe {
+ CppPerformanceEntry::from_raw(web_user_timing_performance_measure_create(
+ measure_name.raw_identity(),
+ start_time,
+ duration,
+ detail.to_raw(),
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index da43fb71266..144e56acbdc 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -20,6 +20,7 @@
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Agent.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
@@ -95,6 +96,7 @@ void web_bindings_push_element_queue();
void web_bindings_pop_element_queue_and_invoke_reactions();
bool web_bindings_realm_is_window(void* realm);
bool web_bindings_realm_is_secure_context(void* realm);
+void web_bindings_report_an_exception(void* realm, JSValue exception);
HTML::Window* web_bindings_window_from_global_object(JSObject* global_object);
void web_bindings_for_each_active_window(void* ctx, void (*on_window)(void*, HTML::Window*));
DOM::Document* web_bindings_window_associated_document(HTML::Window*);
@@ -107,6 +109,7 @@ URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);
HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);
HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object);
JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject*);
+JS::Realm* web_bindings_environment_settings_object_realm(HTML::EnvironmentSettingsObject*);
void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject*, void* ctx, void (*on_id)(void*, ReadonlyBytes));
bool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);
void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget*, bool has_pending_activity);
@@ -158,6 +161,11 @@ bool web_bindings_realm_is_secure_context(void* realm)
return HTML::is_secure_context(principal_host_defined_environment_settings_object(*static_cast<JS::Realm*>(realm)));
}
+void web_bindings_report_an_exception(void* realm, JSValue exception)
+{
+ HTML::report_exception(JS::throw_completion(JS::HostABI::value_from_abi(exception)), *static_cast<JS::Realm*>(realm));
+}
+
void web_bindings_push_element_queue()
{
main_thread_similar_origin_window_agent().custom_element_reactions_stack.element_queue_stack.append({});
@@ -232,6 +240,11 @@ JSObject* web_bindings_environment_settings_object_global_object(HTML::Environme
return JS::HostABI::object_to_abi(&settings_object->global_object());
}
+JS::Realm* web_bindings_environment_settings_object_realm(HTML::EnvironmentSettingsObject* settings_object)
+{
+ return &settings_object->realm();
+}
+
void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject* settings_object, void* ctx, void (*on_id)(void*, ReadonlyBytes))
{
on_id(ctx, settings_object->id.to_string().bytes());
@@ -346,6 +359,7 @@ void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*,
static_assert(to_underlying(HTML::Task::Source::Unspecified) == 0);
static_assert(to_underlying(HTML::Task::Source::Networking) == 3);
static_assert(to_underlying(HTML::Task::Source::FileReading) == 13);
+static_assert(to_underlying(HTML::Task::Source::PerformanceTimeline) == 15);
static_assert(to_underlying(HTML::Task::Source::Crypto) == 27);
static_assert(to_underlying(HTML::Task::Source::Storage) == 29);
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 1b45500d0ad..f6743a28824 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -359,7 +359,6 @@ set(SOURCES
Geometry/DOMRectList.cpp
Geometry/DOMRectReadOnly.cpp
GPC/GlobalPrivacyControl.cpp
- HighResolutionTime/Performance.cpp
HighResolutionTime/TimeOrigin.cpp
HTML/AbstractWorker.cpp
HTML/BitmapDecodedImageData.cpp
@@ -733,10 +732,7 @@ set(SOURCES
Painting/ScrollSnap.cpp
Painting/SvgPaintResources.cpp
PerformanceTimeline/EntryTypes.cpp
- PerformanceTimeline/EventNames.cpp
PerformanceTimeline/PerformanceEntry.cpp
- PerformanceTimeline/PerformanceObserver.cpp
- PerformanceTimeline/PerformanceObserverEntryList.cpp
PermissionsAPI/Permissions.cpp
PermissionsAPI/PermissionStore.cpp
PermissionsAPI/PermissionStatus.cpp
diff --git a/Libraries/LibWeb/EventTiming/EventTiming.cpp b/Libraries/LibWeb/EventTiming/EventTiming.cpp
index 156fcb28621..0e3d56adee1 100644
--- a/Libraries/LibWeb/EventTiming/EventTiming.cpp
+++ b/Libraries/LibWeb/EventTiming/EventTiming.cpp
@@ -18,7 +18,6 @@
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HighResolutionTime/Performance.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/PerformanceTimeline/EntryTypes.h>
@@ -30,6 +29,11 @@
namespace Web::EventTiming {
+extern "C" {
+EventCounts* web_event_timing_event_counts(HTML::Window*);
+u64 web_event_timing_interaction_count(HTML::Window*);
+}
+
WindowEventTimingState::WindowEventTimingState()
// NB: The user interaction value is initially set to a random integer between 100 and 10000.
: user_interaction_value(100 + get_random_uniform(9901))
@@ -46,6 +50,27 @@ void WindowEventTimingState::visit_edges(GC::Cell::Visitor& visitor)
visitor.visit(event_counts);
}
+GC::Ref<EventCounts> event_counts(HTML::Window& window)
+{
+ auto& event_counts = window.event_timing_state().event_counts;
+ if (!event_counts)
+ event_counts = EventCounts::create();
+ return *event_counts;
+}
+
+extern "C" {
+
+EventCounts* web_event_timing_event_counts(HTML::Window* window)
+{
+ return event_counts(*window).ptr();
+}
+
+u64 web_event_timing_interaction_count(HTML::Window* window)
+{
+ return window->event_timing_state().interaction_count;
+}
+}
+
void for_each_event_type_considered_for_event_timing(Function<void(Utf16FlyString const&)> const& callback)
{
// MouseEvents
@@ -518,7 +543,7 @@ static void set_event_timing_entry_duration(PerformanceEventTiming& timing_entry
// 1. Let eventCounts be window's eventCounts.
// 2. Assert that eventCounts contains name.
// 3. Set eventCounts[name] to eventCounts[name] + 1.
- window.performance()->event_counts()->increment(name);
+ event_counts(window)->increment(name);
// 6. If window's has dispatched input event is false, and timingEntry's interactionId is not 0, run the following
// steps:
diff --git a/Libraries/LibWeb/EventTiming/EventTiming.h b/Libraries/LibWeb/EventTiming/EventTiming.h
index c057f139bb0..09797f63eed 100644
--- a/Libraries/LibWeb/EventTiming/EventTiming.h
+++ b/Libraries/LibWeb/EventTiming/EventTiming.h
@@ -41,7 +41,7 @@ struct WindowEventTimingState {
bool is_contextmenu_triggered { false };
// eventCounts, a map with entries of the form type → numEvents.
- // NB: This is created along with the Window's Performance object.
+ // NB: This is created when it is first asked for.
GC::Ptr<EventCounts> event_counts;
// interactionCount, an integer which counts the total number of distinct user interactions, for which there was a
@@ -57,6 +57,8 @@ struct WindowEventTimingState {
// of events that are timed.
HTML::Window* relevant_window_of_event_target(DOM::EventTarget&);
+GC::Ref<EventCounts> event_counts(HTML::Window&);
+
// https://w3c.github.io/event-timing/#considered-for-event-timing
bool is_considered_for_event_timing(DOM::Event const&);
diff --git a/Libraries/LibWeb/EventTiming/PerformanceEventTiming.h b/Libraries/LibWeb/EventTiming/PerformanceEventTiming.h
index d17c98b3d99..959bba9f690 100644
--- a/Libraries/LibWeb/EventTiming/PerformanceEventTiming.h
+++ b/Libraries/LibWeb/EventTiming/PerformanceEventTiming.h
@@ -75,23 +75,4 @@ private:
WebIDL::UnsignedLongLong m_interaction_id { 0 };
};
-// NOTE: These two functions are answered by the registry for the given entry type.
-// https://w3c.github.io/timing-entrytypes-registry/#registry
-// NB: PerformanceEventTiming objects have one of two entry types, which the registry answers for separately.
-struct EventEntryTypeRegistry {
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::No; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 150; }
-};
-
-struct FirstInputEntryTypeRegistry {
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 1; }
-};
-
}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index fdd2b469ce8..cd7b60e58f1 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1008,8 +1008,6 @@ class DocumentPaintState;
namespace Web::PerformanceTimeline {
class PerformanceEntry;
-class PerformanceObserver;
-class PerformanceObserverEntryList;
}
diff --git a/Libraries/LibWeb/HTML/VisibilityStateEntry.h b/Libraries/LibWeb/HTML/VisibilityStateEntry.h
index c7beb9da1e1..ce631fd4877 100644
--- a/Libraries/LibWeb/HTML/VisibilityStateEntry.h
+++ b/Libraries/LibWeb/HTML/VisibilityStateEntry.h
@@ -21,15 +21,6 @@ public:
static GC::Ref<VisibilityStateEntry> create(VisibilityState, HighResolutionTime::DOMHighResTimeStamp timestamp);
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 50; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cpp
index 64625a5f9ce..cde215f1495 100644
--- a/Libraries/LibWeb/HTML/Window.cpp
+++ b/Libraries/LibWeb/HTML/Window.cpp
@@ -188,11 +188,6 @@ WebIDL::ExceptionOr<void> initialize_window_web_interfaces(HTML::Window& window,
window_global_mixin.initialize(realm, global_object);
window_global_mixin.define_unforgeable_attributes(realm, global_object);
- // The interface/unforgeable setup above is realm-scoped and must run for every Window wrapper realm.
- // WindowOrWorkerGlobalScopeMixin state is impl-scoped and shared by all worlds for this Window.
- if (&realm == &window.principal_realm())
- window.WindowOrWorkerGlobalScopeMixin::initialize();
-
if (window.is_internals_object_exposed())
Bindings::define_internals_property(realm, window, global_object);
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 1a4d2a0277b..8354f121438 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -9,7 +9,6 @@
#include <AK/Base64.h>
#include <AK/NumericLimits.h>
-#include <AK/QuickSort.h>
#include <AK/StdLibExtras.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
@@ -60,7 +59,6 @@
#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/Performance.h>
-#include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/IndexedDB/IDBFactory.h>
#include <LibWeb/Infra/SerializedURL.h>
@@ -71,10 +69,6 @@
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/PaintTiming/PerformancePaintTiming.h>
#include <LibWeb/Painting/PaintingRustBridge.h>
-#include <LibWeb/PerformanceTimeline/EntryTypes.h>
-#include <LibWeb/PerformanceTimeline/EventNames.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserver.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h>
#include <LibWeb/PermissionsAPI/PermissionStatus.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
@@ -86,8 +80,6 @@
#include <LibWeb/TrustedTypes/TrustedScript.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicyFactory.h>
-#include <LibWeb/UserTiming/PerformanceMark.h>
-#include <LibWeb/UserTiming/PerformanceMeasure.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -111,24 +103,6 @@ namespace Web::HTML {
WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
-void WindowOrWorkerGlobalScopeMixin::initialize()
-{
- bool global_is_window = is<HTML::Window>(this_impl());
-
-#define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class, globals) \
- if (HighResolutionTime::is_supported_for_global(HighResolutionTime::SupportedPerformanceEntryTypeGlobals::globals, global_is_window)) { \
- m_performance_entry_buffer_map.set(entry_type, \
- PerformanceTimeline::PerformanceEntryTuple { \
- .performance_entry_buffer = {}, \
- .max_buffer_size = cpp_class::max_buffer_size(), \
- .available_from_timeline = cpp_class::available_from_timeline(), \
- .dropped_entries_count = 0, \
- }); \
- }
- ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-#undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-}
-
void WindowOrWorkerGlobalScopeMixin::register_permission_status(PermissionsAPI::PermissionStatus& status)
{
m_permission_statuses.append(status);
@@ -136,12 +110,8 @@ void WindowOrWorkerGlobalScopeMixin::register_permission_status(PermissionsAPI::
void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
{
- visitor.visit(m_performance);
visitor.visit(m_timers);
- visitor.visit(m_registered_performance_observer_objects);
visitor.visit(m_indexed_db);
- for (auto& entry : m_performance_entry_buffer_map)
- entry.value.visit_edges(visitor);
visitor.visit(m_registered_event_sources);
visitor.visit(m_strongly_referenced_broadcast_channels);
visitor.visit(m_objects_with_pending_activity);
@@ -155,7 +125,6 @@ void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
}
visitor.visit(m_crypto);
visitor.visit(m_cache_storage);
- visitor.visit(m_resource_timing_secondary_buffer);
visitor.visit(m_trusted_type_policy_factory);
visitor.ignore(m_outstanding_rejected_promises_weak_set);
visitor.visit(m_about_to_be_notified_rejected_promises_list);
@@ -260,6 +229,11 @@ extern "C" {
bool web_canvas_2d_read_back_video_frame(void* video_wrapper, Optional<Gfx::DecodedImageFrame>* out_frame);
// Defined in Bindings/Rust/src/html/exports.rs.
JSCompletion web_rust_structured_clone(JSVM*, void* realm, JSValue, JSObject* const* transfer, size_t count);
+// Defined in Bindings/Rust/src/performance_timeline/exports.rs.
+HighResolutionTime::Performance* web_rust_performance_timeline_performance(JSVM*, void* realm);
+void web_rust_performance_timeline_queue_performance_entry(JSVM*, void* realm, PerformanceTimeline::PerformanceEntry*);
+void web_rust_performance_timeline_add_performance_entry(JSVM*, void* realm, PerformanceTimeline::PerformanceEntry*, bool check_if_performance_buffer_is_full);
+void web_rust_performance_timeline_add_resource_timing_entry(JSVM*, void* realm, PerformanceTimeline::PerformanceEntry*);
}
// https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
@@ -1085,364 +1059,22 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio
return id;
}
-// 1. https://www.w3.org/TR/performance-timeline/#dfn-relevant-performance-entry-tuple
-PerformanceTimeline::PerformanceEntryTuple& WindowOrWorkerGlobalScopeMixin::relevant_performance_entry_tuple(Utf16FlyString const& entry_type)
-{
- // 1. Let map be the performance entry buffer map associated with globalObject.
- // 2. Return the result of getting the value of an entry from map, given entryType as the key.
- auto tuple = m_performance_entry_buffer_map.get(entry_type);
-
- // This shouldn't be called with entry types that aren't in `ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES`.
- VERIFY(tuple.has_value());
- return tuple.value();
-}
-
-// https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
void WindowOrWorkerGlobalScopeMixin::queue_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry)
{
- // 1. Let interested observers be an initially empty set of PerformanceObserver objects.
- Vector<GC::Root<PerformanceTimeline::PerformanceObserver>> interested_observers;
-
- // 2. Let entryType be newEntry’s entryType value.
- auto const& entry_type = new_entry->entry_type();
-
- // 3. Let relevantGlobal be newEntry's relevant global object.
- // NOTE: Already is `this`.
-
- // 4. For each registered performance observer regObs in relevantGlobal's list of registered performance observer
- // objects:
- for (auto const& registered_observer : m_registered_performance_observer_objects) {
- // 1. If regObs's options list contains a PerformanceObserverInit options whose entryTypes member includes entryType
- // or whose type member equals to entryType:
- auto iterator = registered_observer->options_list().find_if([&entry_type](PerformanceTimeline::PerformanceObserverInit const& entry) {
- if (entry.entry_types.has_value())
- return entry.entry_types->contains_slow(entry_type);
-
- VERIFY(entry.type.has_value());
- return entry.type.value() == entry_type;
- });
-
- if (!iterator.is_end()) {
- // 1. If should add entry with newEntry and options returns true, append regObs's observer to interested observers.
- if (new_entry->should_add_entry(*iterator) == PerformanceTimeline::ShouldAddEntry::Yes)
- interested_observers.append(registered_observer);
- }
- }
-
- // 5. For each observer in interested observers:
- for (auto const& observer : interested_observers) {
- // 1. Append newEntry to observer's observer buffer.
- observer->append_to_observer_buffer({}, new_entry);
- }
-
- // AD-HOC: Steps 6-9 are not here because other engines do not add to the performance entry buffer when queuing
- // the performance observer task. The users of the Performance Timeline specification also do not expect
- // this function to add to the entry buffer, instead queuing the observer task, then adding to the entry
- // buffer separately.
-
- // OPTIMIZATION: The PerformanceObserver task delivers only what observers have buffered. An entry that no observer
- // is interested in buffers nothing, so it doesn't queue the task. A document's initial visibility
- // state entry, e.g., then doesn't queue a task for every new document.
- if (interested_observers.is_empty())
- return;
-
- // 10. Queue the PerformanceObserver task with relevantGlobal as input.
- queue_the_performance_observer_task();
+ auto& realm = relevant_realm(*this);
+ web_rust_performance_timeline_queue_performance_entry(JS::HostABI::vm_to_abi(realm.vm()), &realm, new_entry.ptr());
}
-// https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
-// AD-HOC: This is a separate function because the users of this specification queues PerformanceObserver tasks and add
-// to the entry buffer separately.
void WindowOrWorkerGlobalScopeMixin::add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full)
{
- // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal.
- auto& tuple = relevant_performance_entry_tuple(new_entry->entry_type());
-
- // AD-HOC: We have a custom flag to always append to the buffer by default, as other performance specs do this by default
- // (either they don't have a limit, or they check the limit themselves). This flag allows compatibility for specs
- // that rely do and don't rely on this.
- bool is_buffer_full = false;
- auto should_add = PerformanceTimeline::ShouldAddEntry::Yes;
-
- if (check_if_performance_buffer_is_full == CheckIfPerformanceBufferIsFull::Yes) {
- // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple
- // as input.
- is_buffer_full = tuple.is_full();
-
- // 8. Let shouldAdd be the result of should add entry with newEntry as input.
- should_add = new_entry->should_add_entry();
- }
-
- // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer.
- if (!is_buffer_full && should_add == PerformanceTimeline::ShouldAddEntry::Yes)
- tuple.performance_entry_buffer.append(new_entry);
-}
-
-void WindowOrWorkerGlobalScopeMixin::clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, Utf16FlyString const& entry_type)
-{
- auto& tuple = relevant_performance_entry_tuple(entry_type);
- tuple.performance_entry_buffer.clear();
-}
-
-void WindowOrWorkerGlobalScopeMixin::remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, Utf16FlyString const& entry_type, Utf16View entry_name)
-{
- auto& tuple = relevant_performance_entry_tuple(entry_type);
- tuple.performance_entry_buffer.remove_all_matching([&entry_name](GC::Root<PerformanceTimeline::PerformanceEntry> const& entry) {
- return entry->name().utf16_view() == entry_name;
- });
-}
-
-// https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type
-ErrorOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> WindowOrWorkerGlobalScopeMixin::filter_buffer_map_by_name_and_type(Optional<Utf16String> const& name, Optional<Utf16FlyString> type) const
-{
- // 1. Let result be an initially empty list.
- Vector<GC::Root<PerformanceTimeline::PerformanceEntry>> result;
-
- // 2. Let map be the performance entry buffer map associated with the relevant global object of this.
- auto const& map = m_performance_entry_buffer_map;
-
- // 3. Let tuple list be an empty list.
- Vector<PerformanceTimeline::PerformanceEntryTuple const&> tuple_list;
-
- // 4. If type is not null, append the result of getting the value of entry on map given type as key to tuple list.
- // Otherwise, assign the result of get the values on map to tuple list.
- if (type.has_value()) {
- auto maybe_tuple = map.get(type.value());
- if (maybe_tuple.has_value())
- TRY(tuple_list.try_append(maybe_tuple.release_value()));
- } else {
- for (auto const& it : map)
- TRY(tuple_list.try_append(it.value));
- }
-
- // 5. For each tuple in tuple list, run the following steps:
- for (auto const& tuple : tuple_list) {
- // 1. Let buffer be tuple's performance entry buffer.
- auto const& buffer = tuple.performance_entry_buffer;
-
- // 2. If tuple's availableFromTimeline is false, continue to the next tuple.
- if (tuple.available_from_timeline == PerformanceTimeline::AvailableFromTimeline::No)
- continue;
-
- // 3. Let entries be the result of running filter buffer by name and type with buffer, name and type as inputs.
- Optional<Utf16String> type_string;
- if (type.has_value())
- type_string = Utf16String::from_utf16(type->view());
- auto entries = TRY(filter_buffer_by_name_and_type(buffer, name, move(type_string)));
-
- // 4. For each entry in entries, append entry to result.
- TRY(result.try_extend(entries));
- }
-
- // 6. Sort results's entries in chronological order with respect to startTime
- quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
- return left_entry->start_time() < right_entry->start_time();
- });
-
- // 7. Return result.
- return result;
-}
-
-void WindowOrWorkerGlobalScopeMixin::register_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, GC::Ref<PerformanceTimeline::PerformanceObserver> observer)
-{
- m_registered_performance_observer_objects.set(observer, AK::HashSetExistingEntryBehavior::Keep);
-}
-
-void WindowOrWorkerGlobalScopeMixin::unregister_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, GC::Ref<PerformanceTimeline::PerformanceObserver> observer)
-{
- m_registered_performance_observer_objects.remove(observer);
-}
-
-bool WindowOrWorkerGlobalScopeMixin::has_registered_performance_observer(GC::Ref<PerformanceTimeline::PerformanceObserver> observer)
-{
- return m_registered_performance_observer_objects.contains(observer);
+ auto& realm = relevant_realm(*this);
+ web_rust_performance_timeline_add_performance_entry(JS::HostABI::vm_to_abi(realm.vm()), &realm, new_entry.ptr(), check_if_performance_buffer_is_full == CheckIfPerformanceBufferIsFull::Yes);
}
-// https://w3c.github.io/performance-timeline/#dfn-queue-the-performanceobserver-task
-void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()
-{
- // 1. If relevantGlobal's performance observer task queued flag is set, terminate these steps.
- if (m_performance_observer_task_queued)
- return;
-
- // 2. Set relevantGlobal's performance observer task queued flag.
- m_performance_observer_task_queued = true;
-
- // 3. Queue a task that consists of running the following substeps. The task source for the queued task is the performance
- // timeline task source.
- queue_global_task(Task::Source::PerformanceTimeline, relevant_global_object(*this), GC::create_function(GC::Heap::the(), GC::captures(this_impl()), [](auto& this_object) {
- auto& self = as<WindowOrWorkerGlobalScopeMixin>(this_object);
- auto& realm = relevant_realm(self);
- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
-
- // 1. Unset performance observer task queued flag of relevantGlobal.
- self.m_performance_observer_task_queued = false;
-
- // 2. Let notifyList be a copy of relevantGlobal's list of registered performance observer objects.
- GC::RootVector notify_list { self.m_registered_performance_observer_objects.values() };
-
- // 3. For each registered performance observer object registeredObserver in notifyList, run these steps:
- for (auto& registered_observer : notify_list) {
- // 1. Let po be registeredObserver's observer.
- // 2. Let entries be a copy of po’s observer buffer.
- // 4. Empty po’s observer buffer.
- auto entries = registered_observer->take_records();
-
- // 3. If entries is empty, return.
- // FIXME: Do they mean `continue`?
- if (entries.is_empty())
- continue;
-
- GC::RootVector<GC::Ref<PerformanceTimeline::PerformanceEntry>> entries_as_gc_ptrs;
- for (auto& entry : entries)
- entries_as_gc_ptrs.append(*entry);
-
- // 5. Let observerEntryList be a new PerformanceObserverEntryList, with its entry list set to entries.
- auto observer_entry_list = PerformanceTimeline::PerformanceObserverEntryList::create(move(entries_as_gc_ptrs));
-
- // 6. Let droppedEntriesCount be null.
- Optional<u64> dropped_entries_count;
-
- // 7. If po's requires dropped entries is set, perform the following steps:
- if (registered_observer->requires_dropped_entries()) {
- // 1. Set droppedEntriesCount to 0.
- dropped_entries_count = 0;
-
- // 2. For each PerformanceObserverInit item in registeredObserver's options list:
- for (auto const& item : registered_observer->options_list()) {
- // 1. For each DOMString entryType that appears either as item's type or in item's entryTypes:
- auto increment_dropped_entries_count = [&self, &dropped_entries_count](Utf16FlyString const& type) {
- // 1. Let map be relevantGlobal's performance entry buffer map.
- auto const& map = self.m_performance_entry_buffer_map;
-
- // 2. Let tuple be the result of getting the value of entry on map given entryType as key.
- auto const& tuple = map.get(type);
- VERIFY(tuple.has_value());
-
- // 3. Increase droppedEntriesCount by tuple's dropped entries count.
- dropped_entries_count.value() += tuple->dropped_entries_count;
- };
-
- if (item.type.has_value()) {
- increment_dropped_entries_count(item.type.value());
- } else {
- VERIFY(item.entry_types.has_value());
- for (auto const& type : item.entry_types.value())
- increment_dropped_entries_count(type);
- }
- }
-
- // 3. Set po's requires dropped entries to false.
- registered_observer->unset_requires_dropped_entries({});
- }
-
- // 8. Let callbackOptions be a PerformanceObserverCallbackOptions with its droppedEntriesCount set to
- // droppedEntriesCount if droppedEntriesCount is not null, otherwise unset.
- // 9. Call po’s observer callback with observerEntryList as the first argument, with po as the second
- // argument and as callback this value, and with callbackOptions as the third argument.
- // If this throws an exception, report the exception.
- auto completion = registered_observer->invoke_callback(observer_entry_list, dropped_entries_count);
- if (completion.is_abrupt())
- HTML::report_exception(completion, realm);
- }
- }));
-}
-
-// https://w3c.github.io/resource-timing/#dfn-add-a-performanceresourcetiming-entry
void WindowOrWorkerGlobalScopeMixin::add_resource_timing_entry(Badge<ResourceTiming::PerformanceResourceTiming>, GC::Ref<ResourceTiming::PerformanceResourceTiming> entry)
{
- // 1. If can add resource timing entry returns true and resource timing buffer full event pending flag is false,
- // run the following substeps:
- if (can_add_resource_timing_entry() && !m_resource_timing_buffer_full_event_pending) {
- // a. Add new entry to the performance entry buffer.
- // b. Increase resource timing buffer current size by 1.
- add_performance_entry(entry);
-
- // c. Return.
- return;
- }
-
- // 2. If resource timing buffer full event pending flag is false, run the following substeps:
- if (!m_resource_timing_buffer_full_event_pending) {
- // a. Set resource timing buffer full event pending flag to true.
- m_resource_timing_buffer_full_event_pending = true;
-
- // b. Queue a task on the performance timeline task source to run fire a buffer full event.
- HTML::queue_a_task(HTML::Task::Source::PerformanceTimeline, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(this_impl()), [](auto& this_object) {
- as<WindowOrWorkerGlobalScopeMixin>(this_object).fire_resource_timing_buffer_full_event();
- }));
- }
-
- // 3. Add new entry to the resource timing secondary buffer.
- // 4. Increase resource timing secondary buffer current size by 1.
- m_resource_timing_secondary_buffer.append(entry);
-}
-
-// https://w3c.github.io/resource-timing/#dfn-can-add-resource-timing-entry
-bool WindowOrWorkerGlobalScopeMixin::can_add_resource_timing_entry()
-{
- // 1. If resource timing buffer current size is smaller than resource timing buffer size limit, return true.
- // 2. Return false.
- return resource_timing_buffer_current_size() < m_resource_timing_buffer_size_limit;
-}
-
-// https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-current-size
-size_t WindowOrWorkerGlobalScopeMixin::resource_timing_buffer_current_size()
-{
- // A resource timing buffer current size which is initially 0.
- auto const& resource_timing_tuple = relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::resource);
- return resource_timing_tuple.performance_entry_buffer.size();
-}
-
-// https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event
-void WindowOrWorkerGlobalScopeMixin::fire_resource_timing_buffer_full_event()
-{
- // 1. While resource timing secondary buffer is not empty, run the following substeps:
- while (!m_resource_timing_secondary_buffer.is_empty()) {
- // 1. Let number of excess entries before be resource timing secondary buffer current size.
- auto number_of_excess_entries_before = m_resource_timing_secondary_buffer.size();
-
- // 2. If can add resource timing entry returns false, then fire an event named resourcetimingbufferfull at the Performance object.
- if (!can_add_resource_timing_entry()) {
- auto full_event = DOM::Event::create(PerformanceTimeline::EventNames::resourcetimingbufferfull,
- HighResolutionTime::current_high_resolution_time(relevant_global_object(*this)));
- performance()->dispatch_event(full_event);
- }
-
- // 3. Run copy secondary buffer.
- copy_resource_timing_secondary_buffer();
-
- // 4. Let number of excess entries after be resource timing secondary buffer current size.
- auto number_of_excess_entries_after = m_resource_timing_secondary_buffer.size();
-
- // 5. If number of excess entries before is lower than or equals number of excess entries after, then remove
- // all entries from resource timing secondary buffer, set resource timing secondary buffer current size to
- // 0, and abort these steps.
- if (number_of_excess_entries_before <= number_of_excess_entries_after) {
- m_resource_timing_secondary_buffer.clear();
- break;
- }
- }
-
- // 2. Set resource timing buffer full event pending flag to false.
- m_resource_timing_buffer_full_event_pending = false;
-}
-
-// https://w3c.github.io/resource-timing/#dfn-copy-secondary-buffer
-void WindowOrWorkerGlobalScopeMixin::copy_resource_timing_secondary_buffer()
-{
- // 1. While resource timing secondary buffer is not empty and can add resource timing entry returns true,
- // run the following substeps:
- while (!m_resource_timing_secondary_buffer.is_empty() && can_add_resource_timing_entry()) {
- // 1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
- // 2. Add entry to the end of performance entry buffer.
- // 3. Increment resource timing buffer current size by 1.
- // 4. Remove entry from resource timing secondary buffer.
- // 5. Decrement resource timing secondary buffer current size by 1.
- auto entry = m_resource_timing_secondary_buffer.take_first();
- auto& resource_tuple = relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::resource);
- resource_tuple.performance_entry_buffer.append(entry);
- }
+ auto& realm = relevant_realm(*this);
+ web_rust_performance_timeline_add_resource_timing_entry(JS::HostABI::vm_to_abi(realm.vm()), &realm, entry.ptr());
}
void WindowOrWorkerGlobalScopeMixin::register_event_source(Badge<EventSource>, GC::Ref<EventSource> event_source)
@@ -1828,9 +1460,8 @@ void WindowOrWorkerGlobalScopeMixin::notify_about_rejected_promises(Badge<EventL
// https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
GC::Ref<HighResolutionTime::Performance> WindowOrWorkerGlobalScopeMixin::performance()
{
- if (!m_performance)
- m_performance = GC::Heap::the().allocate<HighResolutionTime::Performance>(this_impl());
- return GC::Ref { *m_performance };
+ auto& realm = relevant_realm(*this);
+ return *web_rust_performance_timeline_performance(JS::HostABI::vm_to_abi(realm.vm()), &realm);
}
GC::Ref<IndexedDB::IDBFactory> WindowOrWorkerGlobalScopeMixin::indexed_db()
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
index b25e0d124a8..490347f77d7 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
@@ -22,7 +22,6 @@
#include <LibWeb/HTML/Scripting/ImportMap.h>
#include <LibWeb/HTML/Timer.h>
#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
-#include <LibWeb/PerformanceTimeline/PerformanceEntryTuple.h>
#include <LibWeb/WebSockets/WebSocket.h>
namespace Web::HTML {
@@ -65,21 +64,9 @@ public:
Yes,
};
- PerformanceTimeline::PerformanceEntryTuple& relevant_performance_entry_tuple(Utf16FlyString const& entry_type);
void queue_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry);
void add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full = CheckIfPerformanceBufferIsFull::No);
- void clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, Utf16FlyString const& entry_type);
- void remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, Utf16FlyString const& entry_type, Utf16View entry_name);
- ErrorOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> filter_buffer_map_by_name_and_type(Optional<Utf16String> const& name, Optional<Utf16FlyString> type) const;
-
- void register_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, GC::Ref<PerformanceTimeline::PerformanceObserver>);
- void unregister_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, GC::Ref<PerformanceTimeline::PerformanceObserver>);
- bool has_registered_performance_observer(GC::Ref<PerformanceTimeline::PerformanceObserver>);
-
- void queue_the_performance_observer_task();
-
- void set_resource_timing_buffer_size_limit(Badge<HighResolutionTime::Performance>, u32 value) { m_resource_timing_buffer_size_limit = value; }
void add_resource_timing_entry(Badge<ResourceTiming::PerformanceResourceTiming>, GC::Ref<ResourceTiming::PerformanceResourceTiming> entry);
void register_event_source(Badge<EventSource>, GC::Ref<EventSource>);
@@ -150,7 +137,6 @@ public:
[[nodiscard]] GC::Ref<TrustedTypes::TrustedTypePolicyFactory> trusted_types();
protected:
- void initialize();
void visit_edges(JS::Cell::Visitor&);
void finalize();
@@ -171,11 +157,6 @@ private:
void create_image_bitmap_impl(JS::Realm&, GC::Ref<WebIDL::Promise>, ImageBitmapSource& image, Optional<WebIDL::Long> sx, Optional<WebIDL::Long> sy, Optional<WebIDL::Long> sw, Optional<WebIDL::Long> sh, ImageBitmapOptions options) const;
- size_t resource_timing_buffer_current_size();
- bool can_add_resource_timing_entry();
- void fire_resource_timing_buffer_full_event();
- void copy_resource_timing_secondary_buffer();
-
IDAllocator m_timer_id_allocator;
HashMap<int, GC::Ref<Timer>> m_timers;
double m_earliest_timer_deadline { NumericLimits<double>::max() };
@@ -193,19 +174,6 @@ private:
// When a chained timer last ran while the document was hidden (see throttled_timer_delay()).
Optional<double> m_last_chained_timer_wake_up;
- // https://www.w3.org/TR/performance-timeline/#performance-timeline
- // Each global object has:
- // - a performance observer task queued flag
- bool m_performance_observer_task_queued { false };
-
- // - a list of registered performance observer objects that is initially empty
- OrderedHashTable<GC::Ref<PerformanceTimeline::PerformanceObserver>> m_registered_performance_observer_objects;
-
- // https://www.w3.org/TR/performance-timeline/#dfn-performance-entry-buffer-map
- // a performance entry buffer map map, keyed on a DOMString, representing the entry type to which the buffer belongs. The map's value is the following tuple:
- // NOTE: See the PerformanceEntryTuple struct above for the map's value tuple.
- OrderedHashMap<Utf16FlyString, PerformanceTimeline::PerformanceEntryTuple> m_performance_entry_buffer_map;
-
HashTable<GC::Ref<EventSource>> m_registered_event_sources;
// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts
@@ -214,8 +182,6 @@ private:
HashTable<GC::Ref<DOM::EventTarget>> m_strongly_referenced_broadcast_channels;
Vector<GC::Weak<PermissionsAPI::PermissionStatus>> m_permission_statuses;
- GC::Ptr<HighResolutionTime::Performance> m_performance;
-
GC::Ptr<IndexedDB::IDBFactory> m_indexed_db;
GC::Ptr<Crypto::Crypto> m_crypto;
@@ -232,24 +198,6 @@ private:
// keeps alive. They're held here rather than rooted, so they can't keep their global alive.
HashTable<GC::Ref<DOM::EventTarget>> m_objects_with_pending_activity;
- // https://w3c.github.io/resource-timing/#sec-extensions-performance-interface
- // Each ECMAScript global environment has:
- // https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-size-limit
- // A resource timing buffer size limit which should initially be 250 or greater.
- // The recommended minimum number of PerformanceResourceTiming objects is 250, though this may be changed by the
- // user agent. setResourceTimingBufferSize can be called to request a change to this limit.
- u32 m_resource_timing_buffer_size_limit { 250 };
-
- // https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-full-event-pending-flag
- // A resource timing buffer full event pending flag which is initially false.
- bool m_resource_timing_buffer_full_event_pending { false };
-
- // https://w3c.github.io/resource-timing/#dfn-resource-timing-secondary-buffer-current-size
- // A resource timing secondary buffer current size which is initially 0.
- // https://w3c.github.io/resource-timing/#dfn-resource-timing-secondary-buffer
- // A resource timing secondary buffer to store PerformanceResourceTiming objects that is initially empty.
- Vector<GC::Ref<ResourceTiming::PerformanceResourceTiming>> m_resource_timing_secondary_buffer;
-
// https://html.spec.whatwg.org/multipage/webappapis.html#about-to-be-notified-rejected-promises-list
GC::Ptr<GC::HeapVector<GC::Ref<JS::Promise>>> m_about_to_be_notified_rejected_promises_list;
diff --git a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
index a6ea0b980f8..ee2499e404d 100644
--- a/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WorkerGlobalScope.cpp
@@ -69,8 +69,6 @@ JS::Realm& WorkerGlobalScope::realm() const
void WorkerGlobalScope::initialize_web_interfaces_impl()
{
- WindowOrWorkerGlobalScopeMixin::initialize();
-
m_navigator = WorkerNavigator::create(*this);
}
diff --git a/Libraries/LibWeb/HighResolutionTime/Performance.cpp b/Libraries/LibWeb/HighResolutionTime/Performance.cpp
deleted file mode 100644
index d7a595ec4c2..00000000000
--- a/Libraries/LibWeb/HighResolutionTime/Performance.cpp
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- * Copyright (c) 2020, Andreas Kling <[email protected]>
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/Performance.h>
-#include <LibWeb/Bindings/PerformanceMeasure.h>
-#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/DOM/EventDispatcher.h>
-#include <LibWeb/EventTiming/EventCounts.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HighResolutionTime/Performance.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/NavigationTiming/EntryNames.h>
-#include <LibWeb/NavigationTiming/PerformanceNavigation.h>
-#include <LibWeb/NavigationTiming/PerformanceTiming.h>
-#include <LibWeb/PerformanceTimeline/EntryTypes.h>
-#include <LibWeb/PerformanceTimeline/EventNames.h>
-
-namespace Web::HighResolutionTime {
-
-GC_DEFINE_ALLOCATOR(Performance);
-
-Performance::Performance(GC::Ref<DOM::EventTarget> relevant_global_object)
- : DOM::EventTarget()
- , m_global_object(relevant_global_object)
-{
-}
-
-Performance::~Performance() = default;
-
-void Performance::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_navigation);
- visitor.visit(m_timing);
- visitor.visit(m_global_object);
-}
-
-GC::Ptr<NavigationTiming::PerformanceTiming> Performance::timing()
-{
- if (!m_timing) {
- auto* window = HTML::window_from_global_object(relevant_global_object());
- VERIFY(window);
- m_timing = NavigationTiming::PerformanceTiming::create(*window);
- }
- return m_timing;
-}
-
-GC::Ptr<NavigationTiming::PerformanceNavigation> Performance::navigation()
-{
- if (!m_navigation) {
- auto* window = HTML::window_from_global_object(relevant_global_object());
- VERIFY(window);
- m_navigation = NavigationTiming::PerformanceNavigation::create(*window);
- }
- return m_navigation;
-}
-
-// https://w3c.github.io/event-timing/#dom-performance-eventcounts
-GC::Ref<EventTiming::EventCounts> Performance::event_counts()
-{
- // The eventCounts attribute's getter returns this's relevant global object's eventCounts.
- auto* window = HTML::window_from_global_object(relevant_global_object());
- VERIFY(window);
- auto& event_counts = window->event_timing_state().event_counts;
- // NB: The eventCounts of a Window are created along with its Performance object, which is when they are first
- // asked for.
- if (!event_counts)
- event_counts = EventTiming::EventCounts::create();
- return *event_counts;
-}
-
-// https://w3c.github.io/event-timing/#dom-performance-interactioncount
-WebIDL::UnsignedLongLong Performance::interaction_count()
-{
- // The interactionCount attribute's getter returns this's relevant global object's interactionCount.
- auto* window = HTML::window_from_global_object(relevant_global_object());
- VERIFY(window);
- return window->event_timing_state().interaction_count;
-}
-
-// https://w3c.github.io/hr-time/#timeorigin-attribute
-double Performance::time_origin() const
-{
- // The timeOrigin attribute MUST return the number of milliseconds in the duration returned by get time origin timestamp for the relevant global object of this.
- return get_time_origin_timestamp(relevant_global_object());
-}
-
-// https://w3c.github.io/hr-time/#now-method
-double Performance::now() const
-{
- // The now() method MUST return the number of milliseconds in the current high resolution time given this's relevant global object (a duration).
- return current_high_resolution_time(relevant_global_object());
-}
-
-// https://w3c.github.io/user-timing/#mark-method
-WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMark>> Performance::mark(Utf16String const& mark_name, Bindings::PerformanceMarkOptions const& mark_options)
-{
- // 1. Run the PerformanceMark constructor and let entry be the newly created object.
- auto entry = TRY(UserTiming::PerformanceMark::create_for_constructor(relevant_global_object(), mark_name, mark_options));
-
- // 2. Queue entry.
- window_or_worker().queue_performance_entry(entry);
-
- // 3. Add entry to the performance entry buffer.
- window_or_worker().add_performance_entry(entry);
-
- // 4. Return entry.
- return entry;
-}
-
-void Performance::clear_marks(Optional<Utf16String> const& mark_name)
-{
- // 1. If markName is omitted, remove all PerformanceMark objects from the performance entry buffer.
- if (!mark_name.has_value()) {
- window_or_worker().clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark);
- return;
- }
-
- // 2. Otherwise, remove all PerformanceMark objects listed in the performance entry buffer whose name is markName.
- window_or_worker().remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::mark, mark_name.value());
-
- // 3. Return undefined.
-}
-
-WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::convert_name_to_timestamp(Utf16String const& name)
-{
- // 1. If the global object is not a Window object, throw a TypeError.
- if (!HTML::window_from_global_object(relevant_global_object()))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is an attribute in the PerformanceTiming interface and thus can only be used in a Window context", name) };
-
- // 2. If name is navigationStart, return 0.
- if (name.utf16_view() == NavigationTiming::EntryNames::navigationStart.view())
- return 0.0;
-
- auto timing_interface = timing();
- VERIFY(timing_interface);
-
- // 3. Let startTime be the value of navigationStart in the PerformanceTiming interface.
- auto start_time = timing_interface->navigation_start();
-
- // 4. Let endTime be the value of name in the PerformanceTiming interface.
- u64 end_time { 0 };
-
-#define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(camel_case_name, snake_case_name) \
- if (name.utf16_view() == NavigationTiming::EntryNames::camel_case_name.view()) \
- end_time = timing_interface->snake_case_name();
- ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
-#undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
-
- // 5. If endTime is 0, throw an InvalidAccessError.
- if (end_time == 0)
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("The '{}' entry in the PerformanceTiming interface is equal to 0, meaning it hasn't happened yet", name));
-
- // 6. Return result of subtracting startTime from endTime.
- return static_cast<HighResolutionTime::DOMHighResTimeStamp>(end_time - start_time);
-}
-
-// https://w3c.github.io/user-timing/#dfn-convert-a-mark-to-a-timestamp
-WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> Performance::convert_mark_to_timestamp(Variant<Utf16String, HighResolutionTime::DOMHighResTimeStamp> const& mark)
-{
- if (mark.has<Utf16String>()) {
- auto const& mark_string = mark.get<Utf16String>();
-
- // 1. If mark is a DOMString and it has the same name as a read only attribute in the PerformanceTiming interface, let end
- // time be the value returned by running the convert a name to a timestamp algorithm with name set to the value of mark.
-#define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(name, _) \
- if (mark_string.utf16_view() == NavigationTiming::EntryNames::name.view()) \
- return convert_name_to_timestamp(mark_string);
- ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
-#undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
-
- // 2. Otherwise, if mark is a DOMString, let end time be the value of the startTime attribute from the most recent occurrence
- // of a PerformanceMark object in the performance entry buffer whose name is mark. If no matching entry is found, throw a
- // SyntaxError.
- auto& tuple = window_or_worker().relevant_performance_entry_tuple(PerformanceTimeline::EntryTypes::mark);
- auto& performance_entry_buffer = tuple.performance_entry_buffer;
-
- auto maybe_entry = performance_entry_buffer.last_matching([&mark_string](GC::Root<PerformanceTimeline::PerformanceEntry> const& entry) {
- return entry->name().utf16_view() == mark_string.utf16_view();
- });
-
- if (!maybe_entry.has_value())
- return WebIDL::SyntaxError::create(Utf16String::formatted("No PerformanceMark object with name '{}' found in the performance timeline", mark_string));
-
- return maybe_entry.value()->start_time();
- }
-
- // 3. Otherwise, if mark is a DOMHighResTimeStamp:
- auto mark_time_stamp = mark.get<HighResolutionTime::DOMHighResTimeStamp>();
-
- // 1. If mark is negative, throw a TypeError.
- if (mark_time_stamp < 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot have negative time values in PerformanceMark"_utf16 };
-
- // 2. Otherwise, let end time be mark.
- return mark_time_stamp;
-}
-
-// https://w3c.github.io/user-timing/#dom-performance-measure
-WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMeasure>> Performance::measure(Utf16String const& measure_name, Variant<Utf16String, Bindings::PerformanceMeasureOptions> const& start_or_measure_options, Optional<Utf16String> end_mark)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object());
- auto& vm = realm.vm();
- // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object and at least one of start, end, duration, and detail
- // are present, run the following checks:
- auto const* options = start_or_measure_options.get_pointer<Bindings::PerformanceMeasureOptions>();
- if (options
- && (options->start.has_value()
- || options->end.has_value()
- || options->duration.has_value()
- || options->detail.has_value())) {
- // 1. If endMark is given, throw a TypeError.
- if (end_mark.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot provide PerformanceMeasureOptions and endMark at the same time"_utf16 };
-
- // 2. If startOrMeasureOptions's start and end members are both omitted, throw a TypeError.
- if (!options->start.has_value() && !options->end.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "PerformanceMeasureOptions must contain one or both of 'start' and 'end'"_utf16 };
-
- // 3. If startOrMeasureOptions's start, duration, and end members are all present, throw a TypeError.
- if (options->start.has_value() && options->end.has_value() && options->duration.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "PerformanceMeasureOptions cannot contain 'start', 'duration' and 'end' properties all at once"_utf16 };
- }
-
- // 2. Compute end time as follows:
- HighResolutionTime::DOMHighResTimeStamp end_time { 0.0 };
-
- // 1. If endMark is given, let end time be the value returned by running the convert a mark to a timestamp algorithm passing
- // in endMark.
- if (end_mark.has_value()) {
- end_time = TRY(convert_mark_to_timestamp(end_mark.value()));
- }
- // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its end member is present, let end
- // time be the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's end.
- else if (options && options->end.has_value()) {
- end_time = TRY(convert_mark_to_timestamp(options->end.value()));
- }
- // 3. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start and duration members are
- // both present:
- else if (options && options->start.has_value() && options->duration.has_value()) {
- // 1. Let start be the value returned by running the convert a mark to a timestamp algorithm passing in start.
- auto start = TRY(convert_mark_to_timestamp(options->start.value()));
-
- // 2. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
- auto duration = TRY(convert_mark_to_timestamp(options->duration.value()));
-
- // 3. Let end time be start plus duration.
- end_time = start + duration;
- }
- // 4. Otherwise, let end time be the value that would be returned by the Performance object's now() method.
- else {
- end_time = now();
- }
-
- // 3. Compute start time as follows:
- HighResolutionTime::DOMHighResTimeStamp start_time { 0.0 };
-
- // 1. If startOrMeasureOptions is a PerformanceMeasureOptions object, and if its start member is present, let start time be
- // the value returned by running the convert a mark to a timestamp algorithm passing in startOrMeasureOptions's start.
- if (options && options->start.has_value()) {
- start_time = TRY(convert_mark_to_timestamp(options->start.value()));
- }
- // 2. Otherwise, if startOrMeasureOptions is a PerformanceMeasureOptions object, and if its duration and end members are
- // both present:
- else if (options && options->duration.has_value() && options->end.has_value()) {
- // 1. Let duration be the value returned by running the convert a mark to a timestamp algorithm passing in duration.
- auto duration = TRY(convert_mark_to_timestamp(options->duration.value()));
-
- // 2. Let end be the value returned by running the convert a mark to a timestamp algorithm passing in end.
- auto end = TRY(convert_mark_to_timestamp(options->end.value()));
-
- // 3. Let start time be end minus duration.
- start_time = end - duration;
- }
- // 3. Otherwise, if startOrMeasureOptions is a DOMString, let start time be the value returned by running the convert a mark
- // to a timestamp algorithm passing in startOrMeasureOptions.
- else if (start_or_measure_options.has<Utf16String>()) {
- start_time = TRY(convert_mark_to_timestamp(start_or_measure_options.get<Utf16String>()));
- }
- // 4. Otherwise, let start time be 0.
- else {
- start_time = 0.0;
- }
-
- // NOTE: Step 4 (creating the entry) is done after determining values, as we set the values once during creation and never
- // change them after.
-
- // 5. Set entry's name attribute to measureName.
- // NOTE: Will be done during construction.
-
- // 6. Set entry's entryType attribute to DOMString "measure".
- // NOTE: Already done via the `entry_type` virtual function.
-
- // 7. Set entry's startTime attribute to start time.
- // NOTE: Will be done during construction.
-
- // 8. Set entry's duration attribute to the duration from start time to end time. The resulting duration value MAY be negative.
- auto duration = end_time - start_time;
-
- // 4. Create a new PerformanceMeasure object (entry).
- JS::Value detail = JS::js_null();
- if (options && options->detail.has_value() && !options->detail->is_null()) {
- auto record = TRY(HTML::structured_serialize(vm, *options->detail));
- detail = TRY(HTML::structured_deserialize(vm, record, realm));
- }
- auto entry = UserTiming::PerformanceMeasure::create(measure_name, start_time, duration, detail);
-
- // 10. Queue entry.
- window_or_worker().queue_performance_entry(entry);
-
- // 11. Add entry to the performance entry buffer.
- window_or_worker().add_performance_entry(entry);
-
- // 12. Return entry.
- return entry;
-}
-
-// https://w3c.github.io/user-timing/#dom-performance-clearmeasures
-void Performance::clear_measures(Optional<Utf16String> const& measure_name)
-{
- // 1. If measureName is omitted, remove all PerformanceMeasure objects in the performance entry buffer.
- if (!measure_name.has_value()) {
- window_or_worker().clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure);
- return;
- }
-
- // 2. Otherwise remove all PerformanceMeasure objects listed in the performance entry buffer whose name is measureName.
- window_or_worker().remove_entries_from_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::measure, measure_name.value());
-
- // 3. Return undefined.
-}
-
-// https://w3c.github.io/resource-timing/#dom-performance-clearresourcetimings
-void Performance::clear_resource_timings()
-{
- // 1. Remove all PerformanceResourceTiming objects in the performance entry buffer.
- // 2. Set resource timing buffer current size to 0.
- window_or_worker().clear_performance_entry_buffer({}, PerformanceTimeline::EntryTypes::resource);
-}
-
-// https://w3c.github.io/resource-timing/#dom-performance-setresourcetimingbuffersize
-void Performance::set_resource_timing_buffer_size(u32 max_size)
-{
- // 1. Set resource timing buffer size limit to the maxSize parameter. If the maxSize parameter is less than
- // resource timing buffer current size, no PerformanceResourceTiming objects are to be removed from the
- // performance entry buffer.
- window_or_worker().set_resource_timing_buffer_size_limit({}, max_size);
-}
-
-// https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
-void Performance::set_onresourcetimingbufferfull(WebIDL::CallbackType* event_handler)
-{
- set_event_handler_attribute(PerformanceTimeline::EventNames::resourcetimingbufferfull, event_handler);
-}
-
-// https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull
-WebIDL::CallbackType* Performance::onresourcetimingbufferfull()
-{
- return event_handler_attribute(PerformanceTimeline::EventNames::resourcetimingbufferfull);
-}
-
-// https://www.w3.org/TR/performance-timeline/#getentries-method
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries() const
-{
- auto& vm = this->vm();
-
- // Returns a PerformanceEntryList object returned by the filter buffer map by name and type algorithm with name and
- // type set to null.
- return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(/* name= */ Optional<Utf16String> {}, /* type= */ Optional<Utf16FlyString> {}));
-}
-
-// https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbytype
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_type(Utf16FlyString const& type) const
-{
- auto& vm = this->vm();
-
- // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to null,
- // and type set to the method's input type parameter.
- return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(/* name= */ Optional<Utf16String> {}, type));
-}
-
-// https://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbyname
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> Performance::get_entries_by_name(Utf16String const& name, Optional<Utf16FlyString> type) const
-{
- auto& vm = this->vm();
-
- // Returns a PerformanceEntryList object returned by filter buffer map by name and type algorithm with name set to the
- // method input name parameter, and type set to null if optional entryType is omitted, or set to the method's input type
- // parameter otherwise.
- return TRY_OR_THROW_OOM(vm, window_or_worker().filter_buffer_map_by_name_and_type(name, type));
-}
-
-HTML::WindowOrWorkerGlobalScopeMixin& Performance::window_or_worker()
-{
- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object());
- VERIFY(global_scope);
- return *global_scope;
-}
-
-HTML::WindowOrWorkerGlobalScopeMixin const& Performance::window_or_worker() const
-{
- return const_cast<Performance*>(this)->window_or_worker();
-}
-
-JS::Object& Performance::relevant_global_object() const
-{
- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));
-}
-
-}
diff --git a/Libraries/LibWeb/HighResolutionTime/Performance.h b/Libraries/LibWeb/HighResolutionTime/Performance.h
index 0d6c9d5b436..63c4a77db6e 100644
--- a/Libraries/LibWeb/HighResolutionTime/Performance.h
+++ b/Libraries/LibWeb/HighResolutionTime/Performance.h
@@ -7,62 +7,13 @@
#pragma once
-#include <AK/Utf16FlyString.h>
-#include <LibCore/ElapsedTimer.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/PerformanceMark.h>
-#include <LibWeb/Bindings/PerformanceMeasure.h>
-#include <LibWeb/DOM/EventTarget.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/UserTiming/PerformanceMark.h>
-#include <LibWeb/UserTiming/PerformanceMeasure.h>
+#include <LibWeb/Bindings/Performance.h>
+#include <LibWeb/Bindings/RustInterface.h>
namespace Web::HighResolutionTime {
-class Performance final : public DOM::EventTarget {
- WEB_WRAPPABLE(Performance, DOM::EventTarget);
- GC_DECLARE_ALLOCATOR(Performance);
-
-public:
- virtual ~Performance() override;
-
- double now() const;
- double time_origin() const;
-
- WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMark>> mark(Utf16String const& mark_name, Bindings::PerformanceMarkOptions const& mark_options = {});
- void clear_marks(Optional<Utf16String> const& mark_name);
- WebIDL::ExceptionOr<GC::Ref<UserTiming::PerformanceMeasure>> measure(Utf16String const& measure_name, Variant<Utf16String, Bindings::PerformanceMeasureOptions> const& start_or_measure_options, Optional<Utf16String> end_mark);
- void clear_measures(Optional<Utf16String> const& measure_name);
-
- void clear_resource_timings();
- void set_resource_timing_buffer_size(u32 max_size);
- void set_onresourcetimingbufferfull(WebIDL::CallbackType*);
- WebIDL::CallbackType* onresourcetimingbufferfull();
-
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries() const;
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries_by_type(Utf16FlyString const& type) const;
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries_by_name(Utf16String const& name, Optional<Utf16FlyString> type) const;
-
- GC::Ptr<NavigationTiming::PerformanceTiming> timing();
- GC::Ptr<NavigationTiming::PerformanceNavigation> navigation();
-
- GC::Ref<EventTiming::EventCounts> event_counts();
- WebIDL::UnsignedLongLong interaction_count();
-
-private:
- explicit Performance(GC::Ref<DOM::EventTarget> relevant_global_object);
-
- HTML::WindowOrWorkerGlobalScopeMixin& window_or_worker();
- HTML::WindowOrWorkerGlobalScopeMixin const& window_or_worker() const;
- JS::Object& relevant_global_object() const;
- virtual void visit_edges(Cell::Visitor&) override;
-
- WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> convert_name_to_timestamp(Utf16String const& name);
- WebIDL::ExceptionOr<HighResolutionTime::DOMHighResTimeStamp> convert_mark_to_timestamp(Variant<Utf16String, HighResolutionTime::DOMHighResTimeStamp> const& mark);
-
- GC::Ptr<NavigationTiming::PerformanceNavigation> m_navigation;
- GC::Ptr<NavigationTiming::PerformanceTiming> m_timing;
- GC::Ref<DOM::EventTarget> m_global_object;
+class Performance final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Performance, performance)
};
}
diff --git a/Libraries/LibWeb/HighResolutionTime/Performance.idl b/Libraries/LibWeb/HighResolutionTime/Performance.idl
index 88384cdcd33..c25e6981598 100644
--- a/Libraries/LibWeb/HighResolutionTime/Performance.idl
+++ b/Libraries/LibWeb/HighResolutionTime/Performance.idl
@@ -7,7 +7,7 @@ partial interface mixin WindowOrWorkerGlobalScope {
typedef sequence<PerformanceEntry> PerformanceEntryList;
// https://w3c.github.io/hr-time/#sec-performance
-[Exposed=(Window, Worker)]
+[Exposed=(Window, Worker), ImplementedIn=Rust]
interface Performance : EventTarget {
DOMHighResTimeStamp now();
readonly attribute DOMHighResTimeStamp timeOrigin;
@@ -29,6 +29,6 @@ interface Performance : EventTarget {
// https://w3c.github.io/performance-timeline/#extensions-to-the-performance-interface
// "Performance Timeline" extensions to the Performance interface
PerformanceEntryList getEntries();
- PerformanceEntryList getEntriesByType([FlyString] DOMString type);
- PerformanceEntryList getEntriesByName(DOMString name, optional [FlyString] DOMString type);
+ PerformanceEntryList getEntriesByType(DOMString type);
+ PerformanceEntryList getEntriesByName(DOMString name, optional DOMString type);
};
diff --git a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h b/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
deleted file mode 100644
index 327db52cf50..00000000000
--- a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace Web::HighResolutionTime {
-
-// The global objects an entry type is supported for.
-enum class SupportedPerformanceEntryTypeGlobals {
- WindowAndWorker,
- WindowOnly,
-};
-
-inline bool is_supported_for_global(SupportedPerformanceEntryTypeGlobals globals, bool global_is_window)
-{
- return globals == SupportedPerformanceEntryTypeGlobals::WindowAndWorker || global_is_window;
-}
-
-// Please keep these in alphabetical order based on the entry type :^)
-#define ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::event, EventTiming::EventEntryTypeRegistry, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::first_input, EventTiming::FirstInputEntryTypeRegistry, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::largest_contentful_paint, LargestContentfulPaint::LargestContentfulPaint, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::mark, UserTiming::PerformanceMark, WindowAndWorker) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::measure, UserTiming::PerformanceMeasure, WindowAndWorker) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::navigation, NavigationTiming::PerformanceNavigationTiming, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::paint, PaintTiming::PerformancePaintTiming, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::resource, ResourceTiming::PerformanceResourceTiming, WindowAndWorker) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::visibility_state, HTML::VisibilityStateEntry, WindowOnly)
-
-}
diff --git a/Libraries/LibWeb/HighResolutionTime/TimeOrigin.cpp b/Libraries/LibWeb/HighResolutionTime/TimeOrigin.cpp
index 8c145b7b03a..b1247f5d5a4 100644
--- a/Libraries/LibWeb/HighResolutionTime/TimeOrigin.cpp
+++ b/Libraries/LibWeb/HighResolutionTime/TimeOrigin.cpp
@@ -7,11 +7,17 @@
#include <AK/Math.h>
#include <AK/Time.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
namespace Web::HighResolutionTime {
+extern "C" {
+double web_high_resolution_time_current_high_resolution_time(JSObject* global_object);
+double web_high_resolution_time_get_time_origin_timestamp(JSObject* global_object);
+}
+
// https://w3c.github.io/hr-time/#dfn-estimated-monotonic-time-of-the-unix-epoch
DOMHighResTimeStamp estimated_monotonic_time_of_the_unix_epoch()
{
@@ -119,4 +125,17 @@ DOMHighResTimeStamp unsafe_shared_current_time()
return MonotonicTime::now().to_seconds_f64() * 1000.0;
}
+extern "C" {
+
+double web_high_resolution_time_current_high_resolution_time(JSObject* global_object)
+{
+ return current_high_resolution_time(*JS::HostABI::object_from_abi(global_object));
+}
+
+double web_high_resolution_time_get_time_origin_timestamp(JSObject* global_object)
+{
+ return get_time_origin_timestamp(*JS::HostABI::object_from_abi(global_object));
+}
+}
+
}
diff --git a/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h
index e6de59c6185..3118c9daa04 100644
--- a/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h
+++ b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h
@@ -26,15 +26,6 @@ public:
virtual ~LargestContentfulPaint() override;
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::No; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 150; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/NavigationTiming/PerformanceNavigation.cpp b/Libraries/LibWeb/NavigationTiming/PerformanceNavigation.cpp
index 5b7646a9a07..0bdeed67c75 100644
--- a/Libraries/LibWeb/NavigationTiming/PerformanceNavigation.cpp
+++ b/Libraries/LibWeb/NavigationTiming/PerformanceNavigation.cpp
@@ -12,6 +12,10 @@
namespace Web::NavigationTiming {
+extern "C" {
+PerformanceNavigation* web_navigation_timing_performance_navigation_create(HTML::Window*);
+}
+
GC_DEFINE_ALLOCATOR(PerformanceNavigation);
GC::Ref<PerformanceNavigation> PerformanceNavigation::create(HTML::Window& window)
@@ -70,4 +74,9 @@ u16 PerformanceNavigation::redirect_count() const
return entry->redirect_count();
}
+PerformanceNavigation* web_navigation_timing_performance_navigation_create(HTML::Window* window)
+{
+ return PerformanceNavigation::create(*window).ptr();
+}
+
}
diff --git a/Libraries/LibWeb/NavigationTiming/PerformanceNavigationTiming.h b/Libraries/LibWeb/NavigationTiming/PerformanceNavigationTiming.h
index 558b54ee507..4a1e5a551a5 100644
--- a/Libraries/LibWeb/NavigationTiming/PerformanceNavigationTiming.h
+++ b/Libraries/LibWeb/NavigationTiming/PerformanceNavigationTiming.h
@@ -21,8 +21,6 @@ public:
static void create_navigation_timing_entry(DOM::Document&, NonnullRefPtr<Fetch::Infrastructure::FetchTimingInfo>, u16 redirect_count, Bindings::NavigationTimingType, Optional<Fetch::Infrastructure::Response::CacheState> const&, Fetch::Infrastructure::Response::BodyInfo, Fetch::Infrastructure::Status);
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
- static Optional<u64> max_buffer_size() { return OptionalNone {}; }
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
virtual Utf16FlyString const& entry_type() const override;
diff --git a/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp b/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp
index cfa94b1bb4b..e144b577024 100644
--- a/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp
+++ b/Libraries/LibWeb/NavigationTiming/PerformanceTiming.cpp
@@ -6,12 +6,20 @@
*/
#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/NavigationTiming/EntryNames.h>
#include <LibWeb/NavigationTiming/PerformanceNavigationTiming.h>
#include <LibWeb/NavigationTiming/PerformanceTiming.h>
namespace Web::NavigationTiming {
+extern "C" {
+PerformanceTiming* web_navigation_timing_performance_timing_create(HTML::Window*);
+bool web_navigation_timing_is_performance_timing_attribute(FlatPtr name);
+u64 web_navigation_timing_performance_timing_attribute(PerformanceTiming*, FlatPtr name);
+}
+
GC_DEFINE_ALLOCATOR(PerformanceTiming);
GC::Ref<PerformanceTiming> PerformanceTiming::create(HTML::Window& window)
@@ -273,4 +281,34 @@ u64 PerformanceTiming::load_event_end() const
return relative_timestamp_to_wall_time_milliseconds(document().load_timing_info().load_event_end_time);
}
+extern "C" {
+
+PerformanceTiming* web_navigation_timing_performance_timing_create(HTML::Window* window)
+{
+ return PerformanceTiming::create(*window).ptr();
+}
+
+bool web_navigation_timing_is_performance_timing_attribute(FlatPtr name)
+{
+ auto attribute_name = Utf16String::from_raw(name);
+#define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(camel_case_name, _) \
+ if (attribute_name.utf16_view() == EntryNames::camel_case_name.view()) \
+ return true;
+ ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
+#undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
+ return false;
+}
+
+u64 web_navigation_timing_performance_timing_attribute(PerformanceTiming* timing, FlatPtr name)
+{
+ auto attribute_name = Utf16String::from_raw(name);
+#define __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME(camel_case_name, snake_case_name) \
+ if (attribute_name.utf16_view() == EntryNames::camel_case_name.view()) \
+ return timing->snake_case_name();
+ ENUMERATE_NAVIGATION_TIMING_ENTRY_NAMES
+#undef __ENUMERATE_NAVIGATION_TIMING_ENTRY_NAME
+ VERIFY_NOT_REACHED();
+}
+}
+
}
diff --git a/Libraries/LibWeb/PaintTiming/PerformancePaintTiming.h b/Libraries/LibWeb/PaintTiming/PerformancePaintTiming.h
index 2dc84b4e730..1a0238e589d 100644
--- a/Libraries/LibWeb/PaintTiming/PerformancePaintTiming.h
+++ b/Libraries/LibWeb/PaintTiming/PerformancePaintTiming.h
@@ -23,15 +23,6 @@ public:
static GC::Ref<PerformancePaintTiming> create(Utf16String const& paint_type, PaintTimingInfo);
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 2; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/PerformanceTimeline/EventNames.cpp b/Libraries/LibWeb/PerformanceTimeline/EventNames.cpp
deleted file mode 100644
index de8d3243f7e..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/EventNames.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/PerformanceTimeline/EventNames.h>
-
-namespace Web::PerformanceTimeline::EventNames {
-
-#define __ENUMERATE_PERFORMANCE_TIMELINE_EVENT(name) \
- Utf16FlyString const& name = *new Utf16FlyString(#name##_utf16_fly_string);
-ENUMERATE_PERFORMANCE_TIMELINE_EVENTS
-#undef __ENUMERATE_PERFORMANCE_TIMELINE_EVENT
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/EventNames.h b/Libraries/LibWeb/PerformanceTimeline/EventNames.h
deleted file mode 100644
index 230358c7b0c..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/EventNames.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-
-namespace Web::PerformanceTimeline::EventNames {
-
-#define ENUMERATE_PERFORMANCE_TIMELINE_EVENTS \
- __ENUMERATE_PERFORMANCE_TIMELINE_EVENT(resourcetimingbufferfull)
-
-#define __ENUMERATE_PERFORMANCE_TIMELINE_EVENT(name) extern Utf16FlyString const& name;
-ENUMERATE_PERFORMANCE_TIMELINE_EVENTS
-#undef __ENUMERATE_PERFORMANCE_TIMELINE_EVENT
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.cpp b/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.cpp
index 26d4315ff58..6f4df8c2bb4 100644
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.cpp
+++ b/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.cpp
@@ -8,6 +8,13 @@
namespace Web::PerformanceTimeline {
+extern "C" {
+FlatPtr web_performance_timeline_entry_name(PerformanceEntry*);
+FlatPtr web_performance_timeline_entry_entry_type(PerformanceEntry*);
+double web_performance_timeline_entry_start_time(PerformanceEntry*);
+bool web_performance_timeline_entry_should_add_entry(PerformanceEntry*, bool has_options, bool has_duration_threshold, double duration_threshold);
+}
+
PerformanceEntry::PerformanceEntry(String const& name, HighResolutionTime::DOMHighResTimeStamp start_time, HighResolutionTime::DOMHighResTimeStamp duration)
: m_name(Utf16String::from_utf8(name))
, m_start_time(start_time)
@@ -24,4 +31,35 @@ PerformanceEntry::PerformanceEntry(Utf16String const& name, HighResolutionTime::
PerformanceEntry::~PerformanceEntry() = default;
+extern "C" {
+
+FlatPtr web_performance_timeline_entry_name(PerformanceEntry* entry)
+{
+ return Utf16String { entry->name() }.into_raw();
+}
+
+FlatPtr web_performance_timeline_entry_entry_type(PerformanceEntry* entry)
+{
+ return entry->entry_type().to_utf16_string().into_raw();
+}
+
+double web_performance_timeline_entry_start_time(PerformanceEntry* entry)
+{
+ return entry->start_time();
+}
+
+bool web_performance_timeline_entry_should_add_entry(PerformanceEntry* entry, bool has_options, bool has_duration_threshold, double duration_threshold)
+{
+ Optional<PerformanceObserverInit> options;
+ if (has_options) {
+ options = PerformanceObserverInit {};
+ if (has_duration_threshold)
+ options->duration_threshold = duration_threshold;
+ }
+ if (options.has_value())
+ return entry->should_add_entry(*options) == ShouldAddEntry::Yes;
+ return entry->should_add_entry() == ShouldAddEntry::Yes;
+}
+}
+
}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.h b/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.h
index 0e24915157e..76ef18f52fb 100644
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.h
+++ b/Libraries/LibWeb/PerformanceTimeline/PerformanceEntry.h
@@ -8,17 +8,13 @@
#include <AK/Optional.h>
#include <AK/String.h>
-#include <LibWeb/Bindings/PerformanceObserver.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
namespace Web::PerformanceTimeline {
-using PerformanceObserverInit = Bindings::PerformanceObserverInit;
-
-enum class AvailableFromTimeline {
- No,
- Yes,
+struct PerformanceObserverInit {
+ Optional<HighResolutionTime::DOMHighResTimeStamp> duration_threshold;
};
enum class ShouldAddEntry {
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntryTuple.h b/Libraries/LibWeb/PerformanceTimeline/PerformanceEntryTuple.h
deleted file mode 100644
index be61d1a59b3..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceEntryTuple.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
-
-namespace Web::PerformanceTimeline {
-
-// https://www.w3.org/TR/performance-timeline/#dfn-performance-entry-buffer-map
-struct PerformanceEntryTuple {
- // https://www.w3.org/TR/performance-timeline/#dfn-performance-entry-buffer
- // A performance entry buffer to store PerformanceEntry objects, that is initially empty.
- Vector<GC::Ref<PerformanceEntry>> performance_entry_buffer;
-
- // https://www.w3.org/TR/performance-timeline/#dfn-maxbuffersize
- // An integer maxBufferSize, initialized to the registry value for this entry type.
- // NOTE: The empty state represents Infinite size.
- Optional<u64> max_buffer_size;
-
- // https://www.w3.org/TR/performance-timeline/#dfn-availablefromtimeline
- // A boolean availableFromTimeline, initialized to the registry value for this entry type.
- AvailableFromTimeline available_from_timeline { AvailableFromTimeline::No };
-
- // https://www.w3.org/TR/performance-timeline/#dfn-dropped-entries-count
- // An integer dropped entries count that is initially 0.
- u64 dropped_entries_count { 0 };
-
- // https://www.w3.org/TR/performance-timeline/#dfn-determine-if-a-performance-entry-buffer-is-full
- bool is_full()
- {
- // 1. Let num current entries be the size of tuple's performance entry buffer.
- auto num_current_entries = performance_entry_buffer.size();
-
- // 2. If num current entries is less than tuples's maxBufferSize, return false.
- if (!max_buffer_size.has_value() || num_current_entries < max_buffer_size.value())
- return false;
-
- // 3. Increase tuple's dropped entries count by 1.
- ++dropped_entries_count;
-
- // 4. Return true.
- return true;
- }
-
- void visit_edges(JS::Cell::Visitor& visitor)
- {
- visitor.visit(performance_entry_buffer);
- }
-};
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp
deleted file mode 100644
index 7e4856a2e25..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibWeb/Bindings/PerformanceObserver.h>
-#include <LibWeb/Bindings/PerformanceObserverEntryList.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/VisibilityStateEntry.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>
-#include <LibWeb/NavigationTiming/PerformanceNavigationTiming.h>
-#include <LibWeb/PerformanceTimeline/EntryTypes.h>
-#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserver.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/CallbackType.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::PerformanceTimeline {
-
-GC_DEFINE_ALLOCATOR(PerformanceObserver);
-
-static Bindings::WrapperWorldWeakValueCacheMap<JS::Object, JS::Object>& supported_entry_types_caches()
-{
- static thread_local NeverDestroyed<Bindings::WrapperWorldWeakValueCacheMap<JS::Object, JS::Object>> caches;
- return *caches;
-}
-
-void clear_supported_entry_types_caches()
-{
- supported_entry_types_caches().clear();
-}
-
-static Bindings::WrapperWorldWeakValueCache<JS::Object>& supported_entry_types_cache_for(JS::Object& global_object)
-{
- return supported_entry_types_caches().cache_for(global_object);
-}
-
-static GC::Ref<JS::Object> create_supported_entry_types_array(JS::Object& relevant_global_object)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto& vm = realm.vm();
- GC::RootVector<JS::Value> supported_entry_types;
-
- bool global_is_window = HTML::window_from_global_object(relevant_global_object);
-
-#define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class, globals) \
- if (HighResolutionTime::is_supported_for_global(HighResolutionTime::SupportedPerformanceEntryTypeGlobals::globals, global_is_window)) \
- supported_entry_types.append(JS::PrimitiveString::create(vm, entry_type));
- ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-#undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-
- auto supported_entry_types_array = JS::Array::create_from(realm, supported_entry_types);
- MUST(supported_entry_types_array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
- return supported_entry_types_array;
-}
-
-static bool is_supported_entry_type(HTML::WindowOrWorkerGlobalScopeMixin const& relevant_global, Utf16FlyString const& type)
-{
- bool global_is_window = is<HTML::Window>(relevant_global.this_impl());
-
-#define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class, globals) \
- if (type == entry_type) \
- return HighResolutionTime::is_supported_for_global(HighResolutionTime::SupportedPerformanceEntryTypeGlobals::globals, global_is_window);
- ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-#undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
-
- return false;
-}
-
-GC::Ref<PerformanceObserver> PerformanceObserver::create(GC::Ptr<WebIDL::CallbackType> callback, HTML::WindowOrWorkerGlobalScopeMixin& relevant_global)
-{
- return GC::Heap::the().allocate<PerformanceObserver>(callback, relevant_global);
-}
-
-GC::Ref<PerformanceObserver> PerformanceObserver::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<WebIDL::CallbackType> callback)
-{
- auto& relevant_global = HTML::relevant_window_or_worker_global_scope(relevant_global_object);
- return create(callback, relevant_global);
-}
-
-PerformanceObserver::PerformanceObserver(GC::Ptr<WebIDL::CallbackType> callback, HTML::WindowOrWorkerGlobalScopeMixin& relevant_global)
- : m_callback(move(callback))
- , m_relevant_global(relevant_global.this_impl())
-{
-}
-
-PerformanceObserver::~PerformanceObserver() = default;
-
-void PerformanceObserver::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_callback);
- visitor.visit(m_relevant_global);
- visitor.visit(m_observer_buffer);
-}
-
-HTML::WindowOrWorkerGlobalScopeMixin& PerformanceObserver::relevant_global() const
-{
- return as<HTML::WindowOrWorkerGlobalScopeMixin>(*m_relevant_global);
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserver-observe
-WebIDL::ExceptionOr<void> PerformanceObserver::observe(PerformanceObserverInit observer_options)
-{
- // 1. Let relevantGlobal be this's relevant global object.
- auto& relevant_global = this->relevant_global();
-
- // 2. If options's entryTypes and type members are both omitted, then throw a "TypeError".
- if (!observer_options.entry_types.has_value() && !observer_options.type.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Must specify one of entryTypes or type"_utf16 };
-
- // 3. If options's entryTypes is present and any other member is also present, then throw a "TypeError".
- if (observer_options.entry_types.has_value() && (observer_options.type.has_value() || observer_options.buffered.has_value()))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot specify type or buffered if entryTypes is specified"_utf16 };
-
- // 4. Update or check this's observer type by running these steps:
- // 1. If this's observer type is "undefined":
- if (m_observer_type == ObserverType::Undefined) {
- // 1. If options's entryTypes member is present, then set this's observer type to "multiple".
- if (observer_options.entry_types.has_value())
- m_observer_type = ObserverType::Multiple;
-
- // 2. If options's type member is present, then set this's observer type to "single".
- if (observer_options.type.has_value())
- m_observer_type = ObserverType::Single;
- }
- // 2. If this's observer type is "single" and options's entryTypes member is present, then throw an "InvalidModificationError".
- else if (m_observer_type == ObserverType::Single) {
- if (observer_options.entry_types.has_value())
- return WebIDL::InvalidModificationError::create("Cannot change a PerformanceObserver from observing a single type to observing multiple types"_utf16);
- }
- // 3. If this's observer type is "multiple" and options's type member is present, then throw an "InvalidModificationError".
- else if (m_observer_type == ObserverType::Multiple) {
- if (observer_options.type.has_value())
- return WebIDL::InvalidModificationError::create("Cannot change a PerformanceObserver from observing multiple types to observing a single type"_utf16);
- }
-
- // 5. Set this's requires dropped entries to true.
- m_requires_dropped_entries = true;
-
- // 6. If this's observer type is "multiple", run the following steps:
- if (m_observer_type == ObserverType::Multiple) {
- // 1. Let entry types be options's entryTypes sequence.
- VERIFY(observer_options.entry_types.has_value());
- auto& entry_types = observer_options.entry_types.value();
-
- // 2. Remove all types from entry types that are not contained in relevantGlobal's frozen array of supported entry types.
- // The user agent SHOULD notify developers if entry types is modified. For example, a console warning listing removed
- // types might be appropriate.
- entry_types.remove_all_matching([&relevant_global](Utf16FlyString const& type) {
- if (is_supported_entry_type(relevant_global, type))
- return false;
-
- dbgln("Potential FIXME: Removing unsupported PerformanceEntry type '{}' from list of observed types in PerformanceObserver::observe()", type);
- return true;
- });
-
- // 3. If the resulting entry types sequence is an empty sequence, abort these steps.
- // The user agent SHOULD notify developers when the steps are aborted to notify that registration has been aborted.
- // For example, a console warning might be appropriate.
- if (entry_types.is_empty()) {
- dbgln("Potential FIXME: Returning from PerformanceObserver::observe() as we don't support any of the specified types (or none was specified).");
- return {};
- }
-
- // 4. If the list of registered performance observer objects of relevantGlobal contains a registered performance
- // observer whose observer is this, replace its options list with a list containing options as its only item.
- // 5. Otherwise, create and append a registered performance observer object to the list of registered performance
- // observer objects of relevantGlobal, with observer set to this and options list set to a list containing
- // options as its only item.
- // NOTE: See the comment on PerformanceObserver::options_list about why this doesn't create a separate registered
- // performance observer object.
- m_options_list.clear();
- m_options_list.append(observer_options);
- relevant_global.register_performance_observer({}, *this);
- }
- // 7. Otherwise, run the following steps:
- else {
- // 1. Assert that this's observer type is "single".
- VERIFY(m_observer_type == ObserverType::Single);
-
- // 2. If options's type is not contained in the relevantGlobal's frozen array of supported entry types, abort these steps.
- // The user agent SHOULD notify developers when this happens, for instance via a console warning.
- VERIFY(observer_options.type.has_value());
- auto& type = observer_options.type.value();
- bool recognized_type = is_supported_entry_type(relevant_global, type);
-
- if (!recognized_type) {
- dbgln("Potential FIXME: Returning from PerformanceObserver::observe() as we don't support the PerformanceEntry type '{}'", type);
- return {};
- }
-
- // 3. If the list of registered performance observer objects of relevantGlobal contains a registered performance
- // observer obs whose observer is this:
- if (relevant_global.has_registered_performance_observer(*this)) {
- // 1. If obs's options list contains a PerformanceObserverInit item currentOptions whose type is equal to options's type,
- // replace currentOptions with options in obs's options list.
- auto index = m_options_list.find_first_index_if([&observer_options](PerformanceObserverInit const& entry) {
- return entry.type == observer_options.type;
- });
- if (index.has_value()) {
- m_options_list[index.value()] = observer_options;
- } else {
- // Otherwise, append options to obs's options list.
- m_options_list.append(observer_options);
- }
- }
- // 4. Otherwise, create and append a registered performance observer object to the list of registered performance
- // observer objects of relevantGlobal, with observer set to the this and options list set to a list containing
- // options as its only item.
- else {
- m_options_list.clear();
- m_options_list.append(observer_options);
- relevant_global.register_performance_observer({}, *this);
- }
-
- // 5. If options's buffered flag is set:
- if (observer_options.buffered.has_value() && observer_options.buffered.value()) {
- // 1. Let tuple be the relevant performance entry tuple of options's type and relevantGlobal.
- auto const& tuple = relevant_global.relevant_performance_entry_tuple(type);
-
- // 2. For each entry in tuple's performance entry buffer:
- for (auto const& entry : tuple.performance_entry_buffer) {
- // 1. If should add entry with entry and options as parameters returns true, append entry to the observer buffer.
- if (entry->should_add_entry(observer_options) == ShouldAddEntry::Yes)
- m_observer_buffer.append(*entry);
- }
-
- // 3. Queue the PerformanceObserver task with relevantGlobal as input.
- relevant_global.queue_the_performance_observer_task();
- }
- }
-
- return {};
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserver-disconnect
-void PerformanceObserver::disconnect()
-{
- // 1. Remove this from the list of registered performance observer objects of relevant global object.
- auto& relevant_global = this->relevant_global();
- relevant_global.unregister_performance_observer({}, *this);
-
- // 2. Empty this's observer buffer.
- m_observer_buffer.clear();
-
- // 3. Empty this's options list.
- m_options_list.clear();
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserver-takerecords
-Vector<GC::Root<PerformanceTimeline::PerformanceEntry>> PerformanceObserver::take_records()
-{
- // The takeRecords() method must return a copy of this's observer buffer, and also empty this's observer buffer.
- Vector<GC::Root<PerformanceTimeline::PerformanceEntry>> records;
- for (auto& record : m_observer_buffer)
- records.append(*record);
- m_observer_buffer.clear();
- return records;
-}
-
-JS::Completion PerformanceObserver::invoke_callback(GC::Ref<PerformanceObserverEntryList> entry_list, Optional<u64> dropped_entries_count)
-{
- auto& callback = this->callback();
- auto& realm = callback.callback_context->realm();
- auto callback_options = JS::Object::create(realm, realm.intrinsics().object_prototype());
- if (dropped_entries_count.has_value())
- MUST(callback_options->create_data_property("droppedEntriesCount"_utf16_fly_string, JS::Value(dropped_entries_count.value())));
-
- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
- auto wrapped_observer_entry_list = Bindings::wrap(wrapper_world, realm, entry_list);
- auto wrapped_observer = Bindings::wrap(wrapper_world, realm, GC::Ref { *this });
- return WebIDL::invoke_callback(callback, wrapped_observer, { { wrapped_observer_entry_list, wrapped_observer, callback_options } });
-}
-
-JS::Value PerformanceObserver::supported_entry_types(JS::VM& vm)
-{
- VERIFY(vm.current_realm());
- auto& realm = *vm.current_realm();
- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
- auto& cache = supported_entry_types_cache_for(realm.global_object());
-
- if (auto supported_entry_types_array = cache.get(wrapper_world))
- return JS::Value(supported_entry_types_array);
-
- auto supported_entry_types_array = create_supported_entry_types_array(realm.global_object());
- cache.set(wrapper_world, supported_entry_types_array);
- return JS::Value(supported_entry_types_array);
-}
-
-void PerformanceObserver::unset_requires_dropped_entries(Badge<HTML::WindowOrWorkerGlobalScopeMixin>)
-{
- m_requires_dropped_entries = false;
-}
-
-void PerformanceObserver::append_to_observer_buffer(Badge<HTML::WindowOrWorkerGlobalScopeMixin>, GC::Ref<PerformanceTimeline::PerformanceEntry> entry)
-{
- m_observer_buffer.append(entry);
-}
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.h b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.h
deleted file mode 100644
index 6844496d7b9..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
-#include <LibWeb/WebIDL/CallbackType.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::PerformanceTimeline {
-
-class PerformanceObserverEntryList;
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserver
-class PerformanceObserver final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(PerformanceObserver, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(PerformanceObserver);
-
-public:
- enum class ObserverType {
- Undefined,
- Single,
- Multiple,
- };
-
- static GC::Ref<PerformanceObserver> create(GC::Ptr<WebIDL::CallbackType>, HTML::WindowOrWorkerGlobalScopeMixin&);
- static GC::Ref<PerformanceObserver> create_for_constructor(JS::Object&, GC::Ptr<WebIDL::CallbackType>);
- virtual ~PerformanceObserver() override;
-
- WebIDL::ExceptionOr<void> observe(PerformanceObserverInit options);
- void disconnect();
- Vector<GC::Root<PerformanceTimeline::PerformanceEntry>> take_records();
-
- bool requires_dropped_entries() const { return m_requires_dropped_entries; }
- void unset_requires_dropped_entries(Badge<HTML::WindowOrWorkerGlobalScopeMixin>);
-
- Vector<PerformanceObserverInit> const& options_list() const { return m_options_list; }
- WebIDL::CallbackType& callback() { return *m_callback; }
- JS::Completion invoke_callback(GC::Ref<PerformanceObserverEntryList>, Optional<u64> dropped_entries_count);
- static JS::Value supported_entry_types(JS::VM&);
-
- void append_to_observer_buffer(Badge<HTML::WindowOrWorkerGlobalScopeMixin>, GC::Ref<PerformanceTimeline::PerformanceEntry>);
-
-private:
- PerformanceObserver(GC::Ptr<WebIDL::CallbackType>, HTML::WindowOrWorkerGlobalScopeMixin&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- HTML::WindowOrWorkerGlobalScopeMixin& relevant_global() const;
-
- // https://w3c.github.io/performance-timeline/#dfn-observer-callback
- // A PerformanceObserverCallback observer callback set on creation.
- GC::Ptr<WebIDL::CallbackType> m_callback;
-
- GC::Ref<DOM::EventTarget> m_relevant_global;
-
- // https://w3c.github.io/performance-timeline/#dfn-observer-buffer
- // A PerformanceEntryList object called the observer buffer that is initially empty.
- Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>> m_observer_buffer;
-
- // https://w3c.github.io/performance-timeline/#dfn-observer-type
- // A DOMString observer type which is initially "undefined".
- ObserverType m_observer_type { ObserverType::Undefined };
-
- // https://w3c.github.io/performance-timeline/#dfn-requires-dropped-entries
- // A boolean requires dropped entries which is initially set to false.
- bool m_requires_dropped_entries { false };
-
- // https://w3c.github.io/performance-timeline/#dfn-options-list
- // A registered performance observer is a struct consisting of an observer member (a PerformanceObserver object)
- // and an options list member (a list of PerformanceObserverInit objects).
- // NOTE: This doesn't use a separate struct as methods such as disconnect() assume it can access an options list from `this`: a PerformanceObserver.
- Vector<PerformanceObserverInit> m_options_list;
-};
-
-// For an agent that goes away, whose weak references the cache would keep beyond the end of its heap.
-void clear_supported_entry_types_caches();
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.idl b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.idl
index 81fcd2a94ee..c84a10073fe 100644
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.idl
+++ b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.idl
@@ -7,13 +7,13 @@ callback PerformanceObserverCallback = undefined (PerformanceObserverEntryList e
// https://w3c.github.io/performance-timeline/#dom-performanceobserverinit
dictionary PerformanceObserverInit {
- sequence<[FlyString] DOMString> entryTypes;
- [FlyString] DOMString type;
+ sequence<DOMString> entryTypes;
+ DOMString type;
boolean buffered;
};
// https://w3c.github.io/performance-timeline/#dom-performanceobserver
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface PerformanceObserver {
constructor(PerformanceObserverCallback callback);
undefined observe(optional PerformanceObserverInit options = {});
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.cpp b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.cpp
deleted file mode 100644
index 4cdc0303dcc..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
-#include <LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::PerformanceTimeline {
-
-GC_DEFINE_ALLOCATOR(PerformanceObserverEntryList);
-
-GC::Ref<PerformanceObserverEntryList> PerformanceObserverEntryList::create(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>>&& entry_list)
-{
- return GC::Heap::the().allocate<PerformanceObserverEntryList>(move(entry_list));
-}
-
-PerformanceObserverEntryList::PerformanceObserverEntryList(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>>&& entry_list)
- : m_entry_list(move(entry_list))
-{
-}
-
-PerformanceObserverEntryList::~PerformanceObserverEntryList() = default;
-
-void PerformanceObserverEntryList::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_entry_list);
-}
-
-// https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-by-name-and-type
-ErrorOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> filter_buffer_by_name_and_type(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>> const& buffer, Optional<Utf16String> const& name, Optional<Utf16String> type)
-{
- // 1. Let result be an initially empty list.
- Vector<GC::Root<PerformanceTimeline::PerformanceEntry>> result;
-
- // 2. For each PerformanceEntry entry in buffer, run the following steps:
- for (auto const& entry : buffer) {
- // 1. If type is not null and if type is not identical to entry's entryType attribute, continue to next entry.
- if (type.has_value() && type->utf16_view() != entry->entry_type().view())
- continue;
-
- // 2. If name is not null and if name is not identical to entry's name attribute, continue to next entry.
- if (name.has_value() && name->utf16_view() != entry->name().utf16_view())
- continue;
-
- // 3. append entry to result.
- TRY(result.try_append(entry));
- }
-
- // 3. Sort results's entries in chronological order with respect to startTime
- quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
- return left_entry->start_time() < right_entry->start_time();
- });
-
- // 4. Return result.
- return result;
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentries
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> PerformanceObserverEntryList::get_entries() const
-{
- // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
- // name and type set to null.
- return TRY_OR_THROW_OOM(JS::VM::the(), filter_buffer_by_name_and_type(m_entry_list, /* name= */ Optional<Utf16String> {}, /* type= */ Optional<Utf16String> {}));
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentriesbytype
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> PerformanceObserverEntryList::get_entries_by_type(Utf16String const& type) const
-{
- // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
- // name set to null, and type set to the method's input type parameter.
- return TRY_OR_THROW_OOM(JS::VM::the(), filter_buffer_by_name_and_type(m_entry_list, /* name= */ Optional<Utf16String> {}, type));
-}
-
-// https://w3c.github.io/performance-timeline/#dom-performanceobserverentrylist-getentriesbyname
-WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> PerformanceObserverEntryList::get_entries_by_name(Utf16String const& name, Optional<Utf16String> type) const
-{
- // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
- // name set to the method input name parameter, and type set to null if optional entryType is omitted, or set to the
- // method's input type parameter otherwise.
- return TRY_OR_THROW_OOM(JS::VM::the(), filter_buffer_by_name_and_type(m_entry_list, name, type));
-}
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h
deleted file mode 100644
index 39fa97651a6..00000000000
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/String.h>
-#include <AK/Vector.h>
-#include <LibGC/Root.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::PerformanceTimeline {
-
-// https://w3c.github.io/performance-timeline/#performanceobserverentrylist-interface
-class PerformanceObserverEntryList final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(PerformanceObserverEntryList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(PerformanceObserverEntryList);
-
-public:
- static GC::Ref<PerformanceObserverEntryList> create(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>>&&);
-
- virtual ~PerformanceObserverEntryList() override;
-
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries() const;
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries_by_type(Utf16String const& type) const;
- WebIDL::ExceptionOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> get_entries_by_name(Utf16String const& name, Optional<Utf16String> type) const;
-
-private:
- explicit PerformanceObserverEntryList(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>>&&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- // https://w3c.github.io/performance-timeline/#dfn-entry-list
- // Returns a PerformanceEntryList object returned by filter buffer by name and type algorithm with this's entry list,
- // name and type set to null.
- Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>> m_entry_list;
-};
-
-ErrorOr<Vector<GC::Root<PerformanceTimeline::PerformanceEntry>>> filter_buffer_by_name_and_type(Vector<GC::Ref<PerformanceTimeline::PerformanceEntry>> const& buffer, Optional<Utf16String> const& name, Optional<Utf16String> type);
-
-}
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.idl b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.idl
index d4ba6b6d7d8..f503e1f6aad 100644
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.idl
+++ b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserverEntryList.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/performance-timeline/#performanceobserverentrylist-interface
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface PerformanceObserverEntryList {
PerformanceEntryList getEntries();
PerformanceEntryList getEntriesByType(DOMString type);
diff --git a/Libraries/LibWeb/ResourceTiming/PerformanceResourceTiming.h b/Libraries/LibWeb/ResourceTiming/PerformanceResourceTiming.h
index 3dcbb12b57e..51ed707b6e4 100644
--- a/Libraries/LibWeb/ResourceTiming/PerformanceResourceTiming.h
+++ b/Libraries/LibWeb/ResourceTiming/PerformanceResourceTiming.h
@@ -37,15 +37,6 @@ public:
static void mark_resource_timing(NonnullRefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Utf16String const& requested_url, Utf16FlyString const& initiator_type, JS::Object& global, Optional<Fetch::Infrastructure::Response::CacheState> const& cache_mode, Fetch::Infrastructure::Response::BodyInfo body_info, Fetch::Infrastructure::Status response_status, Utf16FlyString delivery_type = ""_utf16_fly_string);
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- static Optional<u64> max_buffer_size() { return 250; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/UserTiming/PerformanceMark.cpp b/Libraries/LibWeb/UserTiming/PerformanceMark.cpp
index b83276b707a..7a6a7fd6485 100644
--- a/Libraries/LibWeb/UserTiming/PerformanceMark.cpp
+++ b/Libraries/LibWeb/UserTiming/PerformanceMark.cpp
@@ -5,8 +5,10 @@
*/
#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Object.h>
#include <LibWeb/Bindings/PerformanceMark.h>
+#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
@@ -17,6 +19,10 @@
namespace Web::UserTiming {
+extern "C" {
+JSCompletion web_user_timing_performance_mark_create(JSObject* global_object, FlatPtr mark_name, bool has_detail, JSValue detail, bool has_start_time, double start_time, PerformanceTimeline::PerformanceEntry** entry);
+}
+
GC_DEFINE_ALLOCATOR(PerformanceMark);
PerformanceMark::PerformanceMark(Utf16String const& name, HighResolutionTime::DOMHighResTimeStamp start_time, HighResolutionTime::DOMHighResTimeStamp duration, JS::Value detail)
@@ -105,4 +111,23 @@ void PerformanceMark::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_detail);
}
+extern "C" {
+
+JSCompletion web_user_timing_performance_mark_create(JSObject* global_object, FlatPtr mark_name, bool has_detail, JSValue detail, bool has_start_time, double start_time, PerformanceTimeline::PerformanceEntry** entry)
+{
+ auto& relevant_global_object = *JS::HostABI::object_from_abi(global_object);
+ auto& realm = HTML::relevant_realm(relevant_global_object);
+ Bindings::PerformanceMarkOptions mark_options;
+ if (has_detail)
+ mark_options.detail = JS::HostABI::value_from_abi(detail);
+ if (has_start_time)
+ mark_options.start_time = start_time;
+ auto result = PerformanceMark::create_for_constructor(relevant_global_object, Utf16String::from_raw(mark_name), mark_options);
+ if (result.is_exception())
+ return Bindings::completion_to_abi(realm, result.release_error());
+ *entry = result.release_value().ptr();
+ return Bindings::completion_to_abi(realm, JS::js_undefined());
+}
+}
+
}
diff --git a/Libraries/LibWeb/UserTiming/PerformanceMark.h b/Libraries/LibWeb/UserTiming/PerformanceMark.h
index 45e1f08f386..1efff3920f6 100644
--- a/Libraries/LibWeb/UserTiming/PerformanceMark.h
+++ b/Libraries/LibWeb/UserTiming/PerformanceMark.h
@@ -31,16 +31,6 @@ public:
static WebIDL::ExceptionOr<GC::Ref<PerformanceMark>> create_for_constructor(JS::Object&, Utf16String const& mark_name, Bindings::PerformanceMarkOptions const& mark_options = {});
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- // NOTE: The empty state represents Infinite size.
- static Optional<u64> max_buffer_size() { return OptionalNone {}; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/UserTiming/PerformanceMeasure.cpp b/Libraries/LibWeb/UserTiming/PerformanceMeasure.cpp
index 29a4ebcc592..519d4a3b37c 100644
--- a/Libraries/LibWeb/UserTiming/PerformanceMeasure.cpp
+++ b/Libraries/LibWeb/UserTiming/PerformanceMeasure.cpp
@@ -5,6 +5,7 @@
*/
#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/NavigationTiming/EntryNames.h>
@@ -14,6 +15,10 @@
namespace Web::UserTiming {
+extern "C" {
+PerformanceTimeline::PerformanceEntry* web_user_timing_performance_measure_create(FlatPtr measure_name, double start_time, double duration, JSValue detail);
+}
+
GC_DEFINE_ALLOCATOR(PerformanceMeasure);
PerformanceMeasure::PerformanceMeasure(Utf16String const& name, HighResolutionTime::DOMHighResTimeStamp start_time, HighResolutionTime::DOMHighResTimeStamp duration, JS::Value detail)
@@ -47,4 +52,12 @@ void PerformanceMeasure::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_detail);
}
+extern "C" {
+
+PerformanceTimeline::PerformanceEntry* web_user_timing_performance_measure_create(FlatPtr measure_name, double start_time, double duration, JSValue detail)
+{
+ return PerformanceMeasure::create(Utf16String::from_raw(measure_name), start_time, duration, JS::HostABI::value_from_abi(detail)).ptr();
+}
+}
+
}
diff --git a/Libraries/LibWeb/UserTiming/PerformanceMeasure.h b/Libraries/LibWeb/UserTiming/PerformanceMeasure.h
index d2a93710993..6e6435ce155 100644
--- a/Libraries/LibWeb/UserTiming/PerformanceMeasure.h
+++ b/Libraries/LibWeb/UserTiming/PerformanceMeasure.h
@@ -23,16 +23,6 @@ public:
[[nodiscard]] static GC::Ref<PerformanceMeasure> create(Utf16String const& measure_name, HighResolutionTime::DOMHighResTimeStamp start_time, HighResolutionTime::DOMHighResTimeStamp duration, JS::Value detail);
- // NOTE: These three functions are answered by the registry for the given entry type.
- // https://w3c.github.io/timing-entrytypes-registry/#registry
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
- static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::Yes; }
-
- // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
- // NOTE: The empty state represents Infinite size.
- static Optional<u64> max_buffer_size() { return OptionalNone {}; }
-
// https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.cpp b/Libraries/LibWeb/WebAudio/AudioContext.cpp
index c1d4cb88a00..bac16496fab 100644
--- a/Libraries/LibWeb/WebAudio/AudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioContext.cpp
@@ -11,7 +11,7 @@
#include <LibAudio/PlaybackStream.h>
#include <LibMedia/Sinks/AudioOutputFactory.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HighResolutionTime/Performance.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/WebAudio/RustFFI.h>
@@ -72,6 +72,6 @@ void RustFFI::web_audio_output_discard_and_suspend(void* stream)
static_cast<Audio::PlaybackStream*>(stream)->discard_buffer_and_suspend()->when_rejected([](auto&&) { });
}
i64 RustFFI::web_audio_monotonic_now_nanoseconds() { return MonotonicTime::now().nanoseconds(); }
-double web_audio_realtime_context_performance_now(DOM::EventTarget* global) { return as<HTML::Window>(*global).performance()->now(); }
+double web_audio_realtime_context_performance_now(DOM::EventTarget* global) { return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(as<HTML::Window>(*global))); }
}