Support primary selection on Wayland

Closes #1423
This commit is contained in:
Sebastian Wiesner authored and Wez Furlong committed 2022-03-12 05:42:01 -08:00
1 parent 5d7de61e9e
commit 277d30ef2e
6 files changed
+154 -76

No files matched your search

+4 -1
View File
@@ -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.
+4 -1
View File
@@ -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.
+1
View File
@@ -83,6 +83,7 @@ impl WaylandConnection {
environment.require_global(),
environment.require_global(),
environment.require_global(),
environment.get_primary_selection_manager(),
)?);
}
}
+124 -19
View File
@@ -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<FileDescriptor> {
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<FileDescriptor> {
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::<WlDataDeviceManager>()
.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<WlDataSource>) {
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(())
}
+7
View File
@@ -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<Mutex<Inner>>,
pub(crate) data_device: Main<WlDataDevice>,
pub(crate) primary_selection_device: Option<PrimarySelectionDevice>,
auto_pointer: ThemedPointer,
#[allow(dead_code)]
themer: ThemeManager,
@@ -225,6 +227,7 @@ impl PointerDispatcher {
compositor: Attached<WlCompositor>,
shm: Attached<WlShm>,
dev_mgr: Attached<WlDataDeviceManager>,
selection_manager: Option<PrimarySelectionDeviceManager>,
) -> anyhow::Result<Self> {
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(),
+14 -55
View File
@@ -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<String> {
fn get_clipboard(&self, clipboard: Clipboard) -> Future<String> {
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::<WlDataDeviceManager>()
.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<String> {
let mut result = Vec::new();