Skip to main content

tauri_plugin_geolocation/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Access device geolocation APIs.
6//!
7//! ## Cargo features
8//!
9//! - **specta**: Add support for [`specta::specta`](https://docs.rs/specta/2.0.0-rc.25/specta/attr.specta.html) on structs like [`PermissionStatus`], [`PositionOptions`].
10
11use tauri::{
12    Manager, Runtime,
13    plugin::{Builder, TauriPlugin},
14};
15
16pub use models::*;
17
18#[cfg(desktop)]
19mod desktop;
20#[cfg(mobile)]
21mod mobile;
22
23mod commands;
24mod error;
25mod models;
26
27pub use error::{Error, Result};
28
29#[cfg(desktop)]
30pub use desktop::Geolocation;
31#[cfg(mobile)]
32pub use mobile::Geolocation;
33
34/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the geolocation APIs.
35pub trait GeolocationExt<R: Runtime> {
36    /// Returns the handle to the geolocation APIs.
37    fn geolocation(&self) -> &Geolocation<R>;
38}
39
40impl<R: Runtime, T: Manager<R>> crate::GeolocationExt<R> for T {
41    fn geolocation(&self) -> &Geolocation<R> {
42        self.state::<Geolocation<R>>().inner()
43    }
44}
45
46/// Initializes the plugin.
47pub fn init<R: Runtime>() -> TauriPlugin<R> {
48    Builder::new("geolocation")
49        .invoke_handler(tauri::generate_handler![
50            commands::get_current_position,
51            commands::watch_position,
52            commands::clear_watch,
53            commands::check_permissions,
54            commands::request_permissions
55        ])
56        .setup(|app, api| {
57            #[cfg(mobile)]
58            let geolocation = mobile::init(app, api)?;
59            #[cfg(desktop)]
60            let geolocation = desktop::init(app, api)?;
61            app.manage(geolocation);
62            Ok(())
63        })
64        .build()
65}