Truly independent web browser
LibWeb: Implement Notification in Rust
Shannon Booth65cf717a3aaa
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rsindex d3f4a0b0b23..39b8817df1c 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, Realm, Trace};+use libjs_rust::api::{Gc, Object, Realm, Trace, Vm};use liburl_rust::origin::Origin;use liburl_rust::{FfiOrigin, RustUrl, Url};@@ -19,10 +19,22 @@ 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_principal_realm_settings_object(realm: *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_time_origin(settings_object: *mut c_void) -> f64;fn web_bindings_environment_settings_object_is_secure_context(settings_object: *mut c_void) -> bool;+ fn web_bindings_environment_settings_object_top_level_origin(+ settings_object: *mut c_void,+ origin: *mut c_void,+ on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),+ ) -> bool;+ fn web_bindings_environment_settings_object_api_base_url(+ settings_object: *mut c_void,+ url: *mut c_void,+ on_url: unsafe extern "C" fn(*mut c_void, *const RustUrl),+ );+ fn web_bindings_environment_settings_object_current_wall_time(settings_object: *mut c_void) -> f64;fn web_bindings_environment_settings_object_id(settings_object: *mut c_void,id: *mut c_void,@@ -69,6 +81,18 @@ pub(crate) fn relevant_settings_object(global_object: Gc<Object>) -> CppEnvironm})}+/// https://html.spec.whatwg.org/multipage/webappapis.html#current-settings-object+pub(crate) fn current_settings_object(vm: &Vm) -> CppEnvironmentSettingsObject {+ // Then, the current settings object is the environment settings object of the current realm.+ let current_realm = vm.current_realm().expect("there is a current realm");+ // SAFETY: The realm is live, and LibWeb returns its live environment settings object.+ CppEnvironmentSettingsObject(unsafe {+ CppCell::from_raw(web_bindings_principal_realm_settings_object(+ current_realm.as_ptr().cast(),+ ))+ })+}+impl CppEnvironmentSettingsObject {pub(crate) fn as_ptr(&self) -> *mut c_void {self.0.as_ptr()@@ -118,6 +142,34 @@ impl CppEnvironmentSettingsObject {origin.expect("LibWeb lends the origin")}+ /// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-top-level-origin+ pub(crate) fn top_level_origin(&self) -> Option<Origin> {+ let mut origin = None;+ // SAFETY: The settings object is live, and the origin outlives the call.+ unsafe {+ web_bindings_environment_settings_object_top_level_origin(+ self.as_ptr(),+ (&raw mut origin).cast(),+ on_origin,+ )+ };+ origin+ }++ /// https://html.spec.whatwg.org/multipage/webappapis.html#api-base-url+ pub(crate) fn api_base_url(&self) -> Url {+ let mut url = None;+ // SAFETY: The settings object is live, and the URL outlives the call.+ unsafe { web_bindings_environment_settings_object_api_base_url(self.as_ptr(), (&raw mut url).cast(), on_url) };+ url.expect("LibWeb lends the API base URL")+ }++ /// https://w3c.github.io/hr-time/#dfn-current-wall-time+ pub(crate) fn current_wall_time(&self) -> f64 {+ // SAFETY: The settings object is live.+ unsafe { web_bindings_environment_settings_object_current_wall_time(self.as_ptr()) }+ }+/// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#encoding-parsing-a-urlpub(crate) fn encoding_parse_url(&self, url: &Utf16String) -> Option<Url> {let mut parsed_url = None;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rsindex ee1df89cfad..d6ee60276ef 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs@@ -26,6 +26,9 @@ unsafe extern "C" {fn web_bindings_window_realm(window: *mut c_void) -> *mut c_void;fn web_bindings_window_page_id(window: *mut c_void) -> u64;fn web_bindings_window_has_transient_activation(window: *mut c_void) -> bool;+ fn web_bindings_window_consume_user_activation(window: *mut c_void);+ fn web_bindings_window_set_last_activation_timestamp_to_now(window: *mut c_void);+ fn web_bindings_is_service_worker_global_scope(global_object: *mut c_void) -> bool;fn web_bindings_window_as_event_target(window: *mut c_void) -> *mut c_void;fn web_bindings_worker_global_scope_from_global_object(global_object: *mut c_void) -> *mut c_void;fn web_bindings_worker_global_scope_is_closing(worker_global_scope: *mut c_void) -> bool;@@ -76,6 +79,11 @@ pub(crate) fn worker_global_scope_from_global_object(global_object: Gc<Object>).map(CppWorkerGlobalScope)}+pub(crate) fn is_service_worker_global_scope(global_object: Gc<Object>) -> bool {+ // SAFETY: The global object is live.+ unsafe { web_bindings_is_service_worker_global_scope(global_object.as_ptr().cast()) }+}+pub(crate) fn window_or_worker_global_scope_from_global_object(global_object: Gc<Object>,) -> Option<CppWindowOrWorkerGlobalScope> {@@ -150,6 +158,18 @@ impl CppWindow {unsafe { web_bindings_window_has_transient_activation(self.0.as_ptr()) }}+ /// https://html.spec.whatwg.org/multipage/interaction.html#consume-user-activation+ pub(crate) fn consume_user_activation(&self) {+ // SAFETY: The Window is live.+ unsafe { web_bindings_window_consume_user_activation(self.0.as_ptr()) };+ }++ /// https://html.spec.whatwg.org/multipage/interaction.html#last-activation-timestamp+ pub(crate) fn set_last_activation_timestamp_to_now(&self) {+ // SAFETY: The Window is live.+ unsafe { web_bindings_window_set_last_activation_timestamp_to_now(self.0.as_ptr()) };+ }+/// https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-document-windowpub(crate) fn associated_document(&self) -> CppDocument {// SAFETY: The Window is live, and LibWeb returns its live associated Document.diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex 79f4cf3f98f..39690cdc03b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -80,6 +80,7 @@ unsafe extern "C" {pub(crate) enum TaskSource {Unspecified = 0,DOMManipulation = 1,+ UserInteraction = 2,Networking = 3,PostedMessage = 6,TimerTask = 8,diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rsindex 6152c82ccc9..87a36e9bd57 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs@@ -7,7 +7,8 @@use core::ffi::c_void;use libjs_rust::api::{Trace, Vm};-use liburl_rust::Url;+use liburl_rust::origin::Origin;+use liburl_rust::{FfiOrigin, Url};use crate::bindings::cpp_cell::{CppCell, WeakCppCell};use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};@@ -21,6 +22,11 @@ unsafe extern "C" {fn web_bindings_document_is_fully_active(document: *mut c_void) -> bool;fn web_bindings_document_is_allowed_to_use_feature(document: *mut c_void, feature: u8) -> bool;fn web_bindings_document_visibility_state(document: *mut c_void) -> u8;+ fn web_bindings_document_origin(+ document: *mut c_void,+ origin: *mut c_void,+ on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),+ );fn web_bindings_document_has_focus(document: *mut c_void) -> bool;fn web_bindings_document_has_been_destroyed(document: *mut c_void) -> bool;fn web_bindings_document_url(document: *mut c_void) -> liburl_rust::RustUrl;@@ -99,6 +105,19 @@ impl CppDocument {unsafe { web_bindings_document_is_allowed_to_use_feature(self.0.as_ptr(), feature as u8) }}+ /// https://dom.spec.whatwg.org/#concept-document-origin+ pub(crate) fn origin(&self) -> Origin {+ unsafe extern "C" fn on_origin(origin: *mut c_void, ffi_origin: *const FfiOrigin) {+ // SAFETY: origin is the origin below, and LibWeb lends the origin for the call.+ unsafe { *origin.cast::<Option<Origin>>() = Some((*ffi_origin).to_origin()) };+ }++ let mut origin = None;+ // SAFETY: The Document is live, and the origin outlives the call.+ unsafe { web_bindings_document_origin(self.0.as_ptr(), (&raw mut origin).cast(), on_origin) };+ origin.expect("LibWeb lends the origin")+ }+/// https://html.spec.whatwg.org/multipage/interaction.html#visibility-statepub(crate) fn visibility_state(&self) -> VisibilityState {// SAFETY: The Document is live.diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 53819c704ad..ac5ec004cc4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -199,10 +199,15 @@ pub(crate) mod largest_contentful_paint;reason = "the bindings call every attribute and operation as one that can throw")]pub(crate) mod navigation_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 notifications_api;#[cfg(not(test))]#[cfg_attr(diff --git a/Libraries/LibWeb/Bindings/Rust/src/notifications_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/mod.rsindex 55fee550d30..a08f894bcc7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/notifications_api/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/mod.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The definitions of the Notifications API that the interfaces implemented in Rust use.+//! The Notifications API, https://notifications.spec.whatwg.org/pub(crate) mod notification;+pub(crate) mod notification_permission;diff --git a/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification.rs b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification.rsindex af2ecbbe0b8..701b4c2013a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification.rs@@ -1,12 +1,1135 @@/*+ * Copyright (c) 2025, Niccolo Antonelli-Dziri <[email protected]>* Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/+//! Notification, https://notifications.spec.whatwg.org/#notifications++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{ConsoleLogLevel, Gc, GcRefCell, Object, Realm, Trace, Utf16View, Value, Vm};+use liburl_rust::origin::Origin;+use liburl_rust::url::ExcludeFragment;+use liburl_rust::{BasicParseOptions, RustUrl, Url, basic_parse};++use crate::bindings::callback::CallbackFunction;+use crate::bindings::conversions::{UsvString, enumeration_value_to_js};+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::environment_settings_object::{+ CppEnvironmentSettingsObject, current_settings_object, relevant_settings_object,+};+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};+use crate::bindings::global_object::{CppWindow, is_service_worker_global_scope, window_from_global_object};+use crate::bindings::interface::{+ Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks,+};+use crate::bindings::promise::{TaskSource, WebIdlPromise, create_promise, queue_a_global_task, resolve_promise};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::domurl::url_input;+use crate::html::structured_serialize::{structured_deserialize_for_storage, structured_serialize_for_storage};+use crate::notifications_api::notification_permission::get_the_notifications_permission_state;+use crate::permissions::permissions::PermissionName;+use crate::permissions_api::permission_status::PermissionState;+use crate::permissions_api::permissions::request_permission_to_use;+use crate::platform::timer::CppTimer;++unsafe extern "C" {+ fn web_notifications_api_register_notification(window: *mut c_void, notification: *mut c_void) -> u64;+ fn web_notifications_api_unregister_notification(window: *mut c_void, notification_id: u64);+ fn web_notifications_api_fetch_icon(+ notification: *mut c_void,+ settings_object: *mut c_void,+ url: &RustUrl,+ ) -> *mut c_void;+ fn web_notifications_api_stop_icon_fetch(icon: *mut c_void);+ fn web_notifications_api_show_notification(+ window: *mut c_void,+ notification_id: u64,+ data: &NotificationDataAbi,+ icon: *mut c_void,+ );+ fn web_notifications_api_request_close_notification(window: *mut c_void, notification_id: u64);+ fn web_notifications_api_abandon_notification(window: *mut c_void, notification_id: u64);+ fn web_notifications_api_handle_notification_click(window: *mut c_void, notification_id: u64, into_focus: bool);+}+/// The typedef VibratePattern of NotificationsAPI/Notification.idl, whose union (unsigned long or/// sequence<unsigned long>) other interfaces also name.pub(crate) enum VibratePattern {UnsignedLong(u32),Sequence(Vec<u32>),}++// https://notifications.spec.whatwg.org/#enumdef-notificationpermission+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum NotificationPermission {+ Default,+ Denied,+ Granted,+}++// https://notifications.spec.whatwg.org/#enumdef-notificationdirection+#[derive(Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub(crate) enum NotificationDirection {+ Auto,+ Ltr,+ Rtl,+}++// https://notifications.spec.whatwg.org/#dictdef-notificationaction+pub(crate) struct NotificationAction {+ pub(crate) action: Utf16String,+ pub(crate) title: Utf16String,+ pub(crate) navigate: Option<UsvString>,+ pub(crate) icon: Option<UsvString>,+}++// https://notifications.spec.whatwg.org/#dictdef-notificationoptions+pub(crate) struct NotificationOptions {+ pub(crate) dir: NotificationDirection,+ pub(crate) lang: Utf16String,+ pub(crate) body: Utf16String,+ pub(crate) navigate: Option<UsvString>,+ pub(crate) tag: Utf16String,+ pub(crate) image: Option<UsvString>,+ pub(crate) icon: Option<UsvString>,+ pub(crate) badge: Option<UsvString>,+ pub(crate) vibrate: Option<VibratePattern>,+ pub(crate) timestamp: Option<u64>,+ pub(crate) renotify: bool,+ pub(crate) silent: Option<bool>,+ pub(crate) require_interaction: bool,+ pub(crate) data: Value,+ pub(crate) actions: Vec<NotificationAction>,+}++struct CreateNotificationOptions {+ direction: NotificationDirection,+ language: Utf16String,+ body: Utf16String,+ navigate: Option<UsvString>,+ tag: Utf16String,+ image: Option<UsvString>,+ icon: Option<UsvString>,+ badge: Option<UsvString>,+ // FIXME: Validate and normalize the pattern (create step 15); only its presence matters until then.+ has_vibrate: bool,+ timestamp: Option<u64>,+ renotify: bool,+ silent: Option<bool>,+ require_interaction: bool,+ data: Vec<u8>,+ actions: Vec<NotificationAction>,+}++// https://notifications.spec.whatwg.org/#action+struct ConceptNotificationAction {+ name: Utf16String,+ title: Utf16String,+ navigation_url: Option<Url>,+ icon_url: Option<Url>,+ // FIXME: icon resource+}++// https://notifications.spec.whatwg.org/#concept-notification+// This is the notification described as "notification" in the spec. Do not confuse it with "notification" as in the IDL which is just the JS wrapper.+// "A notification is an abstract representation of something that happened, such as the delivery of a message."+struct ConceptNotification {+ // FIXME: A notification has an associated service worker registration (null or a service worker registration). It is initially null.+ title: Utf16String,+ direction: NotificationDirection,+ language: Utf16String,+ body: Utf16String,+ navigation_url: Option<Url>,+ tag: Utf16String,+ data: Vec<u8>,+ timestamp: u64,+ #[allow(dead_code, reason = "the spec keeps the origin, which no step reads yet")]+ origin: Origin,+ renotify_preference: bool,+ silent_preference: Option<bool>,+ require_interaction_preference: bool,+ image_url: Option<Url>,+ icon_url: Option<Url>,+ badge_url: Option<Url>,++ // FIXME: add the resources from m_image_url, m_icon_url and m_badge_url++ // FIXME: A notification has an associated vibration pattern (a list). It is initially « ».+ actions: Vec<ConceptNotificationAction>,+}++/// Web::NotificationsAPI::NotificationData.+#[repr(C)]+struct NotificationDataAbi {+ title: usize,+ body: usize,+ tag: usize,+ language: usize,+ direction: u8,+ has_silent: bool,+ silent: bool,+ require_interaction: bool,+ renotify: bool,+}++// Where the notification is on its way to the platform. From Pending on it's in the page's list of notifications,+// which keeps it alive; Closed means it has left the list for good.+#[derive(Clone, Copy, PartialEq, Eq)]+enum State {+ Idle,+ Pending,+ Showing,+ Closing,+ Closed,+}++// https://notifications.spec.whatwg.org/#notifications+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Notification {+ event_target: CppEventTarget,++ #[gc(untraced)]+ notification: ConceptNotification,++ // The global the constructor ran in: Where the events fire, and whose window the notification belongs to.+ realm: Gc<Realm>,+ window: Option<CppWindow>,++ #[gc(untraced)]+ state: Cell<State>,+ #[gc(untraced)]+ id: Cell<u64>,++ // https://notifications.spec.whatwg.org/#icon-resource+ icon: GcRefCell<Option<CppCell>>,+ // Bounds the wait for the icon: Past it, the notification shows without one.+ fetch_timeout: GcRefCell<Option<CppTimer>>,+}++impl Wrappable for Notification {+ 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 Notification {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++// The longest a notification waits for its icon before it shows without one.+const ICON_FETCH_TIMEOUT_MS: u64 = 5_000;++fn parse_url(url: &UsvString, base_url: &Url) -> Option<Url> {+ basic_parse(url_input(url.units()), BasicParseOptions::new().base_url(base_url))+}++fn serialize_url_for_bindings(url: Option<&Url>) -> UsvString {+ url.map_or_else(+ || UsvString::from_ascii(b""),+ |url| UsvString::from_utf16_string(&Utf16String::from_utf8(url.serialize(ExcludeFragment::No))),+ )+}++fn notification_permission_from(permission_state: PermissionState) -> NotificationPermission {+ // https://notifications.spec.whatwg.org/#permissions-integration+ // 2. If permissionState is "prompt", then return "default".+ // 3. Return permissionState.+ match permission_state {+ PermissionState::Prompt => NotificationPermission::Default,+ PermissionState::Granted => NotificationPermission::Granted,+ PermissionState::Denied => NotificationPermission::Denied,+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct PermissionRequest {+ realm: Gc<Realm>,+ global: Gc<Object>,+ promise: WebIdlPromise,+ deprecated_callback: Option<CallbackFunction>,+ settings: CppEnvironmentSettingsObject,+}++impl Notification {+ // https://notifications.spec.whatwg.org/#dom-notification-notification+ pub(crate) fn construct(+ cx: &mut CallContext,+ title: Utf16String,+ options: NotificationOptions,+ ) -> WebIdlResult<Ref<Self>> {+ // The constructor rejects actions before attempting to serialize data.+ if !options.actions.is_empty() {+ return Err(Exception::type_error("Options `action` is not empty"));+ }++ let options = CreateNotificationOptions {+ direction: options.dir,+ language: options.lang,+ body: options.body,+ navigate: options.navigate,+ tag: options.tag,+ image: options.image,+ icon: options.icon,+ badge: options.badge,+ has_vibrate: options.vibrate.is_some(),+ timestamp: options.timestamp,+ renotify: options.renotify,+ silent: options.silent,+ require_interaction: options.require_interaction,+ data: structured_serialize_for_storage(cx, options.data)?,+ actions: options.actions,+ };+ Self::create_with_global_scope(cx, title, options)+ }++ // https://notifications.spec.whatwg.org/#constructors+ fn create_with_global_scope(+ cx: &mut CallContext,+ title: Utf16String,+ options: CreateNotificationOptions,+ ) -> WebIdlResult<Ref<Self>> {+ let vm = cx.vm();+ let realm = cx.realm();+ let relevant_global_object = realm.global_object();+ let relevant_settings_object = relevant_settings_object(relevant_global_object);++ // 1. If this’s relevant global object is a ServiceWorkerGlobalScope object, then throw a TypeError.+ if is_service_worker_global_scope(relevant_global_object) {+ return Err(Exception::type_error(+ "This’s relevant global object is a ServiceWorkerGlobalScope object",+ ));+ }++ // 2. If options["actions"] is not empty, then throw a TypeError.+ if !options.actions.is_empty() {+ return Err(Exception::type_error("Options `action` is not empty"));+ }++ // 3. Let notification be the result of creating a notification with a settings object given title, options, and this’s relevant settings object.+ let notification =+ Self::create_a_notification_with_a_settings_object(title, options, &relevant_settings_object)?;++ // 4. Associate this with notification.+ let this_notification = allocate(vm, |_| Self {+ event_target: CppEventTarget::new(),+ notification,+ realm,+ window: window_from_global_object(relevant_global_object),+ state: Cell::new(State::Idle),+ id: Cell::new(0),+ icon: GcRefCell::new(None),+ fetch_timeout: GcRefCell::new(None),+ });+ this_notification.event_target.set_owner(this_notification);++ // 5. Run these steps in parallel:+ // AD-HOC: The steps run from a task on the relevant global instead of in parallel: Showing crosses to the UI+ // process asynchronously anyway, and a task keeps the permission read and the event firing on the main+ // thread, after the constructor's caller has had its turn to attach event handlers.+ queue_a_global_task(+ vm,+ relevant_global_object,+ TaskSource::Unspecified,+ this_notification,+ |vm, this_notification| Self::run_steps_in_parallel_after_construction(this_notification, vm),+ );++ Ok(this_notification)+ }++ // https://notifications.spec.whatwg.org/#create-a-notification-with-a-settings-object+ fn create_a_notification_with_a_settings_object(+ title: Utf16String,+ options: CreateNotificationOptions,+ settings: &CppEnvironmentSettingsObject,+ ) -> WebIdlResult<ConceptNotification> {+ // 1. Let origin be settings’s origin.+ let origin = settings.origin();++ // 2. Let baseURL be settings’s API base URL.+ let base_url = settings.api_base_url();++ // 3. Let fallbackTimestamp be the number of milliseconds from the Unix epoch to settings’s current wall time,+ // rounded to the nearest integer.+ #[allow(+ clippy::cast_possible_truncation,+ clippy::cast_sign_loss,+ reason = "the conversion saturates, as AK::round_to() does"+ )]+ let fallback_timestamp = settings.current_wall_time().round_ties_even() as u64;++ // 4. Return the result of creating a notification given title, options, origin, baseURL, and fallbackTimestamp.+ Self::create_a_notification(title, options, origin, &base_url, fallback_timestamp)+ }++ // https://notifications.spec.whatwg.org/#create-a-notification+ fn create_a_notification(+ title: Utf16String,+ options: CreateNotificationOptions,+ origin: Origin,+ base_url: &Url,+ fallback_timestamp: u64,+ ) -> WebIdlResult<ConceptNotification> {+ // 1. Let notification be a new notification.++ // 2. If options["silent"] is true and options["vibrate"] exists, then throw a TypeError.+ if options.silent == Some(true) && options.has_vibrate {+ return Err(Exception::type_error(+ "options[\"vibrate\"] cannot be set when options[\"silent\"] is true.",+ ));+ }++ // 3. If options["renotify"] is true and options["tag"] is the empty string, then throw a TypeError.+ if options.renotify && options.tag.is_empty() {+ return Err(Exception::type_error(+ "options[\"tag\"] cannot be the empty string when options[\"renotify\"] is set to true.",+ ));+ }++ let mut notification = ConceptNotification {+ // 4. Set notification’s data to StructuredSerializeForStorage(options["data"]).+ data: options.data,++ // 5. Set notification’s title to title.+ title,++ // 6. Set notification’s direction to options["dir"].+ direction: options.direction,++ // 7. Set notification’s language to options["lang"].+ language: options.language,++ // 8. Set notification’s origin to origin.+ origin,++ // 9. Set notification’s body to options["body"].+ body: options.body,++ // 10. If options["navigate"] exists, then parse it using baseURL, and if that does not return failure,+ // set notification’s navigation URL to the return value. (Otherwise notification’s navigation URL remains null.)+ navigation_url: options+ .navigate+ .as_ref()+ .and_then(|navigate| parse_url(navigate, base_url)),++ // 11. Set notification’s tag to options["tag"].+ tag: options.tag,++ // 12. If options["image"] exists, then parse it using baseURL, and if that does not return failure,+ // set notification’s image URL to the return value. (Otherwise notification’s image URL is not set.)+ image_url: options.image.as_ref().and_then(|image| parse_url(image, base_url)),++ // 13. If options["icon"] exists, then parse it using baseURL, and if that does not return failure,+ // set notification’s icon URL to the return value. (Otherwise notification’s icon URL is not set.)+ icon_url: options.icon.as_ref().and_then(|icon| parse_url(icon, base_url)),++ // 14. If options["badge"] exists, then parse it using baseURL, and if that does not return failure,+ // set notification’s badge URL to the return value. (Otherwise notification’s badge URL is not set.)+ badge_url: options.badge.as_ref().and_then(|badge| parse_url(badge, base_url)),++ // FIXME: 15. If options["vibrate"] exists, then validate and normalize it and+ // set notification’s vibration pattern to the return value.++ // 16. If options["timestamp"] exists, then set notification’s timestamp to the value.+ // Otherwise, set notification’s timestamp to fallbackTimestamp.+ timestamp: options.timestamp.unwrap_or(fallback_timestamp),++ // 17. Set notification’s renotify preference to options["renotify"].+ renotify_preference: options.renotify,++ // 18. Set notification’s silent preference to options["silent"].+ silent_preference: options.silent,++ // 19. Set notification’s require interaction preference to options["requireInteraction"].+ require_interaction_preference: options.require_interaction,++ // 20. Set notification’s actions to « ».+ actions: Vec::new(),+ };++ // 21. For each entry in options["actions"], up to the maximum number of actions supported (skip any excess entries):+ for entry in options.actions {+ if notification.actions.len() >= Self::MAX_ACTIONS as usize {+ break;+ }++ // 1. Let action be a new notification action.+ let action = ConceptNotificationAction {+ // 2. Set action’s name to entry["action"].+ name: entry.action,++ // 3. Set action’s title to entry["title"].+ title: entry.title,++ // 4. If entry["navigate"] exists, then parse it using baseURL, and if that does not return failure,+ // set action’s navigation URL to the return value. (Otherwise action’s navigation URL remains null.)+ navigation_url: entry+ .navigate+ .as_ref()+ .and_then(|navigate| parse_url(navigate, base_url)),++ // 5. If entry["icon"] exists, then parse it using baseURL, and if that does not return failure,+ // set action’s icon URL to the return value. (Otherwise action’s icon URL remains null.)+ icon_url: entry.icon.as_ref().and_then(|icon| parse_url(icon, base_url)),+ };++ // 6. Append action to notification’s actions.+ notification.actions.push(action);+ }++ // 22. Return notification.+ Ok(notification)+ }++ // Step 5 of https://notifications.spec.whatwg.org/#constructors+ fn run_steps_in_parallel_after_construction(this: Ref<Self>, vm: &Vm) {+ let settings = relevant_settings_object(this.realm.global_object());++ // 1. If the result of getting the notifications permission state is not "granted", then queue a task to fire an+ // event named error on this, and abort these steps.+ if get_the_notifications_permission_state(&settings) != PermissionState::Granted {+ Self::queue_task_to_fire_event(this, vm, "error");+ return;+ }++ // AD-HOC: The spec lets any document or worker show a notification. We refuse two cases until they're supported:+ // A worker has no page to route the notification's events through, and a document whose origin differs+ // from its top-level origin would have its notification attributed to the top-level site. Both get an+ // error event, as if permission had been denied.+ if this.window.is_none() {+ Self::queue_task_to_fire_event(this, vm, "error");+ return;+ }+ if !settings+ .top_level_origin()+ .is_some_and(|top_level_origin| top_level_origin.is_same_origin(&settings.origin()))+ {+ Self::queue_task_to_fire_event(this, vm, "error");+ return;+ }++ // 2. Run the notification show steps for notification.+ Self::show_steps(this, vm);+ }++ fn window(&self) -> &CppWindow {+ self.window.as_ref().expect("a notification that is shown has a window")+ }++ // https://notifications.spec.whatwg.org/#notification-show-steps+ fn show_steps(this: Ref<Self>, vm: &Vm) {+ // The notification joins the page's list now, rather than once it's displayed: The list is what keeps it alive+ // while its icon is on its way, and what lets the page withdraw it if the document goes away before then.+ // SAFETY: The window and the cell are live.+ this.id+ .set(unsafe { web_notifications_api_register_notification(this.window().as_ptr(), cell_into_abi(this)) });+ this.state.set(State::Pending);++ // 1. Run the fetch steps given notification and settings.+ // 2. Wait for any fetches to complete and notification's image resource, icon resource, and badge resource to+ // be set (if any), as well as the icon resources for the notification's actions (if any).+ // AD-HOC: The wait for the fetch is bounded: An icon that hasn't arrived after a few seconds isn't worth holding+ // the notification back for, so it then shows without one.+ let fetch_timeout = CppTimer::create_single_shot(vm, ICON_FETCH_TIMEOUT_MS, this, |vm, this| {+ if let Some(icon) = &*this.icon.borrow() {+ // SAFETY: The icon is live.+ unsafe { web_notifications_api_stop_icon_fetch(icon.as_ptr()) };+ }+ Self::display(this, vm);+ });+ *this.fetch_timeout.borrow_mut(vm) = Some(fetch_timeout);+ Self::run_the_fetch_steps(this, vm);+ }++ fn fetch_steps_done(this: Ref<Self>, vm: &Vm) {+ let Some(fetch_timeout) = this.fetch_timeout.borrow().clone() else {+ return;+ };+ fetch_timeout.stop();+ Self::display(this, vm);+ }++ // https://notifications.spec.whatwg.org/#fetch-steps+ fn run_the_fetch_steps(this: Ref<Self>, vm: &Vm) {+ // 1. If the notification platform supports images and notification's image URL is set, then fetch a notification+ // resource given notification, notification's image URL, settings, and the following step given a resource+ // resource: set notification's image resource to resource.+ // NB: No platform we show on takes an image.++ // 2. If the notification platform supports icons and notification's icon URL is set, then fetch a notification+ // resource given notification, notification's icon URL, settings, and the following step given a resource+ // resource: set notification's icon resource to resource.+ let Some(icon_url) = &this.notification.icon_url else {+ Self::fetch_steps_done(this, vm);+ return;+ };+ let settings = relevant_settings_object(this.realm.global_object());+ // SAFETY: The cell and the settings object are live, the URL is lent for the call, and LibWeb returns a live+ // icon.+ let icon = unsafe {+ CppCell::from_raw(web_notifications_api_fetch_icon(+ cell_into_abi(this),+ settings.as_ptr(),+ &RustUrl::from_url(icon_url),+ ))+ };+ *this.icon.borrow_mut(vm) = Some(icon);++ // 3. If the notification platform supports badges and notification's badge URL is set, then fetch a notification+ // resource given notification, notification's badge URL, settings, and the following step given a resource+ // resource: set notification's badge resource to resource.+ // NB: No platform we show on takes a badge.++ // 4. If the notification platform supports actions and action icons, then for each entry of notification's+ // actions: if entry's icon URL is non-null, then fetch a notification resource given notification, entry's+ // icon URL, settings, and the following step given a resource resource: set entry's icon resource to resource.+ // NB: A non-persistent notification has no actions.+ }++ // Steps 3 to 8 of https://notifications.spec.whatwg.org/#notification-show-steps+ fn display(this: Ref<Self>, vm: &Vm) {+ *this.fetch_timeout.borrow_mut(vm) = None;+ if this.state.get() != State::Pending {+ return;+ }++ // A document that went away while the icon was on its way gets no notification: The page may show another site+ // by now, and the notification would be attributed to that one.+ if !this.window().associated_document().is_fully_active() {+ this.abandon(vm);+ return;+ }++ // 3. Let shown be false.+ // 4. Let oldNotification be the notification in the list of notifications whose tag is not the empty string and is+ // notification's tag, and whose origin is same origin with notification's origin, if any, and null otherwise.+ // 5. If oldNotification is non-null:+ // 1. Handle close events with oldNotification.+ // 2. If the notification platform supports replacement:+ // 1. Replace oldNotification with notification, in the list of notifications.+ // 2. Set shown to true.+ // 3. Otherwise, remove oldNotification from the list of notifications.+ // 6. If shown is false:+ // 1. Append notification to the list of notifications.+ // 2. Display notification on the device (e.g., by calling the appropriate notification platform API).+ // 7. If shown is false or oldNotification is non-null, and notification's renotify preference is true, then+ // optionally alert the end user in a user-agent-defined manner (e.g., by playing a sound).+ // NB: Steps 4, 5 and 7 are the UI process's: It sees every page's notifications, so it finds oldNotification+ // across pages, replaces it on the platform, and reports its close back through notification_closed().+ // Here, the notification joins this page's part of the list and is sent off for display.+ this.state.set(State::Showing);+ let notification = &this.notification;+ let data = NotificationDataAbi {+ title: notification.title.raw_identity(),+ body: notification.body.raw_identity(),+ tag: notification.tag.raw_identity(),+ language: notification.language.raw_identity(),+ direction: notification.direction as u8,+ has_silent: notification.silent_preference.is_some(),+ silent: notification.silent_preference.unwrap_or(false),+ require_interaction: notification.require_interaction_preference,+ renotify: notification.renotify_preference,+ };+ let icon = this+ .icon+ .borrow()+ .as_ref()+ .map_or(core::ptr::null_mut(), CppCell::as_ptr);+ // SAFETY: The window and the icon are live, and the strings are lent for the call.+ unsafe { web_notifications_api_show_notification(this.window().as_ptr(), this.id.get(), &data, icon) };++ // 8. If notification is a non-persistent notification, then queue a task to fire an event named show on the+ // Notification object representing notification.+ // NB: Fired from did_show(), once the platform has shown the notification: Until then the display can still fail,+ // and a failure fires error instead.+ }++ fn document_ptr(&self) -> *mut c_void {+ self.window+ .as_ref()+ .map_or(core::ptr::null_mut(), |window| window.associated_document().as_ptr())+ }++ fn abandon(&self, vm: &Vm) {+ // Still on its way to the platform: Nothing has been shown, so there's nothing to tell the UI process.+ if self.state.get() == State::Pending {+ self.state.set(State::Closed);+ if let Some(fetch_timeout) = self.fetch_timeout.borrow_mut(vm).take() {+ fetch_timeout.stop();+ }+ if let Some(icon) = &*self.icon.borrow() {+ // SAFETY: The icon is live.+ unsafe { web_notifications_api_stop_icon_fetch(icon.as_ptr()) };+ }+ // SAFETY: The window is live.+ unsafe { web_notifications_api_unregister_notification(self.window().as_ptr(), self.id.get()) };+ return;+ }+ if self.state.get() != State::Showing && self.state.get() != State::Closing {+ return;+ }+ self.state.set(State::Closed);+ // SAFETY: The window is live.+ unsafe {+ web_notifications_api_unregister_notification(self.window().as_ptr(), self.id.get());+ web_notifications_api_abandon_notification(self.window().as_ptr(), self.id.get());+ }+ }++ fn did_show(this: Ref<Self>, vm: &Vm) {+ if this.state.get() != State::Showing {+ return;+ }+ Self::queue_task_to_fire_event(this, vm, "show");+ }++ fn did_fail_to_show(this: Ref<Self>, vm: &Vm) {+ if this.state.get() != State::Showing {+ return;+ }+ this.state.set(State::Closed);+ // SAFETY: The window is live.+ unsafe { web_notifications_api_unregister_notification(this.window().as_ptr(), this.id.get()) };+ Self::queue_task_to_fire_event(this, vm, "error");+ }++ // Step 2 of the non-persistent branch of https://notifications.spec.whatwg.org/#activating-a-notification+ fn did_click(this: Ref<Self>, vm: &Vm) {+ if this.state.get() != State::Showing && this.state.get() != State::Closing {+ return;+ }++ // Otherwise, queue a task to run these steps:+ queue_a_global_task(+ vm,+ this.realm.global_object(),+ TaskSource::UserInteraction,+ this,+ |_, this| {+ // 1. Let intoFocus be the result of firing an event named click on the Notification object representing+ // notification, with its cancelable attribute initialized to true.+ // NB: The user activated the notification, so the window gets transient activation first: That's what lets+ // focus() work from within the event listener, as the spec encourages.+ if let Some(window) = &this.window {+ window.set_last_activation_timestamp_to_now();+ }+ let event = CppEvent::create(this.realm, "click", false, true, false);+ let into_focus = this.event_target.dispatch_event(&event);++ // 2. If intoFocus is true, then the user agent should bring the notification's related browsing context's+ // viewport into focus.+ if let Some(window) = &this.window {+ // SAFETY: The window is live.+ unsafe {+ web_notifications_api_handle_notification_click(window.as_ptr(), this.id.get(), into_focus);+ }+ }+ },+ );+ }++ // https://notifications.spec.whatwg.org/#dom-notification-close+ pub(crate) fn close(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // The close() method steps are to run the close steps for this's notification.+ self.close_steps();+ Ok(())+ }++ // https://notifications.spec.whatwg.org/#close-steps+ fn close_steps(&self) {+ // 1. If the list of notifications does not contain notification, then abort these steps.+ // NB: A notification that's already on its way out (Closing) is left to the close the UI process is carrying out.+ if self.state.get() != State::Showing {+ return;+ }++ // 2. Handle close events with notification.+ // 3. Remove notification from the list of notifications.+ // NB: Both happen in did_close(), once the UI process has withdrawn the notification from the platform.+ self.state.set(State::Closing);+ // SAFETY: The window is live.+ unsafe { web_notifications_api_request_close_notification(self.window().as_ptr(), self.id.get()) };+ }++ // Steps 2 and 3 of https://notifications.spec.whatwg.org/#close-steps+ fn did_close(this: Ref<Self>, vm: &Vm) {+ if this.state.get() != State::Showing && this.state.get() != State::Closing {+ return;+ }++ // 2. Handle close events with notification.+ // https://notifications.spec.whatwg.org/#handle-close-events+ // 2. If notification is a non-persistent notification, then queue a task to fire an event named close on the+ // Notification object representing notification.+ Self::queue_task_to_fire_event(this, vm, "close");++ // 3. Remove notification from the list of notifications.+ this.state.set(State::Closed);+ // SAFETY: The window is live.+ unsafe { web_notifications_api_unregister_notification(this.window().as_ptr(), this.id.get()) };+ }++ fn queue_task_to_fire_event(this: Ref<Self>, vm: &Vm, event_name: &'static str) {+ queue_a_global_task(+ vm,+ this.realm.global_object(),+ TaskSource::Unspecified,+ (this, event_name),+ |_, (this, event_name)| {+ let event = CppEvent::create(this.realm, event_name, false, false, false);+ this.event_target.dispatch_event(&event);+ },+ );+ }++ // https://notifications.spec.whatwg.org/#dom-notification-permission+ pub(crate) fn permission(cx: &mut CallContext) -> WebIdlResult<NotificationPermission> {+ // The static permission getter steps are to return the result of getting the notifications permission state.+ // https://notifications.spec.whatwg.org/#permissions-integration+ // 1. Let permissionState be the result of getting the current permission state with "notifications".+ Ok(notification_permission_from(get_the_notifications_permission_state(+ ¤t_settings_object(cx.vm()),+ )))+ }++ // https://notifications.spec.whatwg.org/#dom-notification-requestpermission+ pub(crate) fn request_permission(+ cx: &mut CallContext,+ deprecated_callback: Option<CallbackFunction>,+ ) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();++ // 1. Let global be the current global object.+ let settings = current_settings_object(vm);+ let realm = settings.realm();+ let global = settings.global_object();++ // 2. Let promise be a new promise in this's relevant Realm.+ // NB: A static method has no "this"; the current realm is the one the call was made from.+ let promise = create_promise(vm, realm);++ // 3. Run these steps in parallel:+ // 1. Let permissionState be the result of requesting permission to use "notifications".+ // 2. Queue a global task on the DOM manipulation task source given global to run these steps:+ let request = PermissionRequest {+ realm,+ global,+ promise,+ deprecated_callback,+ settings: settings.clone(),+ };++ // AD-HOC: "Request permission to use" asks the user whenever the state is "prompt". We ask only from a document+ // that is its own top-level site, and only while it has transient activation, which the request consumes.+ // Any other request resolves with the state as it is, and nothing is stored, so the page may ask again+ // from a click. (A document that isn't a secure context already reads "denied" from the permission+ // state algorithm, so it never gets this far.) Each refusal is explained on the console.+ let current_state = get_the_notifications_permission_state(&settings);+ if current_state == PermissionState::Prompt {+ let window = window_from_global_object(global).expect("requestPermission() is exposed only to windows");+ let refuse = |message: &str| {+ realm.intrinsics().console_object(vm).console().output_debug_message(+ ConsoleLogLevel::Error,+ Utf16View::of_string(&Utf16String::from_utf8(message)),+ );+ Self::settle_permission_request(vm, request.clone());+ Ok(promise)+ };+ let is_its_own_top_level_site = settings.top_level_origin().is_some_and(|top_level_origin| {+ window.associated_document().origin().is_same_origin(&top_level_origin)+ });+ if !is_its_own_top_level_site {+ return refuse(+ "Notification permission can only be requested from a document whose origin is the top-level origin.",+ );+ }+ if !window.has_transient_activation() {+ return refuse("Notification permission can only be requested while handling a user gesture.");+ }+ window.consume_user_activation();+ }+ request_permission_to_use(+ vm,+ PermissionName::Notifications,+ &settings,+ request,+ |vm, request, _| {+ Self::settle_permission_request(vm, request);+ },+ );++ // 4. Return promise.+ Ok(promise)+ }++ fn settle_permission_request(vm: &Vm, request: PermissionRequest) {+ // AD-HOC: "Request permission to use" reports "denied" for a prompt the user dismissed, though it stores nothing+ // for it, and the page would then take a shrug for a refusal. The state the store holds once the+ // answer is in is reported instead: "default" after a dismissal, so the page may ask again later.+ let permission_state = get_the_notifications_permission_state(&request.settings);+ let global = request.global;+ queue_a_global_task(+ vm,+ global,+ TaskSource::DOMManipulation,+ (request, permission_state as u8),+ |vm, (request, permission_state)| {+ let permission_state = match permission_state {+ 0 => PermissionState::Granted,+ 1 => PermissionState::Denied,+ _ => PermissionState::Prompt,+ };+ with_temporary_execution_context_and_callbacks(request.realm, || {+ let cx = CallContext::new(vm, request.realm);+ let permission = enumeration_value_to_js(+ &cx,+ match notification_permission_from(permission_state) {+ NotificationPermission::Default => "default",+ NotificationPermission::Denied => "denied",+ NotificationPermission::Granted => "granted",+ },+ );++ // 1. If deprecatedCallback is given, then invoke deprecatedCallback with « permissionState » and "report".+ if let Some(deprecated_callback) = &request.deprecated_callback {+ deprecated_callback.invoke_and_report(&[permission]);+ }++ // 2. Resolve promise with permissionState.+ resolve_promise(vm, request.promise, permission);+ });+ },+ );+ }++ // https://notifications.spec.whatwg.org/#maximum-number-of-actions-supported+ // Two is what both desktop notification platforms show room for; persistent notifications, the only kind that+ // carries actions, aren't supported yet.+ const MAX_ACTIONS: u32 = 2;++ // https://notifications.spec.whatwg.org/#dom-notification-maxactions+ pub(crate) fn max_actions(_: &mut CallContext) -> WebIdlResult<u32> {+ Ok(Self::MAX_ACTIONS)+ }++ pub(crate) fn title(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.notification.title.clone())+ }++ pub(crate) fn dir(&self, _: &mut CallContext) -> WebIdlResult<NotificationDirection> {+ Ok(self.notification.direction)+ }++ pub(crate) fn lang(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.notification.language.clone())+ }++ pub(crate) fn body(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.notification.body.clone())+ }++ pub(crate) fn navigate(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ Ok(serialize_url_for_bindings(self.notification.navigation_url.as_ref()))+ }++ pub(crate) fn tag(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.notification.tag.clone())+ }++ pub(crate) fn image(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ Ok(serialize_url_for_bindings(self.notification.image_url.as_ref()))+ }++ pub(crate) fn icon(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ Ok(serialize_url_for_bindings(self.notification.icon_url.as_ref()))+ }++ pub(crate) fn badge(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ Ok(serialize_url_for_bindings(self.notification.badge_url.as_ref()))+ }++ pub(crate) fn timestamp(&self, _: &mut CallContext) -> WebIdlResult<u64> {+ Ok(self.notification.timestamp)+ }++ pub(crate) fn renotify(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.notification.renotify_preference)+ }++ pub(crate) fn silent(&self, _: &mut CallContext) -> WebIdlResult<Option<bool>> {+ Ok(self.notification.silent_preference)+ }++ pub(crate) fn require_interaction(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.notification.require_interaction_preference)+ }++ // https://notifications.spec.whatwg.org/#dom-notification-data+ pub(crate) fn data(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ // The data getter steps are to return StructuredDeserialize(this's notification's data, this's relevant Realm).+ // If this throws an exception, then return null.+ Ok(structured_deserialize_for_storage(cx, &self.notification.data).unwrap_or(Value::NULL))+ }++ // https://notifications.spec.whatwg.org/#dom-notification-actions+ pub(crate) fn actions(&self, _: &mut CallContext) -> WebIdlResult<Vec<NotificationAction>> {+ // 1. Let frozenActions be an empty list of type NotificationAction.+ let mut frozen_actions = Vec::with_capacity(self.notification.actions.len());++ // 2. For each entry of this’s notification’s actions:+ for entry in &self.notification.actions {+ // 1. Let action be a new NotificationAction.+ let action = NotificationAction {+ // 2. Set action["action"] to entry’s name.+ action: entry.name.clone(),++ // 3. Set action["title"] to entry’s title.+ title: entry.title.clone(),++ // 4. If entry’s navigation URL is non-null, then set action["navigate"] to entry’s navigation URL, serialized.+ navigate: entry+ .navigation_url+ .as_ref()+ .map(|url| serialize_url_for_bindings(Some(url))),++ // 5. If entry’s icon URL is non-null, then set action["icon"] to entry’s icon URL, serialized.+ icon: entry.icon_url.as_ref().map(|url| serialize_url_for_bindings(Some(url))),+ };++ // FIXME: 6. Call Object.freeze on action, to prevent accidental mutation by scripts.++ // 7. Append action to frozenActions.+ frozen_actions.push(action);+ }++ // 3. Return the result of create a frozen array from frozenActions.+ // NB: The bindings freeze the array they build from this sequence.+ Ok(frozen_actions)+ }+}++/// # Safety+///+/// `notification` must be the live cell of a Notification.+unsafe fn notification_from_abi(notification: *mut c_void) -> Ref<Notification> {+ // SAFETY: The caller passes the live cell of a Notification.+ unsafe { cell_from_abi(notification) }+}++/// # Safety+///+/// `notification` must be the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_id_for_testing(notification: *mut c_void) -> u64 {+ // SAFETY: The caller passes a live cell.+ unsafe { notification_from_abi(notification) }.id.get()+}++/// # Safety+///+/// `notification` must be the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_document(notification: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live cell.+ unsafe { notification_from_abi(notification) }.document_ptr()+}++/// Whether the notification still waits for its icon.+///+/// # Safety+///+/// `notification` must be the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_is_pending(notification: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { notification_from_abi(notification) }.state.get() == State::Pending+}++/// # Safety+///+/// `notification` must be the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_icon_bytes_arrived(notification: *mut c_void) {+ // SAFETY: The caller passes a live cell.+ let notification = unsafe { notification_from_abi(notification) };+ if let Some(fetch_timeout) = &*notification.fetch_timeout.borrow() {+ fetch_timeout.stop();+ }+}++/// The icon resource is set, or there is none.+///+/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_icon_fetched(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ Notification::fetch_steps_done(notification, vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_abandon(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ notification.abandon(vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_did_show(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ Notification::did_show(notification, vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_did_fail_to_show(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ Notification::did_fail_to_show(notification, vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_did_click(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ Notification::did_click(notification, vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `notification` the live cell of a Notification.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_notifications_api_did_close(vm: *mut c_void, notification: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live cell.+ let (vm, notification) = unsafe { (&*vm.cast::<Vm>(), notification_from_abi(notification)) };+ Notification::did_close(notification, vm);+}diff --git a/Libraries/LibWeb/NotificationsAPI/NotificationPermission.cpp b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification_permission.rssimilarity index 53%rename from Libraries/LibWeb/NotificationsAPI/NotificationPermission.cpprename to Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification_permission.rsindex cd40f2ed2c9..a06d43334d9 100644--- a/Libraries/LibWeb/NotificationsAPI/NotificationPermission.cpp+++ b/Libraries/LibWeb/Bindings/Rust/src/notifications_api/notification_permission.rs@@ -4,21 +4,18 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/NotificationsAPI/NotificationPermission.h>-#include <LibWeb/PermissionsAPI/Permissions.h>--namespace Web::NotificationsAPI {+use crate::bindings::environment_settings_object::CppEnvironmentSettingsObject;+use crate::permissions::permissions::PermissionName;+use crate::permissions_api::permission_status::PermissionState;+use crate::permissions_api::permissions::permission_state;// https://notifications.spec.whatwg.org/#permissions-integration-PermissionsAPI::PermissionState get_the_notifications_permission_state(HTML::EnvironmentSettingsObject& settings)-{+pub(crate) fn get_the_notifications_permission_state(settings: &CppEnvironmentSettingsObject) -> PermissionState {// To get the notifications permission state, run these steps:// 1. Let permissionState be the result of getting the current permission state with "notifications".- return PermissionsAPI::permission_state(Web::Permissions::PermissionName::Notifications, settings);+ permission_state(PermissionName::Notifications, settings)// NB: Steps 2 and 3, which turn "prompt" into "default", belong to the permission getter: Every other caller wants// the raw state.}--}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 659e736a3e7..06918d1043c 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -29,9 +29,11 @@#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/HTML/WindowProxy.h>#include <LibWeb/HTML/WorkerGlobalScope.h>+#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/NavigationTiming/PerformanceNavigationTiming.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/EventLoopPlugin.h>+#include <LibWeb/ServiceWorker/ServiceWorkerGlobalScope.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/CallbackType.h>#include <LibWeb/WebIDL/DOMException.h>@@ -109,11 +111,15 @@ DOM::Document* web_bindings_window_associated_document(HTML::Window*);JS::Realm* web_bindings_window_realm(HTML::Window*);u64 web_bindings_window_page_id(HTML::Window*);bool web_bindings_window_has_transient_activation(HTML::Window*);+void web_bindings_window_consume_user_activation(HTML::Window*);+void web_bindings_window_set_last_activation_timestamp_to_now(HTML::Window*);+bool web_bindings_is_service_worker_global_scope(JSObject* global_object);DOM::EventTarget* web_bindings_window_as_event_target(HTML::Window*);HTML::LocalNavigable* web_bindings_document_navigable(DOM::Document*);bool web_bindings_document_is_fully_active(DOM::Document*);bool web_bindings_document_is_allowed_to_use_feature(DOM::Document*, u8 feature);u8 web_bindings_document_visibility_state(DOM::Document*);+void web_bindings_document_origin(DOM::Document*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));bool web_bindings_document_has_focus(DOM::Document*);bool web_bindings_document_has_been_destroyed(DOM::Document*);URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);@@ -123,6 +129,7 @@ NavigationTiming::PerformanceNavigationTiming* web_bindings_document_navigation_void web_bindings_document_set_navigation_timing_entry(DOM::Document*, NavigationTiming::PerformanceNavigationTiming*);HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object);+HTML::EnvironmentSettingsObject* web_bindings_principal_realm_settings_object(void* realm);JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject*);JS::Realm* web_bindings_environment_settings_object_realm(HTML::EnvironmentSettingsObject*);double web_bindings_environment_settings_object_time_origin(HTML::EnvironmentSettingsObject*);@@ -131,6 +138,9 @@ void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObjectbool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget*, bool has_pending_activity);void web_bindings_environment_settings_object_origin(HTML::EnvironmentSettingsObject*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));+bool web_bindings_environment_settings_object_top_level_origin(HTML::EnvironmentSettingsObject*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));+void web_bindings_environment_settings_object_api_base_url(HTML::EnvironmentSettingsObject*, void* url, void (*on_url)(void*, URL::FFI::RustUrl const*));+double web_bindings_environment_settings_object_current_wall_time(HTML::EnvironmentSettingsObject*);void web_bindings_environment_settings_object_encoding_parse_url(HTML::EnvironmentSettingsObject*, FlatPtr url, void* parsed_url, void (*on_url)(void*, URL::FFI::RustUrl const*));void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*));bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);@@ -233,6 +243,22 @@ bool web_bindings_window_has_transient_activation(HTML::Window* window)return window->has_transient_activation();}+void web_bindings_window_consume_user_activation(HTML::Window* window)+{+ window->consume_user_activation();+}++void web_bindings_window_set_last_activation_timestamp_to_now(HTML::Window* window)+{+ window->set_last_activation_timestamp(HighResolutionTime::current_high_resolution_time(HTML::relevant_realm(*window).global_object()));+}++bool web_bindings_is_service_worker_global_scope(JSObject* global_object)+{+ auto* worker_global_scope = Bindings::worker_global_scope_from_global_object(*JS::HostABI::object_from_abi(global_object));+ return worker_global_scope && is<ServiceWorker::ServiceWorkerGlobalScope>(*worker_global_scope);+}+DOM::EventTarget* web_bindings_window_as_event_target(HTML::Window* window){return window;@@ -263,6 +289,13 @@ u8 web_bindings_document_visibility_state(DOM::Document* document)return to_underlying(document->visibility_state());}+void web_bindings_document_origin(DOM::Document* document, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))+{+ URL::RustIntegration::lend_origin_to_ffi(document->origin(), [&](URL::FFI::FfiOrigin const& ffi_origin) {+ on_origin(origin, &ffi_origin);+ });+}+bool web_bindings_document_has_focus(DOM::Document* document){return document->has_focus();@@ -303,6 +336,11 @@ HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject*return &HTML::relevant_settings_object(*JS::HostABI::object_from_abi(global_object));}+HTML::EnvironmentSettingsObject* web_bindings_principal_realm_settings_object(void* realm)+{+ return &HTML::principal_realm_settings_object(*static_cast<JS::Realm*>(realm));+}+JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject* settings_object){return JS::HostABI::object_to_abi(&settings_object->global_object());@@ -345,6 +383,27 @@ void web_bindings_environment_settings_object_origin(HTML::EnvironmentSettingsOb});}+bool web_bindings_environment_settings_object_top_level_origin(HTML::EnvironmentSettingsObject* settings_object, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*))+{+ if (!settings_object->top_level_origin.has_value())+ return false;+ URL::RustIntegration::lend_origin_to_ffi(*settings_object->top_level_origin, [&](URL::FFI::FfiOrigin const& ffi_origin) {+ on_origin(origin, &ffi_origin);+ });+ return true;+}++void web_bindings_environment_settings_object_api_base_url(HTML::EnvironmentSettingsObject* settings_object, void* url, void (*on_url)(void*, URL::FFI::RustUrl const*))+{+ auto rust_url = settings_object->api_base_url().to_rust();+ on_url(url, &rust_url);+}++double web_bindings_environment_settings_object_current_wall_time(HTML::EnvironmentSettingsObject* settings_object)+{+ return settings_object->current_wall_time();+}+void web_bindings_environment_settings_object_encoding_parse_url(HTML::EnvironmentSettingsObject* settings_object, FlatPtr url, void* parsed_url, void (*on_url)(void*, URL::FFI::RustUrl const*)){auto result = settings_object->encoding_parse_url(Utf16String::from_raw(url));@@ -450,6 +509,7 @@ void web_bindings_spin_until_promise_is_settled(JSObject* promise)// NB: The task sources of the Rust bindings' TaskSource.static_assert(to_underlying(HTML::Task::Source::Unspecified) == 0);+static_assert(to_underlying(HTML::Task::Source::UserInteraction) == 2);static_assert(to_underlying(HTML::Task::Source::Networking) == 3);static_assert(to_underlying(HTML::Task::Source::Geolocation) == 10);static_assert(to_underlying(HTML::Task::Source::TimerTask) == 8);diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex d176cfcb791..513de48dec2 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -692,7 +692,6 @@ set(SOURCESNamespace.cppNavigationTiming/PerformanceNavigationTiming.cppNotificationsAPI/Notification.cpp- NotificationsAPI/NotificationPermission.cppPage/AutoScrollHandler.cppPage/DragAndDropEventHandler.cppPage/ElementResizeAction.cppdiff --git a/Libraries/LibWeb/NotificationsAPI/Notification.cpp b/Libraries/LibWeb/NotificationsAPI/Notification.cppindex a7d8f70b39b..80d214f2100 100644--- a/Libraries/LibWeb/NotificationsAPI/Notification.cpp+++ b/Libraries/LibWeb/NotificationsAPI/Notification.cpp@@ -4,390 +4,166 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Math.h>-#include <AK/Time.h>#include <LibGC/Heap.h>-#include <LibJS/Console.h>-#include <LibJS/Runtime/ConsoleObject.h>-#include <LibJS/Runtime/Object.h>+#include <LibGfx/Bitmap.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/Event.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventNames.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/HTML/Window.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/NotificationsAPI/Notification.h>-#include <LibWeb/NotificationsAPI/NotificationPermission.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Painting/PaintingRustBridge.h>-#include <LibWeb/PermissionsAPI/Permissions.h>#include <LibWeb/Platform/ImageCodecPlugin.h>-#include <LibWeb/Platform/Timer.h>-#include <LibWeb/ServiceWorker/ServiceWorkerGlobalScope.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/Promise.h>+#include <LibWebCommon/NotificationsAPI/NotificationData.h>namespace Web::NotificationsAPI {-GC_DEFINE_ALLOCATOR(Notification);+// https://notifications.spec.whatwg.org/#icon-resource+class NotificationIcon final : public GC::Cell {+ GC_CELL(NotificationIcon, GC::Cell);+ GC_DECLARE_ALLOCATOR(NotificationIcon);-Notification::Notification()- : DOM::EventTarget()-{-}--void Notification::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_relevant_global);- visitor.visit(m_page);- visitor.visit(m_icon_fetch_controller);- visitor.visit(m_fetch_timeout);-}--WebIDL::ExceptionOr<NotificationOptions> Notification::options_from_bindings(JS::VM& vm, Bindings::NotificationOptions const& options)-{- Vector<NotificationAction> actions;- actions.ensure_capacity(options.actions.size());- for (auto const& entry : options.actions) {- actions.append(NotificationAction {- .action = entry.action,- .title = entry.title,- .navigate = entry.navigate,- .icon = entry.icon,- });+public:+ explicit NotificationIcon(GC::Ref<Notification> notification)+ : m_notification(notification)+ {}- return NotificationOptions {- .direction = options.dir,- .language = options.lang,- .body = options.body,- .navigate = options.navigate,- .tag = options.tag,- .image = options.image,- .icon = options.icon,- .badge = options.badge,- .vibrate = options.vibrate,- .timestamp = options.timestamp,- .renotify = options.renotify,- .silent = options.silent,- .require_interaction = options.require_interaction,- .data = TRY(HTML::structured_serialize_for_storage(vm, options.data)),- .actions = move(actions),- };-}--WebIDL::ExceptionOr<GC::Ref<Notification>> Notification::create_for_constructor(JS::Object& relevant_global_object, Utf16String const& title, Bindings::NotificationOptions const& options)-{- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object);- VERIFY(global_scope);-- // The constructor rejects actions before attempting to serialize data.- if (!options.actions.is_empty())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Options `action` is not empty"_utf16 };-- auto title_utf8 = title.to_utf8();- return create_with_global_scope(relevant_global_object, *global_scope, title_utf8, TRY(options_from_bindings(relevant_global_object.shape().realm().vm(), options)));-}--// https://notifications.spec.whatwg.org/#create-a-notification-WebIDL::ExceptionOr<ConceptNotification> Notification::create_a_notification(- String const& title,- NotificationOptions options,- URL::Origin origin,- URL::URL base_url,- HighResolutionTime::EpochTimeStamp fallback_timestamp)-{- // 1. Let notification be a new notification.- ConceptNotification notification;-- // 2. If options["silent"] is true and options["vibrate"] exists, then throw a TypeError.- if (options.silent == true && options.vibrate.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "options[\"vibrate\"] cannot be set when options[\"silent\"] is true."_utf16 };+ GC::Ref<Notification> m_notification;+ RefPtr<Gfx::Bitmap const> m_resource;+ GC::Ptr<Fetch::Infrastructure::FetchController> m_fetch_controller;- // 3. If options["renotify"] is true and options["tag"] is the empty string, then throw a TypeError.- if (options.renotify && options.tag.is_empty())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "options[\"tag\"] cannot be the empty string when options[\"renotify\"] is set to true."_utf16 };-- // 4. Set notification’s data to StructuredSerializeForStorage(options["data"]).- notification.data = move(options.data);-- // 5. Set notification’s title to title.- notification.title = title;-- // 6. Set notification’s direction to options["dir"].- notification.direction = options.direction;-- // 7. Set notification’s language to options["lang"].- notification.language = move(options.language);-- // 8. Set notification’s origin to origin.- notification.origin = move(origin);-- // 9. Set notification’s body to options["body"].- notification.body = move(options.body);-- // 10. If options["navigate"] exists, then parse it using baseURL, and if that does not return failure,- // set notification’s navigation URL to the return value. (Otherwise notification’s navigation URL remains null.)- if (options.navigate.has_value()) {- auto navigate = options.navigate->to_utf8();- notification.navigation_url = base_url.complete_url(navigate);- }-- // 11. Set notification’s tag to options["tag"].- notification.tag = move(options.tag);-- // 12. If options["image"] exists, then parse it using baseURL, and if that does not return failure,- // set notification’s image URL to the return value. (Otherwise notification’s image URL is not set.)- if (options.image.has_value()) {- auto image = options.image->to_utf8();- notification.image_url = base_url.complete_url(image);- }-- // 13. If options["icon"] exists, then parse it using baseURL, and if that does not return failure,- // set notification’s icon URL to the return value. (Otherwise notification’s icon URL is not set.)- if (options.icon.has_value()) {- auto icon = options.icon->to_utf8();- notification.icon_url = base_url.complete_url(icon);+private:+ virtual void visit_edges(Cell::Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ visitor.visit(m_notification);+ visitor.visit(m_fetch_controller);}+};- // 14. If options["badge"] exists, then parse it using baseURL, and if that does not return failure,- // set notification’s badge URL to the return value. (Otherwise notification’s badge URL is not set.)- if (options.badge.has_value()) {- auto badge = options.badge->to_utf8();- notification.badge_url = base_url.complete_url(badge);- }-- // FIXME: 15. If options["vibrate"] exists, then validate and normalize it and- // set notification’s vibration pattern to the return value.-- // 16. If options["timestamp"] exists, then set notification’s timestamp to the value.- // Otherwise, set notification’s timestamp to fallbackTimestamp.- if (options.timestamp.has_value())- notification.timestamp = options.timestamp.value();- else- notification.timestamp = fallback_timestamp;-- // 17. Set notification’s renotify preference to options["renotify"].- notification.renotify_preference = options.renotify;+GC_DEFINE_ALLOCATOR(NotificationIcon);- // 18. Set notification’s silent preference to options["silent"].- notification.silent_preference = options.silent;+namespace {- // 19. Set notification’s require interaction preference to options["requireInteraction"].- notification.require_interaction_preference = options.require_interaction;+struct NotificationDataAbi {+ FlatPtr title;+ FlatPtr body;+ FlatPtr tag;+ FlatPtr language;+ u8 direction;+ bool has_silent;+ bool silent;+ bool require_interaction;+ bool renotify;+};- // 20. Set notification’s actions to « ».- notification.actions = {};-- // 21. For each entry in options["actions"], up to the maximum number of actions supported (skip any excess entries):- for (auto const& entry : options.actions) {- if (notification.actions.size() >= max_actions())- break;-- // 1. Let action be a new notification action.- ConceptNotification::Action action;-- // 2. Set action’s name to entry["action"].- action.name = entry.action;-- // 3. Set action’s title to entry["title"].- action.title = entry.title;+}- // 4. If entry["navigate"] exists, then parse it using baseURL, and if that does not return failure,- // set action’s navigation URL to the return value. (Otherwise action’s navigation URL remains null.)- if (entry.navigate.has_value()) {- auto navigate = entry.navigate->to_utf8();- action.navigation_url = base_url.complete_url(navigate);- }+extern "C" {+// Defined in Bindings/Rust/src/notifications_api/notification.rs.+u64 web_rust_notifications_api_id_for_testing(Notification*);+DOM::Document* web_rust_notifications_api_document(Notification*);+bool web_rust_notifications_api_is_pending(Notification*);+void web_rust_notifications_api_icon_bytes_arrived(Notification*);+void web_rust_notifications_api_icon_fetched(JSVM*, Notification*);+void web_rust_notifications_api_abandon(JSVM*, Notification*);+void web_rust_notifications_api_did_show(JSVM*, Notification*);+void web_rust_notifications_api_did_fail_to_show(JSVM*, Notification*);+void web_rust_notifications_api_did_click(JSVM*, Notification*);+void web_rust_notifications_api_did_close(JSVM*, Notification*);++u64 web_notifications_api_register_notification(HTML::Window*, Notification*);+void web_notifications_api_unregister_notification(HTML::Window*, u64 notification_id);+NotificationIcon* web_notifications_api_fetch_icon(Notification*, HTML::EnvironmentSettingsObject*, URL::FFI::RustUrl const*);+void web_notifications_api_stop_icon_fetch(NotificationIcon*);+void web_notifications_api_show_notification(HTML::Window*, u64 notification_id, NotificationDataAbi const*, NotificationIcon*);+void web_notifications_api_request_close_notification(HTML::Window*, u64 notification_id);+void web_notifications_api_abandon_notification(HTML::Window*, u64 notification_id);+void web_notifications_api_handle_notification_click(HTML::Window*, u64 notification_id, bool into_focus);+}- // 5. If entry["icon"] exists, then parse it using baseURL, and if that does not return failure,- // set action’s icon URL to the return value. (Otherwise action’s icon URL remains null.)- if (entry.icon.has_value()) {- auto icon = entry.icon->to_utf8();- action.icon_url = base_url.complete_url(icon);- }+static_assert(to_underlying(Bindings::NotificationDirection::Auto) == 0);+static_assert(to_underlying(Bindings::NotificationDirection::Ltr) == 1);+static_assert(to_underlying(Bindings::NotificationDirection::Rtl) == 2);- // 6. Append action to notification’s actions.- notification.actions.append(action);- }-- // 22. Return notification.- return notification;+static JSVM* the_vm()+{+ return JS::HostABI::vm_to_abi(JS::VM::the());}-// https://notifications.spec.whatwg.org/#create-a-notification-with-a-settings-object-WebIDL::ExceptionOr<ConceptNotification> Notification::create_a_notification_with_a_settings_object(- String const& title,- NotificationOptions options,- GC::Ref<HTML::EnvironmentSettingsObject> settings)+u64 Notification::id_for_testing() const{- // 1. Let origin be settings’s origin.- URL::Origin origin = settings->origin();-- // 2. Let baseURL be settings’s API base URL.- URL::URL base_url = settings->api_base_url();-- // 3. Let fallbackTimestamp be the number of milliseconds from the Unix epoch to settings’s current wall time,- // rounded to the nearest integer.- auto fallback_timestamp = round_to<HighResolutionTime::EpochTimeStamp>(settings->current_wall_time());+ return web_rust_notifications_api_id_for_testing(const_cast<Notification*>(this));+}- // 4. Return the result of creating a notification given title, options, origin, baseURL, and fallbackTimestamp.- return create_a_notification(title, move(options), origin, base_url, fallback_timestamp);+DOM::Document const* Notification::document() const+{+ return web_rust_notifications_api_document(const_cast<Notification*>(this));}-// https://notifications.spec.whatwg.org/#constructors-WebIDL::ExceptionOr<GC::Ref<Notification>> Notification::create_with_global_scope(- JS::Object& relevant_global_object,- HTML::WindowOrWorkerGlobalScopeMixin& global_scope,- String const& title,- NotificationOptions options)+void Notification::abandon(){- auto& relevant_settings_object = HTML::relevant_settings_object(global_scope);-- // 1. If this’s relevant global object is a ServiceWorkerGlobalScope object, then throw a TypeError.- if (is<ServiceWorker::ServiceWorkerGlobalScope>(global_scope.this_impl()))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "This’s relevant global object is a ServiceWorkerGlobalScope object"_utf16 };-- // 2. If options["actions"] is not empty, then throw a TypeError.- if (!options.actions.is_empty())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Options `action` is not empty"_utf16 };-- // 3. Let notification be the result of creating a notification with a settings object given title, options, and this’s relevant settings object.- ConceptNotification notification = TRY(create_a_notification_with_a_settings_object(title, move(options), relevant_settings_object));-- // 4. Associate this with notification.- auto this_notification = GC::Heap::the().allocate<Notification>();- this_notification->m_notification = notification;- this_notification->m_relevant_global = relevant_global_object;- if (auto* window = HTML::window_from_global_object(relevant_global_object))- this_notification->m_page = window->page();-- // 5. Run these steps in parallel:- // AD-HOC: The steps run from a task on the relevant global instead of in parallel: Showing crosses to the UI- // process asynchronously anyway, and a task keeps the permission read and the event firing on the main- // thread, after the constructor's caller has had its turn to attach event handlers.- HTML::queue_global_task(HTML::Task::Source::Unspecified, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(this_notification), [](auto& this_notification) {- this_notification->run_steps_in_parallel_after_construction();- }));-- return this_notification;+ web_rust_notifications_api_abandon(the_vm(), this);}-// Step 5 of https://notifications.spec.whatwg.org/#constructors-void Notification::run_steps_in_parallel_after_construction()+void Notification::did_show(){- // 1. If the result of getting the notifications permission state is not "granted", then queue a task to fire an- // event named error on this, and abort these steps.- if (get_the_notifications_permission_state(HTML::relevant_settings_object(*m_relevant_global)) != PermissionsAPI::PermissionState::Granted) {- queue_task_to_fire_event(HTML::EventNames::error);- return;- }+ web_rust_notifications_api_did_show(the_vm(), this);+}- // AD-HOC: The spec lets any document or worker show a notification. We refuse two cases until they're supported:- // A worker has no page to route the notification's events through, and a document whose origin differs- // from its top-level origin would have its notification attributed to the top-level site. Both get an- // error event, as if permission had been denied.- auto* window = HTML::window_from_global_object(*m_relevant_global);- if (!window || !m_page) {- queue_task_to_fire_event(HTML::EventNames::error);- return;- }- auto& settings = HTML::relevant_settings_object(*m_relevant_global);- if (!settings.top_level_origin.has_value() || !settings.top_level_origin->is_same_origin(settings.origin())) {- queue_task_to_fire_event(HTML::EventNames::error);- return;- }+void Notification::did_fail_to_show()+{+ web_rust_notifications_api_did_fail_to_show(the_vm(), this);+}- // 2. Run the notification show steps for notification.- show_steps();+void Notification::did_click()+{+ web_rust_notifications_api_did_click(the_vm(), this);}-// The longest a notification waits for its icon before it shows without one.-static constexpr auto icon_fetch_timeout = AK::Duration::from_seconds(5);-// The longest side an icon is sent to the platform at; both desktop platforms show icons smaller than this.-static constexpr int icon_maximum_side = 128;+void Notification::did_close(bool)+{+ web_rust_notifications_api_did_close(the_vm(), this);+}-// https://notifications.spec.whatwg.org/#notification-show-steps-void Notification::show_steps()+u64 web_notifications_api_register_notification(HTML::Window* window, Notification* notification){- // The notification joins the page's list now, rather than once it's displayed: The list is what keeps it alive- // while its icon is on its way, and what lets the page withdraw it if the document goes away before then.- m_id = m_page->allocate_notification_id();- m_page->register_showing_notification(m_id, *this);- m_state = State::Pending;-- // 1. Run the fetch steps given notification and settings.- // 2. Wait for any fetches to complete and notification's image resource, icon resource, and badge resource to- // be set (if any), as well as the icon resources for the notification's actions (if any).- // AD-HOC: The wait for the fetch is bounded: An icon that hasn't arrived after a few seconds isn't worth holding- // the notification back for, so it then shows without one.- m_fetch_timeout = Platform::Timer::create_single_shot(heap(), icon_fetch_timeout, GC::create_function(heap(), GC::captures(*this), [](auto& self) {- if (self.m_icon_fetch_controller)- self.m_icon_fetch_controller->stop_fetch();- self.m_icon_fetch_controller = nullptr;- self.display();- }));- m_fetch_timeout->start();- run_the_fetch_steps(GC::create_function(heap(), GC::captures(*this), [](auto& self) {- if (!self.m_fetch_timeout)- return;- self.m_fetch_timeout->stop();- self.display();- }));+ auto& page = window->page();+ auto notification_id = page.allocate_notification_id();+ page.register_showing_notification(notification_id, *notification);+ return notification_id;}-// https://notifications.spec.whatwg.org/#fetch-steps-void Notification::run_the_fetch_steps(GC::Ref<GC::Function<void()>> on_done)+void web_notifications_api_unregister_notification(HTML::Window* window, u64 notification_id){- // 1. If the notification platform supports images and notification's image URL is set, then fetch a notification- // resource given notification, notification's image URL, settings, and the following step given a resource- // resource: set notification's image resource to resource.- // NB: No platform we show on takes an image.-- // 2. If the notification platform supports icons and notification's icon URL is set, then fetch a notification- // resource given notification, notification's icon URL, settings, and the following step given a resource- // resource: set notification's icon resource to resource.- if (!m_notification.icon_url.has_value()) {- on_done->function()();- return;- }- fetch_a_notification_resource(*m_notification.icon_url, GC::create_function(heap(), GC::captures(*this, on_done), [](auto& self, auto& on_done, RefPtr<Gfx::Bitmap const> resource) {- self.m_icon_resource = move(resource);- on_done->function()();- }));-- // 3. If the notification platform supports badges and notification's badge URL is set, then fetch a notification- // resource given notification, notification's badge URL, settings, and the following step given a resource- // resource: set notification's badge resource to resource.- // NB: No platform we show on takes a badge.-- // 4. If the notification platform supports actions and action icons, then for each entry of notification's- // actions: if entry's icon URL is non-null, then fetch a notification resource given notification, entry's- // icon URL, settings, and the following step given a resource resource: set entry's icon resource to resource.- // NB: A non-persistent notification has no actions.+ window->page().unregister_notification(notification_id);}+// The longest side an icon is sent to the platform at; both desktop platforms show icons smaller than this.+static constexpr int icon_maximum_side = 128;+// https://notifications.spec.whatwg.org/#fetch-a-notification-resource-void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GC::Function<void(RefPtr<Gfx::Bitmap const>)>> process_resource)+NotificationIcon* web_notifications_api_fetch_icon(Notification* notification, HTML::EnvironmentSettingsObject* settings, URL::FFI::RustUrl const* rust_url){- auto& settings = HTML::relevant_settings_object(*m_relevant_global);+ URL::URL url;+ url.set_from_rust(*rust_url);+ auto icon = GC::Heap::the().allocate<NotificationIcon>(*notification);+ GC::Ptr<Page> page;+ if (auto* window = HTML::window_from_global_object(settings->global_object()))+ page = window->page();// 1. Let request be a new request whose URL is url, client is settings, destination is "image", mode is// "no-cors", and credentials mode is "include".auto request = Fetch::Infrastructure::Request::create();request->set_url(url);- request->set_client(settings.address());+ request->set_client(settings->address());request->set_destination(Fetch::Infrastructure::Request::Destination::Image);request->set_mode(Fetch::Infrastructure::Request::Mode::NoCORS);request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);@@ -399,34 +175,31 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GC// 3. Fetch request with useParallelQueue set to true and processResponseConsumeBody set to the following steps// given a response response and null, failure, or a byte sequence bytes:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = GC::create_function(heap(), GC::captures(*this, process_resource), [](auto& self, auto& process_resource, GC::Ref<Fetch::Infrastructure::ResponseView>, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bytes) {- self.m_icon_fetch_controller = nullptr;+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(icon, page), [](auto& icon, auto& page, GC::Ref<Fetch::Infrastructure::ResponseView>, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bytes) {+ icon->m_fetch_controller = nullptr;// The bytes are here, so the wait is no longer on the network: Decoding them finishes on its own, however// long a busy machine takes over it.- if (self.m_fetch_timeout)- self.m_fetch_timeout->stop();+ web_rust_notifications_api_icon_bytes_arrived(icon->m_notification.ptr());// 1. If bytes is null or failure, then return.// AD-HOC: The show steps wait on this fetch, so an absent resource is reported as such, rather than left// for the timeout to notice.if (!bytes.has<Core::ImmutableBytes>()) {- process_resource->function()(nullptr);+ web_rust_notifications_api_icon_fetched(the_vm(), icon->m_notification.ptr());return;}// 2. Attempt to decode bytes as an image.// 3. If the image format is supported, then run processResource given the decoded image.- // NB: The decoder answers from outside the heap's view, so the notification and the step it hands the- // resource to are rooted for the wait: Nothing else holds the step once the fetch is over. An answer for a- // notification that's gone in the meantime is dropped.- auto on_decoded = [self = GC::Root(self), process_resource = GC::Root(*process_resource)](Platform::DecodedImage& decoded_image) -> ErrorOr<void> {+ // NB: The decoder answers from outside the heap's view, so the icon, which holds the notification, is rooted+ // for the wait. An answer for a notification that's gone in the meantime is dropped.+ auto on_decoded = [icon = GC::Root(icon), page = GC::Root(page)](Platform::DecodedImage& decoded_image) -> ErrorOr<void> {// NB: Only the first frame is used, so an animation the decoder opened is stopped right away.if (decoded_image.session_id != 0)Platform::ImageCodecPlugin::the().stop_animation_decode(decoded_image.session_id);- if (self->m_state != State::Pending)+ if (!web_rust_notifications_api_is_pending(icon->m_notification.ptr()))return {};- auto* this_notification = self.ptr();- auto* m_page = this_notification->m_page.ptr();+ auto* m_page = page.ptr();RefPtr<Gfx::Bitmap const> bitmap;if (!decoded_image.frames.is_empty() && decoded_image.frames[0].bitmap) {bitmap = decoded_image.frames[0].bitmap;@@ -445,340 +218,57 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GC}}}- process_resource->function()(move(bitmap));+ icon->m_resource = move(bitmap);+ web_rust_notifications_api_icon_fetched(the_vm(), icon->m_notification.ptr());return {};};- auto on_decode_failed = [self = GC::Root(self), process_resource = GC::Root(*process_resource)](Error&) {- if (self->m_state != State::Pending)+ auto on_decode_failed = [icon = GC::Root(icon)](Error&) {+ if (!web_rust_notifications_api_is_pending(icon->m_notification.ptr()))return;- process_resource->function()(nullptr);+ web_rust_notifications_api_icon_fetched(the_vm(), icon->m_notification.ptr());};(void)Platform::ImageCodecPlugin::the().decode_image(bytes.get<Core::ImmutableBytes>().bytes(), move(on_decoded), move(on_decode_failed));});- m_icon_fetch_controller = Fetch::Fetching::fetch(settings.realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);-}--// Steps 3 to 8 of https://notifications.spec.whatwg.org/#notification-show-steps-void Notification::display()-{- m_fetch_timeout = nullptr;- if (m_state != State::Pending)- return;-- // A document that went away while the icon was on its way gets no notification: The page may show another site- // by now, and the notification would be attributed to that one.- auto const* document = this->document();- if (!document || !document->is_fully_active()) {- abandon();- return;- }-- // 3. Let shown be false.- // 4. Let oldNotification be the notification in the list of notifications whose tag is not the empty string and is- // notification's tag, and whose origin is same origin with notification's origin, if any, and null otherwise.- // 5. If oldNotification is non-null:- // 1. Handle close events with oldNotification.- // 2. If the notification platform supports replacement:- // 1. Replace oldNotification with notification, in the list of notifications.- // 2. Set shown to true.- // 3. Otherwise, remove oldNotification from the list of notifications.- // 6. If shown is false:- // 1. Append notification to the list of notifications.- // 2. Display notification on the device (e.g., by calling the appropriate notification platform API).- // 7. If shown is false or oldNotification is non-null, and notification's renotify preference is true, then- // optionally alert the end user in a user-agent-defined manner (e.g., by playing a sound).- // NB: Steps 4, 5 and 7 are the UI process's: It sees every page's notifications, so it finds oldNotification- // across pages, replaces it on the platform, and reports its close back through notification_closed().- // Here, the notification joins this page's part of the list and is sent off for display.- m_state = State::Showing;- m_page->client().page_did_request_show_notification(m_id, document->id(), data(), m_icon_resource);-- // 8. If notification is a non-persistent notification, then queue a task to fire an event named show on the- // Notification object representing notification.- // NB: Fired from did_show(), once the platform has shown the notification: Until then the display can still fail,- // and a failure fires error instead.-}--DOM::Document const* Notification::document() const-{- if (auto const* window = HTML::window_from_global_object(*m_relevant_global))- return &window->associated_document();- return nullptr;-}--void Notification::abandon()-{- // Still on its way to the platform: Nothing has been shown, so there's nothing to tell the UI process.- if (m_state == State::Pending) {- m_state = State::Closed;- if (m_fetch_timeout)- m_fetch_timeout->stop();- m_fetch_timeout = nullptr;- if (m_icon_fetch_controller)- m_icon_fetch_controller->stop_fetch();- m_icon_fetch_controller = nullptr;- m_page->unregister_notification(m_id);- return;- }- if (m_state != State::Showing && m_state != State::Closing)- return;- m_state = State::Closed;- m_page->unregister_notification(m_id);- m_page->client().page_did_abandon_notification(m_id);-}--void Notification::did_show()-{- if (m_state != State::Showing)- return;- queue_task_to_fire_event(HTML::EventNames::show);-}--void Notification::did_fail_to_show()-{- if (m_state != State::Showing)- return;- m_state = State::Closed;- m_page->unregister_notification(m_id);- queue_task_to_fire_event(HTML::EventNames::error);-}--// Step 2 of the non-persistent branch of https://notifications.spec.whatwg.org/#activating-a-notification-void Notification::did_click()-{- if (m_state != State::Showing && m_state != State::Closing)- return;-- // Otherwise, queue a task to run these steps:- HTML::queue_global_task(HTML::Task::Source::UserInteraction, *m_relevant_global, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {- // 1. Let intoFocus be the result of firing an event named click on the Notification object representing- // notification, with its cancelable attribute initialized to true.- // NB: The user activated the notification, so the window gets transient activation first: That's what lets- // focus() work from within the event listener, as the spec encourages.- if (auto* window = HTML::window_from_global_object(*self.m_relevant_global))- window->set_last_activation_timestamp(HighResolutionTime::current_high_resolution_time(*self.m_relevant_global));- auto into_focus = self.dispatch_event(DOM::Event::create(*self.m_relevant_global, HTML::EventNames::click, { .cancelable = true }));-- // 2. If intoFocus is true, then the user agent should bring the notification's related browsing context's- // viewport into focus.- if (self.m_page)- self.m_page->client().page_did_handle_notification_click(self.m_id, into_focus);- }));-}--// https://notifications.spec.whatwg.org/#dom-notification-close-void Notification::close()-{- // The close() method steps are to run the close steps for this's notification.- close_steps();+ icon->m_fetch_controller = Fetch::Fetching::fetch(settings->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);+ return icon.ptr();}-// https://notifications.spec.whatwg.org/#close-steps-void Notification::close_steps()+void web_notifications_api_stop_icon_fetch(NotificationIcon* icon){- // 1. If the list of notifications does not contain notification, then abort these steps.- // NB: A notification that's already on its way out (Closing) is left to the close the UI process is carrying out.- if (m_state != State::Showing)- return;-- // 2. Handle close events with notification.- // 3. Remove notification from the list of notifications.- // NB: Both happen in did_close(), once the UI process has withdrawn the notification from the platform.- m_state = State::Closing;- m_page->client().page_did_request_close_notification(m_id);+ if (icon->m_fetch_controller)+ icon->m_fetch_controller->stop_fetch();+ icon->m_fetch_controller = nullptr;}-// Steps 2 and 3 of https://notifications.spec.whatwg.org/#close-steps-void Notification::did_close(bool)+void web_notifications_api_show_notification(HTML::Window* window, u64 notification_id, NotificationDataAbi const* data, NotificationIcon* icon){- if (m_state != State::Showing && m_state != State::Closing)- return;-- // 2. Handle close events with notification.- // https://notifications.spec.whatwg.org/#handle-close-events- // 2. If notification is a non-persistent notification, then queue a task to fire an event named close on the- // Notification object representing notification.- queue_task_to_fire_event(HTML::EventNames::close);-- // 3. Remove notification from the list of notifications.- m_state = State::Closed;- m_page->unregister_notification(m_id);-}--void Notification::queue_task_to_fire_event(Utf16FlyString const& event_name)-{- HTML::queue_global_task(HTML::Task::Source::Unspecified, *m_relevant_global, GC::create_function(GC::Heap::the(), GC::captures(*this, event_name), [](auto& self, auto& event_name) {- self.dispatch_event(DOM::Event::create(*self.m_relevant_global, event_name));- }));-}--NotificationData Notification::data() const-{- return NotificationData {- .title = Utf16String::from_utf8(m_notification.title),- .body = m_notification.body,- .tag = m_notification.tag,- .language = m_notification.language,- .direction = m_notification.direction,- .silent = m_notification.silent_preference,- .require_interaction = m_notification.require_interaction_preference,- .renotify = m_notification.renotify_preference,+ NotificationData notification_data {+ .title = Utf16String::from_raw(data->title),+ .body = Utf16String::from_raw(data->body),+ .tag = Utf16String::from_raw(data->tag),+ .language = Utf16String::from_raw(data->language),+ .direction = static_cast<Bindings::NotificationDirection>(data->direction),+ .silent = data->has_silent ? Optional<bool> { data->silent } : Optional<bool> {},+ .require_interaction = data->require_interaction,+ .renotify = data->renotify,};+ RefPtr<Gfx::Bitmap const> icon_resource = icon ? icon->m_resource : nullptr;+ window->page().client().page_did_request_show_notification(notification_id, window->associated_document().id(), notification_data, icon_resource);}-#define __ENUMERATE(attribute_name, event_name) \- void Notification::set_##attribute_name(WebIDL::CallbackType* value) \- { \- set_event_handler_attribute(HTML::EventNames::event_name, value); \- } \- WebIDL::CallbackType* Notification::attribute_name() \- { \- return event_handler_attribute(HTML::EventNames::event_name); \- }-__ENUMERATE(onclick, click)-__ENUMERATE(onshow, show)-__ENUMERATE(onerror, error)-__ENUMERATE(onclose, close)-#undef __ENUMERATE--static Bindings::NotificationPermission notification_permission_from(PermissionsAPI::PermissionState permission_state)+void web_notifications_api_request_close_notification(HTML::Window* window, u64 notification_id){- // https://notifications.spec.whatwg.org/#permissions-integration- // 2. If permissionState is "prompt", then return "default".- // 3. Return permissionState.- switch (permission_state) {- case PermissionsAPI::PermissionState::Prompt:- return Bindings::NotificationPermission::Default;- case PermissionsAPI::PermissionState::Granted:- return Bindings::NotificationPermission::Granted;- case PermissionsAPI::PermissionState::Denied:- return Bindings::NotificationPermission::Denied;- }- VERIFY_NOT_REACHED();-}--// https://notifications.spec.whatwg.org/#dom-notification-permission-Bindings::NotificationPermission Notification::permission()-{- // The static permission getter steps are to return the result of getting the notifications permission state.- // https://notifications.spec.whatwg.org/#permissions-integration- // 1. Let permissionState be the result of getting the current permission state with "notifications".- return notification_permission_from(get_the_notifications_permission_state(HTML::current_settings_object()));-}--// https://notifications.spec.whatwg.org/#dom-notification-requestpermission-GC::Ref<WebIDL::Promise> Notification::request_permission(GC::Ptr<WebIDL::CallbackType> deprecated_callback)-{- // 1. Let global be the current global object.- auto& settings = HTML::current_settings_object();- auto& realm = settings.realm();- GC::Ref<JS::Object> global = settings.global_object();-- // 2. Let promise be a new promise in this's relevant Realm.- // NB: A static method has no "this"; the current realm is the one the call was made from.- auto promise = WebIDL::create_promise(realm);-- // 3. Run these steps in parallel:- // 1. Let permissionState be the result of requesting permission to use "notifications".- // 2. Queue a global task on the DOM manipulation task source given global to run these steps:- auto settle = GC::create_function(realm.heap(), GC::captures(realm, global, promise, deprecated_callback, GC::Ref(settings)), [](auto& realm, auto& global, auto& promise, auto& deprecated_callback, auto& settings, PermissionsAPI::PermissionState) {- // AD-HOC: "Request permission to use" reports "denied" for a prompt the user dismissed, though it stores nothing- // for it, and the page would then take a shrug for a refusal. The state the store holds once the- // answer is in is reported instead: "default" after a dismissal, so the page may ask again later.- auto permission_state = get_the_notifications_permission_state(settings);- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), GC::captures(realm, promise, deprecated_callback, permission_state), [](auto& realm, auto& promise, auto& deprecated_callback, auto& permission_state) {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- auto permission = JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(notification_permission_from(permission_state)));-- // 1. If deprecatedCallback is given, then invoke deprecatedCallback with « permissionState » and "report".- if (deprecated_callback)- (void)WebIDL::invoke_callback(*deprecated_callback, {}, WebIDL::ExceptionBehavior::Report, { { permission } });-- // 2. Resolve promise with permissionState.- WebIDL::resolve_promise(realm, promise, permission);- }));- });-- // AD-HOC: "Request permission to use" asks the user whenever the state is "prompt". We ask only from a document- // that is its own top-level site, and only while it has transient activation, which the request consumes.- // Any other request resolves with the state as it is, and nothing is stored, so the page may ask again- // from a click. (A document that isn't a secure context already reads "denied" from the permission- // state algorithm, so it never gets this far.) Each refusal is explained on the console.- auto current_state = get_the_notifications_permission_state(settings);- if (current_state == PermissionsAPI::PermissionState::Prompt) {- auto& window = *HTML::window_from_global_object(*global);- auto refuse = [&](StringView message) {- realm.intrinsics().console_object()->console().output_debug_message(JS::Console::LogLevel::Error, Utf16String::from_utf8(message));- settle->function()(current_state);- return promise;- };- auto const& top_level_origin = settings.top_level_origin;- if (!top_level_origin.has_value() || !window.associated_document().origin().is_same_origin(*top_level_origin))- return refuse("Notification permission can only be requested from a document whose origin is the top-level origin."sv);- if (!window.has_transient_activation())- return refuse("Notification permission can only be requested while handling a user gesture."sv);- window.consume_user_activation();- }- PermissionsAPI::request_permission_with_user_prompt(Web::Permissions::PermissionName::Notifications, settings, settle);-- // 4. Return promise.- return promise;-}--// https://notifications.spec.whatwg.org/#dom-notification-actions-Vector<NotificationAction> Notification::actions() const-{- // 1. Let frozenActions be an empty list of type NotificationAction.- Vector<NotificationAction> frozen_actions;- frozen_actions.ensure_capacity(m_notification.actions.capacity());-- // 2. For each entry of this’s notification’s actions:- for (auto const& entry : m_notification.actions) {- // 1. Let action be a new NotificationAction.- NotificationAction action;-- // 2. Set action["action"] to entry’s name.- action.action = entry.name;-- // 3. Set action["title"] to entry’s title.- action.title = entry.title;-- // 4. If entry’s navigation URL is non-null, then set action["navigate"] to entry’s navigation URL, serialized.- if (entry.navigation_url.has_value())- action.navigate = serialize_url_for_bindings(entry.navigation_url);-- // 5. If entry’s icon URL is non-null, then set action["icon"] to entry’s icon URL, serialized.- if (entry.icon_url.has_value())- action.icon = serialize_url_for_bindings(entry.icon_url);-- // FIXME: 6. Call Object.freeze on action, to prevent accidental mutation by scripts.-- // 7. Append action to frozenActions.- frozen_actions.append(action);- }-- // 3. Return the result of create a frozen array from frozenActions.- // NB: The bindings freeze the array they build from this sequence.- return frozen_actions;+ window->page().client().page_did_request_close_notification(notification_id);}-// https://notifications.spec.whatwg.org/#dom-notification-data-Utf16String Notification::serialize_url_for_bindings(Optional<URL::URL> const& url)+void web_notifications_api_abandon_notification(HTML::Window* window, u64 notification_id){- if (!url.has_value())- return {};- return Utf16String::from_utf8(url->serialize());+ window->page().client().page_did_abandon_notification(notification_id);}-JS::Value Notification::data(JS::Object const& relevant_global_object) const+void web_notifications_api_handle_notification_click(HTML::Window* window, u64 notification_id, bool into_focus){- // The data getter steps are to return StructuredDeserialize(this's notification's data, this's relevant Realm).- // If this throws an exception, then return null.- auto& relevant_realm = HTML::relevant_realm(relevant_global_object);- auto deserialized_data = HTML::structured_deserialize(relevant_realm.vm(), m_notification.data, relevant_realm);- if (!deserialized_data.is_exception())- return deserialized_data.release_value();- return JS::js_null();+ window->page().client().page_did_handle_notification_click(notification_id, into_focus);}}diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.h b/Libraries/LibWeb/NotificationsAPI/Notification.hindex f51a281a899..8f0da4290c9 100644--- a/Libraries/LibWeb/NotificationsAPI/Notification.h+++ b/Libraries/LibWeb/NotificationsAPI/Notification.h@@ -6,130 +6,20 @@#pragma once-#include <AK/Optional.h>-#include <AK/Utf16String.h>-#include <AK/Vector.h>-#include <LibGfx/Bitmap.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Value.h>#include <LibWeb/Bindings/Notification.h>-#include <LibWeb/DOM/EventTarget.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HighResolutionTime/EpochTimeStamp.h>-#include <LibWebCommon/NotificationsAPI/NotificationData.h>-#include <LibWebCommon/WebIDL/Types.h>+#include <LibWeb/Forward.h>namespace Web::NotificationsAPI {-using NotificationDirection = Bindings::NotificationDirection;--struct NotificationAction {- Utf16String action;- Utf16String title;- Optional<Utf16String> navigate;- Optional<Utf16String> icon;-};--struct NotificationOptions {- NotificationDirection direction { NotificationDirection::Auto };- Utf16String language;- Utf16String body;- Optional<Utf16String> navigate;- Utf16String tag;- Optional<Utf16String> image;- Optional<Utf16String> icon;- Optional<Utf16String> badge;- // FIXME: Validate and normalize the pattern (create step 15); only its presence matters until then.- Optional<Variant<WebIDL::UnsignedLong, Vector<WebIDL::UnsignedLong>>> vibrate;- Optional<HighResolutionTime::EpochTimeStamp> timestamp;- bool renotify { false };- Optional<bool> silent;- bool require_interaction { false };- HTML::StorageSerializationRecord data;- Vector<NotificationAction> actions;-};--// https://notifications.spec.whatwg.org/#concept-notification-// This is the notification described as "notification" in the spec. Do not confuse it with "notification" as in the IDL which is just the JS wrapper.-// "A notification is an abstract representation of something that happened, such as the delivery of a message."-struct ConceptNotification {- // FIXME: A notification has an associated service worker registration (null or a service worker registration). It is initially null.- String title;- NotificationDirection direction;- Utf16String language;- Utf16String body;- Optional<URL::URL> navigation_url;- Utf16String tag;- HTML::StorageSerializationRecord data;- HighResolutionTime::EpochTimeStamp timestamp;- URL::Origin origin = URL::Origin({}); // FIXME: Is this a hack ? There is no default constructor to URL::Origin and the value for `origin` is set in `create-a-notification-with-a-settings-object`- bool renotify_preference;- Optional<bool> silent_preference;- bool require_interaction_preference;- Optional<URL::URL> image_url;- Optional<URL::URL> icon_url;- Optional<URL::URL> badge_url;-- // FIXME: add the resources from m_image_url, m_icon_url and m_badge_url-- // FIXME: A notification has an associated vibration pattern (a list). It is initially « ».-- // https://notifications.spec.whatwg.org/#action- struct Action {- Utf16String name;- Utf16String title;- Optional<URL::URL> navigation_url;- Optional<URL::URL> icon_url;- // FIXME: icon resource- };- Vector<Action> actions;-};-// https://notifications.spec.whatwg.org/#notifications-class WEB_API Notification final : public DOM::EventTarget {- WEB_WRAPPABLE(Notification, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(Notification);+class WEB_API Notification final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Notification, notification)public:- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<Notification>> create_with_global_scope(- JS::Object& relevant_global_object,- HTML::WindowOrWorkerGlobalScopeMixin&,- String const& title,- NotificationOptions options);- [[nodiscard]] static WebIDL::ExceptionOr<NotificationOptions> options_from_bindings(JS::VM&, Bindings::NotificationOptions const&);- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<Notification>> create_for_constructor(JS::Object&, Utf16String const& title, Bindings::NotificationOptions const&);-- // https://notifications.spec.whatwg.org/#create-a-notification-with-a-settings-object- static WebIDL::ExceptionOr<ConceptNotification> create_a_notification_with_a_settings_object(- String const& title,- NotificationOptions options,- GC::Ref<HTML::EnvironmentSettingsObject> settings);-- // https://notifications.spec.whatwg.org/#create-a-notification- static WebIDL::ExceptionOr<ConceptNotification> create_a_notification(- String const& title,- NotificationOptions options,- URL::Origin origin,- URL::URL base_url,- HighResolutionTime::EpochTimeStamp fallback_timestamp);-- static Bindings::NotificationPermission permission();- static GC::Ref<WebIDL::Promise> request_permission(GC::Ptr<WebIDL::CallbackType> deprecated_callback);-- void close();-- void set_onclick(WebIDL::CallbackType*);- WebIDL::CallbackType* onclick();- void set_onshow(WebIDL::CallbackType*);- WebIDL::CallbackType* onshow();- void set_onerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onerror();- void set_onclose(WebIDL::CallbackType*);- WebIDL::CallbackType* onclose();-// The id this notification is known by across the Page bridge, for tests that act on it from the UI side.- u64 id_for_testing() const { return m_id; }+ u64 id_for_testing() const;// The document the notification was created in, if a window's.DOM::Document const* document() const;@@ -141,69 +31,6 @@ public:void did_fail_to_show();void did_click();void did_close(bool by_user);-- // https://notifications.spec.whatwg.org/#maximum-number-of-actions-supported- // Two is what both desktop notification platforms show room for; persistent notifications, the only kind that- // carries actions, aren't supported yet.- static unsigned long max_actions() { return 2; }-- String const& title() const { return m_notification.title; }- NotificationDirection direction() const { return m_notification.direction; }- NotificationDirection notification_direction() const { return direction(); }- Utf16String const& lang() const { return m_notification.language; }- Utf16String const& body() const { return m_notification.body; }- String navigate() const { return m_notification.navigation_url.has_value() ? m_notification.navigation_url->serialize() : ""_string; }- Utf16String const& tag() const { return m_notification.tag; }- String image() const { return m_notification.image_url.has_value() ? m_notification.image_url->serialize() : ""_string; }- String icon() const { return m_notification.icon_url.has_value() ? m_notification.icon_url->serialize() : ""_string; }- String badge() const { return m_notification.badge_url.has_value() ? m_notification.badge_url->serialize() : ""_string; }- HighResolutionTime::EpochTimeStamp timestamp() const { return m_notification.timestamp; }- bool renotify() const { return m_notification.renotify_preference; }- Optional<bool> silent() const { return m_notification.silent_preference; }- bool require_interaction() const { return m_notification.require_interaction_preference; }- Vector<NotificationAction> actions() const;- HTML::StorageSerializationRecord const& serialized_data() const { return m_notification.data; }- JS::Value data(JS::Object const& relevant_global_object) const;--private:- Notification();-- virtual void visit_edges(Cell::Visitor&) override;-- static Utf16String serialize_url_for_bindings(Optional<URL::URL> const&);-- void run_steps_in_parallel_after_construction();- void show_steps();- void run_the_fetch_steps(GC::Ref<GC::Function<void()>> on_done);- void fetch_a_notification_resource(URL::URL const&, GC::Ref<GC::Function<void(RefPtr<Gfx::Bitmap const>)>> process_resource);- void display();- void close_steps();- void queue_task_to_fire_event(Utf16FlyString const& event_name);- NotificationData data() const;-- ConceptNotification m_notification;-- // The global the constructor ran in: Where the events fire, and whose window the notification belongs to.- GC::Ptr<JS::Object> m_relevant_global;- GC::Ptr<Page> m_page;-- // Where the notification is on its way to the platform. From Pending on it's in the page's list of notifications,- // which keeps it alive; Closed means it has left the list for good.- enum class State {- Idle,- Pending,- Showing,- Closing,- Closed,- };- State m_state { State::Idle };- u64 m_id { 0 };-- // https://notifications.spec.whatwg.org/#icon-resource- RefPtr<Gfx::Bitmap const> m_icon_resource;- GC::Ptr<Fetch::Infrastructure::FetchController> m_icon_fetch_controller;- // Bounds the wait for the icon: Past it, the notification shows without one.- GC::Ptr<Platform::Timer> m_fetch_timeout;};}diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.idl b/Libraries/LibWeb/NotificationsAPI/Notification.idlindex d019d3f7fb1..729d1dff7e2 100644--- a/Libraries/LibWeb/NotificationsAPI/Notification.idl+++ b/Libraries/LibWeb/NotificationsAPI/Notification.idl@@ -1,5 +1,5 @@// https://notifications.spec.whatwg.org/#notification-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface Notification : EventTarget {constructor(DOMString title, optional NotificationOptions options = {});@@ -14,7 +14,7 @@ interface Notification : EventTarget {attribute EventHandler onclose;readonly attribute DOMString title;- [ImplementedAs=notification_direction] readonly attribute NotificationDirection dir;+ readonly attribute NotificationDirection dir;readonly attribute DOMString lang;readonly attribute DOMString body;readonly attribute USVString navigate;@@ -33,6 +33,7 @@ interface Notification : EventTarget {undefined close();};+[ImplementedIn=Rust]dictionary NotificationOptions {NotificationDirection dir = "auto";DOMString lang = "";@@ -66,6 +67,7 @@ enum NotificationDirection {"rtl"};+[ImplementedIn=Rust]dictionary NotificationAction {required DOMString action;required DOMString title;diff --git a/Libraries/LibWeb/NotificationsAPI/NotificationPermission.h b/Libraries/LibWeb/NotificationsAPI/NotificationPermission.hdeleted file mode 100644index 378ed04f5c9..00000000000--- a/Libraries/LibWeb/NotificationsAPI/NotificationPermission.h+++ /dev/null@@ -1,19 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>-#include <LibWeb/PermissionsAPI/Permissions.h>--namespace Web::NotificationsAPI {--// https://notifications.spec.whatwg.org/#permissions-integration-WEB_API PermissionsAPI::PermissionState get_the_notifications_permission_state(HTML::EnvironmentSettingsObject&);--}