XDND v5 source and target on an own x11rb connection (proxy window via XdndProxy), CLIPBOARD owner and reader. Wayland and X11 share one Backend trait. examples/xdnd_probe drives both directions under Xvfb. Co-Authored-By: Claude Opus 5.5 <[email protected]>
357 lines
12 KiB
Rust
357 lines
12 KiB
Rust
//! Native drag and drop and file clipboard with other apps (D-014): `wayland.rs` (D-039)
|
|
//! or `x11.rs` (XDND, CLIPBOARD), both behind `Backend`. Without a window handle
|
|
//! (screenshots) `current()` is `None` and every caller falls back to in-app behaviour.
|
|
//!
|
|
//! API: `arm` when an in-app drag starts,
|
|
//! `set_clipboard` on copy/cut, `clipboard_has_files` / `read_clipboard` on paste. Drags
|
|
//! coming in are fed to Slint's own drop handling (`process_drag_event`), so the DropZones,
|
|
//! their glow and the drop menu work as for in-app drags.
|
|
|
|
mod wayland;
|
|
mod x11;
|
|
|
|
use std::cell::RefCell;
|
|
use std::rc::Rc;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use i_slint_core::input::BackendDragEvent;
|
|
use i_slint_core::items::{AllowedDragActions, DragAction, DropEvent};
|
|
use i_slint_core::window::WindowInner;
|
|
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
|
use slint::platform::{PointerEventButton, WindowEvent};
|
|
use slint::{ComponentHandle, DataTransfer, LogicalPosition};
|
|
use tunal_core::Uri;
|
|
|
|
use crate::MainWindow;
|
|
use crate::dnd::{parse_uri_list, uri_list};
|
|
use wayland::Wayland;
|
|
use x11::X11;
|
|
|
|
pub mod mime {
|
|
pub const URI_LIST: &str = "text/uri-list";
|
|
pub const TEXT: &str = "text/plain;charset=utf-8";
|
|
pub const TEXT_PLAIN: &str = "text/plain";
|
|
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
|
/// Marks data that comes from Tunal itself.
|
|
pub const INTERNAL: &str = "application/x-tunal-uris";
|
|
}
|
|
|
|
/// From the dispatch thread to the UI thread.
|
|
pub enum Event {
|
|
/// A drag from another app (or our own system drag) moved over the window.
|
|
DragMotion {
|
|
x: f64,
|
|
y: f64,
|
|
},
|
|
/// Its `text/uri-list`, once read.
|
|
DragData(String),
|
|
DragLeave,
|
|
DragDrop,
|
|
/// An in-app drag left the window and became a system drag.
|
|
DragOutStarted {
|
|
x: f64,
|
|
y: f64,
|
|
},
|
|
DragOutFinished {
|
|
copied: bool,
|
|
},
|
|
/// Files read from the clipboard: the text and its mime type.
|
|
Clipboard(String, &'static str),
|
|
}
|
|
|
|
pub type Sink = Arc<dyn Fn(Event) + Send + Sync>;
|
|
|
|
/// Payload by mime type.
|
|
pub type Contents = Vec<(&'static str, Vec<u8>)>;
|
|
|
|
/// Premultiplied RGBA pixels.
|
|
pub struct Icon {
|
|
pub width: u32,
|
|
pub height: u32,
|
|
pub rgba: Vec<u8>,
|
|
}
|
|
|
|
/// Clipboard text and its mime type, read on a backend thread.
|
|
pub type ReadDone = Box<dyn FnOnce(String, &'static str) + Send>;
|
|
|
|
/// One windowing system's side. Positions in `Event`s are logical, relative to the window.
|
|
trait Backend {
|
|
/// An in-app drag carrying `contents` started in a window of `size` (logical).
|
|
fn arm(&self, contents: Contents, size: (f64, f64));
|
|
fn set_icon(&self, _icon: Icon) {}
|
|
/// Whether the drop target under a foreign drag takes it.
|
|
fn accept(&self, yes: bool);
|
|
fn finish_drop(&self);
|
|
fn set_selection(&self, contents: Contents);
|
|
fn selection_has_files(&self) -> bool;
|
|
fn read_selection(&self, done: ReadDone) -> bool;
|
|
}
|
|
|
|
/// Runs with the files read from the clipboard and whether they were cut.
|
|
type PasteDone = Box<dyn FnOnce(Vec<Uri>, bool)>;
|
|
|
|
thread_local! {
|
|
static CURRENT: RefCell<Option<Rc<Native>>> = const { RefCell::new(None) };
|
|
}
|
|
|
|
/// The native backend of this window, once attached.
|
|
pub fn current() -> Option<Rc<Native>> {
|
|
CURRENT.with(|c| c.borrow().clone())
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Incoming {
|
|
data: Option<DataTransfer>,
|
|
position: LogicalPosition,
|
|
hovering: bool,
|
|
/// Dropped before its data was read: drop once it is.
|
|
drop_pending: bool,
|
|
}
|
|
|
|
pub struct Native {
|
|
ui: slint::Weak<MainWindow>,
|
|
backend: Box<dyn Backend>,
|
|
incoming: RefCell<Incoming>,
|
|
paste: RefCell<Option<PasteDone>>,
|
|
}
|
|
|
|
/// Attaches once the window exists (its handle comes after the first event loop turns).
|
|
pub fn attach_later(ui: &MainWindow) {
|
|
fn attempt(ui: slint::Weak<MainWindow>, tries: u32) {
|
|
let Some(window) = ui.upgrade() else {
|
|
return;
|
|
};
|
|
let handle = window.window().window_handle();
|
|
let raw = handle
|
|
.display_handle()
|
|
.ok()
|
|
.zip(handle.window_handle().ok())
|
|
.map(|(d, w)| (d.as_raw(), w.as_raw()));
|
|
let Some((display, raw_window)) = raw else {
|
|
if tries > 0 {
|
|
slint::Timer::single_shot(Duration::from_millis(100), move || {
|
|
attempt(ui, tries - 1)
|
|
});
|
|
}
|
|
return;
|
|
};
|
|
let sink: Sink = Arc::new(|event| {
|
|
let _ = slint::invoke_from_event_loop(move || {
|
|
if let Some(native) = current() {
|
|
native.handle(event);
|
|
}
|
|
});
|
|
});
|
|
let scale = f64::from(window.window().scale_factor());
|
|
let backend: Box<dyn Backend> = match Wayland::attach(display, raw_window, sink.clone()) {
|
|
Some(w) => Box::new(w),
|
|
None => match X11::attach(raw_window, scale, sink) {
|
|
Some(x) => Box::new(x),
|
|
None => return,
|
|
},
|
|
};
|
|
let native = Rc::new(Native {
|
|
ui: ui.clone(),
|
|
backend,
|
|
incoming: RefCell::new(Incoming::default()),
|
|
paste: RefCell::new(None),
|
|
});
|
|
CURRENT.with(|c| *c.borrow_mut() = Some(native));
|
|
}
|
|
let ui = ui.as_weak();
|
|
slint::Timer::single_shot(Duration::ZERO, move || attempt(ui, 20));
|
|
}
|
|
|
|
/// What we hand out for `uris`: URI list, plain paths and our own marker; with `cut` (a
|
|
/// clipboard copy or cut) also the copied-files list file managers read.
|
|
fn contents(uris: &[Uri], cut: Option<bool>) -> Contents {
|
|
let list = uri_list(uris).into_bytes();
|
|
let text = uris
|
|
.iter()
|
|
.map(|u| {
|
|
u.to_path()
|
|
.map_or_else(|| u.to_string(), |p| p.to_string_lossy().into_owned())
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
.into_bytes();
|
|
let mut c = vec![
|
|
(mime::URI_LIST, list.clone()),
|
|
(mime::TEXT, text.clone()),
|
|
(mime::TEXT_PLAIN, text),
|
|
(mime::INTERNAL, list),
|
|
];
|
|
if let Some(cut) = cut {
|
|
let mut copied = String::from(if cut { "cut" } else { "copy" });
|
|
for u in uris {
|
|
copied.push('\n');
|
|
copied.push_str(&u.to_string());
|
|
}
|
|
c.push((mime::GNOME_COPIED, copied.into_bytes()));
|
|
}
|
|
c
|
|
}
|
|
|
|
/// The files of a clipboard text, and whether they were cut.
|
|
fn parse_clipboard(text: &str, mime: &str) -> (Vec<Uri>, bool) {
|
|
if mime == mime::GNOME_COPIED {
|
|
let mut lines = text.lines();
|
|
let cut = lines.next().is_some_and(|l| l.trim() == "cut");
|
|
let uris = lines.filter_map(|l| Uri::parse(l.trim())).collect();
|
|
(uris, cut)
|
|
} else {
|
|
(parse_uri_list(text), false)
|
|
}
|
|
}
|
|
|
|
impl Native {
|
|
/// An in-app drag of `uris` started; it becomes a system drag if it leaves the window.
|
|
pub fn arm(&self, uris: &[Uri]) {
|
|
let Some(ui) = self.ui.upgrade() else {
|
|
return;
|
|
};
|
|
let size = ui.window().size().to_logical(ui.window().scale_factor());
|
|
self.backend.arm(
|
|
contents(uris, None),
|
|
(f64::from(size.width), f64::from(size.height)),
|
|
);
|
|
}
|
|
|
|
/// The drag image, shown under the pointer once the drag leaves the window.
|
|
pub fn set_drag_icon(&self, image: &slint::Image) {
|
|
if let Some(buffer) = image.to_rgba8_premultiplied() {
|
|
self.backend.set_icon(Icon {
|
|
width: buffer.width(),
|
|
height: buffer.height(),
|
|
rgba: buffer.as_bytes().to_vec(),
|
|
});
|
|
}
|
|
}
|
|
|
|
pub fn set_clipboard(&self, uris: &[Uri], cut: bool) {
|
|
self.backend.set_selection(contents(uris, Some(cut)));
|
|
}
|
|
|
|
/// Another app's files are on the clipboard.
|
|
pub fn clipboard_has_files(&self) -> bool {
|
|
self.backend.selection_has_files()
|
|
}
|
|
|
|
/// Reads another app's files from the clipboard; `done(uris, cut)` runs on the UI thread.
|
|
/// False when there are none (the in-app clipboard applies).
|
|
pub fn read_clipboard(&self, done: impl FnOnce(Vec<Uri>, bool) + 'static) -> bool {
|
|
*self.paste.borrow_mut() = Some(Box::new(done));
|
|
let sink_ui = self.ui.clone();
|
|
self.backend.read_selection(Box::new(move |text, mime| {
|
|
let _ = sink_ui.upgrade_in_event_loop(move |_| {
|
|
if let Some(native) = current() {
|
|
native.handle(Event::Clipboard(text, mime));
|
|
}
|
|
});
|
|
}))
|
|
}
|
|
|
|
fn handle(&self, event: Event) {
|
|
let Some(ui) = self.ui.upgrade() else {
|
|
return;
|
|
};
|
|
match event {
|
|
Event::DragMotion { x, y } => {
|
|
let mut incoming = self.incoming.borrow_mut();
|
|
incoming.position = LogicalPosition::new(x as f32, y as f32);
|
|
incoming.hovering = true;
|
|
drop(incoming);
|
|
self.hover(&ui);
|
|
}
|
|
Event::DragData(text) => {
|
|
let mut data = DataTransfer::default();
|
|
data.set_plain_text(text.into());
|
|
let pending = {
|
|
let mut incoming = self.incoming.borrow_mut();
|
|
incoming.data = Some(data);
|
|
incoming.drop_pending
|
|
};
|
|
if pending {
|
|
self.drop_here(&ui);
|
|
} else {
|
|
self.hover(&ui);
|
|
}
|
|
}
|
|
Event::DragLeave => {
|
|
WindowInner::from_pub(ui.window()).process_drag_event(BackendDragEvent::Leave);
|
|
*self.incoming.borrow_mut() = Incoming::default();
|
|
}
|
|
Event::DragDrop => {
|
|
if self.incoming.borrow().data.is_some() {
|
|
self.drop_here(&ui);
|
|
} else {
|
|
self.incoming.borrow_mut().drop_pending = true;
|
|
}
|
|
}
|
|
Event::DragOutStarted { x, y } => {
|
|
eprintln!("tunal: start_drag: the drag left the window at {x:.0},{y:.0}");
|
|
// The compositor has the pointer now: end Slint's in-window drag, which then
|
|
// finds no drop target and cancels.
|
|
ui.window().dispatch_event(WindowEvent::PointerReleased {
|
|
position: LogicalPosition::new(x as f32, y as f32),
|
|
button: PointerEventButton::Left,
|
|
});
|
|
}
|
|
Event::DragOutFinished { copied } => {
|
|
eprintln!(
|
|
"tunal: system drag {}",
|
|
if copied {
|
|
"dropped (copy)"
|
|
} else {
|
|
"cancelled"
|
|
}
|
|
);
|
|
}
|
|
Event::Clipboard(text, mime) => {
|
|
if let Some(done) = self.paste.borrow_mut().take() {
|
|
let (uris, cut) = parse_clipboard(&text, mime);
|
|
if !uris.is_empty() {
|
|
done(uris, cut);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn drop_event(&self) -> Option<(DropEvent, AllowedDragActions)> {
|
|
let incoming = self.incoming.borrow();
|
|
let mut event = DropEvent::default();
|
|
event.data = incoming.data.clone()?;
|
|
event.position = incoming.position;
|
|
// Move with no modifier: our drop targets then open the drop menu.
|
|
event.proposed_action = DragAction::Move;
|
|
let allowed = AllowedDragActions {
|
|
copy: true,
|
|
move_: true,
|
|
link: true,
|
|
};
|
|
Some((event, allowed))
|
|
}
|
|
|
|
/// Lets Slint hit-test the drop targets under the pointer (and glow); the offer is
|
|
/// accepted only over one that takes it.
|
|
fn hover(&self, ui: &MainWindow) {
|
|
let Some((event, allowed)) = self.drop_event() else {
|
|
return;
|
|
};
|
|
let action = WindowInner::from_pub(ui.window())
|
|
.process_drag_event(BackendDragEvent::Move { event, allowed });
|
|
self.backend
|
|
.accept(action.is_some_and(|a| a != DragAction::None));
|
|
}
|
|
|
|
fn drop_here(&self, ui: &MainWindow) {
|
|
if let Some((event, allowed)) = self.drop_event() {
|
|
WindowInner::from_pub(ui.window())
|
|
.process_drag_event(BackendDragEvent::Drop { event, allowed });
|
|
}
|
|
self.backend.finish_drop();
|
|
*self.incoming.borrow_mut() = Incoming::default();
|
|
}
|
|
}
|