From d7e5c00e94938f6be94e693d3f21f1f8f431c4f9 Mon Sep 17 00:00:00 2001 From: Lucas Fernandes Nogueira Date: Wed, 28 Aug 2024 22:34:03 -0300 Subject: [PATCH] feat(core): add `plugin::PermissionState` (#10817) * feat(core): add `plugin::mobile::PermissionState` * move to plugin module * default, specta::Type --- .changes/rust-permission-state.md | 5 +++ crates/tauri/src/plugin.rs | 56 ++++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 .changes/rust-permission-state.md diff --git a/.changes/rust-permission-state.md b/.changes/rust-permission-state.md new file mode 100644 index 000000000000..610624d99cd5 --- /dev/null +++ b/.changes/rust-permission-state.md @@ -0,0 +1,5 @@ +--- +"tauri": patch:enhance +--- + +Added `plugin:::PermissionState` enum. diff --git a/crates/tauri/src/plugin.rs b/crates/tauri/src/plugin.rs index 3bef88e73092..5d874bd69802 100644 --- a/crates/tauri/src/plugin.rs +++ b/crates/tauri/src/plugin.rs @@ -12,7 +12,10 @@ use crate::{ webview::PageLoadPayload, AppHandle, Error, RunEvent, Runtime, Webview, Window, }; -use serde::de::DeserializeOwned; +use serde::{ + de::{Deserialize, DeserializeOwned, Deserializer, Error as DeError}, + Serialize, Serializer, +}; use serde_json::Value as JsonValue; use tauri_macros::default_runtime; use thiserror::Error; @@ -898,3 +901,54 @@ fn initialize( ) .map_err(|e| Error::PluginInitialization(plugin.name().to_string(), e.to_string())) } + +/// Permission state. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[cfg_attr(feature = "specta", derive(specta::Type))] +pub enum PermissionState { + /// Permission access has been granted. + Granted, + /// Permission access has been denied. + Denied, + /// Permission must be requested, but you must explain to the user why your app needs that permission. **Android only**. + PromptWithRationale, + /// Unknown state. Must request permission. + #[default] + Unknown, +} + +impl std::fmt::Display for PermissionState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Granted => write!(f, "granted"), + Self::Denied => write!(f, "denied"), + Self::PromptWithRationale => write!(f, "prompt-with-rationale"), + Self::Unknown => write!(f, "Unknown"), + } + } +} + +impl Serialize for PermissionState { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(self.to_string().as_ref()) + } +} + +impl<'de> Deserialize<'de> for PermissionState { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + let s = ::deserialize(deserializer)?; + match s.to_lowercase().as_str() { + "granted" => Ok(Self::Granted), + "denied" => Ok(Self::Denied), + "prompt-with-rationale" => Ok(Self::PromptWithRationale), + "prompt" => Ok(Self::Unknown), + _ => Err(DeError::custom(format!("unknown permission state '{s}'"))), + } + } +}