Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for wasm32 + web #160

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ wl-clipboard-rs = { version = "0.8", optional = true }
image = { version = "0.25", optional = true, default-features = false, features = ["png"] }
parking_lot = "0.12"

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { version = "0.3.70", default-features = false }
web-sys = { version = "0.3.70", default-features = false, features = [ "Clipboard", "ClipboardEvent", "ClipboardItem", "DataTransfer", "Document", "FileList", "Navigator", "Window" ] }

[[example]]
name = "get_image"
required-features = ["image-data"]
Expand Down
5 changes: 4 additions & 1 deletion src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl std::fmt::Debug for Error {
}

impl Error {
#[cfg(windows)]
#[allow(unused)]
pub(crate) fn unknown<M: Into<String>>(message: M) -> Self {
Error::Unknown { description: message.into() }
}
Expand Down Expand Up @@ -174,6 +174,9 @@ impl<F: FnOnce()> Drop for ScopeGuard<F> {

/// Common trait for sealing platform extension traits.
pub(crate) mod private {
// This is currently unused on macOS and WASM, so silence the warning which appears
// since there's no extension traits making use of this trait sealing structure.
#[allow(unreachable_pub, unused, dead_code)]
pub trait Sealed {}

impl Sealed for crate::Get<'_> {}
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ pub use platform::SetExtApple;
///
/// This means that attempting operations in parallel has a high likelihood to return an error or
/// deadlock. As such, it is recommended to avoid creating/operating clipboard objects on >1 thread.
///
/// ## WASM
///
/// The `Clipboard` is only available on the main browser thread; attempting to use it from a worker
/// will panic. In addition, the user must perform a paste action on the web document before
/// the clipboard contents become available to read with `arboard`.
#[allow(rustdoc::broken_intra_doc_links)]
pub struct Clipboard {
pub(crate) platform: platform::Clipboard,
Expand Down Expand Up @@ -134,6 +140,7 @@ impl Clipboard {
/// - On macOS: `NSImage` object
/// - On Linux: PNG, under the atom `image/png`
/// - On Windows: In order of priority `CF_DIB` and `CF_BITMAP`
/// - On WASM: Currently unsupported
///
/// # Errors
///
Expand Down Expand Up @@ -229,6 +236,7 @@ impl Set<'_> {
/// - On macOS: `NSImage` object
/// - On Linux: PNG, under the atom `image/png`
/// - On Windows: In order of priority `CF_DIB` and `CF_BITMAP`
/// - On WASM: Currently unsupported
#[cfg(feature = "image-data")]
pub fn image(self, image: ImageData) -> Result<(), Error> {
self.platform.image(image)
Expand Down
5 changes: 5 additions & 0 deletions src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ pub use windows::*;
mod osx;
#[cfg(target_os = "macos")]
pub use osx::*;

#[cfg(target_arch = "wasm32")]
mod wasm;
#[cfg(target_arch = "wasm32")]
pub(crate) use wasm::*;
162 changes: 162 additions & 0 deletions src/platform/wasm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
use crate::common::Error;
#[cfg(feature = "image-data")]
use crate::common::ImageData;
use js_sys::wasm_bindgen::JsCast;
use std::borrow::Cow;
use web_sys::wasm_bindgen::closure::Closure;

pub(crate) struct Clipboard {
inner: web_sys::Clipboard,
window: web_sys::Window,
}

impl Clipboard {
const GLOBAL_CLIPBOARD_OBJECT: &str = "__arboard_global_clipboard";
const GLOBAL_CALLBACK_OBJECT: &str = "__arboard_global_callback";

pub(crate) fn new() -> Result<Self, Error> {
let window = web_sys::window().ok_or(Error::ClipboardNotSupported)?;
let inner = window.navigator().clipboard();

// If the clipboard is being opened for the first time, add a paste callback
if js_sys::Reflect::get(&window, &Self::GLOBAL_CALLBACK_OBJECT.into())
.map_err(|_| Error::ClipboardNotSupported)?
.is_falsy()
{
let window_clone = window.clone();

let paste_callback = Closure::wrap(Box::new(move |e: web_sys::ClipboardEvent| {
if let Some(data_transfer) = e.clipboard_data() {
let object_to_set = if let Ok(text_data) = data_transfer.get_data("text") {
text_data.into()
} else {
web_sys::wasm_bindgen::JsValue::NULL.clone()
};

js_sys::Reflect::set(
&window_clone,
&Self::GLOBAL_CLIPBOARD_OBJECT.into(),
&object_to_set,
)
.expect("Failed to set global clipboard object.");
}
}) as Box<dyn FnMut(_)>);

// Set this event handler to execute before any child elements (third argument `true`) so that it is subsequently observed by other events.
window
.document()
.ok_or(Error::ClipboardNotSupported)?
.add_event_listener_with_callback_and_bool(
"paste",
&paste_callback.as_ref().unchecked_ref(),
true,
)
.map_err(|_| Error::unknown("Could not add paste event listener."))?;

js_sys::Reflect::set(
&window,
&Self::GLOBAL_CALLBACK_OBJECT.into(),
&web_sys::wasm_bindgen::JsValue::TRUE,
)
.expect("Failed to set global callback flag.");

paste_callback.forget();
}

Ok(Self { inner, window })
}

fn get_last_clipboard(&self) -> Option<String> {
js_sys::Reflect::get(&self.window, &Self::GLOBAL_CLIPBOARD_OBJECT.into())
.ok()
.and_then(|x| x.as_string())
}

fn set_last_clipboard(&self, value: &str) {
js_sys::Reflect::set(&self.window, &Self::GLOBAL_CLIPBOARD_OBJECT.into(), &value.into())
.expect("Failed to set global clipboard object.");
}
}

pub(crate) struct Clear<'clipboard> {
clipboard: &'clipboard mut Clipboard,
}

impl<'clipboard> Clear<'clipboard> {
pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
Self { clipboard }
}

pub(crate) fn clear(self) -> Result<(), Error> {
let _ = self.clipboard.inner.write_text("");
self.clipboard.set_last_clipboard("");
Ok(())
}
}

pub(crate) struct Get<'clipboard> {
clipboard: &'clipboard mut Clipboard,
}

impl<'clipboard> Get<'clipboard> {
pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
Self { clipboard }
}

pub(crate) fn text(self) -> Result<String, Error> {
self.clipboard.get_last_clipboard().ok_or_else(|| Error::ContentNotAvailable)
}

#[cfg(feature = "image-data")]
pub(crate) fn image(self) -> Result<ImageData<'static>, Error> {
Err(Error::ConversionFailure)
}
}

pub(crate) struct Set<'clipboard> {
clipboard: &'clipboard mut Clipboard,
}

impl<'clipboard> Set<'clipboard> {
pub(crate) fn new(clipboard: &'clipboard mut Clipboard) -> Self {
Self { clipboard }
}

pub(crate) fn text(self, data: Cow<'_, str>) -> Result<(), Error> {
let _ = self.clipboard.inner.write_text(&data);
self.clipboard.set_last_clipboard(&data);
Ok(())
}

pub(crate) fn html(self, html: Cow<'_, str>, alt: Option<Cow<'_, str>>) -> Result<(), Error> {
let alt = match alt {
Some(s) => s.into(),
None => String::new(),
};

let html_item = js_sys::Object::new();
js_sys::Reflect::set(&html_item, &"text/html".into(), &(&*html).into())
.expect("Failed to set HTML item text.");

let alt_item = js_sys::Object::new();
js_sys::Reflect::set(&alt_item, &"text/plain".into(), &alt.into())
.expect("Failed to set alt item text.");

let mut clipboard_items = js_sys::Array::default();
clipboard_items.extend([
web_sys::ClipboardItem::new_with_record_from_str_to_str_promise(&html_item)
.map_err(|_| Error::unknown("Failed to create HTML clipboard item."))?,
web_sys::ClipboardItem::new_with_record_from_str_to_str_promise(&alt_item)
.map_err(|_| Error::unknown("Failed to create alt clipboard item."))?,
]);

let _ = self.clipboard.inner.write(&clipboard_items);
self.clipboard.set_last_clipboard(&html);
Ok(())
}

#[cfg(feature = "image-data")]
pub(crate) fn image(self, _: ImageData) -> Result<(), Error> {
Err(Error::ConversionFailure)
}
}