#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "fuchsia")))]
use std::ffi::c_void;
#[cfg(not(target_os = "fuchsia"))]
use log::{debug, warn};
#[cfg(not(target_os = "fuchsia"))]
use copypasta::nop_clipboard::NopClipboardContext;
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "fuchsia")))]
use copypasta::wayland_clipboard;
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "fuchsia")))]
use copypasta::x11_clipboard::{Primary as X11SelectionClipboard, X11ClipboardContext};
#[cfg(not(target_os = "fuchsia"))]
use copypasta::{ClipboardContext, ClipboardProvider};
pub struct Clipboard {
#[cfg(not(target_os = "fuchsia"))]
clipboard: Box<dyn ClipboardProvider>,
#[cfg(not(target_os = "fuchsia"))]
selection: Option<Box<dyn ClipboardProvider>>,
}
impl Clipboard {
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "fuchsia"))]
pub fn new() -> Self {
Self::default()
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "fuchsia")))]
pub fn new(display: Option<*mut c_void>) -> Self {
if let Some(display) = display {
let (selection, clipboard) =
unsafe { wayland_clipboard::create_clipboards_from_external(display) };
return Self { clipboard: Box::new(clipboard), selection: Some(Box::new(selection)) };
}
Self {
clipboard: Box::new(ClipboardContext::new().unwrap()),
selection: Some(Box::new(X11ClipboardContext::<X11SelectionClipboard>::new().unwrap())),
}
}
#[cfg(not(target_os = "fuchsia"))]
pub fn new_nop() -> Self {
Self { clipboard: Box::new(NopClipboardContext::new().unwrap()), selection: None }
}
#[cfg(target_os = "fuchsia")]
pub fn new_nop() -> Self {
Self {}
}
}
impl Default for Clipboard {
#[cfg(not(target_os = "fuchsia"))]
fn default() -> Self {
Self { clipboard: Box::new(ClipboardContext::new().unwrap()), selection: None }
}
#[cfg(target_os = "fuchsia")]
fn default() -> Self {
Self {}
}
}
#[derive(Debug)]
pub enum ClipboardType {
Clipboard,
Selection,
}
impl Clipboard {
#[cfg(not(target_os = "fuchsia"))]
pub fn store(&mut self, ty: ClipboardType, text: impl Into<String>) {
let clipboard = match (ty, &mut self.selection) {
(ClipboardType::Selection, Some(provider)) => provider,
(ClipboardType::Selection, None) => return,
_ => &mut self.clipboard,
};
clipboard.set_contents(text.into()).unwrap_or_else(|err| {
warn!("Unable to store text in clipboard: {}", err);
});
}
#[cfg(target_os = "fuchsia")]
pub fn store(&mut self, _ty: ClipboardType, _text: impl Into<String>) {
}
#[cfg(not(target_os = "fuchsia"))]
pub fn load(&mut self, ty: ClipboardType) -> String {
let clipboard = match (ty, &mut self.selection) {
(ClipboardType::Selection, Some(provider)) => provider,
_ => &mut self.clipboard,
};
match clipboard.get_contents() {
Err(err) => {
debug!("Unable to load text from clipboard: {}", err);
String::new()
},
Ok(text) => text,
}
}
#[cfg(target_os = "fuchsia")]
pub fn load(&mut self, _ty: ClipboardType) -> String {
String::new()
}
}