pytauri_core/ext_mod_impl/lib/
event.rs

1use pyo3::{prelude::*, types::PyString};
2
3/// See also: [tauri::EventId].
4pub use tauri::EventId;
5
6/// See also: [tauri::Event].
7#[pyclass(frozen)]
8#[non_exhaustive]
9pub struct Event {
10    #[pyo3(get)]
11    pub id: EventId, // TODO, PERF: use `Py<PyInt>` instead of `u32` for getter performance.
12    #[pyo3(get)]
13    pub payload: Py<PyString>,
14}
15
16/// See also: [tauri::EventTarget].
17//
18// NOTE: use `Py<T>` instead of `String` for getter performance.
19#[pyclass(frozen)]
20#[non_exhaustive]
21pub enum EventTarget {
22    Any(),
23    AnyLabel { label: Py<PyString> },
24    App(),
25    Window { label: Py<PyString> },
26    Webview { label: Py<PyString> },
27    WebviewWindow { label: Py<PyString> },
28    _NonExhaustive(),
29}
30
31impl EventTarget {
32    pub(crate) fn from_tauri(py: Python<'_>, value: &tauri::EventTarget) -> Self {
33        match value {
34            tauri::EventTarget::Any => Self::Any(),
35            tauri::EventTarget::AnyLabel { label } => Self::AnyLabel {
36                label: PyString::new(py, label).unbind(),
37            },
38            tauri::EventTarget::App => Self::App(),
39            tauri::EventTarget::Window { label } => Self::Window {
40                label: PyString::new(py, label).unbind(),
41            },
42            tauri::EventTarget::Webview { label } => Self::Webview {
43                label: PyString::new(py, label).unbind(),
44            },
45            tauri::EventTarget::WebviewWindow { label } => Self::WebviewWindow {
46                label: PyString::new(py, label).unbind(),
47            },
48            _ => Self::_NonExhaustive(),
49        }
50    }
51
52    pub(crate) fn to_tauri(&self, py: Python<'_>) -> PyResult<tauri::EventTarget> {
53        // TODO, PERF: once we drop py39, we can use [PyStringMethods::to_str] instead of [PyStringMethods::to_cow]
54        let value = match self {
55            Self::Any() => tauri::EventTarget::Any,
56            Self::AnyLabel { label } => tauri::EventTarget::AnyLabel {
57                label: label.bind(py).to_cow()?.into_owned(),
58            },
59            Self::App() => tauri::EventTarget::App,
60            Self::Window { label } => tauri::EventTarget::Window {
61                label: label.bind(py).to_cow()?.into_owned(),
62            },
63            Self::Webview { label } => tauri::EventTarget::Webview {
64                label: label.bind(py).to_cow()?.into_owned(),
65            },
66            Self::WebviewWindow { label } => tauri::EventTarget::WebviewWindow {
67                label: label.bind(py).to_cow()?.into_owned(),
68            },
69            Self::_NonExhaustive() => panic!("NonExhaustive is reserved for `#[non_exhaustive]`"),
70        };
71        Ok(value)
72    }
73}