Skip to content

Truly independent web browser

LibWeb: Implement Geolocation in Rust

Shannon Booth3a1f3eb5d1d3
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
index aabfbe6cf2b..bc15e72e837 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
@@ -12,7 +12,8 @@ use core::ffi::c_void;
use core::ptr::NonNull;
use libjs_rust::api::{
- ErrorKind, ErrorType, ForeignCellSlot, RawNativeFunctionResult, ThrowCompletionOr, Trace, Value, Vm,
+ ErrorKind, ErrorType, ForeignCellSlot, Gc, Object, RawNativeFunctionResult, Realm, ThrowCompletionOr, Trace, Value,
+ Vm,
};
use crate::bindings::promise::{WebIdlPromise, promise_from_abi};
@@ -30,6 +31,12 @@ unsafe extern "C" {
arguments: ak::Span<'_, Value>,
) -> RawNativeFunctionResult;
+ /// WebIDL::invoke_callback() of the WebIDL::CallbackType with the arguments and the "report" exception behavior.
+ fn web_bindings_invoke_callback_function_and_report(callback: *mut c_void, arguments: ak::Span<'_, Value>);
+
+ /// The callback function object of the WebIDL::CallbackType.
+ fn web_bindings_callback_function_callback(callback: *mut c_void) -> *mut c_void;
+
/// WebIDL::invoke_promise_callback() of the WebIDL::CallbackType, whose return type is a promise type, with the this
/// value, if `has_this_value`, and the arguments.
fn web_bindings_invoke_promise_callback_function(
@@ -122,6 +129,21 @@ impl CallbackFunction {
}
.into_completion()
}
+
+ /// Invokes the callback function with the arguments and "report", https://webidl.spec.whatwg.org/#invoke-a-callback-function
+ pub(crate) fn invoke_and_report(&self, arguments: &[Value]) {
+ // SAFETY: The slot keeps the callback alive, and the values are live for the call.
+ unsafe { web_bindings_invoke_callback_function_and_report(self.0.0.as_ptr(), ak::Span::new(arguments)) };
+ }
+
+ pub(crate) fn callback_realm(&self) -> Gc<Realm> {
+ // SAFETY: The slot keeps the callback alive, and LibWeb returns its live callback function object.
+ let callback = unsafe { web_bindings_callback_function_callback(self.0.0.as_ptr()) };
+ // SAFETY: The callback function object is live.
+ let callback: Gc<Object> =
+ unsafe { Gc::from_non_null(NonNull::new(callback.cast()).expect("a callback has a function object")) };
+ callback.shape().realm()
+ }
}
impl CallbackInterface {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index b83155094bb..d10a66dcd4f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -410,6 +410,16 @@ pub(crate) fn to_long_long_clamping(vm: &Vm, value: Value) -> ThrowCompletionOr<
Ok(to_integer_clamping(vm, value, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)? as i64)
}
+/// A JS value converted to an unsigned long with [Clamp], https://webidl.spec.whatwg.org/#js-unsigned-long
+#[allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "the value is an integer within the bounds of the type"
+)]
+pub(crate) fn to_unsigned_long_clamping(vm: &Vm, value: Value) -> ThrowCompletionOr<u32> {
+ Ok(to_integer_clamping(vm, value, 0.0, f64::from(u32::MAX))? as u32)
+}
+
/// The number that https://webidl.spec.whatwg.org/#abstract-opdef-converttoint has after step 10 for a bit length of
/// 64, as WebIDL::convert_to_int() of the C++ bindings computes it.
///
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
index 4081b291a68..d3f4a0b0b23 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs
@@ -22,6 +22,7 @@ unsafe extern "C" {
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_id(
settings_object: *mut c_void,
id: *mut c_void,
@@ -97,6 +98,12 @@ impl CppEnvironmentSettingsObject {
unsafe { Gc::from_non_null(NonNull::new(realm.cast()).expect("a settings object has a realm")) }
}
+ /// https://html.spec.whatwg.org/multipage/webappapis.html#secure-context
+ pub(crate) fn is_secure_context(&self) -> bool {
+ // SAFETY: The settings object is live.
+ unsafe { web_bindings_environment_settings_object_is_secure_context(self.as_ptr()) }
+ }
+
/// https://html.spec.whatwg.org/multipage/webappapis.html#concept-settings-object-time-origin
pub(crate) fn time_origin(&self) -> f64 {
// SAFETY: The settings object is live.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index 383782a7351..79f4cf3f98f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -47,6 +47,13 @@ unsafe extern "C" {
steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
);
+ /// Queues a task on the task source as web_bindings_queue_a_task() does, but with no execution context on the stack.
+ fn web_bindings_queue_a_task_without_execution_context(
+ task_source: u8,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+
/// Queues a global task on the task source, an HTML::Task::Source, with the global object, that calls the steps with
/// the VM and the cell, as HTML::queue_global_task() queues one. The cell lives until then. Returns the task's
/// HTML::TaskID.
@@ -76,6 +83,7 @@ pub(crate) enum TaskSource {
Networking = 3,
PostedMessage = 6,
TimerTask = 8,
+ Geolocation = 10,
FileReading = 13,
PerformanceTimeline = 15,
Clipboard = 17,
@@ -616,6 +624,19 @@ pub(crate) fn queue_a_task<C: Trace + Copy + 'static>(
unsafe { web_bindings_queue_a_task(realm.as_ptr().cast(), task_source as u8, cell, run_pending_steps) };
}
+/// Queues a task on the task source that performs the steps with the captures, as queue_a_task() does, but with no
+/// execution context of its own on the stack, https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-task
+pub(crate) fn queue_a_task_without_execution_context<C: Trace + Clone + 'static>(
+ vm: &Vm,
+ task_source: TaskSource,
+ captures: C,
+ steps: fn(&Vm, C),
+) {
+ let cell = pending_steps(vm, captures, steps);
+ // SAFETY: The cell is live.
+ unsafe { web_bindings_queue_a_task_without_execution_context(task_source as u8, cell, run_pending_steps) };
+}
+
/// Queues a global task on the task source, given the global object, that performs the steps with the captures,
/// https://html.spec.whatwg.org/multipage/webappapis.html#queue-a-global-task. Unlike queue_a_task(), the steps run
/// with no execution context of their own on the stack.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
index a06d614f86a..6152c82ccc9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
@@ -6,17 +6,21 @@
use core::ffi::c_void;
-use libjs_rust::api::Trace;
+use libjs_rust::api::{Trace, Vm};
use liburl_rust::Url;
-use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::cpp_cell::{CppCell, WeakCppCell};
use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};
use crate::html::navigable::CppNavigable;
+use crate::html::visibility_state::VisibilityState;
use crate::navigation_timing::performance_navigation_timing::PerformanceNavigationTiming;
+use crate::permissions_policy::permissions_policy::PolicyControlledFeature;
unsafe extern "C" {
fn web_bindings_document_navigable(document: *mut c_void) -> *mut c_void;
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_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;
@@ -34,6 +38,16 @@ unsafe extern "C" {
#[gc(crate = libjs_rust)]
pub(crate) struct CppDocument(CppCell);
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WeakCppDocument(WeakCppCell);
+
+impl WeakCppDocument {
+ pub(crate) fn get(&self) -> Option<CppDocument> {
+ self.0.get().map(CppDocument)
+ }
+}
+
/// https://html.spec.whatwg.org/multipage/dom.html#document-load-timing-info
#[derive(Clone, Copy, Default)]
#[repr(C)]
@@ -65,12 +79,36 @@ impl CppDocument {
Self(unsafe { CppCell::from_raw(document) })
}
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+
+ pub(crate) fn downgrade(&self, vm: &Vm) -> WeakCppDocument {
+ WeakCppDocument(WeakCppCell::new(vm, &self.0))
+ }
+
/// https://html.spec.whatwg.org/multipage/document-sequences.html#fully-active
pub(crate) fn is_fully_active(&self) -> bool {
// SAFETY: The Document is live.
unsafe { web_bindings_document_is_fully_active(self.0.as_ptr()) }
}
+ /// https://html.spec.whatwg.org/multipage/iframe-embed-object.html#allowed-to-use
+ pub(crate) fn is_allowed_to_use_feature(&self, feature: PolicyControlledFeature) -> bool {
+ // SAFETY: The Document is live.
+ unsafe { web_bindings_document_is_allowed_to_use_feature(self.0.as_ptr(), feature as u8) }
+ }
+
+ /// https://html.spec.whatwg.org/multipage/interaction.html#visibility-state
+ pub(crate) fn visibility_state(&self) -> VisibilityState {
+ // SAFETY: The Document is live.
+ match unsafe { web_bindings_document_visibility_state(self.0.as_ptr()) } {
+ 0 => VisibilityState::Visible,
+ 1 => VisibilityState::Hidden,
+ _ => unreachable!("LibWeb returns a VisibilityState"),
+ }
+ }
+
/// https://html.spec.whatwg.org/multipage/interaction.html#has-focus-steps
pub(crate) fn has_focus(&self) -> bool {
// SAFETY: The Document is live.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs
new file mode 100644
index 00000000000..24c3239ec1d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation.rs
@@ -0,0 +1,1028 @@
+/*
+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Geolocation, https://w3c.github.io/geolocation/#geolocation_interface
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+use core::ptr::NonNull;
+use std::collections::{HashMap, HashSet};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Trace, Value, Vm};
+
+use crate::bindings::callback::CallbackFunction;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::environment_settings_object::{CppEnvironmentSettingsObject, relevant_settings_object};
+use crate::bindings::global_object::CppWindow;
+use crate::bindings::interface::{
+ Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context, wrap,
+};
+use crate::bindings::promise::{TaskSource, deferred_invoke, queue_a_task_without_execution_context};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::dom::document::{CppDocument, WeakCppDocument};
+use crate::geolocation::geolocation_coordinates::{CoordinatesData, GeolocationCoordinates};
+use crate::geolocation::geolocation_position::GeolocationPosition;
+use crate::geolocation::geolocation_position_error::GeolocationPositionError;
+use crate::geolocation::geolocation_position_error_code::GeolocationPositionErrorCode;
+use crate::html::visibility_state::VisibilityState;
+use crate::permissions::permissions::PermissionName;
+use crate::permissions_api::permission_status::PermissionState;
+use crate::permissions_api::permissions::{permission_state, request_permission_to_use};
+use crate::permissions_policy::permissions_policy::PolicyControlledFeature;
+use crate::platform::timer::CppTimer;
+
+unsafe extern "C" {
+ fn web_geolocation_request_position(window: *mut c_void, request: *mut c_void, is_watch: bool) -> u64;
+ fn web_geolocation_cancel_position_request(window: *mut c_void, request_id: u64);
+ fn web_geolocation_emulated_position_data(window: *mut c_void, data: &mut EmulatedPositionDataAbi);
+ fn web_geolocation_register_emulated_position_data_observer(
+ window: *mut c_void,
+ geolocation: *mut c_void,
+ watch_id: u32,
+ ) -> u64;
+ fn web_geolocation_unregister_emulated_position_data_observer(window: *mut c_void, observer_id: u64);
+ fn web_geolocation_observe_document_visibility(document: *mut c_void, wait: *mut c_void) -> *mut c_void;
+ fn web_geolocation_stop_observing_document_visibility(observer: *mut c_void);
+}
+
+const VISIBILITY_STATE_TIMEOUT_MS: u64 = 5_000;
+
+thread_local! {
+ static NEXT_WATCH_ID: Cell<u32> = const { Cell::new(0) };
+}
+
+// https://w3c.github.io/geolocation/#dom-positionoptions
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PositionOptions {
+ pub(crate) enable_high_accuracy: bool,
+ pub(crate) timeout: u32,
+ pub(crate) maximum_age: u32,
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+struct PositionRequestArguments {
+ success_callback: CallbackFunction,
+ error_callback: Option<CallbackFunction>,
+ options: PositionOptions,
+ watch_id: Option<u32>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct WatchPositionData {
+ success_callback: CallbackFunction,
+ error_callback: Option<CallbackFunction>,
+ options: PositionOptions,
+ emulated_position_data_observer_id: Option<u64>,
+ observed_document: Option<WeakCppDocument>,
+}
+
+/// Web::Geolocation::EmulatedPositionData.
+#[repr(C)]
+struct EmulatedPositionDataAbi {
+ kind: u8,
+ coordinates: *mut c_void,
+ error_code: u16,
+}
+
+/// https://w3c.github.io/geolocation/#dfn-emulated-position-data
+enum EmulatedPositionData {
+ None,
+ Coordinates(Ref<GeolocationCoordinates>),
+ Error(GeolocationPositionErrorCode),
+}
+
+/// Page::GeolocationPositionResult.
+#[repr(C)]
+pub(crate) struct GeolocationPositionResultAbi {
+ is_error: bool,
+ error_code: u16,
+ coordinates: CoordinatesData,
+}
+
+// https://w3c.github.io/geolocation/#geolocation_interface
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Geolocation {
+ window: CppWindow,
+
+ // https://w3c.github.io/geolocation/#dfn-watchids
+ #[gc(untraced)]
+ watch_ids: RefCell<HashSet<u32>>,
+ watch_position_data: GcRefCell<HashMap<u32, WatchPositionData>>,
+ pending_watch_position_requests: GcRefCell<HashMap<u32, PositionRequestRef>>,
+
+ // https://w3c.github.io/geolocation/#dfn-cachedposition
+ cached_position: GcRefCell<Option<Ref<GeolocationPosition>>>,
+
+ timeout_timers: GcRefCell<Vec<(u64, CppTimer)>>,
+ #[gc(untraced)]
+ next_timeout_timer: Cell<u64>,
+}
+
+impl Wrappable for Geolocation {}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct PositionRequest {
+ geolocation: Ref<Geolocation>,
+ arguments: PositionRequestArguments,
+ acquisition_time: u64,
+ weak_document: WeakCppDocument,
+ request_id: Cell<u64>,
+ completed: Cell<bool>,
+ timeout_stopped: Cell<bool>,
+ timeout_timer: Cell<u64>,
+}
+
+static POSITION_REQUEST_CLASS: EmbedderClass<PositionRequest> = EmbedderClass::new("GeolocationPositionRequest");
+
+impl EmbedderValue for PositionRequest {
+ const CLASS: &'static EmbedderClass<Self> = &POSITION_REQUEST_CLASS;
+}
+
+type PositionRequestRef = Gc<EmbedderCell<PositionRequest>>;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct VisibilityWait {
+ geolocation: Ref<Geolocation>,
+ arguments: PositionRequestArguments,
+ observer: GcRefCell<Option<CppCell>>,
+ timeout_timer: Cell<u64>,
+}
+
+static VISIBILITY_WAIT_CLASS: EmbedderClass<VisibilityWait> = EmbedderClass::new("GeolocationVisibilityWait");
+
+impl EmbedderValue for VisibilityWait {
+ const CLASS: &'static EmbedderClass<Self> = &VISIBILITY_WAIT_CLASS;
+}
+
+type VisibilityWaitRef = Gc<EmbedderCell<VisibilityWait>>;
+
+fn now_milliseconds_since_epoch() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_or(0, |duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
+}
+
+fn timeout_milliseconds(timeout: u32) -> u64 {
+ u64::from(timeout.min(i32::MAX.unsigned_abs()))
+}
+
+fn invoke_position_callback(vm: &Vm, callback: &CallbackFunction, position: Ref<GeolocationPosition>) {
+ let callback_realm = callback.callback_realm();
+ let position = wrap(&CallContext::new(vm, callback_realm), position);
+ callback.invoke_and_report(&[Value::from_object(position)]);
+}
+
+fn invoke_position_error_callback(vm: &Vm, callback: &CallbackFunction, error: Ref<GeolocationPositionError>) {
+ let callback_realm = callback.callback_realm();
+ let error = wrap(&CallContext::new(vm, callback_realm), error);
+ callback.invoke_and_report(&[Value::from_object(error)]);
+}
+
+impl Geolocation {
+ fn window_settings_object(&self) -> CppEnvironmentSettingsObject {
+ relevant_settings_object(self.window.realm().global_object())
+ }
+
+ fn queue_success_callback(&self, vm: &Vm, callback: CallbackFunction, position: Ref<GeolocationPosition>) {
+ queue_a_task_without_execution_context(
+ vm,
+ TaskSource::Geolocation,
+ (callback, position),
+ |vm, (callback, position)| invoke_position_callback(vm, &callback, position),
+ );
+ }
+
+ fn next_timeout_timer_token(&self) -> u64 {
+ let token = self.next_timeout_timer.get() + 1;
+ self.next_timeout_timer.set(token);
+ token
+ }
+
+ fn add_timeout_timer(&self, vm: &Vm, token: u64, timer: CppTimer) {
+ self.timeout_timers.borrow_mut(vm).push((token, timer));
+ }
+
+ fn take_timeout_timer(&self, vm: &Vm, token: u64) -> Option<CppTimer> {
+ let mut timers = self.timeout_timers.borrow_mut(vm);
+ let index = timers.iter().position(|(candidate, _)| *candidate == token)?;
+ Some(timers.remove(index).1)
+ }
+
+ // https://w3c.github.io/geolocation/#dom-geolocation-getcurrentposition
+ pub(crate) fn get_current_position(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ success_callback: CallbackFunction,
+ error_callback: Option<CallbackFunction>,
+ options: PositionOptions,
+ ) -> WebIdlResult<()> {
+ let vm = cx.vm();
+
+ // 1. If this's relevant global object's associated Document is not fully active:
+ if !this.window.associated_document().is_fully_active() {
+ // 1. Call back with error errorCallback and POSITION_UNAVAILABLE.
+ this.call_back_with_error(vm, error_callback, GeolocationPositionErrorCode::PositionUnavailable);
+
+ // 2. Terminate this algorithm.
+ return Ok(());
+ }
+
+ // 2. Request a position passing this, successCallback, errorCallback, and options.
+ Self::request_a_position(
+ *this,
+ vm,
+ PositionRequestArguments {
+ success_callback,
+ error_callback,
+ options,
+ watch_id: None,
+ },
+ );
+ Ok(())
+ }
+
+ // https://w3c.github.io/geolocation/#watchposition-method
+ pub(crate) fn watch_position(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ success_callback: CallbackFunction,
+ error_callback: Option<CallbackFunction>,
+ options: PositionOptions,
+ ) -> WebIdlResult<i32> {
+ let vm = cx.vm();
+
+ // 1. If this's relevant global object's associated Document is not fully active:
+ if !this.window.associated_document().is_fully_active() {
+ // 1. Call back with error passing errorCallback and POSITION_UNAVAILABLE.
+ this.call_back_with_error(vm, error_callback, GeolocationPositionErrorCode::PositionUnavailable);
+
+ // 2. Return 0.
+ return Ok(0);
+ }
+
+ // 2. Let watchId be an implementation-defined unsigned long that is greater than zero.
+ let watch_id = NEXT_WATCH_ID.with(|next_watch_id| {
+ let watch_id = next_watch_id.get().wrapping_add(1);
+ next_watch_id.set(watch_id);
+ watch_id
+ });
+
+ // 3. Append watchId to this's [[watchIDs]].
+ this.watch_ids.borrow_mut().insert(watch_id);
+ this.watch_position_data.borrow_mut(vm).insert(
+ watch_id,
+ WatchPositionData {
+ success_callback: success_callback.clone(),
+ error_callback: error_callback.clone(),
+ options,
+ emulated_position_data_observer_id: None,
+ observed_document: None,
+ },
+ );
+
+ // 4. Request a position passing this, successCallback, errorCallback, options, and watchId.
+ Self::request_a_position(
+ *this,
+ vm,
+ PositionRequestArguments {
+ success_callback,
+ error_callback,
+ options,
+ watch_id: Some(watch_id),
+ },
+ );
+
+ // 5. Return watchId.
+ Ok(watch_id.cast_signed())
+ }
+
+ // https://w3c.github.io/geolocation/#clearwatch-method
+ pub(crate) fn clear_watch(&self, cx: &mut CallContext, watch_id: i32) -> WebIdlResult<()> {
+ let watch_id = watch_id.cast_unsigned();
+
+ // 1. Remove watchId from this's [[watchIDs]].
+ self.remove_watch_id(cx.vm(), watch_id);
+
+ let request = self
+ .pending_watch_position_requests
+ .borrow_mut(cx.vm())
+ .remove(&watch_id);
+ if let Some(request) = request {
+ request.stop_timeout_timer(cx.vm());
+ // SAFETY: The window is live.
+ unsafe { web_geolocation_cancel_position_request(self.window.as_ptr(), request.request_id.get()) };
+ }
+ Ok(())
+ }
+
+ // https://w3c.github.io/geolocation/#dfn-get-emulated-position-data
+ fn get_emulated_position_data(&self) -> EmulatedPositionData {
+ // 1. Let navigable be geolocation's relevant global object's associated Document's node navigable.
+ // 2. If navigable is null, return null.
+ // 3. Return navigable's top-level traversable's emulated position data.
+ // NB: The page holds the top-level traversable's, which another process may host.
+ let mut data = EmulatedPositionDataAbi {
+ kind: 0,
+ coordinates: core::ptr::null_mut(),
+ error_code: 0,
+ };
+ // SAFETY: The window is live, and the data outlives the call.
+ unsafe { web_geolocation_emulated_position_data(self.window.as_ptr(), &mut data) };
+ match data.kind {
+ 0 => EmulatedPositionData::None,
+ // SAFETY: LibWeb lends the live cell of a GeolocationCoordinates, which the page keeps alive.
+ 1 => EmulatedPositionData::Coordinates(unsafe { cell_from_abi(data.coordinates) }),
+ 2 => EmulatedPositionData::Error(GeolocationPositionErrorCode::from_u16(data.error_code)),
+ _ => unreachable!("LibWeb lends emulated position data"),
+ }
+ }
+
+ fn remove_watch_id(&self, vm: &Vm, watch_id: u32) {
+ self.watch_ids.borrow_mut().remove(&watch_id);
+ self.unregister_watch_position_observer(vm, watch_id);
+ self.watch_position_data.borrow_mut(vm).remove(&watch_id);
+ }
+
+ fn unregister_watch_position_observer(&self, vm: &Vm, watch_id: u32) {
+ let observer_id = {
+ let mut watch_position_data = self.watch_position_data.borrow_mut(vm);
+ let Some(watch_position_data) = watch_position_data.get_mut(&watch_id) else {
+ return;
+ };
+ let Some(observer_id) = watch_position_data.emulated_position_data_observer_id.take() else {
+ return;
+ };
+ observer_id
+ };
+
+ // SAFETY: The window is live.
+ unsafe { web_geolocation_unregister_emulated_position_data_observer(self.window.as_ptr(), observer_id) };
+ }
+
+ // https://w3c.github.io/geolocation/#dfn-request-a-position
+ fn request_a_position(this: Ref<Self>, vm: &Vm, arguments: PositionRequestArguments) {
+ // 1. Let watchIDs be geolocation's [[watchIDs]].
+
+ // 2. Let document be the geolocation's relevant global object's associated Document.
+ let document = this.window.associated_document();
+
+ // 3. If document is not allowed to use the "geolocation" feature:
+ if !document.is_allowed_to_use_feature(PolicyControlledFeature::Geolocation) {
+ // 1. If watchId was passed, remove watchId from watchIDs.
+ if let Some(watch_id) = arguments.watch_id {
+ this.remove_watch_id(vm, watch_id);
+ }
+
+ // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
+ this.call_back_with_error(
+ vm,
+ arguments.error_callback,
+ GeolocationPositionErrorCode::PermissionDenied,
+ );
+
+ // 3. Terminate this algorithm.
+ return;
+ }
+
+ // 4. If geolocation's environment settings object is a non-secure context:
+ if !this.window_settings_object().is_secure_context() {
+ // 1. If watchId was passed, remove watchId from watchIDs.
+ if let Some(watch_id) = arguments.watch_id {
+ this.remove_watch_id(vm, watch_id);
+ }
+
+ // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
+ this.call_back_with_error(
+ vm,
+ arguments.error_callback,
+ GeolocationPositionErrorCode::PermissionDenied,
+ );
+
+ // 3. Terminate this algorithm.
+ return;
+ }
+
+ // 5. If document's visibility state is "hidden", wait for the following page visibility change steps to run:
+ Self::run_in_parallel_when_document_is_visible(this, vm, &document, arguments);
+ }
+
+ fn request_a_position_when_document_is_visible(this: Ref<Self>, vm: &Vm, arguments: PositionRequestArguments) {
+ // 1. Assert: document's visibility state is "visible".
+ // 2. Continue to the next steps below.
+ // AD-HOC: This is implemented by run_in_parallel_when_document_is_visible().
+
+ // 6. Let descriptor be a new PermissionDescriptor whose name is "geolocation".
+ let descriptor = PermissionName::Geolocation;
+
+ // 7. In parallel:
+ // NB: The round trip to the UI process that asks the user for permission stands in for the parallel steps: the
+ // request goes out as an async IPC, and the rest of the steps run on the main thread once it answers.
+ {
+ // 1. Set permission to request permission to use descriptor.
+ let settings = this.window_settings_object();
+ request_permission_to_use(
+ vm,
+ descriptor,
+ &settings,
+ (this, arguments),
+ |vm, (this, arguments), permission| {
+ // 2. If permission is "denied", then:
+ if permission == PermissionState::Denied {
+ // 1. If watchId was passed, remove watchId from watchIDs.
+ if let Some(watch_id) = arguments.watch_id {
+ this.remove_watch_id(vm, watch_id);
+ }
+
+ // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
+ this.call_back_with_error(
+ vm,
+ arguments.error_callback,
+ GeolocationPositionErrorCode::PermissionDenied,
+ );
+
+ // 3. Terminate this algorithm.
+ return;
+ }
+
+ // FIXME: 3. Wait to acquire a position passing successCallback, errorCallback, options, and watchId.
+ Self::acquire_a_position(this, vm, arguments.clone());
+
+ // 4. If watchId was not passed, terminate this algorithm.
+ let Some(watch_id) = arguments.watch_id else {
+ return;
+ };
+
+ if !this.watch_ids.borrow().contains(&watch_id) {
+ return;
+ }
+
+ // 5. While watchIDs contains watchId:
+ // AD-HOC: The spec expresses this as a loop; register callbacks for significant position changes and
+ // re-enter request a position from those callbacks.
+ {
+ let watch_position_data = this.watch_position_data.borrow();
+ match watch_position_data.get(&watch_id) {
+ Some(data) if data.emulated_position_data_observer_id.is_none() => {}
+ _ => return,
+ }
+ }
+
+ let weak_document = this.window.associated_document().downgrade(vm);
+ // SAFETY: The window and the cell are live.
+ let observer_id = unsafe {
+ web_geolocation_register_emulated_position_data_observer(
+ this.window.as_ptr(),
+ cell_into_abi(this),
+ watch_id,
+ )
+ };
+ if let Some(data) = this.watch_position_data.borrow_mut(vm).get_mut(&watch_id) {
+ data.emulated_position_data_observer_id = Some(observer_id);
+ data.observed_document = Some(weak_document);
+ }
+ },
+ );
+ }
+ }
+
+ fn emulated_position_data_changed(this: Ref<Self>, vm: &Vm, watch_id: u32) {
+ if !this.watch_ids.borrow().contains(&watch_id) {
+ return;
+ }
+
+ let arguments = {
+ let watch_position_data = this.watch_position_data.borrow();
+ let Some(data) = watch_position_data.get(&watch_id) else {
+ return;
+ };
+
+ let document = data.observed_document.as_ref().and_then(WeakCppDocument::get);
+ if !document.is_some_and(|document| document.is_fully_active()) {
+ return;
+ }
+
+ if this.pending_watch_position_requests.borrow().contains_key(&watch_id) {
+ return;
+ }
+
+ PositionRequestArguments {
+ success_callback: data.success_callback.clone(),
+ error_callback: data.error_callback.clone(),
+ options: data.options,
+ watch_id: Some(watch_id),
+ }
+ };
+
+ // FIXME: If document is not fully active or visibility state is not "visible", wait for visibility.
+ Self::request_a_position(this, vm, arguments);
+ }
+
+ // https://w3c.github.io/geolocation/#dfn-acquire-a-position
+ fn acquire_a_position(this: Ref<Self>, vm: &Vm, arguments: PositionRequestArguments) {
+ // 1. If watchId was passed and this's [[watchIDs]] does not contain watchId, terminate this algorithm.
+ if let Some(watch_id) = arguments.watch_id
+ && !this.watch_ids.borrow().contains(&watch_id)
+ {
+ return;
+ }
+
+ // 2. Let acquisitionTime be a new EpochTimeStamp that represents now.
+ let acquisition_time = now_milliseconds_since_epoch();
+
+ // 3. Let timeoutTime be the sum of acquisitionTime and options.timeout.
+ let _timeout_time = acquisition_time.wrapping_add(u64::from(arguments.options.timeout));
+
+ // 4. Let cachedPosition be this's [[cachedPosition]].
+ let cached_position = *this.cached_position.borrow();
+
+ // 5. Create an implementation-specific timeout task that elapses at timeoutTime, during which it tries to acquire
+ // the device's position by running the following steps:
+ {
+ // 1. Let permission be get the current permission state of "geolocation".
+ // NB: This can run outside any script (when the user's answer arrives, e.g.), so the settings object is passed.
+ let permission = permission_state(PermissionName::Geolocation, &this.window_settings_object());
+
+ // 2. If permission is "denied":
+ if permission == PermissionState::Denied {
+ // 1. Stop timeout.
+ // NB: No timeout is running yet because we start the timer immediately before requesting native position
+ // data below.
+
+ // 2. Do the user or system denied permission failure case step.
+ this.call_back_with_error(
+ vm,
+ arguments.error_callback,
+ GeolocationPositionErrorCode::PermissionDenied,
+ );
+ return;
+ }
+
+ // 3. If permission is "granted":
+ if permission == PermissionState::Granted {
+ // 1. Check if an emulated position should be used by running the following steps:
+ {
+ // 1. Let emulatedPositionData be get emulated position data passing this.
+ let emulated_position_data = this.get_emulated_position_data();
+
+ // 2. If emulatedPositionData is not null:
+ match emulated_position_data {
+ EmulatedPositionData::None => {}
+ // 1. If emulatedPositionData is a GeolocationPositionError:
+ EmulatedPositionData::Error(code) => {
+ // 1. Call back with error passing errorCallback and emulatedPositionData.
+ // FIXME: We pass along the code instead of the entire error object. Spec issue:
+ // https://github.com/w3c/geolocation/issues/186
+ this.call_back_with_error(vm, arguments.error_callback, code);
+
+ // 2. Terminate this algorithm.
+ return;
+ }
+ EmulatedPositionData::Coordinates(coordinates) => {
+ // 2. Let position be a new GeolocationPosition passing emulatedPositionData, acquisitionTime and
+ // options.enableHighAccuracy.
+ let position = GeolocationPosition::create(
+ vm,
+ coordinates,
+ acquisition_time,
+ arguments.options.enable_high_accuracy,
+ );
+
+ // 3. Queue a task on the geolocation task source with a step that invokes successCallback with
+ // « position » and "report".
+ this.queue_success_callback(vm, arguments.success_callback, position);
+
+ // 4. Terminate this algorithm.
+ return;
+ }
+ }
+ }
+
+ // 2. Let position be null.
+ // NB: position is created inside the async callback in step 6 below.
+
+ // 3. If cachedPosition is not null, and options.maximumAge is greater than 0:
+ if let Some(cached_position) = cached_position
+ && arguments.options.maximum_age > 0
+ {
+ // 1. Let cacheTime be acquisitionTime minus the value of the options.maximumAge member.
+ let cache_time = acquisition_time.wrapping_sub(u64::from(arguments.options.maximum_age));
+
+ // 2. If cachedPosition's timestamp's value is greater than cacheTime, and
+ // cachedPosition.[[isHighAccuracy]] equals options.enableHighAccuracy:
+ if cached_position.timestamp_value() > cache_time
+ && cached_position.is_high_accuracy() == arguments.options.enable_high_accuracy
+ {
+ // 1. Queue a task on the geolocation task source with a step that invokes successCallback with
+ // « cachedPosition » and "report".
+ this.queue_success_callback(vm, arguments.success_callback, cached_position);
+
+ // 2. Terminate this algorithm.
+ return;
+ }
+ }
+
+ // 4. Otherwise, if position is not cachedPosition, try to acquire position data from the underlying system,
+ // optionally taking into consideration the value of options.enableHighAccuracy during acquisition.
+ Self::acquire_position_from_page(this, vm, arguments, acquisition_time);
+ return;
+ }
+
+ // NB: While the permission is "prompt" (a one-time grant just ended, e.g.), neither step above applies, and the
+ // timeout task elapses without a position.
+ Self::call_back_with_timeout_error(
+ this,
+ vm,
+ arguments.error_callback,
+ arguments.options.timeout,
+ arguments.watch_id,
+ );
+ }
+ }
+
+ // A watch cleared, or a document left, before the timeout elapses hears nothing of it, as with a timeout that elapses
+ // while a position is being acquired.
+ fn call_back_with_timeout_error(
+ this: Ref<Self>,
+ vm: &Vm,
+ error_callback: Option<CallbackFunction>,
+ timeout: u32,
+ watch_id: Option<u32>,
+ ) {
+ let weak_document = this.window.associated_document().downgrade(vm);
+ let token = this.next_timeout_timer_token();
+ let timer = CppTimer::create_single_shot(
+ vm,
+ timeout_milliseconds(timeout),
+ (this, token, error_callback, watch_id, weak_document),
+ |vm, (this, token, error_callback, watch_id, weak_document)| {
+ this.take_timeout_timer(vm, token);
+ if let Some(watch_id) = watch_id
+ && !this.watch_ids.borrow().contains(&watch_id)
+ {
+ return;
+ }
+ if !weak_document.get().is_some_and(|document| document.is_fully_active()) {
+ return;
+ }
+ this.call_back_with_error(vm, error_callback, GeolocationPositionErrorCode::Timeout);
+ },
+ );
+ this.add_timeout_timer(vm, token, timer);
+ }
+
+ fn acquire_position_from_page(
+ this: Ref<Self>,
+ vm: &Vm,
+ arguments: PositionRequestArguments,
+ acquisition_time: u64,
+ ) {
+ let document = this.window.associated_document();
+ let watch_id = arguments.watch_id;
+ let timeout = arguments.options.timeout;
+ let request = POSITION_REQUEST_CLASS.allocate(vm, |_| PositionRequest {
+ geolocation: this,
+ arguments,
+ acquisition_time,
+ weak_document: document.downgrade(vm),
+ request_id: Cell::new(0),
+ completed: Cell::new(false),
+ timeout_stopped: Cell::new(false),
+ timeout_timer: Cell::new(0),
+ });
+
+ // SAFETY: The window and the cell are live.
+ let request_id = unsafe {
+ web_geolocation_request_position(this.window.as_ptr(), request.as_ptr().cast(), watch_id.is_some())
+ };
+ request.request_id.set(request_id);
+ if let Some(watch_id) = watch_id {
+ this.pending_watch_position_requests
+ .borrow_mut(vm)
+ .insert(watch_id, request);
+ }
+
+ let token = this.next_timeout_timer_token();
+ request.timeout_timer.set(token);
+ let timer = CppTimer::create_single_shot(vm, timeout_milliseconds(timeout), request, |vm, request| {
+ PositionRequest::timeout_elapsed(request, vm);
+ });
+ this.add_timeout_timer(vm, token, timer);
+ }
+
+ // https://w3c.github.io/geolocation/#dfn-call-back-with-error
+ fn call_back_with_error(&self, vm: &Vm, callback: Option<CallbackFunction>, code: GeolocationPositionErrorCode) {
+ // 1. If callback is null, return.
+ let Some(callback) = callback else {
+ return;
+ };
+
+ // 2. Let error be a newly created GeolocationPositionError instance whose code attribute is initialized to code.
+ let error = GeolocationPositionError::create(vm, code);
+
+ // 3. Queue a task on the geolocation task source with a step that invokes callback with « error » and "report".
+ queue_a_task_without_execution_context(
+ vm,
+ TaskSource::Geolocation,
+ (callback, error),
+ |vm, (callback, error)| invoke_position_error_callback(vm, &callback, error),
+ );
+ }
+
+ fn run_in_parallel_when_document_is_visible(
+ this: Ref<Self>,
+ vm: &Vm,
+ document: &CppDocument,
+ arguments: PositionRequestArguments,
+ ) {
+ // Run callback in parallel if the document is already visible.
+ if document.visibility_state() == VisibilityState::Visible {
+ deferred_invoke(vm, (this, arguments), |vm, (this, arguments)| {
+ with_temporary_execution_context(this.window.realm(), || {
+ Self::request_a_position_when_document_is_visible(this, vm, arguments);
+ });
+ });
+ return;
+ }
+
+ // Run the callback as soon as the document becomes visible. If we time out, do not run the callback at all.
+ let wait = VISIBILITY_WAIT_CLASS.allocate(vm, |_| VisibilityWait {
+ geolocation: this,
+ arguments,
+ observer: GcRefCell::new(None),
+ timeout_timer: Cell::new(0),
+ });
+ // SAFETY: The Document and the cell are live, and LibWeb returns a live DocumentObserver.
+ let observer = unsafe {
+ CppCell::from_raw(web_geolocation_observe_document_visibility(
+ document.as_ptr(),
+ wait.as_ptr().cast(),
+ ))
+ };
+ *wait.observer.borrow_mut(vm) = Some(observer);
+ let token = this.next_timeout_timer_token();
+ wait.timeout_timer.set(token);
+ let timer = CppTimer::create_single_shot(vm, VISIBILITY_STATE_TIMEOUT_MS, wait, |vm, wait| {
+ eprintln!("Geolocation: Waiting for visibility state update timed out");
+ VisibilityWait::clear_observer_and_timer(wait, vm);
+ });
+ this.add_timeout_timer(vm, token, timer);
+ }
+}
+
+impl PositionRequest {
+ fn stop_timeout_timer(&self, vm: &Vm) {
+ if self.timeout_stopped.get() {
+ return;
+ }
+ self.timeout_stopped.set(true);
+ if let Some(timer) = self.geolocation.take_timeout_timer(vm, self.timeout_timer.get()) {
+ timer.stop();
+ }
+ }
+
+ fn receive_position(request: PositionRequestRef, vm: &Vm, result: &GeolocationPositionResultAbi) {
+ let this = request.geolocation;
+ let arguments = &request.arguments;
+
+ if request.completed.get() {
+ return;
+ }
+
+ if let Some(watch_id) = arguments.watch_id
+ && !this.watch_ids.borrow().contains(&watch_id)
+ {
+ // NB: The position response arrived after the watch was cleared; stop the timeout before ignoring it.
+ request.stop_timeout_timer(vm);
+ return;
+ }
+ if arguments.watch_id.is_none() {
+ request.completed.set(true);
+ }
+
+ if !request
+ .weak_document
+ .get()
+ .is_some_and(|document| document.is_fully_active())
+ {
+ // NB: The position response is no longer observable; stop the timeout before ignoring it.
+ request.stop_timeout_timer(vm);
+ return;
+ }
+
+ // 5. If the timeout elapses during acquisition, or acquiring the device's position results in failure:
+ if result.is_error {
+ let error_code = GeolocationPositionErrorCode::from_u16(result.error_code);
+
+ // 1. Stop the timeout.
+ request.stop_timeout_timer(vm);
+
+ if let Some(watch_id) = arguments.watch_id
+ && error_code == GeolocationPositionErrorCode::PermissionDenied
+ {
+ request.completed.set(true);
+ this.pending_watch_position_requests.borrow_mut(vm).remove(&watch_id);
+ }
+
+ // 2. Go to dealing with failures.
+ this.call_back_with_error(vm, arguments.error_callback.clone(), error_code);
+
+ // 3. Terminate this algorithm.
+ return;
+ }
+
+ // 6. If acquiring the position data from the system succeeds:
+ // 6.1. Let positionData be a map with the following name/value pairs based on the acquired position data:
+ // * latitude:
+ // A double that represents the latitude coordinates on the Earth's surface in degrees, using the
+ // [WGS84] coordinate system. Latitude measures how far north or south a point is from the Equator.
+ // * longitude:
+ // A double that represents the longitude coordinates on the Earth's surface in degrees, using the
+ // [WGS84] coordinate system. Longitude measures how far east or west a point is from the Prime
+ // Meridian.
+ // * altitude:
+ // A double? that represents the altitude in meters above the [WGS84] ellipsoid, or null if not
+ // available. Altitude measures the height above sea level.
+ // * accuracy:
+ // A non-negative double that represents the accuracy value indicating the 95% confidence level in
+ // meters. Accuracy measures how close the measured coordinates are to the true position.
+ // * altitudeAccuracy:
+ // A non-negative double? that represents the altitude accuracy, or null if not available,
+ // indicating the 95% confidence level in meters. Altitude accuracy measures how close the measured
+ // altitude is to the true altitude.
+ // * speed:
+ // A non-negative double? that represents the speed in meters per second, or null if not available.
+ // Speed measures how fast the device is moving.
+ // * heading:
+ // A double? that represents the heading in degrees, or null if not available or the device is
+ // stationary. Heading measures the direction in which the device is moving relative to true north.
+ let position_data = GeolocationCoordinates::create(vm, &result.coordinates);
+
+ // 6.2. Set position to a new GeolocationPosition passing positionData, acquisitionTime and
+ // options.enableHighAccuracy.
+ let position = GeolocationPosition::create(
+ vm,
+ position_data,
+ request.acquisition_time,
+ arguments.options.enable_high_accuracy,
+ );
+
+ // 6.3. Set this's [[cachedPosition]] to position.
+ *this.cached_position.borrow_mut(vm) = Some(position);
+
+ // 7. Stop the timeout.
+ request.stop_timeout_timer(vm);
+
+ // 8. Queue a task on the geolocation task source with a step that invokes successCallback with « position »
+ // and "report".
+ this.queue_success_callback(vm, arguments.success_callback.clone(), position);
+ }
+
+ fn timeout_elapsed(request: PositionRequestRef, vm: &Vm) {
+ let this = request.geolocation;
+ if request.completed.get() {
+ return;
+ }
+ request.completed.set(true);
+ request.stop_timeout_timer(vm);
+ if let Some(watch_id) = request.arguments.watch_id
+ && this
+ .pending_watch_position_requests
+ .borrow_mut(vm)
+ .remove(&watch_id)
+ .is_none()
+ {
+ return;
+ }
+ // SAFETY: The window is live.
+ unsafe { web_geolocation_cancel_position_request(this.window.as_ptr(), request.request_id.get()) };
+ if !request
+ .weak_document
+ .get()
+ .is_some_and(|document| document.is_fully_active())
+ {
+ return;
+ }
+ this.call_back_with_error(
+ vm,
+ request.arguments.error_callback.clone(),
+ GeolocationPositionErrorCode::Timeout,
+ );
+ }
+}
+
+impl VisibilityWait {
+ fn clear_observer_and_timer(wait: VisibilityWaitRef, vm: &Vm) {
+ if let Some(observer) = wait.observer.borrow_mut(vm).take() {
+ // SAFETY: The DocumentObserver is live.
+ unsafe { web_geolocation_stop_observing_document_visibility(observer.as_ptr()) };
+ }
+ if let Some(timer) = wait.geolocation.take_timeout_timer(vm, wait.timeout_timer.get()) {
+ timer.stop();
+ }
+ }
+
+ fn document_visibility_changed(wait: VisibilityWaitRef, vm: &Vm, is_visible: bool) {
+ if !is_visible {
+ return;
+ }
+ Self::clear_observer_and_timer(wait, vm);
+ let geolocation = wait.geolocation;
+ let arguments = wait.arguments.clone();
+ with_temporary_execution_context(geolocation.window.realm(), || {
+ Geolocation::request_a_position_when_document_is_visible(geolocation, vm, arguments);
+ });
+ }
+}
+
+/// A new Geolocation of the window.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `window` a live Window.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_geolocation_create_geolocation(vm: *mut c_void, window: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live Window.
+ let (vm, window) = unsafe { (&*vm.cast::<Vm>(), CppWindow::from_raw(window)) };
+ cell_into_abi(allocate(vm, |_| Geolocation {
+ window,
+ watch_ids: RefCell::new(HashSet::new()),
+ watch_position_data: GcRefCell::new(HashMap::new()),
+ pending_watch_position_requests: GcRefCell::new(HashMap::new()),
+ cached_position: GcRefCell::new(None),
+ timeout_timers: GcRefCell::new(Vec::new()),
+ next_timeout_timer: Cell::new(0),
+ }))
+}
+
+/// The page's answer to a request for a position.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `request` the live cell that the request was made with, and `result` lent for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_geolocation_receive_position(
+ vm: *mut c_void,
+ request: *mut c_void,
+ result: &GeolocationPositionResultAbi,
+) {
+ // SAFETY: The caller passes the live VM and the live cell of a request.
+ let (vm, request) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ POSITION_REQUEST_CLASS
+ .downcast(NonNull::new(request).expect("LibWeb passes the request"))
+ .expect("LibWeb passes a GeolocationPositionRequest"),
+ )
+ };
+ PositionRequest::receive_position(request, vm, result);
+}
+
+/// The page's emulated position data changed, which a watch observes.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `geolocation` the live cell of a Geolocation.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_geolocation_emulated_position_data_changed(
+ vm: *mut c_void,
+ geolocation: *mut c_void,
+ watch_id: u32,
+) {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, geolocation) = unsafe { (&*vm.cast::<Vm>(), cell_from_abi::<Geolocation>(geolocation)) };
+ Geolocation::emulated_position_data_changed(geolocation, vm, watch_id);
+}
+
+/// The visibility state of the document that a request a position waits for changed.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `wait` the live cell that the observer was made with.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_geolocation_document_visibility_changed(
+ vm: *mut c_void,
+ wait: *mut c_void,
+ is_visible: bool,
+) {
+ // SAFETY: The caller passes the live VM and the live cell of a wait.
+ let (vm, wait) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ VISIBILITY_WAIT_CLASS
+ .downcast(NonNull::new(wait).expect("LibWeb passes the wait"))
+ .expect("LibWeb passes a GeolocationVisibilityWait"),
+ )
+ };
+ VisibilityWait::document_visibility_changed(wait, vm, is_visible);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position.rs b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position.rs
index 68fffc79440..3b6b565c522 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position.rs
@@ -7,11 +7,9 @@
//! GeolocationPosition, https://w3c.github.io/geolocation/#position_interface
-use core::ffi::c_void;
-
use libjs_rust::api::{Trace, Vm};
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use crate::geolocation::geolocation_coordinates::GeolocationCoordinates;
@@ -51,39 +49,12 @@ impl GeolocationPosition {
pub(crate) fn timestamp(&self, _: &mut CallContext) -> WebIdlResult<u64> {
Ok(self.timestamp)
}
-}
-/// A new GeolocationPosition.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, and `coords` the live cell of a GeolocationCoordinates.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_geolocation_create_geolocation_position(
- vm: *mut c_void,
- coords: *mut c_void,
- timestamp: u64,
- is_high_accuracy: bool,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM and a live cell.
- let (vm, coords) = unsafe { (&*vm.cast::<Vm>(), cell_from_abi::<GeolocationCoordinates>(coords)) };
- cell_into_abi(GeolocationPosition::create(vm, coords, timestamp, is_high_accuracy))
-}
-
-/// # Safety
-///
-/// `cell` must be the live cell of a GeolocationPosition.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_geolocation_geolocation_position_timestamp(cell: *mut c_void) -> u64 {
- // SAFETY: The caller passes a live cell.
- unsafe { cell_from_abi::<GeolocationPosition>(cell) }.timestamp
-}
+ pub(crate) fn timestamp_value(&self) -> u64 {
+ self.timestamp
+ }
-/// # Safety
-///
-/// `cell` must be the live cell of a GeolocationPosition.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_geolocation_geolocation_position_is_high_accuracy(cell: *mut c_void) -> bool {
- // SAFETY: The caller passes a live cell.
- unsafe { cell_from_abi::<GeolocationPosition>(cell) }.is_high_accuracy
+ pub(crate) fn is_high_accuracy(&self) -> bool {
+ self.is_high_accuracy
+ }
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position_error.rs b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position_error.rs
index 38bdc3ce448..41cd446567d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position_error.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/geolocation/geolocation_position_error.rs
@@ -7,12 +7,10 @@
//! GeolocationPositionError, https://w3c.github.io/geolocation/#dom-geolocationpositionerror
-use core::ffi::c_void;
-
use ak::Utf16String;
use libjs_rust::api::{Trace, Vm};
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use crate::geolocation::geolocation_position_error_code::GeolocationPositionErrorCode;
@@ -46,21 +44,3 @@ impl GeolocationPositionError {
Ok(Utf16String::from_ascii(message))
}
}
-
-/// A new GeolocationPositionError with the code.
-///
-/// # Safety
-///
-/// `vm` must be the live VM.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_geolocation_create_geolocation_position_error(
- vm: *mut c_void,
- code: u16,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { &*vm.cast::<Vm>() };
- cell_into_abi(GeolocationPositionError::create(
- vm,
- GeolocationPositionErrorCode::from_u16(code),
- ))
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/geolocation/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/geolocation/mod.rs
index 7f2646388e0..facaa554878 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/geolocation/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/geolocation/mod.rs
@@ -4,6 +4,11 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#[allow(
+ clippy::module_inception,
+ reason = "the module mirrors the Geolocation interface file"
+)]
+pub(crate) mod geolocation;
pub(crate) mod geolocation_coordinates;
pub(crate) mod geolocation_position;
pub(crate) mod geolocation_position_error;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index e40095d3d56..811a48f60ee 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -95,6 +95,8 @@ pub(crate) mod structured_serialize;
#[cfg(not(test))]
pub(crate) mod text_metrics;
#[cfg(not(test))]
+pub(crate) mod visibility_state;
+#[cfg(not(test))]
pub(crate) mod visibility_state_entry;
#[cfg(not(test))]
pub(crate) mod window;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/visibility_state.rs b/Libraries/LibWeb/Bindings/Rust/src/html/visibility_state.rs
new file mode 100644
index 00000000000..f954a4f9cd9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/visibility_state.rs
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) 2022, Andreas Kling <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+/// https://html.spec.whatwg.org/multipage/interaction.html#visibility-state
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum VisibilityState {
+ Visible,
+ Hidden,
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 4e217c18fe5..53819c704ad 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -237,6 +237,8 @@ pub(crate) mod permissions;
)]
pub(crate) mod permissions_api;
#[cfg(not(test))]
+pub(crate) mod permissions_policy;
+#[cfg(not(test))]
pub(crate) mod platform;
#[cfg(not(test))]
#[cfg_attr(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs
index 5f4ab0ce89a..7b8d02efb86 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs
@@ -7,10 +7,14 @@
//! Permissions, https://w3c.github.io/permissions/#permissions-interface
+use core::cell::RefCell;
use core::ffi::c_void;
+use core::ptr::NonNull;
use ak::Utf16String;
-use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, Throw, Trace, Value, Vm};
+use libjs_rust::api::{
+ EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, Object, Throw, Trace, Value, Visitor, Vm,
+};
#[cfg(web_idl_bindings)]
use crate::bindings::conversions::FromJs;
@@ -26,6 +30,12 @@ use crate::permissions_api::permission_status::{PermissionState, PermissionStatu
unsafe extern "C" {
fn web_permissions_api_permission_state(settings_object: *mut c_void, name: u8) -> u8;
+ fn web_permissions_api_request_permission_to_use(
+ settings_object: *mut c_void,
+ name: u8,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void, u8),
+ );
}
// https://w3c.github.io/permissions/#dom-permissiondescriptor
@@ -52,7 +62,11 @@ impl PermissionName {
// https://w3c.github.io/permissions/#dfn-permission-state
pub(crate) fn permission_state(name: PermissionName, settings: &CppEnvironmentSettingsObject) -> PermissionState {
// SAFETY: The settings object is live.
- match unsafe { web_permissions_api_permission_state(settings.as_ptr(), name as u8) } {
+ permission_state_from(unsafe { web_permissions_api_permission_state(settings.as_ptr(), name as u8) })
+}
+
+fn permission_state_from(state: u8) -> PermissionState {
+ match state {
0 => PermissionState::Granted,
1 => PermissionState::Denied,
2 => PermissionState::Prompt,
@@ -60,6 +74,89 @@ pub(crate) fn permission_state(name: PermissionName, settings: &CppEnvironmentSe
}
}
+/// Steps that run once with the state that requesting permission to use settled on.
+trait DecisionSteps: Trace {
+ fn run(&self, vm: &Vm, state: PermissionState);
+}
+
+struct CapturedDecisionSteps<C> {
+ captures: C,
+ steps: fn(&Vm, C, PermissionState),
+}
+
+// SAFETY: The steps are a plain function, which holds no cells.
+unsafe impl<C: Trace> Trace for CapturedDecisionSteps<C> {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.captures.trace(visitor);
+ }
+}
+
+impl<C: Trace + Clone + 'static> DecisionSteps for CapturedDecisionSteps<C> {
+ fn run(&self, vm: &Vm, state: PermissionState) {
+ (self.steps)(vm, self.captures.clone(), state);
+ }
+}
+
+/// The cell that keeps the steps of a permission request and what they capture alive until the request settles.
+struct PendingDecision(RefCell<Option<Box<dyn DecisionSteps>>>);
+
+// SAFETY: The steps that have not run are all the cells this reaches.
+unsafe impl Trace for PendingDecision {
+ fn trace(&self, visitor: &mut Visitor) {
+ if let Some(steps) = &*self.0.borrow() {
+ steps.trace(visitor);
+ }
+ }
+}
+
+static PENDING_DECISION_CLASS: EmbedderClass<PendingDecision> = EmbedderClass::new("PendingDecision");
+
+impl EmbedderValue for PendingDecision {
+ const CLASS: &'static EmbedderClass<Self> = &PENDING_DECISION_CLASS;
+}
+
+unsafe extern "C" fn run_pending_decision(vm: *mut c_void, cell: *mut c_void, state: u8) {
+ // SAFETY: LibWeb passes the VM and the cell that request_permission_to_use() made, which it kept alive.
+ let (vm, cell) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ PENDING_DECISION_CLASS
+ .downcast(NonNull::new(cell).expect("LibWeb passes the cell"))
+ .expect("LibWeb passes a PendingDecision"),
+ )
+ };
+ // NB: The cell keeps what the steps capture alive while they run, and lets go of it once they have.
+ cell.0
+ .borrow()
+ .as_ref()
+ .expect("a permission request settles once")
+ .run(vm, permission_state_from(state));
+ cell.0.take();
+}
+
+// https://w3c.github.io/permissions/#dfn-request-permission-to-use
+pub(crate) fn request_permission_to_use<C: Trace + Clone + 'static>(
+ vm: &Vm,
+ name: PermissionName,
+ settings: &CppEnvironmentSettingsObject,
+ captures: C,
+ steps: fn(&Vm, C, PermissionState),
+) {
+ let cell = PENDING_DECISION_CLASS.allocate(vm, |_| {
+ let steps: Box<dyn DecisionSteps> = Box::new(CapturedDecisionSteps { captures, steps });
+ PendingDecision(RefCell::new(Some(steps)))
+ });
+ // SAFETY: The settings object and the cell are live.
+ unsafe {
+ web_permissions_api_request_permission_to_use(
+ settings.as_ptr(),
+ name as u8,
+ cell.as_ptr().cast(),
+ run_pending_decision,
+ );
+ }
+}
+
// https://w3c.github.io/permissions/#permissions-interface
#[derive(Trace)]
#[gc(crate = libjs_rust)]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/mod.rs
new file mode 100644
index 00000000000..46c28d56d94
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#[allow(
+ clippy::module_inception,
+ reason = "the module mirrors LibWebCommon/PermissionsPolicy/PermissionsPolicy.h"
+)]
+pub(crate) mod permissions_policy;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs
new file mode 100644
index 00000000000..fa147b52df1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+/// Web::PermissionsPolicy::PolicyControlledFeature.
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub(crate) enum PolicyControlledFeature {
+ Geolocation = 7,
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index a988017bf80..659e736a3e7 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -88,12 +88,15 @@ void web_bindings_queue_a_microtask(void* realm, JSObject* function);
void web_bindings_deferred_invoke(void* cell, void (*steps)(JSVM*, void*));
void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*));
void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*));
+void web_bindings_queue_a_task_without_execution_context(u8 task_source, void* cell, void (*steps)(JSVM*, void*));
u64 web_bindings_queue_a_global_task(JSObject* global_object, u8 task_source, void* cell, void (*steps)(JSVM*, void*));
void web_bindings_remove_tasks(void* realm, ReadonlySpan<u64> task_ids);
u64 web_bindings_currently_running_task(void* realm);
void web_bindings_spin_until_promise_is_settled(JSObject* promise);
void* web_bindings_create_callback_function(JSObject* callable, bool returns_promise);
JSCompletion web_bindings_invoke_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);
+void web_bindings_invoke_callback_function_and_report(void* callback, ReadonlySpan<JSValue> arguments);
+JSObject* web_bindings_callback_function_callback(void* callback);
void* web_bindings_invoke_promise_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments);
void web_bindings_push_element_queue();
void web_bindings_pop_element_queue_and_invoke_reactions();
@@ -109,6 +112,8 @@ bool web_bindings_window_has_transient_activation(HTML::Window*);
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*);
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*);
@@ -121,6 +126,7 @@ HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject*
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*);
+bool web_bindings_environment_settings_object_is_secure_context(HTML::EnvironmentSettingsObject*);
void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject*, void* ctx, void (*on_id)(void*, ReadonlyBytes));
bool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);
void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget*, bool has_pending_activity);
@@ -242,6 +248,21 @@ bool web_bindings_document_is_fully_active(DOM::Document* document)
return document->is_fully_active();
}
+static_assert(to_underlying(DOM::PolicyControlledFeature::Geolocation) == 7);
+
+bool web_bindings_document_is_allowed_to_use_feature(DOM::Document* document, u8 feature)
+{
+ return document->is_allowed_to_use_feature(static_cast<DOM::PolicyControlledFeature>(feature));
+}
+
+static_assert(to_underlying(HTML::VisibilityState::Visible) == 0);
+static_assert(to_underlying(HTML::VisibilityState::Hidden) == 1);
+
+u8 web_bindings_document_visibility_state(DOM::Document* document)
+{
+ return to_underlying(document->visibility_state());
+}
+
bool web_bindings_document_has_focus(DOM::Document* document)
{
return document->has_focus();
@@ -297,6 +318,11 @@ double web_bindings_environment_settings_object_time_origin(HTML::EnvironmentSet
return settings_object->time_origin();
}
+bool web_bindings_environment_settings_object_is_secure_context(HTML::EnvironmentSettingsObject* settings_object)
+{
+ return HTML::is_secure_context(*settings_object);
+}
+
void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject* settings_object, void* ctx, void (*on_id)(void*, ReadonlyBytes))
{
on_id(ctx, settings_object->id.to_string().bytes());
@@ -425,6 +451,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::Networking) == 3);
+static_assert(to_underlying(HTML::Task::Source::Geolocation) == 10);
static_assert(to_underlying(HTML::Task::Source::TimerTask) == 8);
static_assert(to_underlying(HTML::Task::Source::FileReading) == 13);
static_assert(to_underlying(HTML::Task::Source::PerformanceTimeline) == 15);
@@ -443,6 +470,14 @@ void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*s
}));
}
+void web_bindings_queue_a_task_without_execution_context(u8 task_source, void* cell, void (*steps)(JSVM*, void*))
+{
+ // NB: The task's captures, which the collector traces, keep the cell alive until the steps run.
+ HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& cell, auto& steps) {
+ steps(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr());
+ }));
+}
+
u64 web_bindings_queue_a_global_task(JSObject* global_object, u8 task_source, void* cell, void (*steps)(JSVM*, void*))
{
auto& global = *JS::HostABI::object_from_abi(global_object);
@@ -494,6 +529,16 @@ JSCompletion web_bindings_invoke_callback_function(void* callback, bool has_this
return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(completion.value()));
}
+void web_bindings_invoke_callback_function_and_report(void* callback, ReadonlySpan<JSValue> arguments)
+{
+ (void)WebIDL::invoke_callback(*static_cast<WebIDL::CallbackType*>(callback), {}, WebIDL::ExceptionBehavior::Report, callback_arguments(arguments));
+}
+
+JSObject* web_bindings_callback_function_callback(void* callback)
+{
+ return JS::HostABI::object_to_abi(static_cast<WebIDL::CallbackType*>(callback)->callback.ptr());
+}
+
void* web_bindings_invoke_promise_callback_function(void* callback, bool has_this_value, JSValue this_value, ReadonlySpan<JSValue> arguments)
{
Optional<JS::Value> this_argument;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 52cacf4250f..d176cfcb791 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -343,8 +343,6 @@ set(SOURCES
Gamepad/NavigatorGamepad.cpp
Geolocation/Geolocation.cpp
Geolocation/GeolocationCoordinates.cpp
- Geolocation/GeolocationPosition.cpp
- Geolocation/GeolocationPositionError.cpp
Geometry/DOMMatrix.cpp
Geometry/DOMMatrixReadOnly.cpp
Geometry/DOMPoint.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 3b87a19d69b..20b7036d744 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -640,8 +640,6 @@ namespace Web::Geolocation {
class Geolocation;
class GeolocationCoordinates;
-class GeolocationPosition;
-class GeolocationPositionError;
}
diff --git a/Libraries/LibWeb/Geolocation/Geolocation.cpp b/Libraries/LibWeb/Geolocation/Geolocation.cpp
index 9f7b46a6784..908576edb92 100644
--- a/Libraries/LibWeb/Geolocation/Geolocation.cpp
+++ b/Libraries/LibWeb/Geolocation/Geolocation.cpp
@@ -4,578 +4,118 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/RefCounted.h>
-#include <AK/Time.h>
#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/Geolocation.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentObserver.h>
#include <LibWeb/Geolocation/Geolocation.h>
-#include <LibWeb/Geolocation/GeolocationCoordinates.h>
-#include <LibWeb/Geolocation/GeolocationPosition.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/EventLoop/Task.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/PermissionsAPI/Permissions.h>
-#include <LibWeb/Platform/EventLoopPlugin.h>
-#include <LibWeb/Platform/Timer.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/CallbackType.h>
namespace Web::Geolocation {
-static constexpr u32 VISIBILITY_STATE_TIMEOUT_MS = 5'000;
+namespace {
-static WebIDL::UnsignedLong s_next_watch_id = 0;
-
-class GeolocationRequestState : public RefCounted<GeolocationRequestState> {
-public:
- GC_HOLDS_NO_CELL_EDGES;
-
- u64 request_id { 0 };
- bool completed { false };
- bool timeout_stopped { false };
+struct GeolocationPositionResultAbi {
+ bool is_error;
+ u16 error_code;
+ CoordinatesDataAbi coordinates;
};
-GC_DEFINE_ALLOCATOR(Geolocation);
+struct EmulatedPositionDataAbi {
+ u8 kind;
+ void* coordinates;
+ u16 error_code;
+};
-static void invoke_position_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPosition> position)
-{
- auto& callback_realm = callback->callback->shape().realm();
- (void)WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Report,
- { { Bindings::wrap(Bindings::host_defined_wrapper_world(callback_realm), callback_realm, position) } });
}
-static void invoke_position_error_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPositionError> error)
-{
- auto& callback_realm = callback->callback->shape().realm();
- (void)WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Report,
- { { Bindings::wrap(Bindings::host_defined_wrapper_world(callback_realm), callback_realm, error) } });
-}
+extern "C" {
+// Defined in Bindings/Rust/src/geolocation/geolocation.rs.
+Geolocation* web_rust_geolocation_create_geolocation(JSVM*, HTML::Window*);
+void web_rust_geolocation_receive_position(JSVM*, GC::Cell* request, GeolocationPositionResultAbi const&);
+void web_rust_geolocation_emulated_position_data_changed(JSVM*, Geolocation*, u32 watch_id);
+void web_rust_geolocation_document_visibility_changed(JSVM*, GC::Cell* wait, bool is_visible);
-static void queue_success_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPosition> position)
-{
- HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(callback, position), [](auto& callback, auto& position) {
- invoke_position_callback(callback, position);
- }));
+u64 web_geolocation_request_position(HTML::Window*, GC::Cell* request, bool is_watch);
+void web_geolocation_cancel_position_request(HTML::Window*, u64 request_id);
+void web_geolocation_emulated_position_data(HTML::Window*, EmulatedPositionDataAbi*);
+u64 web_geolocation_register_emulated_position_data_observer(HTML::Window*, Geolocation*, u32 watch_id);
+void web_geolocation_unregister_emulated_position_data_observer(HTML::Window*, u64 observer_id);
+DOM::DocumentObserver* web_geolocation_observe_document_visibility(DOM::Document*, GC::Cell* wait);
+void web_geolocation_stop_observing_document_visibility(DOM::DocumentObserver*);
}
-static void queue_error_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPositionError> error)
+static JSVM* the_vm()
{
- HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(callback, error), [](auto& callback, auto& error) {
- invoke_position_error_callback(callback, error);
- }));
+ return JS::HostABI::vm_to_abi(JS::VM::the());
}
GC::Ref<Geolocation> Geolocation::create(HTML::Window& window)
{
- return GC::Heap::the().allocate<Geolocation>(window);
-}
-
-Geolocation::Geolocation(HTML::Window& window)
- : m_window(window)
-{
-}
-
-void Geolocation::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto& watch_position_data : m_watch_position_data) {
- visitor.visit(watch_position_data.value.success_callback);
- visitor.visit(watch_position_data.value.error_callback);
- }
- visitor.visit(m_window);
- visitor.visit(m_cached_position);
- visitor.visit(m_timeout_timers);
+ return *web_rust_geolocation_create_geolocation(the_vm(), &window);
}
-// https://w3c.github.io/geolocation/#dom-geolocation-getcurrentposition
-void Geolocation::get_current_position(GC::Ref<WebIDL::CallbackType> success_callback,
- GC::Ptr<WebIDL::CallbackType> error_callback, PositionOptions const& options)
+u64 web_geolocation_request_position(HTML::Window* window, GC::Cell* request, bool is_watch)
{
- // 1. If this's relevant global object's associated Document is not fully active:
- if (!window().associated_document().is_fully_active()) {
- // 1. Call back with error errorCallback and POSITION_UNAVAILABLE.
- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PositionUnavailable);
-
- // 2. Terminate this algorithm.
- return;
- }
-
- // 2. Request a position passing this, successCallback, errorCallback, and options.
- request_a_position(success_callback, error_callback, options, {});
-}
-
-// https://w3c.github.io/geolocation/#watchposition-method
-WebIDL::Long Geolocation::watch_position(GC::Ref<WebIDL::CallbackType> success_callback,
- GC::Ptr<WebIDL::CallbackType> error_callback, PositionOptions const& options)
-{
- // 1. If this's relevant global object's associated Document is not fully active:
- if (!window().associated_document().is_fully_active()) {
- // 1. Call back with error passing errorCallback and POSITION_UNAVAILABLE.
- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PositionUnavailable);
-
- // 2. Return 0.
- return 0;
- }
-
- // 2. Let watchId be an implementation-defined unsigned long that is greater than zero.
- auto watch_id = ++s_next_watch_id;
-
- // 3. Append watchId to this's [[watchIDs]].
- m_watch_ids.set(watch_id);
- m_watch_position_data.set(watch_id, { success_callback, error_callback, options });
-
- // 4. Request a position passing this, successCallback, errorCallback, options, and watchId.
- request_a_position(success_callback, error_callback, options, watch_id);
-
- // 5. Return watchId.
- return watch_id;
-}
-
-// https://w3c.github.io/geolocation/#clearwatch-method
-void Geolocation::clear_watch(WebIDL::Long watch_id)
-{
- // 1. Remove watchId from this's [[watchIDs]].
- remove_watch_id(watch_id);
-
- if (auto request_id = m_pending_watch_position_request_ids.take(watch_id); request_id.has_value()) {
- auto& document = window().associated_document();
- document.page().cancel_geolocation_position_request(*request_id);
- }
-}
-
-// https://w3c.github.io/geolocation/#dfn-get-emulated-position-data
-EmulatedPositionData Geolocation::get_emulated_position_data() const
-{
- // 1. Let navigable be geolocation's relevant global object's associated Document's node navigable.
- // 2. If navigable is null, return null.
- // 3. Return navigable's top-level traversable's emulated position data.
- // NB: The page holds the top-level traversable's, which another process may host.
- return window().page().emulated_position_data();
+ auto& document = window->associated_document();
+ auto position_callback = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *request }), [](auto& request, Page::GeolocationPositionResult result) {
+ GeolocationPositionResultAbi abi {};
+ if (result.has<GeolocationPositionErrorCode>()) {
+ abi.is_error = true;
+ abi.error_code = to_underlying(result.get<GeolocationPositionErrorCode>());
+ } else {
+ abi.coordinates = coordinates_data_to_abi(result.get<CoordinatesData>());
+ }
+ web_rust_geolocation_receive_position(the_vm(), request.ptr(), abi);
+ });
+ return document.page().request_geolocation_position(document.id(), position_callback, is_watch ? Page::GeolocationRequestType::Watch : Page::GeolocationRequestType::OneShot);
}
-void Geolocation::remove_watch_id(WebIDL::UnsignedLong watch_id)
+void web_geolocation_cancel_position_request(HTML::Window* window, u64 request_id)
{
- m_watch_ids.remove(watch_id);
- unregister_watch_position_observer(watch_id);
- m_watch_position_data.remove(watch_id);
+ window->page().cancel_geolocation_position_request(request_id);
}
-void Geolocation::unregister_watch_position_observer(WebIDL::UnsignedLong watch_id)
+void web_geolocation_emulated_position_data(HTML::Window* window, EmulatedPositionDataAbi* data)
{
- auto watch_position_data = m_watch_position_data.get(watch_id);
- if (!watch_position_data.has_value() || !watch_position_data->emulated_position_data_observer_id.has_value())
- return;
-
- window().page().unregister_emulated_position_data_observer(*watch_position_data->emulated_position_data_observer_id);
- watch_position_data->emulated_position_data_observer_id = {};
+ window->page().emulated_position_data().visit(
+ [&](Empty) { data->kind = 0; },
+ [&](GC::Ref<GeolocationCoordinates> coordinates) {
+ data->kind = 1;
+ data->coordinates = coordinates.ptr();
+ },
+ [&](GeolocationPositionErrorCode code) {
+ data->kind = 2;
+ data->error_code = to_underlying(code);
+ });
}
-// https://w3c.github.io/geolocation/#dfn-request-a-position
-void Geolocation::request_a_position(GC::Ref<WebIDL::CallbackType> success_callback,
- GC::Ptr<WebIDL::CallbackType> error_callback, PositionOptions const& options, Optional<WebIDL::UnsignedLong> watch_id)
+u64 web_geolocation_register_emulated_position_data_observer(HTML::Window* window, Geolocation* geolocation, u32 watch_id)
{
- // 1. Let watchIDs be geolocation's [[watchIDs]].
-
- // 2. Let document be the geolocation's relevant global object's associated Document.
- auto& document = window().associated_document();
-
- // 3. If document is not allowed to use the "geolocation" feature:
- if (!document.is_allowed_to_use_feature(DOM::PolicyControlledFeature::Geolocation)) {
- // 1. If watchId was passed, remove watchId from watchIDs.
- if (watch_id.has_value())
- remove_watch_id(watch_id.value());
-
- // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);
-
- // 3. Terminate this algorithm.
- return;
- }
-
- // 4. If geolocation's environment settings object is a non-secure context:
- if (is_non_secure_context(window().associated_document().relevant_settings_object())) {
- // 1. If watchId was passed, remove watchId from watchIDs.
- if (watch_id.has_value())
- remove_watch_id(watch_id.value());
-
- // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);
-
- // 3. Terminate this algorithm.
- return;
- }
-
- // 5. If document's visibility state is "hidden", wait for the following page visibility change steps to run:
- run_in_parallel_when_document_is_visible(document, GC::create_function(GC::Heap::the(), GC::captures(*this, watch_id, success_callback, error_callback, options), [](auto& self, auto& watch_id, auto& success_callback, auto& error_callback, auto& options) {
- // 1. Assert: document's visibility state is "visible".
- // 2. Continue to the next steps below.
- // AD-HOC: This is implemented by run_in_parallel_when_document_is_visible().
-
- // 6. Let descriptor be a new PermissionDescriptor whose name is "geolocation".
- auto descriptor = Web::Permissions::PermissionName::Geolocation;
-
- // 7. In parallel:
- // NB: The round trip to the UI process that asks the user for permission stands in for the parallel steps: the
- // request goes out as an async IPC, and the rest of the steps run on the main thread once it answers.
- {
- // 1. Set permission to request permission to use descriptor.
- auto& settings = self.window().associated_document().relevant_settings_object();
- PermissionsAPI::request_permission_with_user_prompt(descriptor, settings, GC::create_function(self.heap(), GC::captures(self, watch_id, success_callback, error_callback, options), [](auto& self, auto& watch_id, auto& success_callback, auto& error_callback, auto& options, PermissionsAPI::PermissionState permission) {
- // 2. If permission is "denied", then:
- if (permission == PermissionsAPI::PermissionState::Denied) {
- // 1. If watchId was passed, remove watchId from watchIDs.
- if (watch_id.has_value())
- self.remove_watch_id(watch_id.value());
-
- // 2. Call back with error passing errorCallback and PERMISSION_DENIED.
- self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);
-
- // 3. Terminate this algorithm.
- return;
- }
-
- // FIXME: 3. Wait to acquire a position passing successCallback, errorCallback, options, and watchId.
- self.acquire_a_position(success_callback, error_callback, options, watch_id);
-
- // 4. If watchId was not passed, terminate this algorithm.
- if (!watch_id.has_value())
- return;
-
- if (!self.m_watch_ids.contains(*watch_id))
- return;
-
- // 5. While watchIDs contains watchId:
- // AD-HOC: The spec expresses this as a loop; register callbacks for significant position changes and
- // re-enter request a position from those callbacks.
- auto watch_position_data = self.m_watch_position_data.get(*watch_id);
- if (!watch_position_data.has_value() || watch_position_data->emulated_position_data_observer_id.has_value())
- return;
-
- auto weak_document = GC::Weak<DOM::Document> { self.window().associated_document() };
- auto observer_id = self.window().page().register_emulated_position_data_observer(GC::create_function(self.heap(), GC::captures(self, *watch_id, weak_document), [](auto& self, auto& watch_id, auto& weak_document) {
- if (!self.m_watch_ids.contains(watch_id))
- return;
-
- auto document = weak_document.ptr();
- if (!document || !document->is_fully_active())
- return;
-
- if (self.m_pending_watch_position_request_ids.contains(watch_id))
- return;
-
- auto watch_position_data = self.m_watch_position_data.get(watch_id);
- if (!watch_position_data.has_value())
- return;
-
- // FIXME: If document is not fully active or visibility state is not "visible", wait for visibility.
- self.request_a_position(watch_position_data->success_callback, watch_position_data->error_callback, watch_position_data->options, watch_id);
- }));
- watch_position_data->emulated_position_data_observer_id = observer_id;
- }));
- }
+ return window->page().register_emulated_position_data_observer(GC::create_function(GC::Heap::the(), GC::captures(*geolocation, watch_id), [](auto& geolocation, auto& watch_id) {
+ web_rust_geolocation_emulated_position_data_changed(the_vm(), &geolocation, watch_id);
}));
}
-// https://w3c.github.io/geolocation/#dfn-acquire-a-position
-void Geolocation::acquire_a_position(GC::Ref<WebIDL::CallbackType> success_callback,
- GC::Ptr<WebIDL::CallbackType> error_callback, PositionOptions const& options, Optional<WebIDL::UnsignedLong> watch_id)
+void web_geolocation_unregister_emulated_position_data_observer(HTML::Window* window, u64 observer_id)
{
- // 1. If watchId was passed and this's [[watchIDs]] does not contain watchId, terminate this algorithm.
- if (watch_id.has_value() && !m_watch_ids.contains(watch_id.value()))
- return;
-
- // 2. Let acquisitionTime be a new EpochTimeStamp that represents now.
- HighResolutionTime::EpochTimeStamp const acquisition_time = AK::UnixDateTime::now().milliseconds_since_epoch();
-
- // 3. Let timeoutTime be the sum of acquisitionTime and options.timeout.
- [[maybe_unused]] HighResolutionTime::EpochTimeStamp const timeout_time = acquisition_time + options.timeout;
-
- // 4. Let cachedPosition be this's [[cachedPosition]].
- auto cached_position = m_cached_position;
-
- // 5. Create an implementation-specific timeout task that elapses at timeoutTime, during which it tries to acquire
- // the device's position by running the following steps:
- {
- // 1. Let permission be get the current permission state of "geolocation".
- // NB: This can run outside any script (when the user's answer arrives, e.g.), so the settings object is passed.
- auto permission = Web::PermissionsAPI::permission_state(Web::Permissions::PermissionName::Geolocation, window().associated_document().relevant_settings_object());
-
- // 2. If permission is "denied":
- if (permission == Bindings::PermissionState::Denied) {
- // 1. Stop timeout.
- // NB: No timeout is running yet because we start the timer immediately before requesting native position
- // data below.
-
- // 2. Do the user or system denied permission failure case step.
- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);
- return;
- }
-
- // 3. If permission is "granted":
- if (permission == Bindings::PermissionState::Granted) {
- // 1. Check if an emulated position should be used by running the following steps:
- {
- // 1. Let emulatedPositionData be get emulated position data passing this.
- auto emulated_position_data = get_emulated_position_data();
-
- // 2. If emulatedPositionData is not null:
- if (!emulated_position_data.has<Empty>()) {
- // 1. If emulatedPositionData is a GeolocationPositionError:
- if (emulated_position_data.has<GeolocationPositionError::ErrorCode>()) {
- // 1. Call back with error passing errorCallback and emulatedPositionData.
- // FIXME: We pass along the code instead of the entire error object. Spec issue:
- // https://github.com/w3c/geolocation/issues/186
- call_back_with_error(error_callback, emulated_position_data.get<GeolocationPositionError::ErrorCode>());
-
- // 2. Terminate this algorithm.
- return;
- }
-
- // 2. Let position be a new GeolocationPosition passing emulatedPositionData, acquisitionTime and
- // options.enableHighAccuracy.
- auto position = GeolocationPosition::create(
- emulated_position_data.get<GC::Ref<GeolocationCoordinates>>(),
- acquisition_time,
- options.enable_high_accuracy);
-
- // 3. Queue a task on the geolocation task source with a step that invokes successCallback with
- // « position » and "report".
- queue_success_callback(success_callback, position);
-
- // 4. Terminate this algorithm.
- return;
- }
- }
-
- // 2. Let position be null.
- // NB: position is created inside the async callback in step 6 below.
-
- // 3. If cachedPosition is not null, and options.maximumAge is greater than 0:
- if (cached_position && options.maximum_age > 0) {
- // 1. Let cacheTime be acquisitionTime minus the value of the options.maximumAge member.
- HighResolutionTime::EpochTimeStamp const cache_time = acquisition_time - options.maximum_age;
-
- // 2. If cachedPosition's timestamp's value is greater than cacheTime, and
- // cachedPosition.[[isHighAccuracy]] equals options.enableHighAccuracy:
- if (cached_position->timestamp() > cache_time
- && cached_position->is_high_accuracy() == options.enable_high_accuracy) {
- // 1. Queue a task on the geolocation task source with a step that invokes successCallback with
- // « cachedPosition » and "report".
- queue_success_callback(success_callback, *cached_position);
-
- // 2. Terminate this algorithm.
- return;
- }
- }
-
- // 4. Otherwise, if position is not cachedPosition, try to acquire position data from the underlying system,
- // optionally taking into consideration the value of options.enableHighAccuracy during acquisition.
- acquire_position_from_page(success_callback, error_callback, options, watch_id, acquisition_time);
- return;
- }
-
- // NB: While the permission is "prompt" (a one-time grant just ended, e.g.), neither step above applies, and the
- // timeout task elapses without a position.
- call_back_with_timeout_error(error_callback, options.timeout, watch_id);
- }
-}
-
-// A watch cleared, or a document left, before the timeout elapses hears nothing of it, as with a timeout that elapses
-// while a position is being acquired.
-void Geolocation::call_back_with_timeout_error(GC::Ptr<WebIDL::CallbackType> error_callback, WebIDL::UnsignedLong timeout, Optional<WebIDL::UnsignedLong> watch_id)
-{
- auto weak_document = GC::Weak<DOM::Document> { window().associated_document() };
- auto timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(min(timeout, NumericLimits<int>::max())), {});
- m_timeout_timers.append(timer);
- timer->on_timeout = GC::create_function(heap(), GC::captures(*this, timer, error_callback, watch_id, weak_document), [](auto& self, auto& timer, auto& error_callback, auto& watch_id, auto& weak_document) {
- self.m_timeout_timers.remove_first_matching([&](auto candidate) { return candidate == timer; });
- if (watch_id.has_value() && !self.m_watch_ids.contains(*watch_id))
- return;
- if (!weak_document || !weak_document->is_fully_active())
- return;
- self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);
- });
- timer->start();
+ window->page().unregister_emulated_position_data_observer(observer_id);
}
-void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> success_callback,
- GC::Ptr<WebIDL::CallbackType> error_callback, PositionOptions const& options,
- Optional<WebIDL::UnsignedLong> watch_id, HighResolutionTime::EpochTimeStamp acquisition_time)
+DOM::DocumentObserver* web_geolocation_observe_document_visibility(DOM::Document* document, GC::Cell* wait)
{
- auto& document = window().associated_document();
- auto& page = document.page();
- auto request_state = make_ref_counted<GeolocationRequestState>();
- auto weak_document = GC::Weak<DOM::Document> { document };
- auto weak_page = GC::Weak<Page> { page };
- auto timeout_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(min(options.timeout, NumericLimits<int>::max())), {});
- m_timeout_timers.append(timeout_timer);
-
- auto stop_timeout_timer = GC::create_function(heap(), GC::captures(*this, timeout_timer, request_state), [](auto& self, auto& timeout_timer, auto& request_state) {
- if (request_state->timeout_stopped)
- return;
- request_state->timeout_stopped = true;
- timeout_timer->stop();
- timeout_timer->on_timeout = nullptr;
- self.m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });
- });
-
- auto position_callback = GC::create_function(heap(),
- GC::captures(*this, success_callback, error_callback, options, watch_id, acquisition_time, request_state, weak_document, stop_timeout_timer),
- [](auto& self, auto& success_callback, auto& error_callback, auto& options, auto& watch_id, auto& acquisition_time, auto& request_state, auto& weak_document, auto& stop_timeout_timer, Page::GeolocationPositionResult result) {
- if (request_state->completed)
- return;
-
- if (watch_id.has_value() && !self.m_watch_ids.contains(*watch_id)) {
- // NB: The position response arrived after the watch was cleared; stop the timeout before ignoring it.
- stop_timeout_timer->function()();
- return;
- }
- if (!watch_id.has_value())
- request_state->completed = true;
-
- auto document = weak_document.ptr();
- if (!document || !document->is_fully_active()) {
- // NB: The position response is no longer observable; stop the timeout before ignoring it.
- stop_timeout_timer->function()();
- return;
- }
-
- // 5. If the timeout elapses during acquisition, or acquiring the device's position results in failure:
- if (result.has<GeolocationPositionError::ErrorCode>()) {
- auto error_code = result.get<GeolocationPositionError::ErrorCode>();
-
- // 1. Stop the timeout.
- stop_timeout_timer->function()();
-
- if (watch_id.has_value() && error_code == GeolocationPositionError::ErrorCode::PermissionDenied) {
- request_state->completed = true;
- self.m_pending_watch_position_request_ids.remove(*watch_id);
- }
-
- // 2. Go to dealing with failures.
- self.call_back_with_error(error_callback, error_code);
-
- // 3. Terminate this algorithm.
- return;
- }
-
- // 6. If acquiring the position data from the system succeeds:
- // 6.1. Let positionData be a map with the following name/value pairs based on the acquired position data:
- // * latitude:
- // A double that represents the latitude coordinates on the Earth's surface in degrees, using the
- // [WGS84] coordinate system. Latitude measures how far north or south a point is from the Equator.
- // * longitude:
- // A double that represents the longitude coordinates on the Earth's surface in degrees, using the
- // [WGS84] coordinate system. Longitude measures how far east or west a point is from the Prime
- // Meridian.
- // * altitude:
- // A double? that represents the altitude in meters above the [WGS84] ellipsoid, or null if not
- // available. Altitude measures the height above sea level.
- // * accuracy:
- // A non-negative double that represents the accuracy value indicating the 95% confidence level in
- // meters. Accuracy measures how close the measured coordinates are to the true position.
- // * altitudeAccuracy:
- // A non-negative double? that represents the altitude accuracy, or null if not available,
- // indicating the 95% confidence level in meters. Altitude accuracy measures how close the measured
- // altitude is to the true altitude.
- // * speed:
- // A non-negative double? that represents the speed in meters per second, or null if not available.
- // Speed measures how fast the device is moving.
- // * heading:
- // A double? that represents the heading in degrees, or null if not available or the device is
- // stationary. Heading measures the direction in which the device is moving relative to true north.
- auto position_data = GeolocationCoordinates::create(result.get<CoordinatesData>());
-
- // 6.2. Set position to a new GeolocationPosition passing positionData, acquisitionTime and
- // options.enableHighAccuracy.
- auto position = GeolocationPosition::create(position_data, acquisition_time, options.enable_high_accuracy);
-
- // 6.3. Set this's [[cachedPosition]] to position.
- self.m_cached_position = *position;
-
- // 7. Stop the timeout.
- stop_timeout_timer->function()();
-
- // 8. Queue a task on the geolocation task source with a step that invokes successCallback with « position »
- // and "report".
- queue_success_callback(success_callback, position);
- });
-
- request_state->request_id = page.request_geolocation_position(document.id(), position_callback, watch_id.has_value() ? Page::GeolocationRequestType::Watch : Page::GeolocationRequestType::OneShot);
- if (watch_id.has_value())
- m_pending_watch_position_request_ids.set(*watch_id, request_state->request_id);
-
- timeout_timer->on_timeout = GC::create_function(heap(), GC::captures(*this, error_callback, watch_id, request_state, weak_document, weak_page, stop_timeout_timer), [](auto& self, auto& error_callback, auto& watch_id, auto& request_state, auto& weak_document, auto& weak_page, auto& stop_timeout_timer) {
- if (request_state->completed)
- return;
- request_state->completed = true;
- stop_timeout_timer->function()();
- if (watch_id.has_value() && !self.m_pending_watch_position_request_ids.remove(*watch_id))
- return;
- if (auto page = weak_page.ptr())
- page->cancel_geolocation_position_request(request_state->request_id);
- auto document = weak_document.ptr();
- if (!document || !document->is_fully_active())
- return;
- self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);
- });
- timeout_timer->start();
-}
-
-// https://w3c.github.io/geolocation/#dfn-call-back-with-error
-void Geolocation::call_back_with_error(GC::Ptr<WebIDL::CallbackType> callback, GeolocationPositionError::ErrorCode code) const
-{
- // 1. If callback is null, return.
- if (!callback)
- return;
-
- // 2. Let error be a newly created GeolocationPositionError instance whose code attribute is initialized to code.
- auto error = GeolocationPositionError::create(code);
-
- // 3. Queue a task on the geolocation task source with a step that invokes callback with « error » and "report".
- queue_error_callback(*callback, error);
+ auto observer = DOM::DocumentObserver::create(*document);
+ observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *wait }), [](auto& wait, HTML::VisibilityState state) {
+ web_rust_geolocation_document_visibility_changed(the_vm(), wait.ptr(), state == HTML::VisibilityState::Visible);
+ }));
+ return observer.ptr();
}
-void Geolocation::run_in_parallel_when_document_is_visible(DOM::Document& document, GC::Ref<GC::Function<void()>> callback)
+void web_geolocation_stop_observing_document_visibility(DOM::DocumentObserver* observer)
{
- // Run callback in parallel if the document is already visible.
- if (document.visibility_state() == HTML::VisibilityState::Visible) {
- auto callback_with_context = GC::create_function(GC::Heap::the(), GC::captures(*this, callback), [](auto& self, auto& callback) {
- HTML::TemporaryExecutionContext execution_context { self.window().relevant_settings_object() };
- callback->function()();
- });
- Platform::EventLoopPlugin::the().deferred_invoke(callback_with_context);
- return;
- }
-
- // Run the callback as soon as the document becomes visible. If we time out, do not run the callback at all.
- auto document_observer = DOM::DocumentObserver::create(document);
- auto timeout_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(VISIBILITY_STATE_TIMEOUT_MS), {});
- m_timeout_timers.append(timeout_timer);
- auto clear_observer_and_timer = GC::create_function(GC::Heap::the(), GC::captures(*this, document_observer, timeout_timer), [](auto& self, auto& document_observer, auto& timeout_timer) {
- document_observer->set_document_visibility_state_observer({});
- timeout_timer->stop();
- self.m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });
- });
- timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), GC::captures(clear_observer_and_timer), [](auto& clear_observer_and_timer) {
- dbgln("Geolocation: Waiting for visibility state update timed out");
- clear_observer_and_timer->function()();
- });
-
- document_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(*this, clear_observer_and_timer, callback), [](auto& self, auto& clear_observer_and_timer, auto& callback, HTML::VisibilityState state) {
- if (state == HTML::VisibilityState::Visible) {
- clear_observer_and_timer->function()();
- HTML::TemporaryExecutionContext execution_context { self.window().relevant_settings_object() };
- callback->function()();
- }
- }));
- timeout_timer->start();
+ observer->set_document_visibility_state_observer({});
}
}
diff --git a/Libraries/LibWeb/Geolocation/Geolocation.h b/Libraries/LibWeb/Geolocation/Geolocation.h
index 5d39f42d144..aec75edaa57 100644
--- a/Libraries/LibWeb/Geolocation/Geolocation.h
+++ b/Libraries/LibWeb/Geolocation/Geolocation.h
@@ -6,74 +6,24 @@
#pragma once
+#include <AK/Variant.h>
#include <LibWeb/Bindings/Geolocation.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/Geolocation/GeolocationPositionError.h>
-#include <LibWeb/HighResolutionTime/EpochTimeStamp.h>
-#include <LibWeb/Platform/Timer.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::Bindings {
-
-struct PositionOptions;
-
-}
+#include <LibWeb/Geolocation/GeolocationCoordinates.h>
+#include <LibWebCommon/Geolocation/GeolocationPositionErrorCode.h>
namespace Web::Geolocation {
// https://w3c.github.io/geolocation/#dfn-emulated-position-data
-using EmulatedPositionData = Variant<Empty, GC::Ref<GeolocationCoordinates>, GeolocationPositionError::ErrorCode>;
-
-using PositionOptions = Bindings::PositionOptions;
-
-struct WatchPositionData {
- GC::Ref<WebIDL::CallbackType> success_callback;
- GC::Ptr<WebIDL::CallbackType> error_callback;
- PositionOptions options;
- Optional<u64> emulated_position_data_observer_id {};
-};
+using EmulatedPositionData = Variant<Empty, GC::Ref<GeolocationCoordinates>, GeolocationPositionErrorCode>;
// https://w3c.github.io/geolocation/#geolocation_interface
-class Geolocation : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Geolocation, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Geolocation);
+class Geolocation : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Geolocation, geolocation)
public:
[[nodiscard]] static GC::Ref<Geolocation> create(HTML::Window&);
-
- void get_current_position(GC::Ref<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>, PositionOptions const&);
- WebIDL::Long watch_position(GC::Ref<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>, PositionOptions const&);
- void clear_watch(WebIDL::Long);
-
-private:
- explicit Geolocation(HTML::Window&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- HTML::Window& window() const { return m_window; }
-
- void acquire_a_position(GC::Ref<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>, PositionOptions const&, Optional<WebIDL::UnsignedLong>);
- void call_back_with_timeout_error(GC::Ptr<WebIDL::CallbackType> error_callback, WebIDL::UnsignedLong timeout, Optional<WebIDL::UnsignedLong> watch_id);
- void acquire_position_from_page(GC::Ref<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>, PositionOptions const&, Optional<WebIDL::UnsignedLong>, HighResolutionTime::EpochTimeStamp);
- void call_back_with_error(GC::Ptr<WebIDL::CallbackType>, GeolocationPositionError::ErrorCode) const;
- EmulatedPositionData get_emulated_position_data() const;
- void remove_watch_id(WebIDL::UnsignedLong);
- void request_a_position(GC::Ref<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>, PositionOptions const&, Optional<WebIDL::UnsignedLong>);
- void run_in_parallel_when_document_is_visible(DOM::Document&, GC::Ref<GC::Function<void()>>);
- void unregister_watch_position_observer(WebIDL::UnsignedLong);
-
- // https://w3c.github.io/geolocation/#dfn-watchids
- HashTable<WebIDL::UnsignedLong> m_watch_ids;
- HashMap<WebIDL::UnsignedLong, WatchPositionData> m_watch_position_data;
- HashMap<WebIDL::UnsignedLong, u64> m_pending_watch_position_request_ids;
-
- GC::Ref<HTML::Window> m_window;
-
- // https://w3c.github.io/geolocation/#dfn-cachedposition
- GC::Ptr<GeolocationPosition> m_cached_position;
-
- Vector<GC::Ref<Platform::Timer>> m_timeout_timers;
};
}
diff --git a/Libraries/LibWeb/Geolocation/Geolocation.idl b/Libraries/LibWeb/Geolocation/Geolocation.idl
index 4716d9dd83c..90a2eb9e656 100644
--- a/Libraries/LibWeb/Geolocation/Geolocation.idl
+++ b/Libraries/LibWeb/Geolocation/Geolocation.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/geolocation/#geolocation_interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface Geolocation {
undefined getCurrentPosition (
PositionCallback successCallback,
@@ -17,6 +17,7 @@ interface Geolocation {
};
// https://w3c.github.io/geolocation/#dom-positionoptions
+[ImplementedIn=Rust]
dictionary PositionOptions {
boolean enableHighAccuracy = false;
[Clamp] unsigned long timeout = 0xFFFFFFFF;
diff --git a/Libraries/LibWeb/Geolocation/GeolocationCoordinates.cpp b/Libraries/LibWeb/Geolocation/GeolocationCoordinates.cpp
index 713e0e6f5b0..0af421d946e 100644
--- a/Libraries/LibWeb/Geolocation/GeolocationCoordinates.cpp
+++ b/Libraries/LibWeb/Geolocation/GeolocationCoordinates.cpp
@@ -10,32 +10,14 @@
namespace Web::Geolocation {
-namespace {
-
-struct CoordinatesDataAbi {
- double accuracy;
- double latitude;
- double longitude;
- bool has_altitude;
- double altitude;
- bool has_altitude_accuracy;
- double altitude_accuracy;
- bool has_heading;
- double heading;
- bool has_speed;
- double speed;
-};
-
-}
-
extern "C" {
// Defined in Bindings/Rust/src/geolocation/geolocation_coordinates.rs.
GeolocationCoordinates* web_rust_geolocation_create_geolocation_coordinates(JSVM*, CoordinatesDataAbi const&);
}
-GC::Ref<GeolocationCoordinates> GeolocationCoordinates::create(CoordinatesData const& data)
+CoordinatesDataAbi coordinates_data_to_abi(CoordinatesData const& data)
{
- CoordinatesDataAbi abi {
+ return {
.accuracy = data.accuracy,
.latitude = data.latitude,
.longitude = data.longitude,
@@ -48,7 +30,11 @@ GC::Ref<GeolocationCoordinates> GeolocationCoordinates::create(CoordinatesData c
.has_speed = data.speed.has_value(),
.speed = data.speed.value_or(0),
};
- return *web_rust_geolocation_create_geolocation_coordinates(JS::HostABI::vm_to_abi(JS::VM::the()), abi);
+}
+
+GC::Ref<GeolocationCoordinates> GeolocationCoordinates::create(CoordinatesData const& data)
+{
+ return *web_rust_geolocation_create_geolocation_coordinates(JS::HostABI::vm_to_abi(JS::VM::the()), coordinates_data_to_abi(data));
}
}
diff --git a/Libraries/LibWeb/Geolocation/GeolocationCoordinates.h b/Libraries/LibWeb/Geolocation/GeolocationCoordinates.h
index a91aa8e270d..b34b1f842c7 100644
--- a/Libraries/LibWeb/Geolocation/GeolocationCoordinates.h
+++ b/Libraries/LibWeb/Geolocation/GeolocationCoordinates.h
@@ -22,6 +22,22 @@ struct CoordinatesData {
Optional<double> speed {};
};
+struct CoordinatesDataAbi {
+ double accuracy;
+ double latitude;
+ double longitude;
+ bool has_altitude;
+ double altitude;
+ bool has_altitude_accuracy;
+ double altitude_accuracy;
+ bool has_heading;
+ double heading;
+ bool has_speed;
+ double speed;
+};
+
+CoordinatesDataAbi coordinates_data_to_abi(CoordinatesData const&);
+
// https://w3c.github.io/geolocation/#coordinates_interface
class GeolocationCoordinates : public Bindings::RustInterfaceCell {
WEB_RUST_INTERFACE(GeolocationCoordinates, geolocation_coordinates)
diff --git a/Libraries/LibWeb/Geolocation/GeolocationPosition.cpp b/Libraries/LibWeb/Geolocation/GeolocationPosition.cpp
deleted file mode 100644
index 3464dfb74eb..00000000000
--- a/Libraries/LibWeb/Geolocation/GeolocationPosition.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Geolocation/GeolocationPosition.h>
-
-namespace Web::Geolocation {
-
-extern "C" {
-// Defined in Bindings/Rust/src/geolocation/geolocation_position.rs.
-GeolocationPosition* web_rust_geolocation_create_geolocation_position(JSVM*, GeolocationCoordinates*, u64 timestamp, bool is_high_accuracy);
-u64 web_rust_geolocation_geolocation_position_timestamp(GeolocationPosition*);
-bool web_rust_geolocation_geolocation_position_is_high_accuracy(GeolocationPosition*);
-}
-
-GC::Ref<GeolocationPosition> GeolocationPosition::create(GC::Ref<GeolocationCoordinates> coords, HighResolutionTime::EpochTimeStamp timestamp, bool is_high_accuracy)
-{
- return *web_rust_geolocation_create_geolocation_position(JS::HostABI::vm_to_abi(JS::VM::the()), coords.ptr(), timestamp, is_high_accuracy);
-}
-
-HighResolutionTime::EpochTimeStamp GeolocationPosition::timestamp() const
-{
- return web_rust_geolocation_geolocation_position_timestamp(const_cast<GeolocationPosition*>(this));
-}
-
-bool GeolocationPosition::is_high_accuracy() const
-{
- return web_rust_geolocation_geolocation_position_is_high_accuracy(const_cast<GeolocationPosition*>(this));
-}
-
-}
diff --git a/Libraries/LibWeb/Geolocation/GeolocationPosition.h b/Libraries/LibWeb/Geolocation/GeolocationPosition.h
deleted file mode 100644
index 421f3c56e1c..00000000000
--- a/Libraries/LibWeb/Geolocation/GeolocationPosition.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/GeolocationPosition.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Geolocation/GeolocationCoordinates.h>
-#include <LibWeb/HighResolutionTime/EpochTimeStamp.h>
-
-namespace Web::Geolocation {
-
-// https://w3c.github.io/geolocation/#dom-geolocationposition
-class GeolocationPosition : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(GeolocationPosition, geolocation_position)
-
-public:
- [[nodiscard]] static GC::Ref<GeolocationPosition> create(GC::Ref<GeolocationCoordinates>, HighResolutionTime::EpochTimeStamp, bool is_high_accuracy);
-
- HighResolutionTime::EpochTimeStamp timestamp() const;
- bool is_high_accuracy() const;
-};
-
-}
diff --git a/Libraries/LibWeb/Geolocation/GeolocationPositionError.cpp b/Libraries/LibWeb/Geolocation/GeolocationPositionError.cpp
deleted file mode 100644
index aeceaf18d18..00000000000
--- a/Libraries/LibWeb/Geolocation/GeolocationPositionError.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Geolocation/GeolocationPositionError.h>
-
-namespace Web::Geolocation {
-
-extern "C" {
-// Defined in Bindings/Rust/src/geolocation/geolocation_position_error.rs.
-GeolocationPositionError* web_rust_geolocation_create_geolocation_position_error(JSVM*, u16 code);
-}
-
-GC::Ref<GeolocationPositionError> GeolocationPositionError::create(ErrorCode code)
-{
- return *web_rust_geolocation_create_geolocation_position_error(JS::HostABI::vm_to_abi(JS::VM::the()), to_underlying(code));
-}
-
-}
diff --git a/Libraries/LibWeb/Geolocation/GeolocationPositionError.h b/Libraries/LibWeb/Geolocation/GeolocationPositionError.h
deleted file mode 100644
index c6448d32410..00000000000
--- a/Libraries/LibWeb/Geolocation/GeolocationPositionError.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/GeolocationPositionError.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWebCommon/Geolocation/GeolocationPositionErrorCode.h>
-
-namespace Web::Geolocation {
-
-// https://w3c.github.io/geolocation/#dom-geolocationpositionerror
-class GeolocationPositionError : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(GeolocationPositionError, geolocation_position_error)
-
-public:
- using ErrorCode = GeolocationPositionErrorCode;
-
- [[nodiscard]] static GC::Ref<GeolocationPositionError> create(ErrorCode);
-};
-
-}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 24f40f7c033..79dbce56096 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2543,7 +2543,7 @@ void Internals::set_geolocation_emulated_position(double latitude, double longit
// Every position request then fails with POSITION_UNAVAILABLE, as it does when no position can be found.
void Internals::set_geolocation_emulated_position_unavailable()
{
- page().set_emulated_position_data(Geolocation::GeolocationPositionError::ErrorCode::PositionUnavailable);
+ page().set_emulated_position_data(Geolocation::GeolocationPositionErrorCode::PositionUnavailable);
}
WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> Internals::request_permission(Utf16String const& name)
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 024a01e07be..68fece5a1c8 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -1859,8 +1859,8 @@ void Page::receive_geolocation_position(u64 request_id, GeolocationPositionResul
if (request->type == GeolocationRequestType::Watch) {
auto callback = request->callback;
- if (result.has<Geolocation::GeolocationPositionError::ErrorCode>()
- && result.get<Geolocation::GeolocationPositionError::ErrorCode>() == Geolocation::GeolocationPositionError::ErrorCode::PermissionDenied)
+ if (result.has<Geolocation::GeolocationPositionErrorCode>()
+ && result.get<Geolocation::GeolocationPositionErrorCode>() == Geolocation::GeolocationPositionErrorCode::PermissionDenied)
m_pending_geolocation_requests.remove(request_id);
callback->function()(result);
return;
@@ -1874,8 +1874,8 @@ void Page::receive_geolocation_position(u64 request_id, GeolocationPositionResul
// A position, or a failure to get one, is the same answer for every document on the page, so the queued requests
// complete with it too. A denial is the answer for the requesting document alone, so the others stay queued, and
// the next of them is sent.
- auto denied = result.has<Geolocation::GeolocationPositionError::ErrorCode>()
- && result.get<Geolocation::GeolocationPositionError::ErrorCode>() == Geolocation::GeolocationPositionError::ErrorCode::PermissionDenied;
+ auto denied = result.has<Geolocation::GeolocationPositionErrorCode>()
+ && result.get<Geolocation::GeolocationPositionErrorCode>() == Geolocation::GeolocationPositionErrorCode::PermissionDenied;
GC::RootVector<GeolocationPositionCallback> callbacks;
Vector<u64> completed_request_ids;
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index db72ebb5d8f..40901a722fb 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -48,7 +48,6 @@
#include <LibWeb/Forward.h>
#include <LibWeb/Geolocation/Geolocation.h>
#include <LibWeb/Geolocation/GeolocationCoordinates.h>
-#include <LibWeb/Geolocation/GeolocationPositionError.h>
#include <LibWeb/HTML/DedicatedWorkerThreadLink.h>
#include <LibWeb/HTML/Focus.h>
#include <LibWeb/HTML/NavigationSourceSnapshot.h>
@@ -372,7 +371,7 @@ public:
// For tests: Calls the callback when the next writing suggestion request goes to the UI process.
void when_writing_suggestion_requested(GC::Ref<GC::Function<void()>>);
- using GeolocationPositionResult = Variant<Geolocation::CoordinatesData, Geolocation::GeolocationPositionError::ErrorCode>;
+ using GeolocationPositionResult = Variant<Geolocation::CoordinatesData, Geolocation::GeolocationPositionErrorCode>;
using GeolocationPositionCallback = GC::Ref<GC::Function<void(GeolocationPositionResult)>>;
enum class GeolocationRequestType : u8 {
OneShot,
@@ -662,7 +661,7 @@ private:
// AD-HOC: Denied until the UI process sends the browser-wide setting, so a request cannot observe the test
// position in the short window before that arrives.
- Geolocation::EmulatedPositionData m_emulated_position_data { Geolocation::GeolocationPositionError::ErrorCode::PermissionDenied };
+ Geolocation::EmulatedPositionData m_emulated_position_data { Geolocation::GeolocationPositionErrorCode::PermissionDenied };
HashMap<u64, GC::Ref<GC::Function<void()>>> m_emulated_position_data_observers;
u64 m_next_emulated_position_data_observer_id { 0 };
diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
index 5a037a7d167..53a587a77d3 100644
--- a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp
@@ -159,6 +159,7 @@ PermissionState permission_state(Web::Permissions::PermissionName name, Optional
extern "C" {
Permissions* web_rust_permissions_api_create_permissions(JSVM*);
u8 web_permissions_api_permission_state(HTML::EnvironmentSettingsObject*, u8 name);
+void web_permissions_api_request_permission_to_use(HTML::EnvironmentSettingsObject*, u8 name, GC::Cell* cell, void (*steps)(JSVM*, void*, u8));
}
static_assert(to_underlying(Web::Permissions::PermissionName::Geolocation) == 0);
@@ -178,4 +179,11 @@ u8 web_permissions_api_permission_state(HTML::EnvironmentSettingsObject* setting
return to_underlying(permission_state(static_cast<Web::Permissions::PermissionName>(name), *settings));
}
+void web_permissions_api_request_permission_to_use(HTML::EnvironmentSettingsObject* settings, u8 name, GC::Cell* cell, void (*steps)(JSVM*, void*, u8))
+{
+ request_permission_with_user_prompt(static_cast<Web::Permissions::PermissionName>(name), *settings, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *cell }, steps), [](auto& cell, auto& steps, PermissionState state) {
+ steps(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr(), to_underlying(state));
+ }));
+}
+
}
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 5973605cb1a..8d9e4b5c847 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -1143,7 +1143,8 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]
to_cpp_interface_in_union, to_dom_string,
to_dom_string_treating_null_as_empty, to_double, to_float, to_long, to_long_enforcing_range, to_long_long,
to_long_long_clamping, to_long_long_enforcing_range, to_object, to_promise, to_typed_array,
- to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range,
+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_clamping,
+ to_unsigned_long_enforcing_range,
to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,
};
use crate::bindings::interface::{
@@ -2557,7 +2558,8 @@ pub(crate) mod definitions {
to_byte_string, to_cpp_interface,
to_dom_string, to_dom_string_treating_null_as_empty, to_double, to_enumeration_value, to_float, to_long,
to_long_enforcing_range, to_long_long, to_long_long_enforcing_range, to_object, to_typed_array,
- to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_enforcing_range,
+ to_unrestricted_double, to_unrestricted_float, to_unsigned_long, to_unsigned_long_clamping,
+ to_unsigned_long_enforcing_range,
to_unsigned_long_long, to_unsigned_long_long_enforcing_range, to_usv_string,
};
use crate::bindings::interface::{
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index c416ac0ba48..641471657be 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -43,7 +43,6 @@
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Geolocation/GeolocationCoordinates.h>
-#include <LibWeb/Geolocation/GeolocationPositionError.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/LocalNavigable.h>
@@ -69,6 +68,7 @@
#include <LibWeb/WebDriver/InputState.h>
#include <LibWeb/WebDriver/UserPrompt.h>
#include <LibWeb/WebIDL/Promise.h>
+#include <LibWebCommon/Geolocation/GeolocationPositionErrorCode.h>
#include <LibWebCommon/HTML/NavigationPopulationRequest.h>
#include <LibWebCommon/WebDriver/Input.h>
#include <LibWebCommon/WebView/Debugger.h>
@@ -91,9 +91,9 @@ static constexpr size_t s_max_download_data_ipc_chunk_size = 16 * MiB;
GC_DEFINE_ALLOCATOR(PageClient);
-static Web::Geolocation::GeolocationPositionError::ErrorCode geolocation_position_error_code_from_ipc(u16 error_code)
+static Web::Geolocation::GeolocationPositionErrorCode geolocation_position_error_code_from_ipc(u16 error_code)
{
- using ErrorCode = Web::Geolocation::GeolocationPositionError::ErrorCode;
+ using ErrorCode = Web::Geolocation::GeolocationPositionErrorCode;
switch (error_code) {
case to_underlying(ErrorCode::PermissionDenied):
@@ -1346,7 +1346,7 @@ void PageClient::geolocation_position_response(u64 request_id, WebView::Geolocat
else if (auto coordinates = geolocation_coordinates_from_ipc(position); coordinates.has_value())
page().receive_geolocation_position(request_id, *coordinates);
else
- page().receive_geolocation_position(request_id, Web::Geolocation::GeolocationPositionError::ErrorCode::PositionUnavailable);
+ page().receive_geolocation_position(request_id, Web::Geolocation::GeolocationPositionErrorCode::PositionUnavailable);
}
void PageClient::page_did_request_geolocation_position(u64 request_id, Web::HTML::CrossProcessId requesting_document_id)