From 277d30ef2ed50a9f659ea03a1ec86cfdd1ee2bf2 Mon Sep 17 00:00:00 2001 From: Sebastian Wiesner Date: Wed, 9 Mar 2022 22:40:22 +0100 Subject: [PATCH] Support primary selection on Wayland Closes #1423 --- docs/config/lua/keyassignment/CopyTo.md | 5 +- docs/config/lua/keyassignment/PasteFrom.md | 5 +- window/src/os/wayland/connection.rs | 1 + window/src/os/wayland/copy_and_paste.rs | 143 ++++++++++++++++++--- window/src/os/wayland/pointer.rs | 7 + window/src/os/wayland/window.rs | 69 ++-------- 6 files changed, 154 insertions(+), 76 deletions(-) diff --git a/docs/config/lua/keyassignment/CopyTo.md b/docs/config/lua/keyassignment/CopyTo.md index 69aa19696..0d163d0e1 100644 --- a/docs/config/lua/keyassignment/CopyTo.md +++ b/docs/config/lua/keyassignment/CopyTo.md @@ -5,7 +5,7 @@ Copy the selection to the specified clipboard buffer. Possible values for destination are: * `Clipboard` - copy the text to the system clipboard. -* `PrimarySelection` - Copy the test to the primary selection buffer (applicable to X11 systems only) +* `PrimarySelection` - Copy the test to the primary selection buffer (applicable to X11 and some Wayland systems only) * `ClipboardAndPrimarySelection` - Copy to both the clipboard and the primary selection. ```lua @@ -17,3 +17,6 @@ return { } ``` +*Since: nightly builds only* + +`PrimarySelection` is now also supported on Wayland systems that support [primary-selection-unstable-v1](https://wayland.app/protocols/primary-selection-unstable-v1) or the older Gtk primary selection protocol. diff --git a/docs/config/lua/keyassignment/PasteFrom.md b/docs/config/lua/keyassignment/PasteFrom.md index 57254af2b..c99eaeb17 100644 --- a/docs/config/lua/keyassignment/PasteFrom.md +++ b/docs/config/lua/keyassignment/PasteFrom.md @@ -2,7 +2,7 @@ Paste the specified clipboard to the current pane. -This is only really meaningful on X11 systems that have multiple clipboards. +This is only really meaningful on X11 and some Wayland systems that have multiple clipboards. Possible values for source are: @@ -24,3 +24,6 @@ return { } ``` +*Since: nightly builds only* + +`PrimarySelection` is now also supported on Wayland systems that support [primary-selection-unstable-v1](https://wayland.app/protocols/primary-selection-unstable-v1) or the older Gtk primary selection protocol. diff --git a/window/src/os/wayland/connection.rs b/window/src/os/wayland/connection.rs index 01483824d..b984220a9 100644 --- a/window/src/os/wayland/connection.rs +++ b/window/src/os/wayland/connection.rs @@ -83,6 +83,7 @@ impl WaylandConnection { environment.require_global(), environment.require_global(), environment.require_global(), + environment.get_primary_selection_manager(), )?); } } diff --git a/window/src/os/wayland/copy_and_paste.rs b/window/src/os/wayland/copy_and_paste.rs index f5d5db5bc..f70f031a4 100644 --- a/window/src/os/wayland/copy_and_paste.rs +++ b/window/src/os/wayland/copy_and_paste.rs @@ -1,11 +1,17 @@ -use anyhow::{anyhow, Error}; +use anyhow::{anyhow, bail, Context, Error}; use filedescriptor::{FileDescriptor, Pipe}; use smithay_client_toolkit as toolkit; +use std::io::Write; use std::os::unix::io::AsRawFd; +use std::os::unix::prelude::{FromRawFd, IntoRawFd}; use std::sync::{Arc, Mutex}; +use toolkit::primary_selection::*; use toolkit::reexports::client::protocol::wl_data_offer::{Event as DataOfferEvent, WlDataOffer}; -use toolkit::reexports::client::protocol::wl_data_source::WlDataSource; -use wayland_client::Attached; +use wayland_client::protocol::wl_data_device_manager::WlDataDeviceManager; +use wayland_client::protocol::wl_data_source::Event as DataSourceEvent; + +use crate::connection::ConnectionOps; +use crate::Clipboard; #[derive(Default)] pub struct CopyAndPaste { @@ -35,14 +41,88 @@ impl CopyAndPaste { } } - pub fn get_clipboard_data(&mut self) -> anyhow::Result { - let offer = self - .data_offer - .as_ref() - .ok_or_else(|| anyhow!("no data offer"))?; - let pipe = Pipe::new().map_err(Error::msg)?; - offer.receive(TEXT_MIME_TYPE.to_string(), pipe.write.as_raw_fd()); - Ok(pipe.read) + pub fn get_clipboard_data(&mut self, clipboard: Clipboard) -> anyhow::Result { + let conn = crate::Connection::get().unwrap().wayland(); + let primary_selection = if let Clipboard::PrimarySelection = clipboard { + conn.pointer.primary_selection_device.as_ref() + } else { + None + }; + match primary_selection { + Some(device) => { + let pipe = device.with_selection(|offer| { + offer + .ok_or_else(|| anyhow!("no primary selection offer")) + .and_then(|o| { + o.receive(TEXT_MIME_TYPE.to_string()) + .with_context(|| "failed to open read pipe".to_string()) + }) + })?; + Ok(unsafe { FileDescriptor::from_raw_fd(pipe.into_raw_fd()) }) + } + None => { + let offer = self + .data_offer + .as_ref() + .ok_or_else(|| anyhow!("no data offer"))?; + let pipe = Pipe::new().map_err(Error::msg)?; + offer.receive(TEXT_MIME_TYPE.to_string(), pipe.write.as_raw_fd()); + Ok(pipe.read) + } + } + } + + pub fn set_clipboard_data(&mut self, clipboard: Clipboard, data: String) { + let conn = crate::Connection::get().unwrap().wayland(); + let primary_selection = if let Clipboard::PrimarySelection = clipboard { + conn.environment + .borrow() + .get_primary_selection_manager() + .zip(conn.pointer.primary_selection_device.as_ref()) + } else { + None + }; + + match primary_selection { + Some((manager, device)) => { + let source = PrimarySelectionSource::new( + &manager, + &[TEXT_MIME_TYPE.to_string()], + move |event, _dispatch_data| match event { + PrimarySelectionSourceEvent::Cancelled => { + crate::Connection::get() + .unwrap() + .wayland() + .pointer + .data_device + .set_selection(None, 0); + } + PrimarySelectionSourceEvent::Send { pipe, .. } => { + let fd = unsafe { FileDescriptor::from_raw_fd(pipe.into_raw_fd()) }; + write_selection_to_pipe(fd, &data); + } + }, + ); + device.set_selection(&Some(source), self.last_serial) + } + None => { + let source = conn + .environment + .borrow() + .require_global::() + .create_data_source(); + source.quick_assign(move |_source, event, _dispatch_data| { + if let DataSourceEvent::Send { fd, .. } = event { + let fd = unsafe { FileDescriptor::from_raw_fd(fd) }; + write_selection_to_pipe(fd, &data); + } + }); + source.offer(TEXT_MIME_TYPE.to_string()); + conn.pointer + .data_device + .set_selection(Some(&source), self.last_serial); + } + } } pub fn handle_data_offer(&mut self, event: DataOfferEvent, offer: WlDataOffer) { @@ -69,14 +149,39 @@ impl CopyAndPaste { pub fn confirm_selection(&mut self, offer: WlDataOffer) { self.data_offer.replace(offer); } +} - pub fn set_selection(&mut self, source: &Attached) { - use crate::connection::ConnectionOps; - crate::Connection::get() - .unwrap() - .wayland() - .pointer - .data_device - .set_selection(Some(&source), self.last_serial); +fn write_selection_to_pipe(fd: FileDescriptor, text: &str) { + if let Err(e) = write_pipe_with_timeout(fd, text.as_bytes()) { + log::error!("while sending primary selection to pipe: {}", e); } } + +fn write_pipe_with_timeout(mut file: FileDescriptor, data: &[u8]) -> anyhow::Result<()> { + file.set_non_blocking(true)?; + let mut pfd = libc::pollfd { + fd: file.as_raw_fd(), + events: libc::POLLOUT, + revents: 0, + }; + + let mut buf = data; + + while !buf.is_empty() { + if unsafe { libc::poll(&mut pfd, 1, 3000) == 1 } { + match file.write(buf) { + Ok(size) if size == 0 => { + bail!("zero byte write"); + } + Ok(size) => { + buf = &buf[size..]; + } + Err(e) => bail!("error writing to pipe: {}", e), + } + } else { + bail!("timed out writing to pipe"); + } + } + + Ok(()) +} diff --git a/window/src/os/wayland/pointer.rs b/window/src/os/wayland/pointer.rs index 50cbca992..080ab3795 100644 --- a/window/src/os/wayland/pointer.rs +++ b/window/src/os/wayland/pointer.rs @@ -3,6 +3,7 @@ use crate::os::wayland::connection::WaylandConnection; use smithay_client_toolkit as toolkit; use std::collections::HashMap; use std::sync::{Arc, Mutex}; +use toolkit::primary_selection::{PrimarySelectionDevice, PrimarySelectionDeviceManager}; use toolkit::reexports::client::protocol::wl_data_device::{ Event as DataDeviceEvent, WlDataDevice, }; @@ -91,6 +92,7 @@ impl Inner { pub struct PointerDispatcher { inner: Arc>, pub(crate) data_device: Main, + pub(crate) primary_selection_device: Option, auto_pointer: ThemedPointer, #[allow(dead_code)] themer: ThemeManager, @@ -225,6 +227,7 @@ impl PointerDispatcher { compositor: Attached, shm: Attached, dev_mgr: Attached, + selection_manager: Option, ) -> anyhow::Result { let inner = Arc::new(Mutex::new(Inner::default())); let pointer = seat.get_pointer(); @@ -246,9 +249,13 @@ impl PointerDispatcher { } }); + let primary_selection_device = + selection_manager.map(|m| PrimarySelectionDevice::init_for_seat(&m, seat)); + Ok(Self { inner, data_device, + primary_selection_device, themer, auto_pointer, seat: seat.clone(), diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rs index 806b65edd..27daa4c07 100644 --- a/window/src/os/wayland/window.rs +++ b/window/src/os/wayland/window.rs @@ -20,18 +20,16 @@ use smithay_client_toolkit as toolkit; use std::any::Any; use std::cell::RefCell; use std::convert::TryInto; -use std::io::{Read, Write}; -use std::os::unix::io::{AsRawFd, FromRawFd}; +use std::io::Read; +use std::os::unix::io::AsRawFd; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use toolkit::get_surface_scale_factor; -use toolkit::reexports::client::protocol::wl_data_source::Event as DataSourceEvent; use toolkit::reexports::client::protocol::wl_pointer::ButtonState; use toolkit::reexports::client::protocol::wl_surface::WlSurface; use toolkit::window::{Decorations, Event as SCTKWindowEvent, State}; use wayland_client::protocol::wl_callback::WlCallback; -use wayland_client::protocol::wl_data_device_manager::WlDataDeviceManager; use wayland_client::protocol::wl_keyboard::{Event as WlKeyboardEvent, KeyState}; use wayland_client::{Attached, Main}; use wayland_egl::{is_available as egl_is_available, WlEglSurface}; @@ -872,12 +870,16 @@ impl WindowOps for WaylandWindow { }); } - fn get_clipboard(&self, _clipboard: Clipboard) -> Future { + fn get_clipboard(&self, clipboard: Clipboard) -> Future { let mut promise = Promise::new(); let future = promise.get_future().unwrap(); let promise = Arc::new(Mutex::new(promise)); WaylandConnection::with_window_inner(self.0, move |inner| { - let read = inner.copy_and_paste.lock().unwrap().get_clipboard_data()?; + let read = inner + .copy_and_paste + .lock() + .unwrap() + .get_clipboard_data(clipboard)?; let promise = Arc::clone(&promise); std::thread::spawn(move || { let mut promise = promise.lock().unwrap(); @@ -899,61 +901,18 @@ impl WindowOps for WaylandWindow { future } - fn set_clipboard(&self, _clipboard: Clipboard, text: String) { + fn set_clipboard(&self, clipboard: Clipboard, text: String) { WaylandConnection::with_window_inner(self.0, move |inner| { - let text = text.clone(); - let conn = Connection::get().unwrap().wayland(); - - let source = conn - .environment - .borrow() - .require_global::() - .create_data_source(); - source.quick_assign(move |_source, event, _dispatch_data| { - if let DataSourceEvent::Send { fd, .. } = event { - let fd = unsafe { FileDescriptor::from_raw_fd(fd) }; - if let Err(e) = write_pipe_with_timeout(fd, text.as_bytes()) { - log::error!("while sending paste to pipe: {}", e); - } - } - }); - source.offer(TEXT_MIME_TYPE.to_string()); - inner.copy_and_paste.lock().unwrap().set_selection(&source); - + inner + .copy_and_paste + .lock() + .unwrap() + .set_clipboard_data(clipboard, text); Ok(()) }); } } -fn write_pipe_with_timeout(mut file: FileDescriptor, data: &[u8]) -> anyhow::Result<()> { - file.set_non_blocking(true)?; - let mut pfd = libc::pollfd { - fd: file.as_raw_fd(), - events: libc::POLLOUT, - revents: 0, - }; - - let mut buf = data; - - while !buf.is_empty() { - if unsafe { libc::poll(&mut pfd, 1, 3000) == 1 } { - match file.write(buf) { - Ok(size) if size == 0 => { - bail!("zero byte write"); - } - Ok(size) => { - buf = &buf[size..]; - } - Err(e) => bail!("error writing to pipe: {}", e), - } - } else { - bail!("timed out writing to pipe"); - } - } - - Ok(()) -} - fn read_pipe_with_timeout(mut file: FileDescriptor) -> anyhow::Result { let mut result = Vec::new();