pytauri_core/ext_mod_impl/lib/
event.rs

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