use std::{
fs::File,
io::{ErrorKind, Write},
os::fd::{AsRawFd, BorrowedFd, OwnedFd},
};
use calloop::{LoopHandle, PostAction};
use filedescriptor::Pipe;
use strum::IntoEnumIterator;
use wayland_client::{Connection, protocol::wl_data_offer::WlDataOffer};
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1;
use crate::linux::{
WaylandClientStatePtr,
platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout},
};
use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};
pub(crate) const TEXT_MIME_TYPES: [&str; 3] =
["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
pub(crate) const FILE_LIST_MIME_TYPE: &str = "text/uri-list";
pub(crate) const ALLOWED_TEXT_MIME_TYPES: [&str; 2] = ["text/plain;charset=utf-8", "UTF8_STRING"];
pub(crate) struct Clipboard {
connection: Connection,
loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
self_mime: String,
contents: Option<std::sync::Arc<ClipboardItem>>,
file_operation: Option<gpui::FileClipboardOperation>,
primary_contents: Option<ClipboardItem>,
cached_read: Option<ClipboardItem>,
current_offer: Option<DataOffer<WlDataOffer>>,
cached_primary_read: Option<ClipboardItem>,
current_primary_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
}
pub(crate) trait ReceiveData {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>);
}
impl ReceiveData for WlDataOffer {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
self.receive(mime_type, fd);
}
}
impl ReceiveData for ZwpPrimarySelectionOfferV1 {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
self.receive(mime_type, fd);
}
}
#[derive(Clone, Debug)]
pub(crate) struct DataOffer<T: ReceiveData> {
pub inner: T,
mime_types: Vec<String>,
}
impl<T: ReceiveData> DataOffer<T> {
pub fn new(offer: T) -> Self {
Self {
inner: offer,
mime_types: Vec::new(),
}
}
pub fn add_mime_type(&mut self, mime_type: String) {
self.mime_types.push(mime_type)
}
fn has_mime_type(&self, mime_type: &str) -> bool {
self.mime_types.iter().any(|t| t == mime_type)
}
fn receive_text(&self) -> Option<filedescriptor::FileDescriptor> {
let mime = TEXT_MIME_TYPES
.iter()
.find(|mime| self.has_mime_type(mime))?;
let pipe = Pipe::new().ok()?;
self.inner.receive_data((*mime).to_string(), unsafe {
BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
});
drop(pipe.write);
Some(pipe.read)
}
fn read_bytes(&self, connection: &Connection, mime_type: &str) -> Option<Vec<u8>> {
let pipe = Pipe::new().unwrap();
self.inner.receive_data(mime_type.to_string(), unsafe {
BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
});
let fd = pipe.read;
drop(pipe.write);
connection.flush().unwrap();
match read_fd_with_timeout(fd, PIPE_READ_TIMEOUT) {
Ok(bytes) => Some(bytes),
Err(err) => {
log::error!("error reading clipboard pipe: {err:?}");
None
}
}
}
fn read_text(&self, connection: &Connection) -> Option<ClipboardItem> {
let mime_type = self.mime_types.iter().find(|&mime_type| {
ALLOWED_TEXT_MIME_TYPES
.iter()
.any(|&allowed| allowed == mime_type)
})?;
let bytes = self.read_bytes(connection, mime_type)?;
let text_content = match String::from_utf8(bytes) {
Ok(content) => content,
Err(e) => {
log::error!("Failed to convert clipboard content to UTF-8: {}", e);
return None;
}
};
let result = text_content.replace("\r\n", "\n");
Some(ClipboardItem::new_string(result))
}
fn read_image(&self, connection: &Connection) -> Option<ClipboardItem> {
for format in ImageFormat::iter() {
let mime_type = format.mime_type();
if !self.has_mime_type(mime_type) {
continue;
}
if let Some(bytes) = self.read_bytes(connection, mime_type) {
let id = hash(&bytes);
return Some(ClipboardItem {
entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
});
}
}
None
}
}
impl Clipboard {
pub fn new(
connection: Connection,
loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
) -> Self {
Self {
connection,
loop_handle,
self_mime: format!("pid/{}", std::process::id()),
contents: None,
file_operation: None,
primary_contents: None,
cached_read: None,
current_offer: None,
cached_primary_read: None,
current_primary_offer: None,
}
}
pub fn set(&mut self, item: ClipboardItem) {
self.contents = Some(std::sync::Arc::new(item));
self.file_operation = None;
}
pub fn set_files(
&mut self,
paths: gpui::ExternalPaths,
operation: gpui::FileClipboardOperation,
) {
self.contents = Some(std::sync::Arc::new(ClipboardItem {
entries: vec![ClipboardEntry::ExternalPaths(paths)],
}));
self.file_operation = Some(operation);
}
pub fn set_primary(&mut self, item: ClipboardItem) {
self.primary_contents = Some(item);
}
pub fn set_offer(&mut self, data_offer: Option<DataOffer<WlDataOffer>>) {
self.cached_read = None;
self.current_offer = data_offer;
}
pub fn set_primary_offer(&mut self, data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>) {
self.cached_primary_read = None;
self.current_primary_offer = data_offer;
}
pub fn self_mime(&self) -> String {
self.self_mime.clone()
}
pub fn send(&self, mime_type: String, fd: OwnedFd) {
if let Some(operation) = self.file_operation {
let Some(ClipboardEntry::ExternalPaths(paths)) =
self.contents.as_ref().and_then(|item| item.entries.first())
else {
return;
};
let bytes = match mime_type.as_str() {
FILE_LIST_MIME_TYPE => paths.clipboard_uri_list().map(String::into_bytes),
"x-special/gnome-copied-files" => paths
.clipboard_gnome_files(operation)
.map(String::into_bytes),
"application/x-kde-cutselection" => {
Ok(if operation == gpui::FileClipboardOperation::Move {
b"1"
} else {
b"0"
}
.to_vec())
}
_ => return,
};
if let Ok(bytes) = bytes {
self.send_bytes(fd, bytes);
}
return;
}
if let Some(text) = self.contents.as_ref().and_then(|contents| contents.text()) {
self.send_bytes(fd, text.as_bytes().to_owned());
}
}
pub fn send_primary(&self, _mime_type: String, fd: OwnedFd) {
if let Some(text) = self
.primary_contents
.as_ref()
.and_then(|contents| contents.text())
{
self.send_bytes(fd, text.as_bytes().to_owned());
}
}
pub fn read_text_async(
&self,
executor: &gpui::BackgroundExecutor,
) -> gpui::Task<Option<String>> {
let Some(offer) = &self.current_offer else {
return gpui::Task::ready(None);
};
if offer.has_mime_type(&self.self_mime) {
let contents = self.contents.clone();
return executor.spawn(async move { contents.and_then(|item| item.plain_text()) });
}
let Some(fd) = offer.receive_text() else {
return gpui::Task::ready(None);
};
if let Err(error) = self.connection.flush()
&& !matches!(error, wayland_client::backend::WaylandError::Io(ref error)
if error.kind() == ErrorKind::WouldBlock)
{
return gpui::Task::ready(None);
}
executor.spawn(async move { read_received_text(fd) })
}
pub fn read(&mut self) -> Option<ClipboardItem> {
let offer = self.current_offer.as_ref()?;
if let Some(cached) = self.cached_read.clone() {
return Some(cached);
}
if offer.has_mime_type(&self.self_mime) {
return self.contents.as_deref().cloned();
}
let item = offer
.read_text(&self.connection)
.or_else(|| offer.read_image(&self.connection))?;
self.cached_read = Some(item.clone());
Some(item)
}
pub fn read_primary(&mut self) -> Option<ClipboardItem> {
let offer = self.current_primary_offer.as_ref()?;
if let Some(cached) = self.cached_primary_read.clone() {
return Some(cached);
}
if offer.has_mime_type(&self.self_mime) {
return self.primary_contents.clone();
}
let item = offer
.read_text(&self.connection)
.or_else(|| offer.read_image(&self.connection))?;
self.cached_primary_read = Some(item.clone());
Some(item)
}
pub fn send_bytes(&self, fd: OwnedFd, bytes: Vec<u8>) {
let mut fd = filedescriptor::FileDescriptor::new(File::from(fd));
if let Err(error) = fd.set_non_blocking(true) {
log::error!("failed to prepare clipboard pipe: {error}");
return;
}
let mut written = 0;
if let Err(error) = self.loop_handle.insert_source(
calloop::generic::Generic::new(fd, calloop::Interest::WRITE, calloop::Mode::Level),
move |_, file, _| {
let file = unsafe { file.get_mut() };
loop {
match file.write(&bytes[written..]) {
Ok(0) => break Ok(PostAction::Remove),
Ok(n) if written + n == bytes.len() => {
written += n;
break Ok(PostAction::Remove);
}
Ok(n) => written += n,
Err(err) if err.kind() == ErrorKind::WouldBlock => {
break Ok(PostAction::Continue);
}
Err(err) if err.kind() == ErrorKind::Interrupted => continue,
Err(_) => break Ok(PostAction::Remove),
}
}
},
) {
log::error!("failed to register clipboard pipe: {error}");
}
}
}
fn read_received_text(fd: filedescriptor::FileDescriptor) -> Option<String> {
let bytes = read_fd_with_timeout(fd, PIPE_READ_TIMEOUT).ok()?;
String::from_utf8(bytes)
.ok()
.filter(|text| !text.is_empty())
}
#[cfg(test)]
mod text_read_tests {
use super::*;
use std::cell::RefCell;
#[derive(Default)]
struct Receiver {
writer: RefCell<Option<File>>,
mime: RefCell<Option<String>>,
}
impl ReceiveData for Receiver {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
*self.writer.borrow_mut() =
Some(File::from(fd.try_clone_to_owned().expect("duplicate pipe")));
*self.mime.borrow_mut() = Some(mime_type);
}
}
#[test]
fn text_offer_prepares_without_waiting_for_data_and_preserves_unicode() {
let mut offer = DataOffer::new(Receiver::default());
offer.add_mime_type("image/png".into());
offer.add_mime_type("text/plain".into());
let fd = offer.receive_text().expect("text pipe");
assert_eq!(offer.inner.mime.borrow().as_deref(), Some("text/plain"));
let mut writer = offer.inner.writer.borrow_mut().take().expect("writer");
drop(offer);
let text = "日本語🙂e\u{301}\r\n".repeat(20_000);
let bytes = text.clone().into_bytes();
let sender = std::thread::spawn(move || writer.write_all(&bytes).expect("send text"));
let reader = std::thread::spawn(move || read_received_text(fd));
sender.join().expect("sender");
assert_eq!(reader.join().expect("reader"), Some(text));
}
#[test]
fn nontext_offers_and_invalid_or_empty_utf8_return_none() {
let mut offer = DataOffer::new(Receiver::default());
offer.add_mime_type("image/png".into());
assert!(offer.receive_text().is_none());
assert!(offer.inner.writer.borrow().is_none());
for bytes in [vec![], vec![0xff]] {
let pipe = Pipe::new().expect("pipe");
let mut writer = pipe.write;
writer.write_all(&bytes).expect("write");
drop(writer);
assert_eq!(read_received_text(pipe.read), None);
}
}
}