Skip to main content

servo/
geolocation_delegate.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use embedder_traits::{
6    GeolocationError, GeolocationPositionData, GeolocationRequestOptions, GeolocationResult,
7    GeolocationWatchId,
8};
9use servo_base::generic_channel::GenericCallback;
10use servo_config::pref;
11
12use crate::WebView;
13#[cfg(all(feature = "geolocation", target_os = "linux", not(target_env = "ohos")))]
14use crate::geoclue::Geoclue;
15
16/// A request for a single geolocation fix, corresponding to one call to
17/// navigator.geolocation.getCurrentPosition()
18pub struct PositionRequest {
19    result_sender: GenericCallback<GeolocationResult>,
20    options: GeolocationRequestOptions,
21    response_sent: bool,
22}
23
24impl PositionRequest {
25    pub(crate) fn new(
26        result_sender: GenericCallback<GeolocationResult>,
27        options: GeolocationRequestOptions,
28    ) -> Self {
29        Self {
30            result_sender,
31            options,
32            response_sent: false,
33        }
34    }
35
36    /// Hints about how the position should be acquired.
37    pub fn options(&self) -> &GeolocationRequestOptions {
38        &self.options
39    }
40
41    /// Report the acquired position.
42    pub fn success(mut self, position: GeolocationPositionData) {
43        let _ = self.result_sender.send(Ok(position));
44        self.response_sent = true;
45    }
46
47    /// Report that the position could not be acquired.
48    pub fn failure(mut self, error: GeolocationError) {
49        let _ = self.result_sender.send(Err(error));
50        self.response_sent = true;
51    }
52}
53
54impl Drop for PositionRequest {
55    fn drop(&mut self) {
56        if !self.response_sent {
57            let _ = self
58                .result_sender
59                .send(Err(GeolocationError::position_unavailable(
60                    "No response sent for request.",
61                )));
62        }
63    }
64}
65
66/// An ongoing subscription to position updates, corresponding to one call to
67/// navigator.geolocation.watchPosition()
68pub struct PositionWatch {
69    id: GeolocationWatchId,
70    result_sender: GenericCallback<GeolocationResult>,
71    options: GeolocationRequestOptions,
72}
73
74impl PositionWatch {
75    pub(crate) fn new(
76        id: GeolocationWatchId,
77        result_sender: GenericCallback<GeolocationResult>,
78        options: GeolocationRequestOptions,
79    ) -> Self {
80        Self {
81            id,
82            result_sender,
83            options,
84        }
85    }
86
87    /// The identifier used to stop this watch.
88    pub fn id(&self) -> GeolocationWatchId {
89        self.id.clone()
90    }
91
92    /// Hints about how positions should be acquired.
93    pub fn options(&self) -> &GeolocationRequestOptions {
94        &self.options
95    }
96
97    /// Deliver a new position to script. May be called any number of times.
98    pub fn update(&self, position: GeolocationPositionData) {
99        let _ = self.result_sender.send(Ok(position));
100    }
101
102    /// Report that a position could not be acquired. This does not end the watch: script keeps
103    /// listening, and the embedder may still call PositionWatch::update() later.
104    pub fn error(&self, error: GeolocationError) {
105        let _ = self.result_sender.send(Err(error));
106    }
107}
108
109/// A delegate responsible for acquiring the device's geographic position.
110pub trait GeolocationDelegate {
111    /// A request for a single position fix.
112    fn request_position(&self, _webview: WebView, request: PositionRequest) {
113        match default_position_response() {
114            Ok(position) => request.success(position),
115            Err(error) => request.failure(error),
116        }
117    }
118
119    /// A request to start delivering continuous position updates.
120    fn start_watch(&self, _webview: WebView, watch: PositionWatch) {
121        match default_position_response() {
122            Ok(position) => watch.update(position),
123            Err(error) => watch.error(error),
124        }
125    }
126
127    /// A request to stop delivering updates for a watch previously passed to
128    /// GeolocationDelegate::start_watch(), and to drop the corresponding PositionWatch.
129    fn stop_watch(&self, _webview: WebView, _id: &GeolocationWatchId) {}
130}
131
132/// The position described by the `dom_geolocation_test_position_*` preferences, or an error if
133/// they are not set.
134fn default_position_response() -> GeolocationResult {
135    if !pref!(dom_geolocation_test_position_enabled) {
136        return Err(GeolocationError::position_unavailable(
137            "No geolocation backend is available.",
138        ));
139    }
140
141    Ok(GeolocationPositionData {
142        accuracy: pref!(dom_geolocation_test_accuracy),
143        latitude: pref!(dom_geolocation_test_latitude),
144        longitude: pref!(dom_geolocation_test_longitude),
145        altitude: None,
146        altitude_accuracy: None,
147        heading: Some(pref!(dom_geolocation_test_heading)),
148        speed: Some(pref!(dom_geolocation_test_speed)),
149    })
150}
151
152/// The delegate installed when the embedder does not supply one. It uses the platform's location
153/// service when Servo has a backend for it, and otherwise reports that no position is available.
154#[derive(Default)]
155pub(crate) struct DefaultGeolocationDelegate {}
156
157#[cfg(all(feature = "geolocation", target_os = "linux", not(target_env = "ohos")))]
158impl DefaultGeolocationDelegate {
159    /// The system backend, or `None` if it is unavailable or the testing preferences are standing
160    /// in for one.
161    fn backend(&self) -> Option<&Geoclue> {
162        if pref!(dom_geolocation_test_position_enabled) {
163            return None;
164        }
165
166        Geoclue::singleton()
167    }
168}
169
170impl GeolocationDelegate for DefaultGeolocationDelegate {
171    fn request_position(&self, _webview: WebView, request: PositionRequest) {
172        #[cfg(all(feature = "geolocation", target_os = "linux", not(target_env = "ohos")))]
173        if let Some(geoclue) = self.backend() {
174            return geoclue.request_position(request);
175        }
176        match default_position_response() {
177            Ok(position) => request.success(position),
178            Err(error) => request.failure(error),
179        }
180    }
181
182    fn start_watch(&self, _webview: WebView, watch: PositionWatch) {
183        #[cfg(all(feature = "geolocation", target_os = "linux", not(target_env = "ohos")))]
184        if let Some(geoclue) = self.backend() {
185            return geoclue.start_watch(watch);
186        }
187        match default_position_response() {
188            Ok(position) => watch.update(position),
189            Err(error) => watch.error(error),
190        }
191    }
192
193    fn stop_watch(&self, _webview: WebView, _id: &GeolocationWatchId) {
194        #[cfg(all(feature = "geolocation", target_os = "linux", not(target_env = "ohos")))]
195        if let Some(geoclue) = self.backend() {
196            geoclue.stop_watch(_id);
197        }
198    }
199}