1
0
Fork 0
mirror of https://github.com/Zedfrigg/ironbar.git synced 2025-08-18 07:11:04 +02:00

refactor(wayland): update to 0.30.0

This is pretty much a rewrite of the Wayland client code for `wayland-client` and `wayland-protocols` v0.30.0, and `smithay-client-toolkit` v0.17.0
This commit is contained in:
Jake Stanger 2023-04-29 22:08:02 +01:00
parent 5c18ec8ba0
commit 7f46cb4976
No known key found for this signature in database
GPG key ID: C51FC8F9CB0BEA61
23 changed files with 1779 additions and 1338 deletions

View file

@ -1,88 +1,166 @@
use super::offer::DataControlOffer;
use super::source::DataControlSource;
use super::manager::DataControlDeviceManagerState;
use super::offer::{
DataControlOfferData, DataControlOfferDataExt, DataControlOfferHandler, SelectionOffer,
};
use crate::error::ERR_WAYLAND_DATA;
use crate::lock;
use std::sync::{Arc, Mutex};
use wayland_client::protocol::wl_seat::WlSeat;
use wayland_client::{Attached, DispatchData, Main};
use wayland_protocols::wlr::unstable::data_control::v1::client::{
use tracing::warn;
use wayland_client::{event_created_child, Connection, Dispatch, Proxy, QueueHandle};
use wayland_protocols_wlr::data_control::v1::client::{
zwlr_data_control_device_v1::{Event, ZwlrDataControlDeviceV1},
zwlr_data_control_manager_v1::ZwlrDataControlManagerV1,
zwlr_data_control_offer_v1::ZwlrDataControlOfferV1,
};
#[derive(Debug)]
struct Inner {
offer: Option<Arc<DataControlOffer>>,
}
impl Inner {
fn new_offer(&mut self, offer: &Main<ZwlrDataControlOfferV1>) {
self.offer.replace(Arc::new(DataControlOffer::new(offer)));
}
}
#[derive(Debug, Clone)]
pub struct DataControlDeviceEvent(pub Arc<DataControlOffer>);
fn data_control_device_implem<F>(
event: Event,
inner: &mut Inner,
implem: &mut F,
ddata: DispatchData,
) where
F: FnMut(DataControlDeviceEvent, DispatchData),
{
match event {
Event::DataOffer { id } => {
inner.new_offer(&id);
}
Event::Selection { id: Some(offer) } => {
let inner_offer = inner
.offer
.clone()
.expect("Offer should exist at this stage");
if offer == inner_offer.offer {
implem(DataControlDeviceEvent(inner_offer), ddata);
}
}
_ => {}
}
}
pub struct DataControlDevice {
device: ZwlrDataControlDeviceV1,
_inner: Arc<Mutex<Inner>>,
pub device: ZwlrDataControlDeviceV1,
}
impl DataControlDevice {
pub fn init_for_seat<F>(
manager: &Attached<ZwlrDataControlManagerV1>,
seat: &WlSeat,
mut callback: F,
) -> Self
where
F: FnMut(DataControlDeviceEvent, DispatchData) + 'static,
{
let inner = Arc::new(Mutex::new(Inner { offer: None }));
#[derive(Debug, Default)]
pub struct DataControlDeviceInner {
/// the active selection offer and its data
selection_offer: Arc<Mutex<Option<ZwlrDataControlOfferV1>>>,
/// the active undetermined offers and their data
pub undetermined_offers: Arc<Mutex<Vec<ZwlrDataControlOfferV1>>>,
}
let device = manager.get_data_device(seat);
#[derive(Debug, Default)]
pub struct DataControlDeviceData {
pub(super) inner: Arc<Mutex<DataControlDeviceInner>>,
}
{
let inner = inner.clone();
device.quick_assign(move |_handle, event, ddata| {
let mut inner = lock!(inner);
data_control_device_implem(event, &mut inner, &mut callback, ddata);
});
}
pub trait DataControlDeviceDataExt: Send + Sync {
type DataControlOfferInner: DataControlOfferDataExt + Send + Sync + 'static;
Self {
device: device.detach(),
_inner: inner,
}
fn data_control_device_data(&self) -> &DataControlDeviceData;
fn selection_mime_types(&self) -> Vec<String> {
let inner = self.data_control_device_data();
lock!(lock!(inner.inner).selection_offer)
.as_ref()
.map(|offer| {
let data = offer
.data::<Self::DataControlOfferInner>()
.expect(ERR_WAYLAND_DATA);
data.mime_types()
})
.unwrap_or_default()
}
pub fn set_selection(&self, source: &Option<DataControlSource>) {
self.device
.set_selection(source.as_ref().map(|s| &s.source));
/// Get the active selection offer if it exists.
fn selection_offer(&self) -> Option<SelectionOffer> {
let inner = self.data_control_device_data();
lock!(lock!(inner.inner).selection_offer)
.as_ref()
.and_then(|offer| {
let data = offer
.data::<Self::DataControlOfferInner>()
.expect(ERR_WAYLAND_DATA);
data.as_selection_offer()
})
}
}
impl DataControlDeviceDataExt for DataControlDevice {
type DataControlOfferInner = DataControlOfferData;
fn data_control_device_data(&self) -> &DataControlDeviceData {
self.device.data().expect(ERR_WAYLAND_DATA)
}
}
impl DataControlDeviceDataExt for DataControlDeviceData {
type DataControlOfferInner = DataControlOfferData;
fn data_control_device_data(&self) -> &DataControlDeviceData {
self
}
}
/// Handler trait for `DataDevice` events.
///
/// The functions defined in this trait are called as `DataDevice` events are received from the compositor.
pub trait DataControlDeviceHandler: Sized {
/// Advertises a new selection.
fn selection(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
data_device: DataControlDevice,
);
}
impl<D, U, V> Dispatch<ZwlrDataControlDeviceV1, U, D> for DataControlDeviceManagerState<V>
where
D: Dispatch<ZwlrDataControlDeviceV1, U>
+ Dispatch<ZwlrDataControlOfferV1, V>
+ DataControlDeviceHandler
+ DataControlOfferHandler
+ 'static,
U: DataControlDeviceDataExt,
V: DataControlOfferDataExt + Default + 'static + Send + Sync,
{
event_created_child!(D, ZwlrDataControlDeviceV1, [
0 => (ZwlrDataControlOfferV1, V::default())
]);
fn event(
state: &mut D,
data_device: &ZwlrDataControlDeviceV1,
event: Event,
data: &U,
conn: &Connection,
qh: &QueueHandle<D>,
) {
let data = data.data_control_device_data();
let inner = lock!(data.inner);
match event {
Event::DataOffer { id } => {
// XXX Drop done here to prevent Mutex deadlocks.S
lock!(inner.undetermined_offers).push(id.clone());
let data = id
.data::<V>()
.expect(ERR_WAYLAND_DATA)
.data_control_offer_data();
data.init_undetermined_offer(&id);
// Append the data offer to our list of offers.
drop(inner);
}
Event::Selection { id } => {
let mut selection_offer = lock!(inner.selection_offer);
if let Some(offer) = id {
let mut undetermined = lock!(inner.undetermined_offers);
if let Some(i) = undetermined.iter().position(|o| o == &offer) {
undetermined.remove(i);
}
drop(undetermined);
let data = offer
.data::<V>()
.expect(ERR_WAYLAND_DATA)
.data_control_offer_data();
data.to_selection_offer();
// XXX Drop done here to prevent Mutex deadlocks.
*selection_offer = Some(offer.clone());
drop(selection_offer);
drop(inner);
state.selection(
conn,
qh,
DataControlDevice {
device: data_device.clone(),
},
);
} else {
*selection_offer = None;
}
}
Event::Finished => {
warn!("Data control offer is no longer valid, but has not been dropped by client. This could cause clipboard issues.");
}
_ => {}
}
}
}

View file

@ -1,253 +1,132 @@
use super::device::{DataControlDevice, DataControlDeviceEvent};
use super::source::DataControlSource;
use smithay_client_toolkit::data_device::WritePipe;
use smithay_client_toolkit::environment::{Environment, GlobalHandler};
use smithay_client_toolkit::seat::{SeatHandling, SeatListener};
use smithay_client_toolkit::MissingGlobal;
use std::cell::RefCell;
use std::rc::{self, Rc};
use tracing::warn;
use wayland_client::protocol::wl_registry::WlRegistry;
use super::device::{DataControlDevice, DataControlDeviceData, DataControlDeviceDataExt};
use super::offer::DataControlOfferData;
use super::source::{CopyPasteSource, DataControlSourceData, DataControlSourceDataExt};
use smithay_client_toolkit::error::GlobalError;
use smithay_client_toolkit::globals::{GlobalData, ProvidesBoundGlobal};
use std::marker::PhantomData;
use tracing::debug;
use wayland_client::globals::{BindError, GlobalList};
use wayland_client::protocol::wl_seat::WlSeat;
use wayland_client::{Attached, DispatchData};
use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_control_manager_v1::ZwlrDataControlManagerV1;
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle};
use wayland_protocols_wlr::data_control::v1::client::{
zwlr_data_control_device_v1::ZwlrDataControlDeviceV1,
zwlr_data_control_manager_v1::ZwlrDataControlManagerV1,
zwlr_data_control_source_v1::ZwlrDataControlSourceV1,
};
enum DataControlDeviceHandlerInner {
Ready {
manager: Attached<ZwlrDataControlManagerV1>,
devices: Vec<(WlSeat, DataControlDevice)>,
status_listeners: Rc<RefCell<Vec<rc::Weak<RefCell<DataControlDeviceStatusCallback>>>>>,
},
Pending {
seats: Vec<WlSeat>,
status_listeners: Rc<RefCell<Vec<rc::Weak<RefCell<DataControlDeviceStatusCallback>>>>>,
},
pub struct DataControlDeviceManagerState<V = DataControlOfferData> {
manager: ZwlrDataControlManagerV1,
_phantom: PhantomData<V>,
}
impl DataControlDeviceHandlerInner {
fn init_manager(&mut self, manager: Attached<ZwlrDataControlManagerV1>) {
let (seats, status_listeners) = if let Self::Pending {
seats,
status_listeners,
} = self
{
(std::mem::take(seats), status_listeners.clone())
} else {
warn!("Ignoring second zwlr_data_control_manager_v1");
return;
};
let mut devices = Vec::new();
for seat in seats {
let my_seat = seat.clone();
let status_listeners = status_listeners.clone();
let device =
DataControlDevice::init_for_seat(&manager, &seat, move |event, dispatch_data| {
notify_status_listeners(&my_seat, &event, dispatch_data, &status_listeners);
});
devices.push((seat.clone(), device));
}
*self = Self::Ready {
impl DataControlDeviceManagerState {
pub fn bind<State>(globals: &GlobalList, qh: &QueueHandle<State>) -> Result<Self, BindError>
where
State: Dispatch<ZwlrDataControlManagerV1, GlobalData, State> + 'static,
{
let manager = globals.bind(qh, 1..=2, GlobalData)?;
debug!("Bound to ZwlDataControlManagerV1 global");
Ok(Self {
manager,
devices,
status_listeners,
};
}
fn get_manager(&self) -> Option<Attached<ZwlrDataControlManagerV1>> {
match self {
Self::Ready { manager, .. } => Some(manager.clone()),
Self::Pending { .. } => None,
}
}
fn new_seat(&mut self, seat: &WlSeat) {
match self {
Self::Ready {
manager,
devices,
status_listeners,
} => {
if devices.iter().any(|(s, _)| s == seat) {
// the seat already exists, nothing to do
return;
}
let my_seat = seat.clone();
let status_listeners = status_listeners.clone();
let device =
DataControlDevice::init_for_seat(manager, seat, move |event, dispatch_data| {
notify_status_listeners(&my_seat, &event, dispatch_data, &status_listeners);
});
devices.push((seat.clone(), device));
}
Self::Pending { seats, .. } => {
seats.push(seat.clone());
}
}
}
fn remove_seat(&mut self, seat: &WlSeat) {
match self {
Self::Ready { devices, .. } => devices.retain(|(s, _)| s != seat),
Self::Pending { seats, .. } => seats.retain(|s| s != seat),
}
}
fn create_source<F>(&self, mime_types: Vec<String>, callback: F) -> Option<DataControlSource>
where
F: FnMut(String, WritePipe, DispatchData) + 'static,
{
match self {
Self::Ready { manager, .. } => {
let source = DataControlSource::new(manager, mime_types, callback);
Some(source)
}
Self::Pending { .. } => None,
}
}
fn with_device<F>(&self, seat: &WlSeat, f: F) -> Result<(), MissingGlobal>
where
F: FnOnce(&DataControlDevice),
{
match self {
Self::Ready { devices, .. } => {
let device = devices
.iter()
.find_map(|(s, device)| if s == seat { Some(device) } else { None });
device.map_or(Err(MissingGlobal), |device| {
f(device);
Ok(())
})
}
Self::Pending { .. } => Err(MissingGlobal),
}
}
}
pub struct DataControlDeviceHandler {
inner: Rc<RefCell<DataControlDeviceHandlerInner>>,
status_listeners: Rc<RefCell<Vec<rc::Weak<RefCell<DataControlDeviceStatusCallback>>>>>,
_seat_listener: SeatListener,
}
impl DataControlDeviceHandler {
pub fn init<S>(seat_handler: &mut S) -> Self
where
S: SeatHandling,
{
let status_listeners = Rc::new(RefCell::new(Vec::new()));
let inner = Rc::new(RefCell::new(DataControlDeviceHandlerInner::Pending {
seats: Vec::new(),
status_listeners: status_listeners.clone(),
}));
let seat_inner = inner.clone();
let seat_listener = seat_handler.listen(move |seat, seat_data, _| {
if seat_data.defunct {
seat_inner.borrow_mut().remove_seat(&seat);
} else {
seat_inner.borrow_mut().new_seat(&seat);
}
});
Self {
inner,
_seat_listener: seat_listener,
status_listeners,
}
}
}
impl GlobalHandler<ZwlrDataControlManagerV1> for DataControlDeviceHandler {
fn created(
&mut self,
registry: Attached<WlRegistry>,
id: u32,
version: u32,
_ddata: DispatchData,
) {
// data control manager is supported until version 2
let version = std::cmp::min(version, 2);
let manager = registry.bind::<ZwlrDataControlManagerV1>(version, id);
self.inner.borrow_mut().init_manager((*manager).clone());
}
fn get(&self) -> Option<Attached<ZwlrDataControlManagerV1>> {
RefCell::borrow(&self.inner).get_manager()
}
}
type DataControlDeviceStatusCallback =
dyn FnMut(WlSeat, DataControlDeviceEvent, DispatchData) + 'static;
/// Notifies the callbacks of an event on the data device
fn notify_status_listeners(
seat: &WlSeat,
event: &DataControlDeviceEvent,
mut ddata: DispatchData,
listeners: &RefCell<Vec<rc::Weak<RefCell<DataControlDeviceStatusCallback>>>>,
) {
listeners.borrow_mut().retain(|lst| {
rc::Weak::upgrade(lst).map_or(false, |cb| {
(cb.borrow_mut())(seat.clone(), event.clone(), ddata.reborrow());
true
_phantom: PhantomData,
})
});
}
pub struct DataControlDeviceStatusListener {
_cb: Rc<RefCell<DataControlDeviceStatusCallback>>,
}
pub trait DataControlDeviceHandling {
fn listen<F>(&mut self, f: F) -> DataControlDeviceStatusListener
where
F: FnMut(WlSeat, DataControlDeviceEvent, DispatchData) + 'static;
fn with_data_control_device<F>(&self, seat: &WlSeat, f: F) -> Result<(), MissingGlobal>
where
F: FnOnce(&DataControlDevice);
fn create_source<F>(&self, mime_types: Vec<String>, callback: F) -> Option<DataControlSource>
where
F: FnMut(String, WritePipe, DispatchData) + 'static;
}
impl DataControlDeviceHandling for DataControlDeviceHandler {
fn listen<F>(&mut self, f: F) -> DataControlDeviceStatusListener
where
F: FnMut(WlSeat, DataControlDeviceEvent, DispatchData) + 'static,
{
let rc = Rc::new(RefCell::new(f)) as Rc<_>;
self.status_listeners.borrow_mut().push(Rc::downgrade(&rc));
DataControlDeviceStatusListener { _cb: rc }
}
fn with_data_control_device<F>(&self, seat: &WlSeat, f: F) -> Result<(), MissingGlobal>
/// creates a data source for copy paste
pub fn create_copy_paste_source<'s, D, I>(
&self,
qh: &QueueHandle<D>,
mime_types: I,
) -> CopyPasteSource
where
F: FnOnce(&DataControlDevice),
D: Dispatch<ZwlrDataControlSourceV1, DataControlSourceData> + 'static,
I: IntoIterator<Item = &'s str>,
{
RefCell::borrow(&self.inner).with_device(seat, f)
CopyPasteSource {
inner: self.create_data_control_source(qh, mime_types),
}
}
fn create_source<F>(&self, mime_types: Vec<String>, callback: F) -> Option<DataControlSource>
/// creates a data source
fn create_data_control_source<'s, D, I>(
&self,
qh: &QueueHandle<D>,
mime_types: I,
) -> ZwlrDataControlSourceV1
where
F: FnMut(String, WritePipe, DispatchData) + 'static,
D: Dispatch<ZwlrDataControlSourceV1, DataControlSourceData> + 'static,
I: IntoIterator<Item = &'s str>,
{
RefCell::borrow(&self.inner).create_source(mime_types, callback)
let source =
self.create_data_control_source_with_data(qh, DataControlSourceData::default());
for mime in mime_types {
source.offer(mime.to_string());
}
source
}
/// create a new data source for a given seat with some user data
pub fn create_data_control_source_with_data<D, U>(
&self,
qh: &QueueHandle<D>,
data: U,
) -> ZwlrDataControlSourceV1
where
D: Dispatch<ZwlrDataControlSourceV1, U> + 'static,
U: DataControlSourceDataExt + 'static,
{
self.manager.create_data_source(qh, data)
}
/// create a new data device for a given seat
pub fn get_data_device<D>(&self, qh: &QueueHandle<D>, seat: &WlSeat) -> DataControlDevice
where
D: Dispatch<ZwlrDataControlDeviceV1, DataControlDeviceData> + 'static,
{
DataControlDevice {
device: self.get_data_control_device_with_data(
qh,
seat,
DataControlDeviceData::default(),
),
}
}
/// create a new data device for a given seat with some user data
pub fn get_data_control_device_with_data<D, U>(
&self,
qh: &QueueHandle<D>,
seat: &WlSeat,
data: U,
) -> ZwlrDataControlDeviceV1
where
D: Dispatch<ZwlrDataControlDeviceV1, U> + 'static,
U: DataControlDeviceDataExt + 'static,
{
self.manager.get_data_device(seat, qh, data)
}
}
pub fn listen_to_devices<E, F>(env: &Environment<E>, f: F) -> DataControlDeviceStatusListener
impl ProvidesBoundGlobal<ZwlrDataControlManagerV1, 2> for DataControlDeviceManagerState {
fn bound_global(&self) -> Result<ZwlrDataControlManagerV1, GlobalError> {
Ok(self.manager.clone())
}
}
impl<D> Dispatch<ZwlrDataControlManagerV1, GlobalData, D> for DataControlDeviceManagerState
where
E: DataControlDeviceHandling,
F: FnMut(WlSeat, DataControlDeviceEvent, DispatchData) + 'static,
D: Dispatch<ZwlrDataControlManagerV1, GlobalData>,
{
env.with_inner(move |inner| DataControlDeviceHandling::listen(inner, f))
fn event(
_state: &mut D,
_proxy: &ZwlrDataControlManagerV1,
_event: <ZwlrDataControlManagerV1 as Proxy>::Event,
_data: &GlobalData,
_conn: &Connection,
_qhandle: &QueueHandle<D>,
) {
unreachable!()
}
}

View file

@ -3,28 +3,25 @@ pub mod manager;
pub mod offer;
pub mod source;
use super::Env;
use crate::clients::wayland::DData;
use crate::send;
use color_eyre::Report;
use device::{DataControlDevice, DataControlDeviceEvent};
use self::device::{DataControlDeviceDataExt, DataControlDeviceHandler};
use self::offer::{DataControlDeviceOffer, DataControlOfferHandler, SelectionOffer};
use self::source::DataControlSourceHandler;
use crate::clients::wayland::Environment;
use crate::{lock, send};
use device::DataControlDevice;
use glib::Bytes;
use manager::{DataControlDeviceHandling, DataControlDeviceStatusListener};
use smithay_client_toolkit::data_device::WritePipe;
use smithay_client_toolkit::environment::Environment;
use smithay_client_toolkit::reexports::calloop::LoopHandle;
use smithay_client_toolkit::MissingGlobal;
use source::DataControlSource;
use smithay_client_toolkit::data_device_manager::WritePipe;
use smithay_client_toolkit::reexports::calloop::RegistrationToken;
use std::fmt::{Debug, Formatter};
use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::os::fd::OwnedFd;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::UNIX_EPOCH;
use tokio::sync::broadcast;
use tracing::{debug, error, trace};
use wayland_client::protocol::wl_seat::WlSeat;
use wayland_client::DispatchData;
use tracing::{debug, error};
use wayland_client::{Connection, QueueHandle};
use wayland_protocols_wlr::data_control::v1::client::zwlr_data_control_source_v1::ZwlrDataControlSourceV1;
static COUNTER: AtomicUsize = AtomicUsize::new(1);
@ -34,6 +31,11 @@ fn get_id() -> usize {
COUNTER.fetch_add(1, Ordering::Relaxed)
}
pub struct SelectionOfferItem {
offer: SelectionOffer,
token: Option<RegistrationToken>,
}
#[derive(Debug, Clone, Eq)]
pub struct ClipboardItem {
pub id: usize,
@ -47,77 +49,27 @@ impl PartialEq<Self> for ClipboardItem {
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Clone, PartialEq, Eq)]
pub enum ClipboardValue {
Text(String),
Image(Bytes),
Other,
}
impl DataControlDeviceHandling for Env {
fn listen<F>(&mut self, f: F) -> DataControlDeviceStatusListener
where
F: FnMut(WlSeat, DataControlDeviceEvent, DispatchData) + 'static,
{
self.data_control_device.listen(f)
}
fn with_data_control_device<F>(&self, seat: &WlSeat, f: F) -> Result<(), MissingGlobal>
where
F: FnOnce(&DataControlDevice),
{
self.data_control_device.with_data_control_device(seat, f)
}
fn create_source<F>(&self, mime_types: Vec<String>, callback: F) -> Option<DataControlSource>
where
F: FnMut(String, WritePipe, DispatchData) + 'static,
{
self.data_control_device.create_source(mime_types, callback)
}
}
pub fn copy_to_clipboard<E>(
env: &Environment<E>,
seat: &WlSeat,
item: &ClipboardItem,
) -> Result<(), MissingGlobal>
where
E: DataControlDeviceHandling,
{
debug!("Copying item with id {} [{}]", item.id, item.mime_type);
trace!("Copying: {item:?}");
let item = item.clone();
env.with_inner(|env| {
let mime_types = vec![INTERNAL_MIME_TYPE.to_string(), item.mime_type];
let source = env.create_source(mime_types, move |mime_type, mut pipe, _ddata| {
debug!(
"Triggering source callback for item with id {} [{}]",
item.id, mime_type
);
// FIXME: Not working for large (buffered) values in xwayland
let bytes = match &item.value {
ClipboardValue::Text(text) => text.as_bytes(),
ClipboardValue::Image(bytes) => bytes.as_ref(),
ClipboardValue::Other => panic!(
"{:?}",
io::Error::new(
io::ErrorKind::Other,
"Attempted to copy unsupported mime type",
)
),
};
if let Err(err) = pipe.write_all(bytes) {
error!("{err:?}");
impl Debug for ClipboardValue {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Text(text) => text.clone(),
Self::Image(bytes) => {
format!("[{} Bytes]", bytes.len())
}
Self::Other => "[Unknown]".to_string(),
}
});
env.with_data_control_device(seat, |device| device.set_selection(&source))
})
)
}
}
#[derive(Debug)]
@ -133,126 +85,230 @@ enum MimeTypeCategory {
}
impl MimeType {
fn parse(mime_types: &[String]) -> Option<Self> {
mime_types
.iter()
.map(|s| s.to_lowercase())
.find_map(|mime_type| match mime_type.as_str() {
"text"
| "string"
| "utf8_string"
| "text/plain"
| "text/plain;charset=utf-8"
| "text/plain;charset=iso-8859-1"
| "text/plain;charset=us-ascii"
| "text/plain;charset=unicode" => Some(Self {
value: mime_type,
category: MimeTypeCategory::Text,
}),
"image/png" | "image/jpg" | "image/jpeg" | "image/tiff" | "image/bmp"
| "image/x-bmp" | "image/icon" => Some(Self {
value: mime_type,
category: MimeTypeCategory::Image,
}),
_ => None,
})
fn parse(mime_type: &str) -> Option<Self> {
match mime_type.to_lowercase().as_str() {
"text"
| "string"
| "utf8_string"
| "text/plain"
| "text/plain;charset=utf-8"
| "text/plain;charset=iso-8859-1"
| "text/plain;charset=us-ascii"
| "text/plain;charset=unicode" => Some(Self {
value: mime_type.to_string(),
category: MimeTypeCategory::Text,
}),
"image/png" | "image/jpg" | "image/jpeg" | "image/tiff" | "image/bmp"
| "image/x-bmp" | "image/icon" => Some(Self {
value: mime_type.to_string(),
category: MimeTypeCategory::Image,
}),
_ => None,
}
}
fn parse_multiple(mime_types: &[String]) -> Option<Self> {
mime_types.iter().find_map(|mime| Self::parse(mime))
}
}
pub fn receive_offer(
event: DataControlDeviceEvent,
handle: &LoopHandle<DData>,
tx: broadcast::Sender<Arc<ClipboardItem>>,
mut ddata: DispatchData,
) {
let timestamp = std::time::SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Could not get epoch, system time is probably very wrong")
.as_nanos();
impl Environment {
pub fn copy_to_clipboard(&mut self, item: Arc<ClipboardItem>, qh: &QueueHandle<Self>) {
debug!("Copying item to clipboard");
let offer = event.0;
// TODO: Proper device tracking
let device = self.data_control_devices.first();
if let Some(device) = device {
let source = self
.data_control_device_manager_state
.create_copy_paste_source(qh, [item.mime_type.as_str()]);
let ddata = ddata
.get::<DData>()
.expect("Expected dispatch data to exist");
source.set_selection(&device.device);
self.copy_paste_sources.push(source);
let handle2 = handle.clone();
lock!(self.clipboard).replace(item);
}
}
let res = offer.with_mime_types(|mime_types| {
debug!("Offer mime types: {mime_types:?}");
fn read_file(mime_type: &MimeType, file: &mut File) -> io::Result<ClipboardItem> {
let value = match mime_type.category {
MimeTypeCategory::Text => {
let mut txt = String::new();
file.read_to_string(&mut txt)?;
ClipboardValue::Text(txt)
}
MimeTypeCategory::Image => {
let mut bytes = vec![];
file.read_to_end(&mut bytes)?;
let bytes = Bytes::from(&bytes);
ClipboardValue::Image(bytes)
}
};
Ok(ClipboardItem {
id: get_id(),
value,
mime_type: mime_type.value.clone(),
})
}
}
impl DataControlDeviceHandler for Environment {
fn selection(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
data_device: DataControlDevice,
) {
debug!("Handler received selection event");
let mime_types = data_device.selection_mime_types();
if mime_types.contains(&INTERNAL_MIME_TYPE.to_string()) {
debug!("Skipping value provided by bar");
return Ok(());
return;
}
let mime_type = MimeType::parse(mime_types);
debug!("Detected mime type: {mime_type:?}");
if let Some(offer) = data_device.selection_offer() {
self.selection_offers
.push(SelectionOfferItem { offer, token: None });
match mime_type {
Some(mime_type) => {
debug!("[{timestamp}] Sending clipboard read request ({mime_type:?})");
let read_pipe = offer.receive(mime_type.value.clone())?;
let source = handle.insert_source(read_pipe, move |(), file, ddata| {
debug!(
"[{timestamp}] Reading clipboard contents ({:?})",
&mime_type.category
);
match read_file(&mime_type, file) {
Ok(item) => {
send!(tx, Arc::new(item));
}
Err(err) => error!("{err:?}"),
}
let cur_offer = self
.selection_offers
.last_mut()
.expect("Failed to get current offer");
if let Some(src) = ddata.offer_tokens.remove(&timestamp) {
handle2.remove(src);
}
})?;
ddata.offer_tokens.insert(timestamp, source);
}
None => {
let Some(mime_type) = MimeType::parse_multiple(&mime_types) else {
lock!(self.clipboard).take();
// send an event so the clipboard module is aware it's changed
send!(
tx,
self.clipboard_tx,
Arc::new(ClipboardItem {
id: usize::MAX,
mime_type: String::new(),
value: ClipboardValue::Other
})
);
return;
};
if let Ok(read_pipe) = cur_offer.offer.receive(mime_type.value.clone()) {
let offer_clone = cur_offer.offer.clone();
let tx = self.clipboard_tx.clone();
let clipboard = self.clipboard.clone();
let token = self
.loop_handle
.insert_source(read_pipe, move |_, file, state| {
let item = state
.selection_offers
.iter()
.position(|o| o.offer == offer_clone)
.map(|p| state.selection_offers.remove(p))
.expect("Failed to find selection offer item");
match Self::read_file(&mime_type, file) {
Ok(item) => {
let item = Arc::new(item);
lock!(clipboard).replace(item.clone());
send!(tx, item);
}
Err(err) => error!("{err:?}"),
}
state
.loop_handle
.remove(item.token.expect("Missing item token"));
});
match token {
Ok(token) => {
cur_offer.token.replace(token);
}
Err(err) => error!("{err:?}"),
}
}
}
Ok::<(), Report>(())
});
if let Err(err) = res {
error!("{err:?}");
}
}
fn read_file(mime_type: &MimeType, file: &mut File) -> io::Result<ClipboardItem> {
let value = match mime_type.category {
MimeTypeCategory::Text => {
let mut txt = String::new();
file.read_to_string(&mut txt)?;
ClipboardValue::Text(txt)
}
MimeTypeCategory::Image => {
let mut bytes = vec![];
file.read_to_end(&mut bytes)?;
let bytes = Bytes::from(&bytes);
ClipboardValue::Image(bytes)
}
};
Ok(ClipboardItem {
id: get_id(),
value,
mime_type: mime_type.value.clone(),
})
impl DataControlOfferHandler for Environment {
fn offer(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_offer: &mut DataControlDeviceOffer,
_mime_type: String,
) {
debug!("Handler received offer");
}
}
impl DataControlSourceHandler for Environment {
fn accept_mime(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_source: &ZwlrDataControlSourceV1,
mime: Option<String>,
) {
debug!("Accepted mime type: {mime:?}");
}
fn send_request(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &ZwlrDataControlSourceV1,
mime: String,
write_pipe: WritePipe,
) {
debug!("Handler received source send request event");
if let Some(item) = lock!(self.clipboard).clone() {
let fd = OwnedFd::from(write_pipe);
if let Some(_source) = self
.copy_paste_sources
.iter_mut()
.find(|s| s.inner() == source && MimeType::parse(&mime).is_some())
{
let mut file = File::from(fd);
// FIXME: Not working for large (buffered) values in xwayland
// Might be something strange going on with byte count?
let bytes = match &item.value {
ClipboardValue::Text(text) => text.as_bytes(),
ClipboardValue::Image(bytes) => bytes.as_ref(),
ClipboardValue::Other => panic!(
"{:?}",
io::Error::new(
io::ErrorKind::Other,
"Attempted to copy unsupported mime type",
)
),
};
if let Err(err) = file.write_all(bytes) {
error!("{err:?}");
}
}
}
}
fn cancelled(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
source: &ZwlrDataControlSourceV1,
) {
debug!("Handler received source cancelled event");
self.copy_paste_sources
.iter()
.position(|s| s.inner() == source)
.map(|pos| self.copy_paste_sources.remove(pos));
source.destroy();
}
}

View file

@ -1,74 +1,182 @@
use super::manager::DataControlDeviceManagerState;
use crate::lock;
use nix::fcntl::OFlag;
use nix::unistd::{close, pipe2};
use smithay_client_toolkit::data_device::ReadPipe;
use std::io;
use smithay_client_toolkit::data_device_manager::data_offer::DataOfferError;
use smithay_client_toolkit::data_device_manager::ReadPipe;
use std::ops::DerefMut;
use std::os::fd::FromRawFd;
use std::sync::{Arc, Mutex};
use tracing::warn;
use wayland_client::Main;
use wayland_protocols::wlr::unstable::data_control::v1::client::zwlr_data_control_offer_v1::{
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle};
use wayland_protocols_wlr::data_control::v1::client::zwlr_data_control_offer_v1::{
Event, ZwlrDataControlOfferV1,
};
#[derive(Debug, Clone)]
struct Inner {
mime_types: Vec<String>,
pub struct UndeterminedOffer {
pub(crate) data_offer: Option<ZwlrDataControlOfferV1>,
}
impl PartialEq for UndeterminedOffer {
fn eq(&self, other: &Self) -> bool {
self.data_offer == other.data_offer
}
}
#[derive(Debug, Clone)]
pub struct DataControlOffer {
inner: Arc<Mutex<Inner>>,
pub(crate) offer: ZwlrDataControlOfferV1,
pub struct SelectionOffer {
pub data_offer: ZwlrDataControlOfferV1,
}
impl DataControlOffer {
pub(crate) fn new(offer: &Main<ZwlrDataControlOfferV1>) -> Self {
let inner = Arc::new(Mutex::new(Inner {
mime_types: Vec::new(),
}));
{
let inner = inner.clone();
offer.quick_assign(move |_, event, _| {
let mut inner = lock!(inner);
if let Event::Offer { mime_type } = event {
inner.mime_types.push(mime_type);
}
});
}
Self {
offer: offer.detach(),
inner,
}
}
pub fn with_mime_types<F, T>(&self, f: F) -> T
where
F: FnOnce(&[String]) -> T,
{
let inner = lock!(self.inner);
f(&inner.mime_types)
}
pub fn receive(&self, mime_type: String) -> io::Result<ReadPipe> {
// create a pipe
let (readfd, writefd) = pipe2(OFlag::O_CLOEXEC)?;
self.offer.receive(mime_type, writefd);
if let Err(err) = close(writefd) {
warn!("Failed to close write pipe: {}", err);
}
Ok(unsafe { FromRawFd::from_raw_fd(readfd) })
impl PartialEq for SelectionOffer {
fn eq(&self, other: &Self) -> bool {
self.data_offer == other.data_offer
}
}
impl Drop for DataControlOffer {
fn drop(&mut self) {
self.offer.destroy();
impl SelectionOffer {
pub fn receive(&self, mime_type: String) -> Result<ReadPipe, DataOfferError> {
receive(&self.data_offer, mime_type).map_err(DataOfferError::Io)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum DataControlDeviceOffer {
Selection(SelectionOffer),
Undetermined(UndeterminedOffer),
}
impl Default for DataControlDeviceOffer {
fn default() -> Self {
Self::Undetermined(UndeterminedOffer { data_offer: None })
}
}
#[derive(Debug, Default)]
pub struct DataControlOfferData {
pub(crate) inner: Arc<Mutex<DataControlDeviceOfferInner>>,
}
#[derive(Debug, Default)]
pub struct DataControlDeviceOfferInner {
pub(crate) offer: DataControlDeviceOffer,
pub(crate) mime_types: Vec<String>,
}
impl DataControlOfferData {
pub(crate) fn push_mime_type(&self, mime_type: String) {
lock!(self.inner).mime_types.push(mime_type);
}
pub(crate) fn to_selection_offer(&self) {
let mut inner = lock!(self.inner);
match &mut inner.deref_mut().offer {
DataControlDeviceOffer::Selection(_) => {}
DataControlDeviceOffer::Undetermined(o) => {
inner.offer = DataControlDeviceOffer::Selection(SelectionOffer {
data_offer: o.data_offer.clone().expect("Missing current data offer"),
});
}
}
}
pub(crate) fn init_undetermined_offer(&self, offer: &ZwlrDataControlOfferV1) {
let mut inner = lock!(self.inner);
match &mut inner.deref_mut().offer {
DataControlDeviceOffer::Selection(_) => {
inner.offer = DataControlDeviceOffer::Undetermined(UndeterminedOffer {
data_offer: Some(offer.clone()),
});
}
DataControlDeviceOffer::Undetermined(o) => {
o.data_offer = Some(offer.clone());
}
}
}
}
pub trait DataControlOfferDataExt {
fn data_control_offer_data(&self) -> &DataControlOfferData;
fn mime_types(&self) -> Vec<String>;
fn as_selection_offer(&self) -> Option<SelectionOffer>;
}
impl DataControlOfferDataExt for DataControlOfferData {
fn data_control_offer_data(&self) -> &DataControlOfferData {
self
}
fn mime_types(&self) -> Vec<String> {
lock!(self.inner).mime_types.clone()
}
fn as_selection_offer(&self) -> Option<SelectionOffer> {
match &lock!(self.inner).offer {
DataControlDeviceOffer::Selection(o) => Some(o.clone()),
DataControlDeviceOffer::Undetermined(_) => None,
}
}
}
/// Handler trait for `DataOffer` events.
///
/// The functions defined in this trait are called as `DataOffer` events are received from the compositor.
pub trait DataControlOfferHandler: Sized {
// Called for each mime type the data offer advertises.
fn offer(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
offer: &mut DataControlDeviceOffer,
mime_type: String,
);
}
impl<D, U> Dispatch<ZwlrDataControlOfferV1, U, D> for DataControlDeviceManagerState
where
D: Dispatch<ZwlrDataControlOfferV1, U> + DataControlOfferHandler,
U: DataControlOfferDataExt,
{
fn event(
state: &mut D,
_offer: &ZwlrDataControlOfferV1,
event: <ZwlrDataControlOfferV1 as Proxy>::Event,
data: &U,
conn: &Connection,
qh: &QueueHandle<D>,
) {
let data = data.data_control_offer_data();
if let Event::Offer { mime_type } = event {
data.push_mime_type(mime_type.clone());
state.offer(conn, qh, &mut lock!(data.inner).offer, mime_type);
}
}
}
/// Request to receive the data of a given mime type.
///
/// You can do this several times, as a reaction to motion of
/// the dnd cursor, or to inspect the data in order to choose your
/// response.
///
/// Note that you should *not* read the contents right away in a
/// blocking way, as you may deadlock your application doing so.
/// At least make sure you flush your events to the server before
/// doing so.
///
/// Fails if too many file descriptors were already open and a pipe
/// could not be created.
pub fn receive(offer: &ZwlrDataControlOfferV1, mime_type: String) -> std::io::Result<ReadPipe> {
// create a pipe
let (readfd, writefd) = pipe2(OFlag::O_CLOEXEC)?;
offer.receive(mime_type, writefd);
if let Err(err) = close(writefd) {
warn!("Failed to close write pipe: {}", err);
}
Ok(unsafe { FromRawFd::from_raw_fd(readfd) })
}

View file

@ -1,54 +1,101 @@
use smithay_client_toolkit::data_device::WritePipe;
use std::os::fd::FromRawFd;
use wayland_client::{Attached, DispatchData};
use wayland_protocols::wlr::unstable::data_control::v1::client::{
zwlr_data_control_manager_v1::ZwlrDataControlManagerV1,
zwlr_data_control_source_v1::{Event, ZwlrDataControlSourceV1},
use super::device::DataControlDevice;
use super::manager::DataControlDeviceManagerState;
use smithay_client_toolkit::data_device_manager::WritePipe;
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle};
use wayland_protocols_wlr::data_control::v1::client::zwlr_data_control_source_v1::{
Event, ZwlrDataControlSourceV1,
};
fn data_control_source_impl<F>(
source: &ZwlrDataControlSourceV1,
event: Event,
implem: &mut F,
ddata: DispatchData,
) where
F: FnMut(String, WritePipe, DispatchData),
#[derive(Debug, Default)]
pub struct DataControlSourceData {}
pub trait DataControlSourceDataExt: Send + Sync {
fn data_source_data(&self) -> &DataControlSourceData;
}
impl DataControlSourceDataExt for DataControlSourceData {
fn data_source_data(&self) -> &DataControlSourceData {
self
}
}
/// Handler trait for `DataSource` events.
///
/// The functions defined in this trait are called as `DataSource` events are received from the compositor.
pub trait DataControlSourceHandler: Sized {
/// This may be called multiple times, once for each accepted mime type from the destination, if any.
fn accept_mime(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
source: &ZwlrDataControlSourceV1,
mime: Option<String>,
);
/// The client has requested the data for this source to be sent.
/// Send the data, then close the fd.
fn send_request(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
source: &ZwlrDataControlSourceV1,
mime: String,
fd: WritePipe,
);
/// The data source is no longer valid
/// Cleanup & destroy this resource
fn cancelled(
&mut self,
conn: &Connection,
qh: &QueueHandle<Self>,
source: &ZwlrDataControlSourceV1,
);
}
impl<D, U> Dispatch<ZwlrDataControlSourceV1, U, D> for DataControlDeviceManagerState
where
D: Dispatch<ZwlrDataControlSourceV1, U> + DataControlSourceHandler,
U: DataControlSourceDataExt,
{
match event {
Event::Send { mime_type, fd } => {
let pipe = unsafe { FromRawFd::from_raw_fd(fd) };
implem(mime_type, pipe, ddata);
}
Event::Cancelled => source.destroy(),
_ => unreachable!(),
}
}
pub struct DataControlSource {
pub(crate) source: ZwlrDataControlSourceV1,
}
impl DataControlSource {
pub fn new<F>(
manager: &Attached<ZwlrDataControlManagerV1>,
mime_types: Vec<String>,
mut callback: F,
) -> Self
where
F: FnMut(String, WritePipe, DispatchData) + 'static,
{
let source = manager.create_data_source();
source.quick_assign(move |source, evt, ddata| {
data_control_source_impl(&source, evt, &mut callback, ddata);
});
for mime_type in mime_types {
source.offer(mime_type);
}
Self {
source: source.detach(),
fn event(
state: &mut D,
source: &ZwlrDataControlSourceV1,
event: <ZwlrDataControlSourceV1 as Proxy>::Event,
_data: &U,
conn: &Connection,
qh: &QueueHandle<D>,
) {
match event {
Event::Send { mime_type, fd } => {
state.send_request(conn, qh, source, mime_type, fd.into());
}
Event::Cancelled => {
state.cancelled(conn, qh, source);
}
_ => {}
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CopyPasteSource {
pub(crate) inner: ZwlrDataControlSourceV1,
}
impl CopyPasteSource {
/// Set the selection of the provided data device as a response to the event with with provided serial.
pub fn set_selection(&self, device: &DataControlDevice) {
device.device.set_selection(Some(&self.inner));
}
pub const fn inner(&self) -> &ZwlrDataControlSourceV1 {
&self.inner
}
}
impl Drop for CopyPasteSource {
fn drop(&mut self) {
self.inner.destroy();
}
}