mod ext;
mod keyboard;
mod pipe;
mod read_ext;
mod wlr;
mod write_ext;
mod write_wlr;
use crate::backend::ClipboardWatcher;
use crate::types::{Content, Entry, Mime};
use crate::write::{ClipboardWriter, Offers, Waiter};
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
pub use keyboard::WaylandPaster;
pub struct WaylandWatcher {
subscribers: Arc<Mutex<Vec<UnboundedSender<Entry>>>>,
}
impl WaylandWatcher {
pub fn connect() -> anyhow::Result<Self> {
let subscribers = Arc::new(Mutex::new(Vec::new()));
match ext::connect(subscribers.clone()) {
Ok(()) => return Ok(WaylandWatcher { subscribers }),
Err(e) => {
tracing::info!(
error = %e,
"ext-data-control-v1 unavailable; falling back to zwlr-data-control-v1"
);
}
}
wlr::connect(subscribers.clone())
.map_err(|e| anyhow::anyhow!("no clipboard protocol available (tried ext-data-control-v1, then zwlr-data-control-v1): {e}"))?;
Ok(WaylandWatcher { subscribers })
}
}
impl ClipboardWatcher for WaylandWatcher {
fn subscribe(&self) -> UnboundedReceiver<Entry> {
let (tx, rx) = mpsc::unbounded_channel();
self.subscribers
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(tx);
rx
}
}
pub struct WaylandWriter;
impl WaylandWriter {
pub fn new() -> Self {
WaylandWriter
}
}
impl WaylandWriter {
pub fn set_offers(&self, offers: Offers) -> anyhow::Result<Arc<Waiter>> {
match write_ext::set_offers(offers.clone()) {
Ok(waiter) => Ok(waiter),
Err(e) => {
tracing::info!(
error = %e,
"ext-data-control-v1 unavailable for writing; falling back to zwlr-data-control-v1"
);
write_wlr::set_offers(offers).map_err(|e| {
anyhow::anyhow!(
"no clipboard protocol available to write to (tried ext-data-control-v1, then zwlr-data-control-v1): {e}"
)
})
}
}
}
}
pub fn read_selection(
preferred: Vec<Mime>,
timeout: std::time::Duration,
) -> anyhow::Result<Option<(Mime, Vec<u8>)>> {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::Builder::new()
.name("hyprforge-clip-read-once".to_string())
.spawn(move || {
let _ = tx.send(read_ext::read(&preferred));
})?;
match rx.recv_timeout(timeout) {
Ok(result) => result,
Err(_) => Err(anyhow::anyhow!("the compositor did not answer a clipboard read in time")),
}
}
impl Default for WaylandWriter {
fn default() -> Self {
Self::new()
}
}
impl ClipboardWriter for WaylandWriter {
type Guard = Arc<Waiter>;
fn set_selection(&self, content: Content) -> anyhow::Result<Self::Guard> {
match write_ext::set_selection(content.clone()) {
Ok(waiter) => Ok(waiter),
Err(e) => {
tracing::info!(
error = %e,
"ext-data-control-v1 unavailable for writing; falling back to zwlr-data-control-v1"
);
write_wlr::set_selection(content).map_err(|e| {
anyhow::anyhow!(
"no clipboard protocol available to write to (tried ext-data-control-v1, then zwlr-data-control-v1): {e}"
)
})
}
}
}
}