-
Notifications
You must be signed in to change notification settings - Fork 0
/
clipboard.rs
77 lines (66 loc) · 2.26 KB
/
clipboard.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
//! Cross-platform clipboard utilities, letting you save and load data from the clipboard
//! on the fly.
//!
//! The windows implementation doesn't even segfault, Fedor!
use crate::waiter::Waiter;
/// Try and get the string value off the clipboard.
/// This could support other things (like images) but ehhhhh
///
/// Because the JS clipboard API is `async` for some horrid reason, returns a Waiter.
///
/// If an error occurs on desktop it will return a Waiter that will never return Some.
pub fn get_clipboard() -> Waiter<String> {
#[cfg(target_arch = "wasm32")]
{
wasm::get_clipboard()
}
#[cfg(not(target_arch = "wasm32"))]
{
use copypasta::{ClipboardContext, ClipboardProvider};
let res: Result<String, ()> = (|| {
let mut provider = ClipboardContext::new().map_err(|_| ())?;
provider.get_contents().map_err(|_| ())
})();
match res {
Ok(text) => Waiter::new_immediate(text),
Err(_) => Waiter::new_empty(),
}
}
}
/// Try and set the clipboard.
///
/// The returned `Waiter` will resolve to `()` once its task is complete.
pub fn set_clipboard(text: String) -> Waiter<()> {
#[cfg(target_arch = "wasm32")]
{
wasm::set_clipboard(&text)
}
#[cfg(not(target_arch = "wasm32"))]
{
use copypasta::{ClipboardContext, ClipboardProvider};
let res: Result<(), ()> = (|| {
let mut provider = ClipboardContext::new().map_err(|_| ())?;
provider.set_contents(text).map_err(|_| ())
})();
match res {
Ok(()) => Waiter::new_immediate(()),
Err(_) => Waiter::new_empty(),
}
}
}
#[cfg(target_arch = "wasm32")]
mod wasm {
use sapp_jsutils::{JsObject, JsObjectWeak};
use crate::waiter::Waiter;
extern "C" {
fn clipboard_get() -> JsObject;
fn clipboard_set(text: JsObjectWeak) -> JsObject;
}
pub fn get_clipboard() -> Waiter<String> {
Waiter::new_waiting(unsafe { clipboard_get() })
}
pub fn set_clipboard(text: &str) -> Waiter<()> {
let text = JsObject::string(&text);
Waiter::new_waiting(unsafe { clipboard_set(text.weak()) })
}
}