-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
80 lines (71 loc) · 2.61 KB
/
lib.rs
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
//! A simple way to call invoke in [tauri](https://crates.io/crates/tauri) from rust.
//!
//! ```rust
//! // define an invoke
//! tauri_invoke::invoke!(async fn example_invoke(foo: f32, bar: bool) -> String);
//!
//! // call the invoke
//! let future = example_invoke(1.0, false);
//! ```
use wasm_bindgen::prelude::*;
#[doc(hidden)]
pub use js_sys;
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use serde_wasm_bindgen;
#[doc(hidden)]
pub use wasm_bindgen;
#[doc(hidden)]
pub use wasm_bindgen_futures;
#[wasm_bindgen]
extern "C" {
#[doc(hidden)]
#[wasm_bindgen(js_namespace = window)]
pub fn __TAURI_INVOKE__(name: &str, arguments: JsValue) -> JsValue;
}
#[doc(hidden)]
pub type InvokeResult<T = ()> = Result<T, String>;
/// # Examples
/// ```rust
/// // define an invoke
/// tauri_invoke::invoke!(async fn example_invoke(foo: f32, bar: bool) -> String);
///
/// // call the invoke
/// let future = example_invoke(1.0, false);
/// ```
#[macro_export]
macro_rules! invoke {
{ $( $vis:vis async fn $name:ident ( $($arg:ident : $arg_ty:ty),* $(,)? ) $(-> $ty:ty)? ; )* } => {
$crate::invoke!($( $vis async fn $name($($arg: $arg_ty),*) $(-> $ty)? ),*);
};
{ $( $vis:vis async fn $name:ident ( $($arg:ident : $arg_ty:ty),* $(,)? ) $(-> $ty:ty)? ),* $(,)? } => {$(
$vis async fn $name($($arg: $arg_ty),*) -> $crate::InvokeResult$(<$ty>)? {
let args = $crate::js_sys::Object::new();
let serializer = $crate::serde_wasm_bindgen::Serializer::json_compatible();
$(
$crate::js_sys::Reflect::set(
&args,
&$crate::wasm_bindgen::JsValue::from_str(::std::stringify!($arg)),
&$crate::serde::Serialize::serialize(&$arg, &serializer).unwrap(),
).expect("failed to set argument");
)*
let output = $crate::__TAURI_INVOKE__(
::std::stringify!($name),
::std::convert::From::from(args),
);
let promise = $crate::js_sys::Promise::from(output);
let result = $crate::wasm_bindgen_futures::JsFuture::from(promise).await;
Ok(match result {
#[allow(unused_variables)]
::std::result::Result::Ok(value) => {$(
$crate::serde_wasm_bindgen::from_value::<$ty>(value)
.expect("Failed to deserialize output of invoke, maybe the type is wrong?")
)?},
::std::result::Result::Err(err) => {
return ::std::result::Result::Err(err.as_string().unwrap());
}
})
}
)*};
}