diff --git a/Cargo.lock b/Cargo.lock index 988e0a8..d6960e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6013,6 +6013,7 @@ dependencies = [ "i-slint-renderer-software", "once_cell", "pin-weak", + "raw-window-handle", "slint-macros", "vtable", ] @@ -6991,9 +6992,11 @@ checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" name = "tunal" version = "0.1.0" dependencies = [ + "i-slint-core", "image", "jiff", "png", + "raw-window-handle", "secrecy", "serde", "slint", @@ -7008,6 +7011,8 @@ dependencies = [ "tunal-tags", "tunal-theme", "tunal-thumbs", + "wayland-backend", + "wayland-client", "zbus", ] diff --git a/Plans/11 Native drag and drop/S030-native-dnd-wayland.md b/Plans/11 Native drag and drop/S030-native-dnd-wayland.md index 30891e0..e0f26e8 100644 --- a/Plans/11 Native drag and drop/S030-native-dnd-wayland.md +++ b/Plans/11 Native drag and drop/S030-native-dnd-wayland.md @@ -10,16 +10,16 @@ Drag files from Tunal into other apps (e.g. Discord) and from other apps into Tu docs/DECISIONS.md D-014, D-016; crates/tunal/src/dnd.rs; Slint 1.19 winit accessor and `i-slint-core` drag code in ~/.cargo/registry. ## Steps -- [ ] Spike, then record the approach in DECISIONS.md: get `wl_display`/`wl_surface` from Slint's winit window (raw-window-handle), wrap the foreign display with `wayland-backend` (`client_system`), bind `wl_data_device_manager` and our own `wl_pointer`/`wl_keyboard` for serials; dispatch our queue on a thread. -- [ ] Drag out: when an in-app drag leaves the window, start `wl_data_device.start_drag` with the press serial; offer `text/uri-list`, `text/plain;charset=utf-8` and an internal type; drag icon surface; finish reports the action. -- [ ] Drag in: data offers on our surface → hit-test the Slint drop target under the pointer (choose: Slint's internal native-drag path pinned to 1.19, or our own hit test) → highlight → drop menu → ops job. -- [ ] File clipboard: copy/cut set `text/uri-list` + `x-special/gnome-copied-files`; paste reads them from other apps. -- [ ] X11 or no Wayland: code path disabled cleanly. -- [ ] PROGRESS entry, INDEX line, commit `S030: …` +- [x] Spike, then record the approach in DECISIONS.md: get `wl_display`/`wl_surface` from Slint's winit window (raw-window-handle), wrap the foreign display with `wayland-backend` (`client_system`), bind `wl_data_device_manager` and our own `wl_pointer`/`wl_keyboard` for serials; dispatch our queue on a thread. +- [x] Drag out: when an in-app drag leaves the window, start `wl_data_device.start_drag` with the press serial; offer `text/uri-list`, `text/plain;charset=utf-8` and an internal type; drag icon surface; finish reports the action. +- [x] Drag in: data offers on our surface → hit-test the Slint drop target under the pointer (choose: Slint's internal native-drag path pinned to 1.19, or our own hit test) → highlight → drop menu → ops job. +- [x] File clipboard: copy/cut set `text/uri-list` + `x-special/gnome-copied-files`; paste reads them from other apps. +- [x] X11 or no Wayland: code path disabled cleanly. +- [x] PROGRESS entry, INDEX line, commit `S030: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. -- App still runs under `WAYLAND_DISPLAY` unset (X11 fallback) and with Wayland; a drag that leaves the window doesn't crash (log line shows start_drag). +- App still runs under `WAYLAND_DISPLAY` unset (X11 fallback) and with Wayland; a drag that leaves the window doesn't crash (log line shows start_drag). *(Orchestrator: X11 fallback checked under Xvfb; the Wayland attach check and the start_drag log line are deferred to S036, no window on the user's live session.)* ## Pitfalls - libwayland is already loaded by Slint/winit; no new system package (D-016). diff --git a/Plans/INDEX.md b/Plans/INDEX.md index bb5d3ed..334e768 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -67,7 +67,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 11 Native drag and drop -- [ ] [S030 — Native drag and drop and file clipboard on Wayland](11%20Native%20drag%20and%20drop/S030-native-dnd-wayland.md) · Opus high +- [x] [S030 — Native drag and drop and file clipboard on Wayland](11%20Native%20drag%20and%20drop/S030-native-dnd-wayland.md) · Opus high - [ ] [S031 — Native drag and drop and file clipboard on X11](11%20Native%20drag%20and%20drop/S031-native-dnd-x11.md) · Opus high ## 12 Testing diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index f49df0a..ddaa3cc 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true publish.workspace = true [dependencies] -slint = { workspace = true, features = ["unstable-winit-030"] } +slint = { workspace = true, features = ["unstable-winit-030", "raw-window-handle-06"] } tunal-theme = { path = "../tunal-theme" } png.workspace = true tunal-core = { path = "../tunal-core" } @@ -23,6 +23,12 @@ jiff.workspace = true serde.workspace = true zbus.workspace = true toml.workspace = true +# Native drag and drop and file clipboard (D-014): Slint's own libwayland connection, and +# Slint's internal drag entry point, pinned to the Slint release in use. +i-slint-core = { version = "=1.19.0", default-features = false } +raw-window-handle = "0.6" +wayland-backend = { version = "0.3", features = ["client_system"] } +wayland-client = "0.31" [build-dependencies] slint-build.workspace = true diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index 10ffe01..c6687d4 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -10,6 +10,7 @@ use slint::{ComponentHandle, Model, ModelRc, VecModel}; use tunal_core::ops::{self, JobKind}; use tunal_core::{Locations, Uri}; +use crate::clipboard; use crate::folder::appearance::Appearance; use crate::jobs_bridge::Bridge; use crate::menus::{Context as MenuContext, Menus}; @@ -353,7 +354,7 @@ impl Actions { in_trash: pane.dir().is_some_and(|d| d.scheme() == tunal_core::TRASH), writable: caps.write, can_trash: caps.trash, - paste: !self.clipboard.borrow().uris.is_empty(), + paste: !self.clipboard.borrow().uris.is_empty() || clipboard::has_foreign(), } } @@ -609,6 +610,7 @@ impl Actions { if uris.is_empty() { return; } + clipboard::offer(&uris, cut); *self.clipboard.borrow_mut() = Clipboard { uris: uris.clone(), cut, @@ -626,6 +628,20 @@ impl Actions { } fn paste(&self, shell: &Shell, dest: Uri) { + // Files another app copied since ours win. + let me = self.me.clone(); + let to = dest.clone(); + if clipboard::paste_foreign(move |sources, cut| { + if let Some(me) = me.upgrade() { + me.bridge.submit(if cut { + JobKind::Move { sources, dest: to } + } else { + JobKind::Copy { sources, dest: to } + }); + } + }) { + return; + } let (sources, cut) = { let clipboard = self.clipboard.borrow(); (clipboard.uris.clone(), clipboard.cut) diff --git a/crates/tunal/src/clipboard.rs b/crates/tunal/src/clipboard.rs new file mode 100644 index 0000000..16dc45f --- /dev/null +++ b/crates/tunal/src/clipboard.rs @@ -0,0 +1,25 @@ +//! Copy, cut and paste of files with other apps through the system clipboard (D-014). The +//! in-app clipboard (actions.rs) stays the source of truth while it is ours; files another +//! app copied later win on paste. + +use tunal_core::Uri; + +use crate::native; + +/// Copy or cut `uris`: offered to other apps too. +pub fn offer(uris: &[Uri], cut: bool) { + if let Some(native) = native::current() { + native.set_clipboard(uris, cut); + } +} + +/// Another app's files are on the clipboard. +pub fn has_foreign() -> bool { + native::current().is_some_and(|n| n.clipboard_has_files()) +} + +/// Reads another app's files; `done(uris, cut)` runs later on the UI thread. False when the +/// clipboard holds none. +pub fn paste_foreign(done: impl FnOnce(Vec, bool) + 'static) -> bool { + native::current().is_some_and(|n| n.read_clipboard(done)) +} diff --git a/crates/tunal/src/dnd.rs b/crates/tunal/src/dnd.rs index 3e6e144..1aee2b0 100644 --- a/crates/tunal/src/dnd.rs +++ b/crates/tunal/src/dnd.rs @@ -15,6 +15,7 @@ use tunal_core::ops::JobKind; use tunal_core::{Locations, Uri}; use crate::actions::Actions; +use crate::native; use crate::shell::Shell; use crate::shell::places::Section; use crate::{Dnd, DropAction, DropTarget, MainWindow}; @@ -81,6 +82,7 @@ impl DragDrop { pending: RefCell::new(None), }); dnd.bind(ui); + native::attach_later(ui); dnd } @@ -94,9 +96,14 @@ impl DragDrop { }); let me = Rc::downgrade(self); global.on_image(move |pane, row, _, fill, ink, badge, badge_ink| { - me.upgrade() + let image = me + .upgrade() .map(|d| drag_image(&d.drag_uris(pane, row), [fill, ink, badge, badge_ink])) - .unwrap_or_default() + .unwrap_or_default(); + if let Some(native) = native::current() { + native.set_drag_icon(&image); + } + image }); global.on_bookmark_payload(|index| { let mut data = DataTransfer::default(); @@ -140,11 +147,15 @@ impl DragDrop { .unwrap_or_default() } + /// Read once when a drag starts, so the drag may also leave the window (native). fn payload(&self, uris: &[Uri]) -> DataTransfer { let mut data = DataTransfer::default(); if uris.is_empty() { return data; } + if let Some(native) = native::current() { + native.arm(uris); + } data.set_plain_text(uri_list(uris).into()); let paths: Option> = uris.iter().map(Uri::to_path).collect(); if let Some(paths) = paths { diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 4f5228a..6a72ef1 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -1,4 +1,5 @@ mod actions; +mod clipboard; mod config; mod desktop_apps; mod devices_bridge; @@ -7,6 +8,7 @@ mod folder; mod icons; mod jobs_bridge; mod menus; +mod native; mod net_bridge; mod open; mod player_bridge; diff --git a/crates/tunal/src/native/mod.rs b/crates/tunal/src/native/mod.rs new file mode 100644 index 0000000..1666449 --- /dev/null +++ b/crates/tunal/src/native/mod.rs @@ -0,0 +1,325 @@ +//! Native drag and drop and file clipboard with other apps (D-014). Wayland only for now +//! (`wayland.rs`); on X11, or without a window handle (screenshots), `current()` is `None` +//! and every caller falls back to in-app behaviour. +//! +//! API (S031's X11 backend implements the same): `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; + +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::{Contents, Wayland}; + +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; + +/// Runs with the files read from the clipboard and whether they were cut. +type PasteDone = Box, bool)>; + +thread_local! { + static CURRENT: RefCell>> = const { RefCell::new(None) }; +} + +/// The native backend of this window, once attached. +pub fn current() -> Option> { + CURRENT.with(|c| c.borrow().clone()) +} + +#[derive(Default)] +struct Incoming { + data: Option, + position: LogicalPosition, + hovering: bool, + /// Dropped before its data was read: drop once it is. + drop_pending: bool, +} + +pub struct Native { + ui: slint::Weak, + wayland: Wayland, + incoming: RefCell, + paste: RefCell>, +} + +/// 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, 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); + } + }); + }); + // X11 (or anything else) leaves this off: S031. + let Some(wayland) = Wayland::attach(display, raw_window, sink) else { + return; + }; + let native = Rc::new(Native { + ui: ui.clone(), + wayland, + 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) -> 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::>() + .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, 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.wayland.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.wayland.set_icon(wayland::Icon { + width: buffer.width(), + height: buffer.height(), + rgba: buffer.as_bytes().to_vec(), + }); + } + } + + pub fn set_clipboard(&self, uris: &[Uri], cut: bool) { + self.wayland.set_selection(contents(uris, Some(cut))); + } + + /// Another app's files are on the clipboard. + pub fn clipboard_has_files(&self) -> bool { + self.wayland.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, bool) + 'static) -> bool { + *self.paste.borrow_mut() = Some(Box::new(done)); + let sink_ui = self.ui.clone(); + self.wayland.read_selection(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.wayland + .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.wayland.finish_drop(); + *self.incoming.borrow_mut() = Incoming::default(); + } +} diff --git a/crates/tunal/src/native/wayland.rs b/crates/tunal/src/native/wayland.rs new file mode 100644 index 0000000..cb77f98 --- /dev/null +++ b/crates/tunal/src/native/wayland.rs @@ -0,0 +1,604 @@ +//! Wayland drag and drop and file clipboard on Slint's own libwayland connection (D-014): +//! the foreign `wl_display` is wrapped with `wayland-backend` (`client_system`), and our own +//! queue (own `wl_seat` bindings, `wl_pointer`/`wl_keyboard` for serials, a +//! `wl_data_device`) is dispatched on a thread. UI work goes back through `Event`s. + +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::os::fd::{AsFd, OwnedFd}; +use std::sync::{Arc, Mutex}; + +use raw_window_handle::{RawDisplayHandle, RawWindowHandle}; +use wayland_client::backend::{Backend, ObjectId}; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::wl_buffer::WlBuffer; +use wayland_client::protocol::wl_compositor::WlCompositor; +use wayland_client::protocol::wl_data_device::{self, WlDataDevice}; +use wayland_client::protocol::wl_data_device_manager::{DndAction, WlDataDeviceManager}; +use wayland_client::protocol::wl_data_offer::{self, WlDataOffer}; +use wayland_client::protocol::wl_data_source::{self, WlDataSource}; +use wayland_client::protocol::wl_keyboard::{self, WlKeyboard}; +use wayland_client::protocol::wl_pointer::{self, WlPointer}; +use wayland_client::protocol::wl_registry::WlRegistry; +use wayland_client::protocol::wl_seat::{self, WlSeat}; +use wayland_client::protocol::wl_shm::{self, WlShm}; +use wayland_client::protocol::wl_shm_pool::WlShmPool; +use wayland_client::protocol::wl_surface::WlSurface; +use wayland_client::{ + Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum, event_created_child, +}; + +use super::{Event, Sink, mime}; + +/// `BTN_LEFT` from linux/input-event-codes.h. +const BTN_LEFT: u32 = 0x110; + +/// What the dispatch thread and the UI thread share. +#[derive(Default)] +struct Shared { + /// Serial of the left-button press while it is held (start_drag needs it). + press: Option, + /// Serial of the last key or button event (set_selection needs one). + serial: u32, + /// An in-app drag that may leave the window: its payload and the window's size. + armed: Option<(Contents, (f64, f64))>, + /// The picture under the pointer for the next system drag. + icon: Option, + /// Mime types of each live offer, as announced. + offers: HashMap>, + /// The offer hovering our window, with its enter serial. + dnd: Option<(WlDataOffer, u32)>, + /// The action the compositor settled for `dnd`. + dnd_action: Option, + /// `dnd` was dropped; the UI finishes it (a late leave must not destroy it first). + dropped: bool, + /// Our source of the running system drag. + drag_source: Option, + selection: Option, + /// What each of our sources hands out, by mime type. + sources: HashMap, +} + +/// Payload by mime type. +pub type Contents = Vec<(&'static str, Vec)>; + +/// Premultiplied RGBA pixels. +pub struct Icon { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +struct State { + shared: Arc>, + sink: Sink, + surface: WlSurface, + device: WlDataDevice, + manager: WlDataDeviceManager, + pointer: Option, + keyboard: Option, + compositor: Option, + shm: Option, + /// The drag icon of the running system drag. + icon: Option<(WlSurface, WlBuffer)>, +} + +pub struct Wayland { + conn: Connection, + qh: QueueHandle, + shared: Arc>, + device: WlDataDevice, + manager: WlDataDeviceManager, +} + +impl Wayland { + /// Binds to the window's Wayland connection; `None` on X11 or when anything is missing. + pub fn attach(display: RawDisplayHandle, window: RawWindowHandle, sink: Sink) -> Option { + let (RawDisplayHandle::Wayland(display), RawWindowHandle::Wayland(window)) = + (display, window) + else { + return None; + }; + // SAFETY: Slint's winit backend owns the display and the surface for the window's + // lifetime, which outlives the app; we only borrow them. + let backend = unsafe { Backend::from_foreign_display(display.display.as_ptr().cast()) }; + let conn = Connection::from_backend(backend); + let surface_id = + unsafe { ObjectId::from_ptr(WlSurface::interface(), window.surface.as_ptr().cast()) } + .ok()?; + let surface = WlSurface::from_id(&conn, surface_id).ok()?; + let (globals, mut queue): (_, EventQueue) = registry_queue_init(&conn).ok()?; + let qh = queue.handle(); + let seat: WlSeat = globals.bind(&qh, 1..=7, ()).ok()?; + let manager: WlDataDeviceManager = globals.bind(&qh, 3..=3, ()).ok()?; + let device = manager.get_data_device(&seat, &qh, ()); + let shared = Arc::new(Mutex::new(Shared::default())); + let mut state = State { + shared: shared.clone(), + sink, + surface, + device: device.clone(), + manager: manager.clone(), + pointer: None, + keyboard: None, + compositor: globals.bind(&qh, 1..=4, ()).ok(), + shm: globals.bind(&qh, 1..=1, ()).ok(), + icon: None, + }; + queue.roundtrip(&mut state).ok()?; + std::thread::Builder::new() + .name("tunal-wayland".into()) + .spawn(move || while queue.blocking_dispatch(&mut state).is_ok() {}) + .ok()?; + Some(Self { + conn, + qh, + shared, + device, + manager, + }) + } + + /// An in-app drag started: if the pointer leaves the window while the button is held, + /// the drag becomes a system drag carrying `contents`. + pub fn arm(&self, contents: Contents, size: (f64, f64)) { + let mut s = self.shared.lock().unwrap(); + if s.press.is_some() { + s.armed = Some((contents, size)); + } + } + + pub fn set_icon(&self, icon: Icon) { + self.shared.lock().unwrap().icon = Some(icon); + } + + /// Accept the hovering offer (or not), as the drop target under the pointer decides. + pub fn accept(&self, yes: bool) { + let s = self.shared.lock().unwrap(); + if let Some((offer, serial)) = &s.dnd { + offer.accept(*serial, yes.then(|| mime::URI_LIST.into())); + } + drop(s); + let _ = self.conn.flush(); + } + + /// The drop was handled: tell the source and let the offer go. + pub fn finish_drop(&self) { + let mut s = self.shared.lock().unwrap(); + s.dropped = false; + if let Some((offer, _)) = s.dnd.take() { + if s.dnd_action.take().is_some_and(|a| !a.is_empty()) { + offer.finish(); + } + s.offers.remove(&offer.id()); + offer.destroy(); + } + drop(s); + let _ = self.conn.flush(); + } + + /// Reads the hovering offer as `text/uri-list` (on a thread); `Event::DragData` follows. + fn read_dnd(shared: &Shared, offer: &WlDataOffer, conn: &Connection, sink: &Sink) { + let has = |m: &str| { + shared + .offers + .get(&offer.id()) + .is_some_and(|l| l.iter().any(|x| x == m)) + }; + if !has(mime::URI_LIST) { + return; + } + let sink = sink.clone(); + receive(offer, mime::URI_LIST, conn, move |bytes| { + sink(Event::DragData( + String::from_utf8_lossy(&bytes).into_owned(), + )); + }); + } + + /// The clipboard holds another app's files. + pub fn selection_has_files(&self) -> bool { + let s = self.shared.lock().unwrap(); + let Some(offer) = &s.selection else { + return false; + }; + s.offers.get(&offer.id()).is_some_and(|mimes| { + !mimes.iter().any(|m| m == mime::INTERNAL) + && mimes + .iter() + .any(|m| m == mime::GNOME_COPIED || m == mime::URI_LIST) + }) + } + + /// Puts files on the system clipboard. + pub fn set_selection(&self, contents: Contents) { + let source = self.manager.create_data_source(&self.qh, ()); + for (m, _) in &contents { + source.offer((*m).into()); + } + let mut s = self.shared.lock().unwrap(); + s.sources.insert(source.id(), contents); + self.device.set_selection(Some(&source), s.serial); + drop(s); + let _ = self.conn.flush(); + } + + /// Reads files another app put on the clipboard, if it holds any: `done(text, mime)` runs + /// on a thread with `x-special/gnome-copied-files` or else `text/uri-list` text. + /// Returns false when the clipboard holds no files or is ours. + pub fn read_selection(&self, done: impl FnOnce(String, &'static str) + Send + 'static) -> bool { + let s = self.shared.lock().unwrap(); + let Some(offer) = &s.selection else { + return false; + }; + let mimes = s.offers.get(&offer.id()).cloned().unwrap_or_default(); + if mimes.iter().any(|m| m == mime::INTERNAL) { + return false; + } + let Some(m) = [mime::GNOME_COPIED, mime::URI_LIST] + .into_iter() + .find(|m| mimes.iter().any(|x| x == m)) + else { + return false; + }; + receive(offer, m, &self.conn, move |bytes| { + done(String::from_utf8_lossy(&bytes).into_owned(), m) + }); + true + } +} + +/// Asks `offer` for `mime` through a pipe and reads it to the end on a thread. +fn receive( + offer: &WlDataOffer, + mime: &str, + conn: &Connection, + done: impl FnOnce(Vec) + Send + 'static, +) { + let Ok((mut reader, writer)) = std::io::pipe() else { + return; + }; + offer.receive(mime.into(), writer.as_fd()); + let _ = conn.flush(); + drop(writer); + std::thread::spawn(move || { + let mut bytes = Vec::new(); + if reader.read_to_end(&mut bytes).is_ok() { + done(bytes); + } + }); +} + +/// Writes `bytes` to a requesting app on a thread (it may read slowly). +fn send(fd: OwnedFd, bytes: Vec) { + std::thread::spawn(move || { + let _ = std::fs::File::from(fd).write_all(&bytes); + }); +} + +impl State { + /// The pointer left the window during an in-app drag: hand it to the compositor. + fn start_drag(&mut self, x: f64, y: f64, qh: &QueueHandle) { + let mut s = self.shared.lock().unwrap(); + let (Some(serial), Some((contents, _))) = (s.press, s.armed.take()) else { + return; + }; + let icon = s.icon.take().and_then(|i| self.icon_surface(&i, qh)); + let source = self.manager.create_data_source(qh, ()); + for (m, _) in &contents { + source.offer((*m).into()); + } + // Copy only: a drop into another app never removes our files. + source.set_actions(DndAction::Copy); + s.sources.insert(source.id(), contents); + s.drag_source = Some(source.id()); + drop(s); + self.device.start_drag( + Some(&source), + &self.surface, + icon.as_ref().map(|(surface, _)| surface), + serial, + ); + self.icon = icon; + (self.sink)(Event::DragOutStarted { x, y }); + } +} + +impl State { + /// A surface showing `icon`, from a shared-memory buffer (unlinked file in the runtime dir). + fn icon_surface(&self, icon: &Icon, qh: &QueueHandle) -> Option<(WlSurface, WlBuffer)> { + let (compositor, shm) = (self.compositor.as_ref()?, self.shm.as_ref()?); + let dir = std::env::var_os("XDG_RUNTIME_DIR")?; + let path = std::path::Path::new(&dir).join(format!("tunal-drag-{}", std::process::id())); + let mut file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&path) + .ok()?; + let _ = std::fs::remove_file(&path); + // ARGB8888 is premultiplied BGRA in memory (little endian). + let bgra: Vec = icon + .rgba + .as_chunks::<4>() + .0 + .iter() + .flat_map(|p| [p[2], p[1], p[0], p[3]]) + .collect(); + file.write_all(&bgra).ok()?; + let (w, h) = (icon.width as i32, icon.height as i32); + let pool = shm.create_pool(file.as_fd(), bgra.len() as i32, qh, ()); + let buffer = pool.create_buffer(0, w, h, w * 4, wl_shm::Format::Argb8888, qh, ()); + pool.destroy(); + let surface = compositor.create_surface(qh, ()); + surface.attach(Some(&buffer), 0, 0); + surface.damage(0, 0, w, h); + surface.commit(); + Some((surface, buffer)) + } + + fn drop_icon(&mut self) { + if let Some((surface, buffer)) = self.icon.take() { + surface.destroy(); + buffer.destroy(); + } + } +} + +/// Objects whose events we ignore. +macro_rules! ignore_events { + ($($t:ty),*) => {$( + impl Dispatch<$t, ()> for State { + fn event( + _: &mut Self, + _: &$t, + _: <$t as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } + } + )*}; +} +ignore_events!( + WlCompositor, + WlShm, + WlShmPool, + WlBuffer, + WlSurface, + WlDataDeviceManager +); + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &WlRegistry, + _: ::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + seat: &WlSeat, + event: wl_seat::Event, + _: &(), + _: &Connection, + qh: &QueueHandle, + ) { + if let wl_seat::Event::Capabilities { + capabilities: WEnum::Value(caps), + } = event + { + if caps.contains(wl_seat::Capability::Pointer) && state.pointer.is_none() { + state.pointer = Some(seat.get_pointer(qh, ())); + } + if caps.contains(wl_seat::Capability::Keyboard) && state.keyboard.is_none() { + state.keyboard = Some(seat.get_keyboard(qh, ())); + } + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &WlPointer, + event: wl_pointer::Event, + _: &(), + _: &Connection, + qh: &QueueHandle, + ) { + match event { + wl_pointer::Event::Button { + serial, + button, + state: WEnum::Value(pressed), + .. + } => { + let mut s = state.shared.lock().unwrap(); + s.serial = serial; + if button == BTN_LEFT { + if pressed == wl_pointer::ButtonState::Pressed { + s.press = Some(serial); + } else { + s.press = None; + s.armed = None; + } + } + } + wl_pointer::Event::Motion { + surface_x, + surface_y, + .. + } => { + let outside = { + let s = state.shared.lock().unwrap(); + s.armed.as_ref().is_some_and(|(_, (w, h))| { + surface_x < 0.0 || surface_y < 0.0 || surface_x >= *w || surface_y >= *h + }) + }; + if outside { + state.start_drag(surface_x, surface_y, qh); + } + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &WlKeyboard, + event: wl_keyboard::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + if let wl_keyboard::Event::Key { serial, .. } | wl_keyboard::Event::Enter { serial, .. } = + event + { + state.shared.lock().unwrap().serial = serial; + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &WlDataDevice, + event: wl_data_device::Event, + _: &(), + conn: &Connection, + _: &QueueHandle, + ) { + let mut s = state.shared.lock().unwrap(); + match event { + wl_data_device::Event::DataOffer { id } => { + s.offers.insert(id.id(), Vec::new()); + } + wl_data_device::Event::Enter { + serial, + surface, + x, + y, + id, + } => { + let Some(offer) = id.filter(|_| surface.id() == state.surface.id()) else { + return; + }; + offer.set_actions(DndAction::Copy | DndAction::Move, DndAction::Copy); + Wayland::read_dnd(&s, &offer, conn, &state.sink); + s.dnd = Some((offer, serial)); + s.dnd_action = None; + s.dropped = false; + drop(s); + (state.sink)(Event::DragMotion { x, y }); + } + wl_data_device::Event::Motion { x, y, .. } => { + if s.dnd.is_some() { + drop(s); + (state.sink)(Event::DragMotion { x, y }); + } + } + wl_data_device::Event::Leave => { + if s.dropped { + return; + } + if let Some((offer, _)) = s.dnd.take() { + s.offers.remove(&offer.id()); + offer.destroy(); + drop(s); + (state.sink)(Event::DragLeave); + } + } + wl_data_device::Event::Drop => { + if s.dnd.is_some() { + s.dropped = true; + drop(s); + (state.sink)(Event::DragDrop); + } + } + wl_data_device::Event::Selection { id } => { + if let Some(old) = s.selection.take() { + s.offers.remove(&old.id()); + old.destroy(); + } + s.selection = id; + } + _ => {} + } + } + + event_created_child!(State, WlDataDevice, [ + wl_data_device::EVT_DATA_OFFER_OPCODE => (WlDataOffer, ()), + ]); +} + +impl Dispatch for State { + fn event( + state: &mut Self, + offer: &WlDataOffer, + event: wl_data_offer::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + let mut s = state.shared.lock().unwrap(); + match event { + wl_data_offer::Event::Offer { mime_type } => { + s.offers.entry(offer.id()).or_default().push(mime_type); + } + wl_data_offer::Event::Action { + dnd_action: WEnum::Value(action), + } => { + s.dnd_action = Some(action); + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + source: &WlDataSource, + event: wl_data_source::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + let mut s = state.shared.lock().unwrap(); + match event { + wl_data_source::Event::Send { mime_type, fd } => { + let bytes = s.sources.get(&source.id()).and_then(|c| { + c.iter() + .find(|(m, _)| *m == mime_type) + .map(|(_, b)| b.clone()) + }); + if let Some(bytes) = bytes { + send(fd, bytes); + } + } + wl_data_source::Event::DndFinished | wl_data_source::Event::Cancelled => { + let copied = matches!(event, wl_data_source::Event::DndFinished); + s.sources.remove(&source.id()); + let dragging = s.drag_source.take_if(|id| *id == source.id()).is_some(); + source.destroy(); + drop(s); + if dragging { + state.drop_icon(); + (state.sink)(Event::DragOutFinished { copied }); + } + } + _ => {} + } + } +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index eb23e23..5d1860c 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -235,6 +235,15 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: no live clicks (add/edit flow, password dialog with a real server, press motion not watched); the dialogs reuse `Dialog` motion only. Keyboard-interactive and password logins untested. Connection dialog is tall at 480 px window height. No key-file picker (path typed). - Later: file picker for the key; show connection errors in the sidebar; per-connection options (compression, keepalive). +## S030 — Native DnD and file clipboard on Wayland +- Done (D-039): `native/wayland.rs`: our own queue on Slint's foreign `wl_display` (seat → own pointer/keyboard for serials, `wl_data_device` v3, `wl_compositor`/`wl_shm` for the drag icon), dispatched on the `tunal-wayland` thread; events go to the UI as `native::Event`s. `native/mod.rs` `Native` (`native::current()`, attached by `attach_later` once the window has a handle; `None` on X11 and in screenshots): `arm(uris)` + `set_drag_icon(image)` (called from `dnd.rs` when an in-app drag starts), `set_clipboard(uris, cut)`, `clipboard_has_files()`, `read_clipboard(done)`. **S031 implements the same API for X11.** +- Drag out: when the pointer leaves the window with the button held, `start_drag` (press serial) with uri-list, `text/plain;charset=utf-8`, `text/plain` and `application/x-tunal-uris`, SVG drag image as an shm icon; Copy only; a synthetic release ends Slint's in-window drag; stderr logs `start_drag` and the finish. +- Drag in: offers on our surface are read as uri-list and fed to Slint's `WindowInner::process_drag_event` (`i-slint-core =1.19.0`): same DropZones, glow and drop menu as in-app; the offer is accepted only over a target that takes it. +- Clipboard (`clipboard.rs`): copy/cut also set the selection (+ `x-special/gnome-copied-files`); paste prefers another app's files (cut → move). +- Verified: build, clippy -D warnings, fmt; X11 fallback: app ran 8 s under Xvfb with `WAYLAND_DISPLAY` unset, no crash. +- Not done: no Wayland run at all (no headless compositor; orchestrator: no window on the live session); attach, drag out/in and clipboard with other apps are deferred to S036. +- Later: Move/Link for drag out; modifiers for drags coming in (keyboard focus during a foreign drag). + ## Later - (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034. -