robius_location/lib.rs
1//! A library to access system location data.
2//!
3//! ## Linux
4//!
5//! Uses the XDG Desktop Portal, falling back to GeoClue directly if the portal isn't there (never
6//! after a portal denial). No setup needed on a normal desktop install; see the README for what
7//! minimal distros need. Both [`Access`] variants map to the same portal permission, and one-shot
8//! requests give up after 60 seconds.
9//!
10//! **Note:** every `Manager` method blocks on D-Bus round trips. Usually milliseconds, but a wedged
11//! service can stall [`Manager::new`] for 45s and the rest for 30s (portal) or 45s (GeoClue), so
12//! keep them off your UI thread.
13//!
14//! If the provider dies, you get [`Error::TemporarilyUnavailable`] and updates stop. The next call
15//! reconnects, so just retry. Nothing carries over though, so the user may be asked to authorize
16//! again.
17//!
18//! ## Android
19//!
20//! On Android the following must be added to the manifest:
21//! ```xml
22//! <manifest ... >
23//! <!-- Always include this permission -->
24//! <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
25//!
26//! <!-- Include only if your app benefits from precise location access. -->
27//! <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
28//! </manifest>
29//! ```
30//! As specified in the [Android documentation][android-docs].
31//!
32//! ### Minimum API level
33//!
34//! The minimum supported Android API level is **26 (Android 8.0)**: the bundled
35//! Java helper is loaded via `InMemoryDexClassLoader`, which requires API 26.
36//! Newer location APIs (e.g. `getCurrentLocation`) are used only when the device
37//! supports them, with a fallback for older versions, so set `minSdk` to at least
38//! 26 in your app.
39//!
40//! [android-docs]: https://developer.android.com/develop/sensors-and-location/location/permissions
41
42mod error;
43mod sys;
44
45use std::time::SystemTime;
46
47pub use crate::error::{Error, Result};
48
49/// A manager for dealing with location data and handling location updates.
50///
51/// All functions must be called from the main thread, except on Linux, where any thread works
52/// (including from inside a handler callback).
53///
54/// As soon as the handler is registered, it may receive updates immediately,
55/// even if `update_once` or `start_updates` are not called.
56/// When the manager is dropped, the handler is no longer guaranteed to receive updates.
57pub struct Manager {
58 inner: sys::Manager,
59}
60
61impl Manager {
62 /// Creates a new location manager with the given handler.
63 ///
64 /// Must be called from the main thread, except on Linux.
65 pub fn new<T>(handler: T) -> Result<Self>
66 where
67 T: Handler,
68 {
69 Ok(Manager {
70 inner: sys::Manager::new(handler)?,
71 })
72 }
73
74 /// Like [`Manager::new`], but with an explicit GeoClue desktop ID.
75 ///
76 /// Prefer [`Manager::new`], which works this out itself. This is an escape hatch for odd or
77 /// legacy GeoClue setups. Pass an installed desktop-file ID without the `.desktop` suffix
78 /// (ASCII letters, digits, `.`, `_`, `-`); it's validated either way.
79 ///
80 /// Available everywhere so cross-platform code can call it unconditionally; off Linux the ID is
81 /// ignored.
82 #[cfg(target_os = "linux")]
83 pub fn new_with_desktop_id<T>(handler: T, desktop_id: &str) -> Result<Self>
84 where
85 T: Handler,
86 {
87 Ok(Manager {
88 inner: sys::Manager::new_with_desktop_id(handler, desktop_id)?,
89 })
90 }
91
92 /// See the Linux variant; off Linux the desktop ID is ignored.
93 #[cfg(not(target_os = "linux"))]
94 pub fn new_with_desktop_id<T>(handler: T, _desktop_id: &str) -> Result<Self>
95 where
96 T: Handler,
97 {
98 Self::new(handler)
99 }
100
101 /// Requests authorization to access location data.
102 ///
103 /// Linux (portal), iOS, and Android return immediately; a request made beforehand waits for the
104 /// user, and a denial goes to [`Handler::error`]. Linux (GeoClue) and Windows block and return
105 /// the result.
106 pub fn request_authorization(&self, access: Access, accuracy: Accuracy) -> Result<()> {
107 self.inner.request_authorization(access, accuracy)
108 }
109
110 /// Requests the device's current location, delivered to the handler. May deliver a cached fix
111 /// immediately, then a fresher one once acquired. On Linux, gives up after 60 seconds with
112 /// [`Error::TemporarilyUnavailable`] if nothing arrives.
113 pub fn update_once(&self) -> Result<()> {
114 self.inner.update_once()
115 }
116
117 /// Begins delivering continuous updates to the handler.
118 pub fn start_updates(&mut self) -> Result<()> {
119 self.inner.start_updates()
120 }
121
122 /// Stops delivering continuous updates to the handler.
123 pub fn stop_updates(&mut self) -> Result<()> {
124 self.inner.stop_updates()
125 }
126}
127
128/// A handler that handles location events and errors.
129///
130/// The handler should be registered with [`Manager::new`].
131pub trait Handler: 'static + Send + Sync {
132 fn handle(&self, location: Location<'_>);
133
134 fn error(&self, error: Error);
135}
136
137/// Data about the device's current whereabouts.
138///
139/// Despite the name, `Location` contains more than just the location of the
140/// device. See the methods for all available information.
141pub struct Location<'a> {
142 inner: sys::Location<'a>,
143}
144
145impl Location<'_> {
146 pub fn coordinates(&self) -> Result<Coordinates> {
147 self.inner.coordinates()
148 }
149
150 pub fn altitude(&self) -> Result<f64> {
151 self.inner.altitude()
152 }
153
154 /// The direction in which the device is travelling, measured in degrees and
155 /// relative to due north.
156 pub fn bearing(&self) -> Result<f64> {
157 self.inner.bearing()
158 }
159
160 /// The instantaneous speed of the device measured in meters per second.
161 pub fn speed(&self) -> Result<f64> {
162 self.inner.speed()
163 }
164
165 /// The time at which the location was acquired.
166 ///
167 /// This is not currently supported on Windows.
168 pub fn time(&self) -> Result<SystemTime> {
169 self.inner.time()
170 }
171}
172
173#[derive(Copy, Clone, Debug)]
174pub struct Coordinates {
175 pub latitude: f64,
176 pub longitude: f64,
177}
178
179/// The kind of location access.
180#[derive(Copy, Clone, Debug)]
181pub enum Access {
182 Foreground,
183 Background,
184}
185
186/// The accuracy of the location data.
187#[derive(Copy, Clone, Debug)]
188pub enum Accuracy {
189 /// Approximate location accuracy.
190 ///
191 /// Corresponds to
192 /// [`ACCESS_COARSE_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_COARSE_LOCATION)
193 /// on Android.
194 Approximate,
195 /// Precise location accuracy.
196 ///
197 /// Corresponds to
198 /// [`ACCESS_FINE_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION)
199 /// on Android.
200 Precise,
201}