robius-location 0.3.1

Rust abstractions for accessing native geo-location (e.g., GPS) across platforms.
Documentation
//! A library to access system location data.
//!
//! ## Linux
//!
//! Uses the XDG Desktop Portal, falling back to GeoClue directly if the portal isn't there (never
//! after a portal denial). No setup needed on a normal desktop install; see the README for what
//! minimal distros need. Both [`Access`] variants map to the same portal permission, and one-shot
//! requests give up after 60 seconds.
//!
//! **Note:** every `Manager` method blocks on D-Bus round trips. Usually milliseconds, but a wedged
//! service can stall [`Manager::new`] for 45s and the rest for 30s (portal) or 45s (GeoClue), so
//! keep them off your UI thread.
//!
//! If the provider dies, you get [`Error::TemporarilyUnavailable`] and updates stop. The next call
//! reconnects, so just retry. Nothing carries over though, so the user may be asked to authorize
//! again.
//!
//! ## Android
//!
//! On Android the following must be added to the manifest:
//! ```xml
//! <manifest ... >
//!   <!-- Always include this permission -->
//!   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//!
//!   <!-- Include only if your app benefits from precise location access. -->
//!   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
//! </manifest>
//! ```
//! As specified in the [Android documentation][android-docs].
//!
//! ### Minimum API level
//!
//! The minimum supported Android API level is **26 (Android 8.0)**: the bundled
//! Java helper is loaded via `InMemoryDexClassLoader`, which requires API 26.
//! Newer location APIs (e.g. `getCurrentLocation`) are used only when the device
//! supports them, with a fallback for older versions, so set `minSdk` to at least
//! 26 in your app.
//!
//! [android-docs]: https://developer.android.com/develop/sensors-and-location/location/permissions

mod error;
mod sys;

use std::time::SystemTime;

pub use crate::error::{Error, Result};

/// A manager for dealing with location data and handling location updates.
///
/// All functions must be called from the main thread, except on Linux, where any thread works
/// (including from inside a handler callback).
///
/// As soon as the handler is registered, it may receive updates immediately,
/// even if `update_once` or `start_updates` are not called.
/// When the manager is dropped, the handler is no longer guaranteed to receive updates.
pub struct Manager {
    inner: sys::Manager,
}

impl Manager {
    /// Creates a new location manager with the given handler.
    ///
    /// Must be called from the main thread, except on Linux.
    pub fn new<T>(handler: T) -> Result<Self>
    where
        T: Handler,
    {
        Ok(Manager {
            inner: sys::Manager::new(handler)?,
        })
    }

    /// Like [`Manager::new`], but with an explicit GeoClue desktop ID.
    ///
    /// Prefer [`Manager::new`], which works this out itself. This is an escape hatch for odd or
    /// legacy GeoClue setups. Pass an installed desktop-file ID without the `.desktop` suffix
    /// (ASCII letters, digits, `.`, `_`, `-`); it's validated either way.
    ///
    /// Available everywhere so cross-platform code can call it unconditionally; off Linux the ID is
    /// ignored.
    #[cfg(target_os = "linux")]
    pub fn new_with_desktop_id<T>(handler: T, desktop_id: &str) -> Result<Self>
    where
        T: Handler,
    {
        Ok(Manager {
            inner: sys::Manager::new_with_desktop_id(handler, desktop_id)?,
        })
    }

    /// See the Linux variant; off Linux the desktop ID is ignored.
    #[cfg(not(target_os = "linux"))]
    pub fn new_with_desktop_id<T>(handler: T, _desktop_id: &str) -> Result<Self>
    where
        T: Handler,
    {
        Self::new(handler)
    }

    /// Requests authorization to access location data.
    ///
    /// Linux (portal), iOS, and Android return immediately; a request made beforehand waits for the
    /// user, and a denial goes to [`Handler::error`]. Linux (GeoClue) and Windows block and return
    /// the result.
    pub fn request_authorization(&self, access: Access, accuracy: Accuracy) -> Result<()> {
        self.inner.request_authorization(access, accuracy)
    }

    /// Requests the device's current location, delivered to the handler. May deliver a cached fix
    /// immediately, then a fresher one once acquired. On Linux, gives up after 60 seconds with
    /// [`Error::TemporarilyUnavailable`] if nothing arrives.
    pub fn update_once(&self) -> Result<()> {
        self.inner.update_once()
    }

    /// Begins delivering continuous updates to the handler.
    pub fn start_updates(&mut self) -> Result<()> {
        self.inner.start_updates()
    }

    /// Stops delivering continuous updates to the handler.
    pub fn stop_updates(&mut self) -> Result<()> {
        self.inner.stop_updates()
    }
}

/// A handler that handles location events and errors.
///
/// The handler should be registered with [`Manager::new`].
pub trait Handler: 'static + Send + Sync {
    fn handle(&self, location: Location<'_>);

    fn error(&self, error: Error);
}

/// Data about the device's current whereabouts.
///
/// Despite the name, `Location` contains more than just the location of the
/// device. See the methods for all available information.
pub struct Location<'a> {
    inner: sys::Location<'a>,
}

impl Location<'_> {
    pub fn coordinates(&self) -> Result<Coordinates> {
        self.inner.coordinates()
    }

    pub fn altitude(&self) -> Result<f64> {
        self.inner.altitude()
    }

    /// The direction in which the device is travelling, measured in degrees and
    /// relative to due north.
    pub fn bearing(&self) -> Result<f64> {
        self.inner.bearing()
    }

    /// The instantaneous speed of the device measured in meters per second.
    pub fn speed(&self) -> Result<f64> {
        self.inner.speed()
    }

    /// The time at which the location was acquired.
    ///
    /// This is not currently supported on Windows.
    pub fn time(&self) -> Result<SystemTime> {
        self.inner.time()
    }
}

#[derive(Copy, Clone, Debug)]
pub struct Coordinates {
    pub latitude: f64,
    pub longitude: f64,
}

/// The kind of location access.
#[derive(Copy, Clone, Debug)]
pub enum Access {
    Foreground,
    Background,
}

/// The accuracy of the location data.
#[derive(Copy, Clone, Debug)]
pub enum Accuracy {
    /// Approximate location accuracy.
    ///
    /// Corresponds to
    /// [`ACCESS_COARSE_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_COARSE_LOCATION)
    /// on Android.
    Approximate,
    /// Precise location accuracy.
    ///
    /// Corresponds to
    /// [`ACCESS_FINE_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION)
    /// on Android.
    Precise,
}