pytauri_core/plugins/global_shortcut/
mod.rs

1use std::{
2    error::Error,
3    fmt::{Debug, Display, Formatter},
4};
5
6use pyo3::{exceptions::PyRuntimeError, prelude::*, types::PyDict};
7use pyo3_utils::from_py_dict::{derive_from_py_dict, FromPyDict as _};
8use tauri_plugin_global_shortcut::{self as plugin};
9
10use crate::{ext_mod::plugin::Plugin, tauri_runtime::Runtime, utils::TauriError};
11
12#[derive(Debug)]
13struct PluginError(plugin::Error);
14
15impl Display for PluginError {
16    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
17        Display::fmt(&self.0, f)
18    }
19}
20
21impl Error for PluginError {}
22
23impl From<PluginError> for PyErr {
24    fn from(value: PluginError) -> Self {
25        match value.0 {
26            plugin::Error::Tauri(e) => TauriError::from(e).into(),
27            e @ (plugin::Error::GlobalHotkey(_) | plugin::Error::RecvError(_)) => {
28                PyRuntimeError::new_err(e.to_string())
29            }
30            non_exhaustive => PyRuntimeError::new_err(format!(
31                "Unimplemented plugin error, please report this to the pytauri developers: {non_exhaustive}"
32            )),
33        }
34    }
35}
36
37impl From<plugin::Error> for PluginError {
38    fn from(value: plugin::Error) -> Self {
39        Self(value)
40    }
41}
42
43/// See also: [tauri_plugin_global_shortcut::Builder]
44#[non_exhaustive]
45pub struct BuilderArgs {}
46
47derive_from_py_dict!(BuilderArgs {});
48
49impl BuilderArgs {
50    fn from_kwargs(kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<Option<Self>> {
51        kwargs.map(Self::from_py_dict).transpose()
52    }
53
54    fn apply_to_builder(self, builder: plugin::Builder<Runtime>) -> plugin::Builder<Runtime> {
55        let Self {} = self;
56        builder
57    }
58}
59
60/// See also: [tauri_plugin_global_shortcut::Builder]
61#[pyclass(frozen)]
62#[non_exhaustive]
63pub struct Builder;
64
65#[pymethods]
66impl Builder {
67    #[staticmethod]
68    #[pyo3(signature = (**kwargs))]
69    fn build(kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<Plugin> {
70        let args = BuilderArgs::from_kwargs(kwargs)?;
71
72        let mut builder = plugin::Builder::new();
73        if let Some(args) = args {
74            builder = args.apply_to_builder(builder);
75        }
76
77        let plugin = Plugin::new(Box::new(move || Box::new(builder.build())));
78        Ok(plugin)
79    }
80}
81
82/// See also: [tauri_plugin_global_shortcut]
83#[pymodule(submodule, gil_used = false)]
84pub mod global_shortcut {
85    #[pymodule_export]
86    pub use super::Builder;
87
88    pub use super::BuilderArgs;
89}