use std::io::{Read, Write};
use std::os::fd::{BorrowedFd, OwnedFd};
use std::time::Duration;
use wayland_client::Connection;
pub const MAX_READ_BYTES: usize = 16 * 1024 * 1024;
pub const READ_TIMEOUT: Duration = Duration::from_secs(2);
pub fn receive(
connection: &Connection,
do_receive: impl FnOnce(BorrowedFd<'_>),
) -> Option<Vec<u8>> {
let (mut reader, writer) = match std::io::pipe() {
Ok(pair) => pair,
Err(e) => {
tracing::warn!(error = %e, "could not create a pipe to read a clipboard offer");
return None;
}
};
use std::os::fd::AsFd;
do_receive(writer.as_fd());
if let Err(e) = connection.flush() {
tracing::warn!(error = %e, "could not flush a clipboard receive request");
return None;
}
drop(writer);
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("hyprforge-clip-read".to_string())
.spawn(move || {
let result: std::io::Result<Vec<u8>> = (|| {
let mut buf = Vec::new();
let mut chunk = [0u8; 64 * 1024];
loop {
if buf.len() >= MAX_READ_BYTES {
break;
}
let n = reader.read(&mut chunk)?;
if n == 0 {
break;
}
let take = n.min(MAX_READ_BYTES - buf.len());
buf.extend_from_slice(&chunk[..take]);
}
Ok(buf)
})();
let _ = tx.send(result);
});
if spawned.is_err() {
tracing::warn!("could not spawn a thread to read a clipboard offer");
return None;
}
match rx.recv_timeout(READ_TIMEOUT) {
Ok(Ok(bytes)) => Some(bytes),
Ok(Err(e)) => {
tracing::warn!(error = %e, "reading a clipboard offer failed");
None
}
Err(_) => {
tracing::warn!("timed out reading a clipboard offer; the source may be stuck");
None
}
}
}
pub const WRITE_TIMEOUT: Duration = Duration::from_secs(2);
pub fn send(fd: OwnedFd, bytes: Vec<u8>) {
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("hyprforge-clip-write".to_string())
.spawn(move || {
let mut file = std::fs::File::from(fd);
let result = file.write_all(&bytes);
let _ = tx.send(result);
});
if spawned.is_err() {
tracing::warn!("could not spawn a thread to write a clipboard offer");
return;
}
match rx.recv_timeout(WRITE_TIMEOUT) {
Ok(Ok(())) => {}
Ok(Err(e)) => tracing::warn!(error = %e, "writing a clipboard offer failed"),
Err(_) => {
tracing::warn!("timed out writing a clipboard offer; the reader may be stuck")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SKIP_MARKER: &str = "HYPRFORGE-SKIP:";
fn connection_or_skip() -> Option<Connection> {
match Connection::connect_to_env() {
Ok(c) => Some(c),
Err(e) => {
eprintln!(
"{SKIP_MARKER} no Wayland compositor to flush a Connection against ({e})"
);
None
}
}
}
#[test]
fn a_reader_that_drains_the_pipe_gets_everything_written() {
use std::os::fd::OwnedFd;
let (mut reader, writer) = std::io::pipe().unwrap();
let owned: OwnedFd = writer.into();
let handle = std::thread::spawn(move || {
let mut buf = Vec::new();
reader.read_to_end(&mut buf).unwrap();
buf
});
send(owned, b"hello paste target".to_vec());
assert_eq!(handle.join().unwrap(), b"hello paste target");
}
#[test]
fn a_reader_that_never_drains_does_not_hang_the_write() {
use std::os::fd::OwnedFd;
let (reader, writer) = std::io::pipe().unwrap();
let owned: OwnedFd = writer.into();
let _keep_open = std::thread::spawn(move || {
let _reader = reader;
std::thread::sleep(Duration::from_secs(30));
});
let started = std::time::Instant::now();
send(owned, vec![0u8; 8 * 1024 * 1024]);
assert!(
started.elapsed() < Duration::from_secs(10),
"send() must return around WRITE_TIMEOUT, not wait out a stuck reader"
);
}
#[test]
#[ignore = "live (the Wayland compositor's protocols): changes nothing"]
fn a_source_that_writes_and_closes_is_read_back_in_full() {
use std::io::Write;
use std::os::fd::AsFd;
let Some(connection) = connection_or_skip() else {
return;
};
let bytes = receive(&connection, |fd| {
let owned = fd.as_fd().try_clone_to_owned().unwrap();
std::thread::spawn(move || {
let mut writer = std::fs::File::from(owned);
writer.write_all(b"hello clipboard").unwrap();
});
});
assert_eq!(bytes, Some(b"hello clipboard".to_vec()));
}
#[test]
#[ignore = "live (the Wayland compositor's protocols): changes nothing"]
fn a_source_that_never_writes_times_out_rather_than_hanging() {
use std::os::fd::AsFd;
let Some(connection) = connection_or_skip() else {
return;
};
let started = std::time::Instant::now();
let bytes = receive(&connection, |fd| {
let owned = fd.as_fd().try_clone_to_owned().unwrap();
std::thread::spawn(move || {
let _keep_open = owned;
std::thread::sleep(Duration::from_secs(30));
});
});
assert_eq!(bytes, None);
assert!(
started.elapsed() < Duration::from_secs(10),
"receive() must return around READ_TIMEOUT, not wait out the stuck source"
);
}
}