1use std::collections::HashMap;
17
18use embedder_traits::{GeolocationError, GeolocationPositionData, GeolocationWatchId};
19use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
20use futures::{FutureExt, StreamExt, select};
21use log::{debug, error};
22use net::async_runtime;
23use servo_config::pref;
24use zbus::proxy::CacheProperties;
25use zbus::zvariant::OwnedObjectPath;
26use zbus::{Connection, proxy};
27
28use crate::geolocation_delegate::{PositionRequest, PositionWatch};
29
30#[derive(Clone, Copy, PartialEq)]
32#[repr(u32)]
33enum AccuracyLevel {
34 City = 4,
35 Exact = 8,
36}
37
38const MINIMUM_PLAUSIBLE_ALTITUDE: f64 = -500.0;
41
42#[proxy(
43 interface = "org.freedesktop.GeoClue2.Manager",
44 default_service = "org.freedesktop.GeoClue2",
45 default_path = "/org/freedesktop/GeoClue2/Manager"
46)]
47trait Manager {
48 fn get_client(&self) -> zbus::Result<OwnedObjectPath>;
49}
50
51#[proxy(
52 interface = "org.freedesktop.GeoClue2.Client",
53 default_service = "org.freedesktop.GeoClue2",
54 assume_defaults = false
55)]
56trait Client {
57 fn start(&self) -> zbus::Result<()>;
58 fn stop(&self) -> zbus::Result<()>;
59
60 #[zbus(property)]
62 fn set_desktop_id(&self, id: &str) -> zbus::Result<()>;
63
64 #[zbus(property)]
65 fn set_requested_accuracy_level(&self, level: u32) -> zbus::Result<()>;
66
67 #[zbus(property)]
69 fn location(&self) -> zbus::Result<OwnedObjectPath>;
70
71 #[zbus(signal)]
72 fn location_updated(
73 &self,
74 previous: OwnedObjectPath,
75 current: OwnedObjectPath,
76 ) -> zbus::Result<()>;
77}
78
79#[proxy(
80 interface = "org.freedesktop.GeoClue2.Location",
81 default_service = "org.freedesktop.GeoClue2",
82 assume_defaults = false
83)]
84trait Location {
85 #[zbus(property)]
86 fn latitude(&self) -> zbus::Result<f64>;
87 #[zbus(property)]
88 fn longitude(&self) -> zbus::Result<f64>;
89 #[zbus(property)]
91 fn accuracy(&self) -> zbus::Result<f64>;
92 #[zbus(property)]
93 fn altitude(&self) -> zbus::Result<f64>;
94 #[zbus(property)]
96 fn speed(&self) -> zbus::Result<f64>;
97 #[zbus(property)]
99 fn heading(&self) -> zbus::Result<f64>;
100}
101
102fn convert_error(error: zbus::Error) -> GeolocationError {
105 let zbus::Error::MethodError(ref name, _, _) = error else {
106 return GeolocationError::position_unavailable(error.to_string());
107 };
108 match name.as_str() {
109 "org.freedesktop.DBus.Error.Timeout" | "org.freedesktop.DBus.Error.TimedOut" => {
110 GeolocationError::timeout(error.to_string())
111 },
112 "org.freedesktop.DBus.Error.AccessDenied" |
113 "org.freedesktop.DBus.Error.AuthFailed" |
114 "org.freedesktop.DBus.Error.LimitsExceeded" => {
115 GeolocationError::permission_denied(error.to_string())
116 },
117 _ => GeolocationError::position_unavailable(error.to_string()),
118 }
119}
120
121async fn read_position(
122 connection: &Connection,
123 path: OwnedObjectPath,
124) -> zbus::Result<GeolocationPositionData> {
125 let location = LocationProxy::builder(connection)
128 .path(path)?
129 .cache_properties(CacheProperties::No)
130 .build()
131 .await?;
132
133 let altitude = location.altitude().await?;
134 let speed = location.speed().await?;
135 let heading = location.heading().await?;
136
137 Ok(GeolocationPositionData {
138 accuracy: location.accuracy().await?,
139 latitude: location.latitude().await?,
140 longitude: location.longitude().await?,
141 altitude: (altitude >= MINIMUM_PLAUSIBLE_ALTITUDE).then_some(altitude),
142 altitude_accuracy: None,
144 heading: (heading >= 0.).then_some(heading),
145 speed: (speed >= 0.).then_some(speed),
146 })
147}
148
149enum Request {
151 Acquire(PositionRequest),
153 StartWatch(PositionWatch),
154 StopWatch(GeolocationWatchId),
155}
156
157pub(crate) struct Geoclue(UnboundedSender<Request>);
159
160static GEOCLUE: std::sync::OnceLock<Option<Geoclue>> = std::sync::OnceLock::new();
161
162impl Geoclue {
163 pub(crate) fn singleton() -> Option<&'static Self> {
165 GEOCLUE.get_or_init(Geoclue::spawn).as_ref()
166 }
167
168 pub(crate) fn spawn() -> Option<Self> {
171 debug!("Spawning Geoclue DBus client");
172 if !async_runtime::async_runtime_initialized() {
173 error!("No async runtime yet; geolocation is unavailable.");
174 return None;
175 }
176 let (sender, receiver) = unbounded();
177 async_runtime::spawn_task(GeoclueTaskState::default().run(receiver));
178 Some(Self(sender))
179 }
180
181 pub(crate) fn request_position(&self, request: PositionRequest) {
182 let _ = self.0.unbounded_send(Request::Acquire(request));
183 }
184
185 pub(crate) fn start_watch(&self, watch: PositionWatch) {
186 if self.0.unbounded_send(Request::StartWatch(watch)).is_err() {
187 error!("The GeoClue task is gone; no positions will be delivered.");
188 }
189 }
190
191 pub(crate) fn stop_watch(&self, id: &GeolocationWatchId) {
192 let _ = self.0.unbounded_send(Request::StopWatch(id.clone()));
193 }
194}
195
196struct Session {
198 connection: Connection,
199 client: ClientProxy<'static>,
200 accuracy: AccuracyLevel,
201}
202
203#[derive(Default)]
205struct GeoclueTaskState {
206 session: Option<Session>,
207 generation: u64,
210 pending: Vec<PositionRequest>,
212 watches: HashMap<GeolocationWatchId, PositionWatch>,
214}
215
216impl GeoclueTaskState {
217 async fn run(mut self, mut requests: UnboundedReceiver<Request>) {
218 let mut updates_stream: Option<LocationUpdatedStream> = None;
219 let mut subscribed_to = None;
220
221 loop {
222 if subscribed_to != Some(self.generation) {
223 updates_stream = None;
225 let client = self.session.as_ref().map(|session| session.client.clone());
226 if let Some(client) = client {
227 match client.receive_location_updated().await {
228 Ok(stream) => updates_stream = Some(stream),
229 Err(error) => {
230 self.handle_failure(error);
231 continue;
232 },
233 }
234 }
235 subscribed_to = Some(self.generation);
236
237 if updates_stream.is_some() && !self.is_idle() {
241 self.report_current_position().await;
242 }
243 }
244
245 let next_update = async {
246 match updates_stream.as_mut() {
247 Some(stream) => stream.next().await,
248 None => futures::future::pending::<Option<LocationUpdated>>().await,
250 }
251 };
252
253 select! {
254 request = requests.next() => {
255 let Some(request) = request else {
256 break;
258 };
259 self.handle_request(request).await;
260 },
261 update = next_update.fuse() => match update {
262 Some(update) => self.handle_update(update).await,
263 None => self.close_session().await,
265 },
266 }
267 }
268 self.close_session().await;
269 }
270
271 async fn handle_request(&mut self, request: Request) {
272 match request {
273 Request::Acquire(request) => {
274 let wants_high_accuracy = request.options().high_accuracy;
275 self.pending.push(request);
276 if let Err(error) = self.open_or_update_session(wants_high_accuracy).await {
277 self.handle_failure(error);
278 return;
279 }
280 self.report_current_position().await;
283 },
284 Request::StartWatch(watch) => {
285 let wants_high_accuracy = watch.options().high_accuracy;
286 self.watches.insert(watch.id(), watch);
287 if let Err(error) = self.open_or_update_session(wants_high_accuracy).await {
288 self.handle_failure(error);
289 return;
290 }
291 self.report_current_position().await;
292 },
293 Request::StopWatch(id) => {
294 self.watches.remove(&id);
295 if self.is_idle() {
296 self.close_session().await;
297 }
298 },
299 }
300 }
301
302 async fn handle_update(&mut self, update: LocationUpdated) {
303 let Ok(args) = update.args() else {
304 return;
305 };
306 let Some(connection) = self
307 .session
308 .as_ref()
309 .map(|session| session.connection.clone())
310 else {
311 return;
312 };
313 match read_position(&connection, args.current().clone()).await {
314 Ok(position) => self.report(Ok(position)).await,
315 Err(error) => self.handle_failure(error),
316 }
317 }
318
319 async fn report_current_position(&mut self) {
322 let Some((connection, client)) = self
323 .session
324 .as_ref()
325 .map(|session| (session.connection.clone(), session.client.clone()))
326 else {
327 error!("No client!");
328 return;
329 };
330 let path = match client.location().await {
331 Ok(path) if path.as_str() != "/" => path,
332 Ok(_) => return,
333 Err(error) => return self.handle_failure(error),
334 };
335 match read_position(&connection, path).await {
336 Ok(position) => self.report(Ok(position)).await,
337 Err(error) => self.handle_failure(error),
338 }
339 }
340
341 async fn report(&mut self, result: Result<GeolocationPositionData, GeolocationError>) {
346 for request in self.pending.drain(..) {
347 match result.clone() {
348 Ok(position) => request.success(position),
349 Err(error) => request.failure(error),
350 }
351 }
352 for watch in self.watches.values() {
353 match result.clone() {
354 Ok(position) => watch.update(position),
355 Err(error) => watch.error(error),
356 }
357 }
358 if self.is_idle() {
359 self.close_session().await;
360 }
361 }
362
363 fn handle_failure(&mut self, error: zbus::Error) {
370 let error = convert_error(error);
371 error!("GeoClue request failed: {}", error.message);
372
373 self.session = None;
376
377 for request in self.pending.drain(..) {
378 request.failure(error.clone());
379 }
380 for watch in self.watches.values() {
384 watch.error(error.clone());
385 }
386 }
387
388 fn is_idle(&self) -> bool {
389 self.pending.is_empty() && self.watches.is_empty()
390 }
391
392 fn wanted_accuracy(&self, wants_high_accuracy: bool) -> AccuracyLevel {
394 let high = wants_high_accuracy ||
395 self.pending
396 .iter()
397 .any(|request| request.options().high_accuracy) ||
398 self.watches
399 .values()
400 .any(|watch| watch.options().high_accuracy);
401 if high {
402 AccuracyLevel::Exact
403 } else {
404 AccuracyLevel::City
405 }
406 }
407
408 async fn open_or_update_session(&mut self, wants_high_accuracy: bool) -> zbus::Result<()> {
411 let accuracy = self.wanted_accuracy(wants_high_accuracy);
412
413 let existing = self
414 .session
415 .as_ref()
416 .map(|session| (session.client.clone(), session.accuracy));
417 if let Some((client, started_with)) = existing {
418 if started_with == accuracy {
419 return Ok(());
420 }
421 client.stop().await?;
422 client.set_requested_accuracy_level(accuracy as u32).await?;
423 client.start().await?;
424 if let Some(session) = self.session.as_mut() {
425 session.accuracy = accuracy;
426 }
427 return Ok(());
428 }
429
430 let connection = Connection::system().await?;
431 let manager = ManagerProxy::new(&connection).await?;
432 let client = ClientProxy::builder(&connection)
433 .path(manager.get_client().await?)?
434 .cache_properties(CacheProperties::No)
435 .build()
436 .await?;
437
438 let desktop_id = pref!(embedder_name);
441 client.set_desktop_id(&desktop_id).await?;
442
443 client.set_requested_accuracy_level(accuracy as u32).await?;
444 client.start().await?;
445
446 self.session = Some(Session {
447 connection,
448 client,
449 accuracy,
450 });
451 self.generation += 1;
452 Ok(())
453 }
454
455 async fn close_session(&mut self) {
456 let Some(session) = self.session.take() else {
457 return;
458 };
459 if let Err(error) = session.client.stop().await {
460 error!("Could not stop the GeoClue client ({error}).");
461 }
462 }
463}