Skip to main content

plat/
dnd.rs

1// dnd -- drag and drop between programs: what a drag carries, the target hook, the pending
2// drop and the app's own outgoing drag (the parts every OS shares)       (docs/GUIDE.md ยง7)
3//
4//   DT_FILES / DT_TEXT / DT_URL / DT_HTML / DT_IMAGE   kinds of content (bits, DT_STD = all);
5//                                DT_USER0 << k: the app's own kinds (internal drags only)
6//   DE_COPY / DE_MOVE / DE_LINK  effects (bits)
7//   DragData                     the content of one drag (paths, text, URLs, HTML, an image, the
8//                                app's own bytes) and the effects
9//   drag_hook(Some(f))           f(pw, x, y, types) -> (accepted types, accepted effects): what the
10//                                UI takes at a point (px) of platform window pw.  The OS layers
11//                                ask it synchronously while something is dragged over a window
12//                                (IDropTarget::DragOver, XdndPosition, wl_data_device.motion).
13//   drag_query(pw, x, y, types, allowed, mods) -> (types, effect)   (OS layers) the hook's answer
14//                                with one effect picked; without a hook: files, copy (as before).
15//                                Files are never moved: a source deletes what it moved, and
16//                                the app gets only the paths (copy or link instead).  The hook
17//                                answers per drop target (ui: drop_effect_set): a target that
18//                                takes no effect refuses the drag there (the system's pointer
19//                                shows it)
20//   drag_query_all(...) -> (types, effect, effects)   drag_query and every effect the target
21//                                takes there (Wayland's set_actions names them all)
22//   drag_decide(types, effects, offered, allowed, mods) -> (types, effect, effects)   what
23//                                drag_query makes of a hook's answer (tests ask it headless)
24//   drag_effect_pick(allowed, mods) -> effect   Ctrl copy, Shift move, Ctrl+Shift link; else
25//                                the first of copy / move / link the mask allows
26//   drop_data_take() -> DragData the pending drop of E_DROP: the paths of drop_take and the rest
27//   drop_hold(on)                (the UI) the program answers drops itself: where the platform
28//                                allows a later answer, a drop's answer to its source waits after
29//                                E_DROP for drop_finish (Windows: a source whose data object is in
30//                                IDataObjectAsyncCapability's async mode; X11: XdndFinished;
31//                                Wayland: wl_data_offer.finish); elsewhere it went at the drop
32//   drop_waiting() -> serial     the drop whose answer waits (0: none), read after drop_data_take
33//   drop_allowed() -> DE_*       the effects the source of that drop allows, as the platform gives
34//                                them with the drop (0: it does not say), read after drop_data_take
35//   drop_finish(serial, effect) -> answered   answer that drop's source: the effect it was taken
36//                                with, 0 = not taken
37//   drop_set_text / drop_set_html / drop_add_url / drop_set_image / drop_set_effect /
38//   drop_set_allowed             (OS layers) fill the pending drop (drop_reset empties it)
39//   drop_text_from(bytes, utf16) / drop_url_list(text)   decoding helpers of the OS layers
40//   drag_start(data) -> bool     drag data out of the app while the left button is held (the UI
41//                                calls it when an internal drag leaves its window); false when
42//                                the platform cannot (headless, browser) or a drag runs.
43//                                E_DRAG_END follows (data = the effect, 0 = cancelled / refused).
44//   drag_running() -> bool       an outgoing drag runs
45//
46// Events: E_DRAG (x, y = position in window px, data = DT_* offered | DE_* allowed << 8; data 0:
47// the drag left the window, was dropped or cancelled) while another program's drag (or our
48// own outgoing one) is over a window; E_DROP (x, y, data = the number of paths) when it is
49// dropped there; E_DRAG_END when our own outgoing drag ended.
50// Windows: OLE (win_dnd.rs: IDropTarget per window, DoDragDrop with our IDataObject / IDropSource);
51// X11: Xdnd 5 target and source (linux_x11_dnd.rs); Wayland: wl_data_device (linux_wl_clip.rs).
52// Everything that comes from another program is bounded (sizes, counts) and checked.
53
54use alloc::string::String;
55use alloc::vec::Vec;
56use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
57
58use rt::sync::SpinLock;
59
60// ---- kinds of content (bits)
61pub const DT_FILES: u32 = 1; // paths (file:// URIs, CF_HDROP)
62pub const DT_TEXT: u32 = 2; // UTF-8 text
63pub const DT_URL: u32 = 4; // URLs that are not local files
64pub const DT_HTML: u32 = 8; // a UTF-8 HTML fragment
65pub const DT_IMAGE: u32 = 16; // an image file (PNG; a DIB arrives as BMP)
66pub const DT_STD: u32 = 31; // every kind other programs know
67pub const DT_USER0: u32 = 1 << 8; // the app's own kinds: DT_USER0 << k, k = 0..23
68
69// ---- effects (bits).  An empty set of the effects a source allows (DragData::effects of a drag
70// out, drag_query's and drag_decide's `allowed`, the DE_* of E_DRAG, drop_allowed) means the
71// source does not say: every effect, DE_ALL -- the same everywhere (ui: drag_allowed)
72pub const DE_COPY: u32 = 1; // the target copies (DROPEFFECT_COPY, XdndActionCopy)
73pub const DE_MOVE: u32 = 2; // the target moves: the source deletes its original
74pub const DE_LINK: u32 = 4; // the target links to it (not on Wayland)
75pub const DE_ALL: u32 = 7; // every effect
76
77const TEXT_MAX: usize = crate::CLIP_RICH_MAX; // text / HTML of one drop
78const IMAGE_MAX: usize = 1 << 28; // one image file
79const URL_MAX: usize = 32768; // bytes of one URL
80const URLS_MAX: usize = 4096;
81const URL_BYTES_MAX: usize = 1 << 24;
82
83/// the content of one drag (a drop that arrives, or what the app drags)
84#[derive(Clone, Default, Debug, PartialEq)]
85pub struct DragData {
86    /// paths of files and folders
87    pub files: Vec<String>,
88    /// plain text
89    pub text: Option<String>,
90    /// URLs (not local files)
91    pub urls: Vec<String>,
92    /// an HTML fragment (UTF-8)
93    pub html: Option<String>,
94    /// an image file: PNG (a drop of a DIB / image/bmp arrives as a BMP file)
95    pub image: Option<Vec<u8>>,
96    /// (drag out) the same image as a BMP file, offered as DIB / image/bmp too (optional)
97    pub bmp: Option<Vec<u8>>,
98    /// the app's own kind (DT_USER0 << k bits) and bytes: internal drags only
99    pub app: u32,
100    pub bytes: Vec<u8>,
101    /// what the drag shows next to the pointer inside the app (empty: from the content)
102    pub label: String,
103    /// drag out: the DE_* effects the source allows (0: it does not say, every effect); a drop: the
104    /// effect chosen
105    pub effects: u32,
106}
107
108impl DragData {
109    /// the DT_* kinds it carries (the app's own kinds included)
110    pub fn types(&self) -> u32 {
111        let mut t = self.app & !DT_STD;
112        if !self.files.is_empty() {
113            t |= DT_FILES;
114        }
115        if self.text.is_some() {
116            t |= DT_TEXT;
117        }
118        if !self.urls.is_empty() {
119            t |= DT_URL;
120        }
121        if self.html.is_some() {
122            t |= DT_HTML;
123        }
124        if self.image.is_some() {
125            t |= DT_IMAGE;
126        }
127        t
128    }
129
130    /// nothing to drag
131    pub fn is_empty(&self) -> bool {
132        self.types() == 0
133    }
134
135    /// text only
136    pub fn of_text(s: &str) -> DragData {
137        DragData { text: Some(String::from(s)), ..DragData::default() }
138    }
139
140    /// paths only
141    pub fn of_files(paths: &[&str]) -> DragData {
142        DragData { files: paths.iter().map(|p| String::from(*p)).collect(), ..DragData::default() }
143    }
144
145    /// the app's own kind (DT_USER0 << k) and bytes
146    pub fn of_app(kind: u32, bytes: &[u8]) -> DragData {
147        DragData { app: kind & !DT_STD, bytes: bytes.to_vec(), ..DragData::default() }
148    }
149
150    /// the effects a drag out allows: `effects`, every one (DE_ALL) when it names none
151    pub fn allowed(&self) -> u32 {
152        if self.effects & DE_ALL == 0 { DE_ALL } else { self.effects & DE_ALL }
153    }
154}
155
156// ---------------------------------------------------------------- the target hook
157
158/// what the UI takes at a point: f(platform window, x, y px, offered DT_*) -> (accepted DT_*,
159/// accepted DE_*)
160pub type DragHook = fn(i32, i32, i32, u32) -> (u32, u32);
161
162static HOOK: AtomicUsize = AtomicUsize::new(0);
163
164/// install (Some) or remove (None) the drop target hook (the UI does it for its windows)
165pub fn drag_hook(f: Option<DragHook>) {
166    HOOK.store(f.map_or(0, |f| f as usize), Ordering::Release);
167}
168
169/// the effect of a drop: the modifier keys choose (Ctrl copy, Shift move, Ctrl+Shift link),
170/// else the first of copy / move / link that `allowed` has (0: none)
171pub fn drag_effect_pick(allowed: u32, mods: u8) -> u32 {
172    let a = allowed & DE_ALL;
173    let ctrl = mods & crate::MOD_CTRL != 0;
174    let shift = mods & crate::MOD_SHIFT != 0;
175    let want = match (ctrl, shift) {
176        (true, true) => DE_LINK,
177        (true, false) => DE_COPY,
178        (false, true) => DE_MOVE,
179        _ => 0,
180    };
181    if want & a != 0 {
182        return want;
183    }
184    [DE_COPY, DE_MOVE, DE_LINK].into_iter().find(|e| a & e != 0).unwrap_or(0)
185}
186
187/// (OS layers) what platform window pw takes at (x, y) px of a drag offering `types` with the
188/// effects `allowed` (0: the source does not say, every effect) -> (accepted types, the effect);
189/// (0, 0) = refused
190pub fn drag_query(pw: i32, x: i32, y: i32, types: u32, allowed: u32, mods: u8) -> (u32, u32) {
191    let (t, e, _) = drag_query_all(pw, x, y, types, allowed, mods);
192    (t, e)
193}
194
195/// (OS layers) drag_query and every DE_* effect the target there takes of the allowed ones
196/// (Wayland's wl_data_offer.set_actions) -> (accepted types, the effect, the effects); (0, 0, 0)
197/// = refused
198pub fn drag_query_all(pw: i32, x: i32, y: i32, types: u32, allowed: u32, mods: u8) -> (u32, u32, u32) {
199    let h = HOOK.load(Ordering::Acquire);
200    let (t, e) = if h == 0 {
201        (types & DT_FILES, DE_ALL) // no UI: files, as before
202    } else {
203        // SAFETY: HOOK only ever holds 0 or a DragHook stored by drag_hook.
204        let f: DragHook = unsafe { core::mem::transmute::<usize, DragHook>(h) };
205        f(pw, x, y, types)
206    };
207    drag_decide(t, e, types, allowed, mods)
208}
209
210/// what drag_query makes of the hook's answer (accepted types t, effects e) to a drag offering
211/// `types` with the effects `allowed` (0: not said, every effect) and the modifier keys `mods` -> (accepted
212/// types, the effect, every effect taken); (0, 0, 0) = refused (no kind or no effect in common).
213/// Files are never moved.  For the OS layers and headless tests (ui's `dragover expect`)
214pub fn drag_decide(t: u32, e: u32, types: u32, allowed: u32, mods: u8) -> (u32, u32, u32) {
215    let t = t & types;
216    let mut allowed = if allowed & DE_ALL == 0 { DE_ALL } else { allowed & DE_ALL };
217    if t & DT_FILES != 0 {
218        // a move would make the source delete the files: the app gets only their paths
219        allowed &= !DE_MOVE;
220    }
221    let all = e & allowed;
222    let eff = drag_effect_pick(all, mods);
223    if t == 0 || eff == 0 { (0, 0, 0) } else { (t, eff, all) }
224}
225
226// ---------------------------------------------------------------- the pending drop
227
228struct Rich {
229    text: Option<String>,
230    html: Option<String>,
231    urls: Vec<String>,
232    url_bytes: usize,
233    image: Option<Vec<u8>>,
234    effect: u32,
235    allowed: u32,
236}
237
238static RICH: SpinLock<Rich> =
239    SpinLock::new(Rich { text: None, html: None, urls: Vec::new(), url_bytes: 0, image: None, effect: 0, allowed: 0 });
240
241// the effects the source of the drop drop_data_take took last allows (drop_allowed)
242static TAKEN_ALLOWED: AtomicU32 = AtomicU32::new(0);
243
244/// (drop_reset) forget the pending text, HTML, URLs and image
245pub(crate) fn rich_reset() {
246    let mut r = RICH.lock();
247    r.text = None;
248    r.html = None;
249    r.urls = Vec::new();
250    r.url_bytes = 0;
251    r.image = None;
252    r.effect = 0;
253    r.allowed = 0;
254}
255
256// text of another program: UTF-8 (invalid bytes replaced), up to the first NUL, bounded
257fn text_of(bytes: &[u8]) -> Option<String> {
258    let end = bytes.iter().position(|&c| c == 0).unwrap_or(bytes.len());
259    if end > TEXT_MAX {
260        return None;
261    }
262    Some(String::from_utf8_lossy(&bytes[..end]).into_owned())
263}
264
265/// (OS layers) the pending drop's text (UTF-8 bytes; cut at a NUL) -> false when too large
266pub fn drop_set_text(bytes: &[u8]) -> bool {
267    let Some(s) = text_of(bytes) else { return false };
268    RICH.lock().text = Some(s);
269    true
270}
271
272/// (OS layers) the pending drop's HTML fragment (UTF-8 bytes) -> false when too large
273pub fn drop_set_html(bytes: &[u8]) -> bool {
274    let Some(s) = text_of(bytes) else { return false };
275    RICH.lock().html = Some(s);
276    true
277}
278
279/// (OS layers) one URL of the pending drop ("scheme:...", no blanks or control characters,
280/// bounded, no duplicates) -> added
281pub fn drop_add_url(url: &str) -> bool {
282    let url = url.trim();
283    if url.is_empty() || url.len() > URL_MAX || url.chars().any(|c| c.is_control() || c.is_whitespace()) || !has_scheme(url) {
284        return false;
285    }
286    let mut r = RICH.lock();
287    if r.urls.len() >= URLS_MAX || r.url_bytes + url.len() > URL_BYTES_MAX || r.urls.iter().any(|u| u == url) {
288        return false;
289    }
290    r.url_bytes += url.len();
291    r.urls.push(String::from(url));
292    true
293}
294
295/// (OS layers) the pending drop's image file (PNG or BMP bytes) -> false when too large
296pub fn drop_set_image(bytes: Vec<u8>) -> bool {
297    if bytes.is_empty() || bytes.len() > IMAGE_MAX {
298        return false;
299    }
300    RICH.lock().image = Some(bytes);
301    true
302}
303
304/// (OS layers) the effect the drop was made with (DE_*)
305pub fn drop_set_effect(effect: u32) {
306    RICH.lock().effect = effect & DE_ALL;
307}
308
309/// (OS layers) the DE_* effects the source of the pending drop allows, as the platform gives them
310/// with the drop: Windows IDropTarget::Drop's pdwEffect, X11 the source's XdndActionList with the
311/// action of its last XdndPosition (every effect without a list), Wayland the offer's
312/// source_actions, macOS the drag's operation mask.  Not called (the browser, Android): 0
313pub fn drop_set_allowed(effects: u32) {
314    RICH.lock().allowed = effects & DE_ALL;
315}
316
317/// the pending drop (E_DROP): its paths (drop_take) and the rest; both start empty again
318pub fn drop_data_take() -> DragData {
319    let files = crate::drop_take();
320    let mut r = RICH.lock();
321    let d = DragData {
322        files,
323        text: r.text.take(),
324        urls: core::mem::take(&mut r.urls),
325        html: r.html.take(),
326        image: r.image.take(),
327        effects: core::mem::take(&mut r.effect),
328        ..DragData::default()
329    };
330    r.url_bytes = 0;
331    TAKEN_ALLOWED.store(core::mem::take(&mut r.allowed), Ordering::Release);
332    d
333}
334
335/// drop_allowed() -> the DE_* effects the source of the drop drop_data_take took last allows, as
336/// the platform gave them with the drop (drop_set_allowed: the same the drag said in E_DRAG over
337/// the window); 0: the platform does not say (the browser, Android).  Read it right after
338/// drop_data_take
339pub fn drop_allowed() -> u32 {
340    TAKEN_ALLOWED.load(Ordering::Acquire)
341}
342
343// "scheme:" in front (RFC 3986: a letter, then letters, digits, + - .)
344fn has_scheme(u: &str) -> bool {
345    let b = u.as_bytes();
346    let Some(colon) = b.iter().position(|&c| c == b':') else { return false };
347    colon > 0
348        && b[0].is_ascii_alphabetic()
349        && b[..colon].iter().all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.'))
350}
351
352/// (OS layers) text in other programs' encodings -> UTF-8 bytes: UTF-16 LE (utf16, up to a
353/// NUL unit) or bytes as they are (up to a NUL)
354pub fn drop_text_from(bytes: &[u8], utf16: bool) -> Vec<u8> {
355    if !utf16 {
356        let end = bytes.iter().position(|&c| c == 0).unwrap_or(bytes.len());
357        return bytes[..end].to_vec();
358    }
359    let units = bytes.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&u| u != 0);
360    let mut s = String::new();
361    for c in core::char::decode_utf16(units) {
362        s.push(c.unwrap_or('\u{FFFD}'));
363    }
364    s.into_bytes()
365}
366
367/// (OS layers) the lines of a URL list (text/uri-list, text/x-moz-url, UniformResourceLocator):
368/// '#' lines skipped, every other line one URL; local files are left to drop_uri_list -> URLs
369/// added (also used for the URL a browser drags)
370pub fn drop_url_list(text: &[u8]) -> u32 {
371    let mut n = 0;
372    for line in text.split(|&c| c == b'\n') {
373        let l = line.strip_suffix(b"\r").unwrap_or(line);
374        if l.is_empty() || l[0] == b'#' || (l.len() >= 5 && l[..5].eq_ignore_ascii_case(b"file:")) {
375            continue;
376        }
377        if let Ok(s) = core::str::from_utf8(l) {
378            if drop_add_url(s) {
379                n += 1;
380            }
381        }
382    }
383    n
384}
385
386// ---------------------------------------------------------------- the answer of a drop
387
388// drop_hold is on; the serial of the drop whose answer waits (0: none) and the OS layer's function
389// that gives it; the last serial handed out
390static HOLD: AtomicBool = AtomicBool::new(false);
391static WAITING: AtomicU32 = AtomicU32::new(0);
392static FINISH: AtomicUsize = AtomicUsize::new(0);
393static SERIAL: AtomicU32 = AtomicU32::new(0);
394
395/// drop_hold(on): (the UI, at its start) the program answers drops itself.  On, the OS layers keep
396/// a drop's answer to its source open after E_DROP where the platform allows a later answer, until
397/// drop_finish: Windows when the source's data object offers IDataObjectAsyncCapability in async
398/// mode (StartOperation in IDropTarget::Drop, EndOperation later), X11 (XdndFinished), Wayland
399/// (wl_data_offer.finish); everywhere else, and on Windows for every other source, the answer went
400/// at the drop (drop_waiting says 0).  Off (the default): every drop is answered at once, as before
401pub fn drop_hold(on: bool) {
402    HOLD.store(on, Ordering::Release);
403}
404
405/// (OS layers) drop_hold is on
406#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), allow(dead_code))]
407pub(crate) fn drop_held() -> bool {
408    HOLD.load(Ordering::Acquire)
409}
410
411/// drop_waiting() -> the serial of the last drop whose answer to its source waits for drop_finish;
412/// 0: none (it was answered at the drop, or no drop came).  Read it right after drop_data_take
413pub fn drop_waiting() -> u32 {
414    WAITING.load(Ordering::Acquire)
415}
416
417/// drop_finish(serial, effect) -> answered: the source of drop `serial` (drop_waiting) learns how
418/// the drop ended: the DE_* effect it was taken with, 0 = not taken.  false: that drop does not
419/// wait (answered already, or a newer drop replaced it).  Windows: EndOperation(S_OK, effect),
420/// not taken EndOperation(E_ABORT, DROPEFFECT_NONE); X11: XdndFinished with "accepted" and the
421/// effect's action; Wayland: taken wl_data_offer.finish (the action stays the one negotiated
422/// before the drop), not taken the offer destroyed without finish
423pub fn drop_finish(serial: u32, effect: u32) -> bool {
424    if serial == 0 || WAITING.compare_exchange(serial, 0, Ordering::AcqRel, Ordering::Acquire).is_err() {
425        return false;
426    }
427    let f = FINISH.swap(0, Ordering::AcqRel);
428    if f != 0 {
429        // SAFETY: FINISH only ever holds 0 or a fn(u32) stored by drop_wait_begin.
430        let f: fn(u32) = unsafe { core::mem::transmute::<usize, fn(u32)>(f) };
431        f(effect & DE_ALL);
432    }
433    true
434}
435
436/// (OS layers) the drop about to be pushed keeps its answer open until finish(effect) is called
437/// through drop_finish -> its serial.  A drop that still waited is no longer waited for: the layer
438/// answers it itself before (as at its drop)
439#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), allow(dead_code))]
440pub(crate) fn drop_wait_begin(finish: fn(u32)) -> u32 {
441    let mut s = SERIAL.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
442    if s == 0 {
443        s = SERIAL.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
444    }
445    FINISH.store(finish as usize, Ordering::Release);
446    WAITING.store(s, Ordering::Release);
447    s
448}
449
450/// (OS layers) the drop that waited was answered by the layer itself (its window went away)
451#[cfg_attr(any(target_arch = "wasm32", target_os = "android", target_vendor = "apple"), allow(dead_code))]
452pub(crate) fn drop_wait_clear() {
453    WAITING.store(0, Ordering::Release);
454    FINISH.store(0, Ordering::Release);
455}
456
457// ---------------------------------------------------------------- the outgoing drag
458
459static RUNNING: AtomicBool = AtomicBool::new(false);
460
461/// drag `data` out of the app (call while the left button is held) -> started; E_DRAG_END
462/// (data = the effect, 0 = cancelled or refused) follows.  Only the standard kinds leave
463/// the app.
464pub fn drag_start(data: DragData) -> bool {
465    if data.types() & DT_STD == 0 || RUNNING.load(Ordering::Acquire) {
466        return false;
467    }
468    RUNNING.store(true, Ordering::Release);
469    let ok = crate::os_drag_start(data);
470    if !ok {
471        RUNNING.store(false, Ordering::Release);
472    }
473    ok
474}
475
476/// an outgoing drag runs (until its E_DRAG_END is queued)
477pub fn drag_running() -> bool {
478    RUNNING.load(Ordering::Acquire)
479}
480
481/// (OS layers) the outgoing drag ended: E_DRAG_END for window w with the effect (0 = none)
482#[cfg_attr(any(target_arch = "wasm32", target_os = "android"), allow(dead_code))] // no drags out there yet
483pub(crate) fn drag_finished(w: u8, effect: u32) {
484    RUNNING.store(false, Ordering::Release);
485    crate::evq_push(crate::Event { typ: crate::E_DRAG_END, win: w, data: effect & DE_ALL, ..crate::Event::default() });
486}