use crate::permissions::PermissionState;
use serde::{Deserialize, Serialize};
#[cfg(target_os = "android")]
#[manganis::ffi("src/android/geolocation")]
unsafe extern "Kotlin" {
pub type GeolocationPlugin;
}
#[cfg(target_os = "android")]
const GEOLOCATION_CLASS: &str = "dev.dioxus.g3_native_plugins.geolocation.GeolocationPlugin";
#[cfg(target_os = "android")]
type GeolocationHandle = crate::android_bridge::AndroidPlugin;
#[cfg(target_os = "ios")]
type GeolocationHandle = GeolocationPlugin;
#[cfg(target_os = "ios")]
#[manganis::ffi("src/ios")]
unsafe extern "Swift" {
pub type GeolocationPlugin;
pub fn startPositionRequestFromRust(this: &GeolocationPlugin, optionsJson: String);
pub fn getLocationStateFromRust(this: &GeolocationPlugin) -> Option<String>;
pub fn takePositionFromRust(this: &GeolocationPlugin) -> Option<String>;
pub fn checkPermissionsFromRust(this: &GeolocationPlugin) -> Option<String>;
pub fn requestPermissionsFromRust(this: &GeolocationPlugin);
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionStatus {
pub location: PermissionState,
pub coarse_location: PermissionState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionOptions {
pub enable_high_accuracy: bool,
pub timeout: u32,
pub maximum_age: u32,
}
impl Default for PositionOptions {
fn default() -> Self {
Self {
enable_high_accuracy: false,
timeout: 10_000,
maximum_age: 0,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Coordinates {
pub latitude: f64,
pub longitude: f64,
pub accuracy: f64,
pub altitude_accuracy: Option<f64>,
pub altitude: Option<f64>,
pub speed: Option<f64>,
pub heading: Option<f64>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Position {
pub timestamp: u64,
pub coords: Coordinates,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LocationState {
#[default]
Idle,
Locating,
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub struct Geolocation {
plugin: Option<GeolocationHandle>,
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
pub struct Geolocation;
#[cfg(any(target_os = "android", target_os = "ios"))]
impl Geolocation {
pub(crate) fn new() -> Self {
Self { plugin: None }
}
fn get_plugin(&mut self) -> Result<&GeolocationHandle, String> {
if self.plugin.is_none() {
#[cfg(target_os = "android")]
let created = GeolocationHandle::new(GEOLOCATION_CLASS)?;
#[cfg(target_os = "ios")]
let created = GeolocationPlugin::new()
.map_err(|error| format!("Failed to create GeolocationPlugin: {error:?}"))?;
self.plugin = Some(created);
}
Ok(self.plugin.as_ref().unwrap())
}
pub fn prepare(&mut self) -> Result<(), String> {
self.get_plugin()?;
Ok(())
}
pub fn check_permissions(&mut self) -> Result<PermissionStatus, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("checkPermissionsFromRust")?;
#[cfg(target_os = "ios")]
let reported = checkPermissionsFromRust(plugin)?;
let json =
reported.ok_or_else(|| "Geolocation permissions were not reported".to_string())?;
serde_json::from_str(&json)
.map_err(|error| format!("Failed to read permission status: {error}"))
}
pub fn request_permissions(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("requestPermissionsFromRust")?;
#[cfg(target_os = "ios")]
requestPermissionsFromRust(plugin)?;
Ok(())
}
pub fn start_position_request(&mut self, options: PositionOptions) -> Result<(), String> {
let options = serde_json::to_string(&options)
.map_err(|error| format!("Failed to encode position options: {error}"))?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit_str("startPositionRequestFromRust", &options)?;
#[cfg(target_os = "ios")]
startPositionRequestFromRust(plugin, options)?;
Ok(())
}
pub fn location_state(&mut self) -> LocationState {
let Ok(plugin) = self.get_plugin() else {
return LocationState::Idle;
};
#[cfg(target_os = "android")]
let state = plugin
.call_string("getLocationStateFromRust")
.ok()
.flatten();
#[cfg(target_os = "ios")]
let state = getLocationStateFromRust(plugin).ok().flatten();
match state.as_deref() {
Some("locating") => LocationState::Locating,
_ => LocationState::Idle,
}
}
pub fn poll_position(&mut self) -> Result<Option<Position>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let taken = plugin.call_string("takePositionFromRust")?;
#[cfg(target_os = "ios")]
let taken = takePositionFromRust(plugin)?;
let Some(json) = taken else {
return Ok(None);
};
let value: serde_json::Value = serde_json::from_str(&json)
.map_err(|error| format!("Failed to read position: {error}"))?;
if let Some(error) = value.get("error").and_then(|error| error.as_str()) {
return Err(error.to_string());
}
let position = serde_json::from_value(value)
.map_err(|error| format!("Failed to read position: {error}"))?;
Ok(Some(position))
}
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
impl Geolocation {
pub(crate) fn new() -> Self {
Self
}
pub fn prepare(&mut self) -> Result<(), String> {
Ok(())
}
pub fn check_permissions(&mut self) -> Result<PermissionStatus, String> {
Ok(PermissionStatus::default())
}
pub fn request_permissions(&mut self) -> Result<(), String> {
Ok(())
}
pub fn start_position_request(&mut self, _options: PositionOptions) -> Result<(), String> {
Ok(())
}
pub fn location_state(&mut self) -> LocationState {
LocationState::Idle
}
pub fn poll_position(&mut self) -> Result<Option<Position>, String> {
Ok(None)
}
}