Tunal/crates/tunal/src/dnd.rs
astar76 34c76a2c66 S030: native drag and drop and file clipboard on Wayland
Own queue on Slint's wl_display (thread), drag out via start_drag with an shm icon,
drag in through Slint's drop handling (same drop targets and menu), copy/cut/paste
of files with other apps. Off on X11. Wayland checks deferred to S036 (D-038).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 00:39:24 -06:00

334 lines
12 KiB
Rust

//! In-app drag and drop: files from the views onto folders, panes, tabs, breadcrumb
//! segments and places; bookmarks onto bookmarks (reorder) or the bookmarks section (add).
//!
//! The payload is a `text/uri-list` string (one URI per line, CRLF), plus the file paths
//! when every item is local, so other applications can take it (native DnD hands the same
//! text to `drop_uris`). A drop without modifiers opens the drop menu; Shift moves, Ctrl
//! copies and Ctrl+Shift links at once.
use std::any::Any;
use std::cell::{OnceCell, RefCell};
use std::rc::{Rc, Weak};
use slint::{ComponentHandle, DataTransfer, Image, SharedString};
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};
/// A bookmark being dragged (in-process only, carried as user data).
struct BookmarkDrag(usize);
/// The last payload read back, since `accepts` runs on every pointer move.
#[derive(Default)]
struct Parsed {
text: SharedString,
uris: Rc<Vec<Uri>>,
/// Every item is a local folder (bookmarks section), checked once when first asked.
dirs: OnceCell<bool>,
}
pub struct DragDrop {
ui: slint::Weak<MainWindow>,
shell: Weak<Shell>,
actions: Weak<Actions>,
locations: Locations,
parsed: RefCell<Parsed>,
/// Sources and folder of a drop waiting for the drop menu.
pending: RefCell<Option<(Vec<Uri>, Uri)>>,
}
/// One URI per line, as `text/uri-list` has them.
pub fn uri_list(uris: &[Uri]) -> String {
uris.iter().map(|u| format!("{u}\r\n")).collect()
}
/// The URIs of a `text/uri-list` (comments and blank lines skipped).
pub fn parse_uri_list(text: &str) -> Vec<Uri> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.filter_map(Uri::parse)
.collect()
}
/// `dir` is `src` or lies inside it.
fn within(dir: &Uri, src: &Uri) -> bool {
if dir.scheme() != src.scheme() || dir.authority() != src.authority() {
return false;
}
let src = src.path().strip_suffix(b"/").unwrap_or(src.path());
let dir = dir.path().strip_suffix(b"/").unwrap_or(dir.path());
dir.starts_with(src) && (dir.len() == src.len() || dir[src.len()] == b'/' || src.is_empty())
}
impl DragDrop {
pub fn attach(
ui: &MainWindow,
shell: &Rc<Shell>,
actions: &Rc<Actions>,
locations: Locations,
) -> Rc<Self> {
let dnd = Rc::new(Self {
ui: ui.as_weak(),
shell: Rc::downgrade(shell),
actions: Rc::downgrade(actions),
locations,
parsed: RefCell::new(Parsed::default()),
pending: RefCell::new(None),
});
dnd.bind(ui);
native::attach_later(ui);
dnd
}
fn bind(self: &Rc<Self>, ui: &MainWindow) {
let global = ui.global::<Dnd>();
let me = Rc::downgrade(self);
global.on_payload(move |pane, row, _| {
me.upgrade()
.map(|d| d.payload(&d.drag_uris(pane, row)))
.unwrap_or_default()
});
let me = Rc::downgrade(self);
global.on_image(move |pane, row, _, fill, ink, badge, badge_ink| {
let image = me
.upgrade()
.map(|d| drag_image(&d.drag_uris(pane, row), [fill, ink, badge, badge_ink]))
.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();
data.set_user_data(Rc::new(BookmarkDrag(index.max(0) as usize)));
data
});
let me = Rc::downgrade(self);
global.on_accepts(move |data, target, a, b| {
me.upgrade().is_some_and(|d| d.accepts(&data, target, a, b))
});
let me = Rc::downgrade(self);
global.on_dropped(move |data, action, target, a, b, x, y| {
if let Some(d) = me.upgrade() {
d.dropped(&data, action, target, a, b, x, y);
}
});
let me = Rc::downgrade(self);
ui.on_drop_chosen(move |choice| {
let Some(d) = me.upgrade() else { return };
let Some((sources, dir)) = d.pending.take() else {
return;
};
let action = match choice {
0 => DropAction::Move,
1 => DropAction::Copy,
2 => DropAction::Link,
_ => return,
};
d.drop_uris(sources, dir, action);
});
}
fn drag_uris(&self, pane: i32, row: i32) -> Vec<Uri> {
let (Ok(pane), Ok(row)) = (usize::try_from(pane), usize::try_from(row)) else {
return Vec::new();
};
self.shell
.upgrade()
.and_then(|s| s.pane_at(pane))
.map(|p| p.model.drag_uris(row))
.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<Vec<_>> = uris.iter().map(Uri::to_path).collect();
if let Some(paths) = paths {
data.set_file_paths(paths);
}
data
}
/// The payload's URIs, parsed once per drag.
fn uris(&self, data: &DataTransfer) -> Rc<Vec<Uri>> {
let text = data.plain_text().unwrap_or_default();
let mut parsed = self.parsed.borrow_mut();
if parsed.text != text {
*parsed = Parsed {
uris: Rc::new(parse_uri_list(&text)),
text,
dirs: OnceCell::new(),
};
}
parsed.uris.clone()
}
fn bookmark(data: &DataTransfer) -> Option<usize> {
let any: Rc<dyn Any> = data.user_data()?;
any.downcast_ref::<BookmarkDrag>().map(|b| b.0)
}
fn target_dir(&self, target: DropTarget, a: i32, b: i32) -> Option<Uri> {
let shell = self.shell.upgrade()?;
let index = |i: i32| usize::try_from(i).ok();
match target {
DropTarget::Row => shell.pane_at(index(a)?)?.model.folder_at(index(b)?),
DropTarget::Pane => shell.pane_at(index(a)?)?.dir(),
DropTarget::Tab => shell.tab_dir(a),
DropTarget::Crumb => shell.crumb_uri(index(a)?),
DropTarget::Place => shell.place_uri(*Section::ALL.get(index(a)?)?, index(b)?),
DropTarget::Bookmarks => None,
}
}
fn accepts(&self, data: &DataTransfer, target: DropTarget, a: i32, b: i32) -> bool {
let bookmarks = Section::ALL.iter().position(|&s| s == Section::Bookmarks);
if let Some(from) = Self::bookmark(data) {
return target == DropTarget::Place
&& usize::try_from(a).ok() == bookmarks
&& usize::try_from(b).is_ok_and(|to| to != from);
}
let uris = self.uris(data);
if uris.is_empty() {
return false;
}
if target == DropTarget::Bookmarks {
return usize::try_from(a).ok() == bookmarks && self.all_dirs();
}
let Some(dir) = self.target_dir(target, a, b) else {
return false;
};
self.can_drop(&uris, &dir)
}
/// Every dragged item is a local folder.
fn all_dirs(&self) -> bool {
let parsed = self.parsed.borrow();
*parsed.dirs.get_or_init(|| {
parsed
.uris
.iter()
.all(|u| u.to_path().is_some_and(|p| p.is_dir()))
})
}
/// `dir` can take `uris`: it is writable, not one of them or inside one, and not the
/// folder they are all in already.
fn can_drop(&self, uris: &[Uri], dir: &Uri) -> bool {
let writable = self
.locations
.resolve(dir)
.is_ok_and(|l| l.capabilities().write);
writable
&& !uris.iter().any(|u| within(dir, u))
&& !uris.iter().all(|u| u.parent().as_ref() == Some(dir))
}
#[allow(clippy::too_many_arguments)]
fn dropped(
&self,
data: &DataTransfer,
action: DropAction,
target: DropTarget,
a: i32,
b: i32,
x: f32,
y: f32,
) {
let Some(shell) = self.shell.upgrade() else {
return;
};
if let Some(from) = Self::bookmark(data) {
if let Ok(to) = usize::try_from(b) {
shell.move_bookmark(from, to);
}
return;
}
let uris = self.uris(data).to_vec();
if target == DropTarget::Bookmarks {
shell.add_bookmarks(&uris);
return;
}
let Some(dir) = self.target_dir(target, a, b) else {
return;
};
if action == DropAction::Ask {
*self.pending.borrow_mut() = Some((uris, dir));
// After the drop has finished dispatching, so the menu takes the focus.
let ui = self.ui.clone();
slint::Timer::single_shot(std::time::Duration::ZERO, move || {
if let Some(ui) = ui.upgrade() {
ui.invoke_open_drop_menu(x, y);
}
});
} else {
self.drop_uris(uris, dir, action);
}
}
/// Moves, copies or links `sources` into `dir`; also the entry point for native drops.
pub fn drop_uris(&self, sources: Vec<Uri>, dir: Uri, action: DropAction) {
if sources.is_empty() || !self.can_drop(&sources, &dir) {
return;
}
let Some(actions) = self.actions.upgrade() else {
return;
};
actions.submit(match action {
DropAction::Copy => JobKind::Copy { sources, dest: dir },
DropAction::Link => JobKind::Link { sources, dest: dir },
_ => JobKind::Move { sources, dest: dir },
});
}
}
/// The picture under the pointer: a tonal pill with the first item's name and, for several
/// items, a count badge. Drawn as SVG in the theme's colours (fill, ink, badge, badge ink).
fn drag_image(uris: &[Uri], colors: [slint::Color; 4]) -> Image {
let Some(first) = uris.first() else {
return Image::default();
};
let hex = |c: slint::Color| format!("#{:02x}{:02x}{:02x}", c.red(), c.green(), c.blue());
let [fill, ink, badge, badge_ink] = colors.map(hex);
let name = first
.file_name()
.map(|n| String::from_utf8_lossy(n).into_owned())
.unwrap_or_else(|| first.to_string());
let mut name: String = name.chars().take(28).collect();
if name.chars().count() == 28 {
name.push('…');
}
let escape = |s: &str| {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
};
let count = if uris.len() > 1 {
format!(
r#"<circle cx="228" cy="14" r="12" fill="{badge}"/><text x="228" y="18.5" font-family="sans-serif" font-size="12" font-weight="600" text-anchor="middle" fill="{badge_ink}">{}</text>"#,
uris.len().min(999)
)
} else {
String::new()
};
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="244" height="52" viewBox="0 0 244 52"><rect x="4" y="12" width="224" height="36" rx="18" fill="{fill}" fill-opacity="0.94"/><text x="22" y="35" font-family="sans-serif" font-size="14" fill="{ink}">{}</text>{count}</svg>"#,
escape(&name)
);
Image::load_from_svg_data(svg.as_bytes()).unwrap_or_default()
}