1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! Register global shortcuts.
//!
//! ## Differences to the JavaScript API
//!
//! ## `registerAll`
//!
//! ```rust,no_run
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let shortcuts = ["CommandOrControl+Shift+C", "Ctrl+Alt+F12"];
//!
//! let streams = futures::future::try_join_all(shortcuts.map(|s| async move {
//!     let stream = global_shortcut::register(s).await?;
//!
//!     anyhow::Ok(stream.map(move |_| s))
//! }))
//! .await?;
//!
//! let mut events = futures::stream::select_all(streams);
//!
//! while let Some(shortcut) = events.next().await {
//!     log::debug!("Shortcut {} triggered", shortcut)
//! }
//! # Ok(())
//! # }
//! ```
//!
//! The APIs must be added to tauri.allowlist.globalShortcut in tauri.conf.json:
//!
//! ```json
//! {
//!     "tauri": {
//!         "allowlist": {
//!             "globalShortcut": {
//!                 "all": true // enable all global shortcut APIs
//!             }
//!         }
//!     }
//! }
//! ```
//! It is recommended to allowlist only the APIs you use for optimal bundle size and security.

use futures::{channel::mpsc, Stream, StreamExt};
use wasm_bindgen::{prelude::Closure, JsValue};

/// Determines whether the given shortcut is registered by this application or not.
///
/// # Example
///
/// ```rust,no_run
/// use tauri_sys::global_shortcut::is_registered;
///
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let registered = is_registered("CommandOrControl+P").await?;
/// # Ok(())
/// # }
/// ```
pub async fn is_registered(shortcut: &str) -> crate::Result<bool> {
    let raw = inner::isRegistered(shortcut).await?;

    Ok(serde_wasm_bindgen::from_value(raw)?)
}

/// Register a global shortcut.
///
/// The returned Future will automatically clean up it's underlying event listener when dropped, so no manual unlisten function needs to be called.
/// See [Differences to the JavaScript API](../index.html#differences-to-the-javascript-api) for details.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri_sys::global_shortcut::register;
/// use web_sys::console;
///
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let events = register("CommandOrControl+Shift+C").await?;
///
/// while let Some(_) in events.next().await {
///     console::log_1(&"Shortcut triggered".into());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn register(shortcut: &str) -> crate::Result<impl Stream<Item = ()>> {
    let (tx, rx) = mpsc::unbounded();

    let closure = Closure::<dyn FnMut(JsValue)>::new(move |_| {
        let _ = tx.unbounded_send(());
    });
    inner::register(shortcut, &closure).await?;
    closure.forget();

    Ok(Listen {
        shortcut: JsValue::from_str(shortcut),
        rx,
    })
}

struct Listen<T> {
    pub shortcut: JsValue,
    pub rx: mpsc::UnboundedReceiver<T>,
}

impl<T> Drop for Listen<T> {
    fn drop(&mut self) {
        log::debug!("Unregistering shortcut {:?}", self.shortcut);
        inner::unregister(self.shortcut.clone());
    }
}

impl<T> Stream for Listen<T> {
    type Item = T;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.rx.poll_next_unpin(cx)
    }
}

/// Register a collection of global shortcuts.
///
/// # Example
///
/// ```rust,no_run
/// use tauri_sys::global_shortcut::register;
/// use web_sys::console;
///
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let events = register_all(["CommandOrControl+Shift+C", "Ctrl+Alt+F12"]).await?;
///
/// while let Some(shortcut) in events.next().await {
///     console::log_1(&format!("Shortcut {} triggered", shortcut).into());
/// }
/// # Ok(())
/// # }
/// ```
// pub async fn register_all<I>(shortcuts: impl IntoIterator<Item = &str>) -> crate::Result<impl Stream<Item = String>>
// {
//     let shortcuts: Array = shortcuts.into_iter().map(JsValue::from_str).collect();
//     let (tx, rx) = mpsc::unbounded::<String>();

//     let closure = Closure::<dyn FnMut(JsValue)>::new(move |raw| {
//         let _ = tx.unbounded_send(serde_wasm_bindgen::from_value(raw).unwrap());
//     });
//     inner::registerAll(shortcuts.clone(), &closure).await?;
//     closure.forget();

//     Ok(ListenAll { shortcuts, rx })
// }

// struct ListenAll<T> {
//     pub shortcuts: js_sys::Array,
//     pub rx: mpsc::UnboundedReceiver<T>,
// }

// impl<T> Drop for ListenAll<T> {
//     fn drop(&mut self) {
//         for shortcut in self.shortcuts.iter() {
//             inner::unregister(shortcut);
//         }
//     }
// }

// impl<T> Stream for ListenAll<T> {
//     type Item = T;

//     fn poll_next(
//         mut self: std::pin::Pin<&mut Self>,
//         cx: &mut std::task::Context<'_>,
//     ) -> std::task::Poll<Option<Self::Item>> {
//         self.rx.poll_next_unpin(cx)
//     }
// }

mod inner {
    // use js_sys::Array;
    use wasm_bindgen::{
        prelude::{wasm_bindgen, Closure},
        JsValue,
    };

    #[wasm_bindgen(module = "/src/globalShortcut.js")]
    extern "C" {
        #[wasm_bindgen(catch)]
        pub async fn isRegistered(shortcut: &str) -> Result<JsValue, JsValue>;
        #[wasm_bindgen(catch)]
        pub async fn register(
            shortcut: &str,
            handler: &Closure<dyn FnMut(JsValue)>,
        ) -> Result<(), JsValue>;
        // #[wasm_bindgen(catch)]
        // pub async fn registerAll(
        //     shortcuts: Array,
        //     handler: &Closure<dyn FnMut(JsValue)>,
        // ) -> Result<(), JsValue>;
        pub fn unregister(shortcut: JsValue);
    }
}