Skip to main content

day_spec/
transfer.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Native drag data and synchronous destination policy. No clipboard or process-local transport.
5use crate::Point;
6use std::{rc::Rc, sync::Arc};
7
8pub const BUNDLE_MIME: &str = "application/vnd.day.transfer";
9pub const MAX_BYTES: usize = 64 * 1024 * 1024;
10pub const MAX_ITEMS: usize = 256;
11
12/// One representation of an item. File references use standard `text/uri-list` bytes.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Representation {
15    pub mime: String,
16    pub bytes: Arc<Vec<u8>>,
17}
18impl Representation {
19    pub fn new(mime: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
20        Self {
21            mime: mime.into(),
22            bytes: Arc::new(bytes.into()),
23        }
24    }
25}
26/// Representations in an item are alternatives; items in an offer are separate objects.
27#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct Item {
29    pub representations: Vec<Representation>,
30}
31impl Item {
32    #[must_use]
33    pub fn new(representations: Vec<Representation>) -> Self {
34        Self { representations }
35    }
36    #[must_use]
37    pub fn get(&self, mime: &str) -> Option<&[u8]> {
38        self.representations
39            .iter()
40            .find(|r| r.mime == mime)
41            .map(|r| r.bytes.as_slice())
42    }
43}
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub enum Operation {
46    #[default]
47    None,
48    Copy,
49    Move,
50    Link,
51}
52#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub struct Offer {
54    pub items: Vec<Item>,
55}
56
57#[derive(Clone, Debug)]
58pub struct Location {
59    /// Target-local logical coordinates, not screen pixels.
60    pub position: Point,
61    pub types: Vec<String>,
62    pub allowed: Vec<Operation>,
63    /// Provenance supplied by the native session, never decoded from a payload.
64    pub local: bool,
65}
66impl Location {
67    #[must_use]
68    pub fn has(&self, mime: &str) -> bool {
69        self.types.iter().any(|m| m == mime)
70    }
71}
72#[derive(Clone, Debug)]
73pub struct Drop {
74    pub local: bool,
75    pub position: Point,
76    pub operation: Operation,
77    pub items: Vec<Item>,
78}
79impl Drop {
80    /// The local files among the dropped items, in order: every `text/uri-list`
81    /// representation read through [`file_paths`]. Empty when the drop carried none.
82    #[must_use]
83    pub fn file_paths(&self) -> Vec<std::path::PathBuf> {
84        self.items
85            .iter()
86            .filter_map(|item| item.get("text/uri-list"))
87            .filter_map(file_paths)
88            .flatten()
89            .collect()
90    }
91}
92/// Called on the UI thread at native drag start, outside any tree borrow.
93pub type Source = Rc<dyn Fn(Point) -> Option<Offer>>;
94type Policy = Rc<dyn Fn(&Location) -> Operation>;
95type OnEnter = Rc<dyn Fn(&Location)>;
96/// What [`Target::guarded`] runs each callback through: it is handed the callback as a thunk
97/// and decides whether, and in which scope, to run it.
98pub type Guard = Rc<dyn Fn(&mut dyn FnMut())>;
99
100/// A drop destination: the types it takes, its acceptance policy, and what runs as a drag
101/// enters, leaves and drops (docs/drag-and-drop.md "Accepting drops").
102///
103/// ```ignore
104/// DropTarget::new(["text/uri-list"])
105///     .on_enter(move |_| hovering.set(true))
106///     .on_leave(move || hovering.set(false))
107///     .on_drop(move |drop| { files.set(drop.file_paths()); true })
108/// ```
109///
110/// The policy ([`Target::accept`]) is consulted during hover AND again at drop; without one a
111/// target takes a copy of any offer that carries one of its types. Every `on_enter` is
112/// followed by exactly one `on_leave`: when the drag moves off the target, when the session
113/// is cancelled, or right after the drop is delivered, so a highlight needs the pair and
114/// nothing else. `on_drop` returns whether the owned data was accepted. Do not delete a
115/// source based on asynchronous work started there: external transfers currently advertise
116/// Copy only.
117///
118/// A backend holds the target it was given and calls [`Target::proposal`] as the drag moves,
119/// [`Target::deliver`] at the drop and [`Target::leave`] when the session leaves the view or
120/// is cancelled; the enter and leave callbacks are derived from those three calls.
121#[derive(Clone)]
122pub struct Target {
123    /// The MIME types the target registers for with the platform.
124    pub types: Vec<String>,
125    accept: Option<Policy>,
126    enter: Option<OnEnter>,
127    leave: Option<Rc<dyn Fn()>>,
128    receive: Rc<dyn Fn(Drop) -> bool>,
129    /// Whether a drag is over the target, shared by every clone a backend keeps.
130    hovering: Rc<std::cell::Cell<bool>>,
131}
132impl Target {
133    /// A target for offers that carry any of `types`. It accepts nothing until
134    /// [`Target::on_drop`] gives it a receiver.
135    pub fn new<S: Into<String>>(types: impl IntoIterator<Item = S>) -> Self {
136        Self {
137            types: types.into_iter().map(Into::into).collect(),
138            accept: None,
139            enter: None,
140            leave: None,
141            receive: Rc::new(|_| false),
142            hovering: Rc::new(std::cell::Cell::new(false)),
143        }
144    }
145    /// A target for file references (`text/uri-list`).
146    #[must_use]
147    pub fn files() -> Self {
148        Self::new(["text/uri-list"])
149    }
150    /// Decide what a drag at `location` would do: called during hover and again at the drop.
151    /// [`Operation::None`] refuses this location. Without a policy the target proposes
152    /// [`Operation::Copy`] for an offer that carries one of its types.
153    #[must_use]
154    pub fn accept(mut self, policy: impl Fn(&Location) -> Operation + 'static) -> Self {
155        self.accept = Some(Rc::new(policy));
156        self
157    }
158    /// Run when a drag the target would accept comes over it.
159    #[must_use]
160    pub fn on_enter(mut self, f: impl Fn(&Location) + 'static) -> Self {
161        self.enter = Some(Rc::new(f));
162        self
163    }
164    /// Run when the hover ends: the drag left, the session was cancelled, or the drop was
165    /// delivered. Paired with [`Target::on_enter`].
166    #[must_use]
167    pub fn on_leave(mut self, f: impl Fn() + 'static) -> Self {
168        self.leave = Some(Rc::new(f));
169        self
170    }
171    /// Take the dropped items. Return whether they were accepted.
172    #[must_use]
173    pub fn on_drop(mut self, f: impl Fn(Drop) -> bool + 'static) -> Self {
174        self.receive = Rc::new(f);
175        self
176    }
177    /// This target with every callback run through `guard`, sharing the hover state: how the
178    /// pieces layer scopes the callbacks to the piece that declared them. `guard` is handed
179    /// each callback as a thunk and decides whether, and in which scope, to run it.
180    #[must_use]
181    pub fn guarded(self, guard: Guard) -> Self {
182        let Target {
183            types,
184            accept,
185            enter,
186            leave,
187            receive,
188            hovering,
189        } = self;
190        let g = guard.clone();
191        let accept = accept.map(|f| -> Policy {
192            Rc::new(move |location| {
193                let mut op = Operation::None;
194                g(&mut || op = f(location));
195                op
196            })
197        });
198        let g = guard.clone();
199        let enter = enter.map(|f| -> OnEnter { Rc::new(move |location| g(&mut || f(location))) });
200        let g = guard.clone();
201        let leave = leave.map(|f| -> Rc<dyn Fn()> { Rc::new(move || g(&mut || f())) });
202        let receive: Rc<dyn Fn(Drop) -> bool> = Rc::new(move |drop| {
203            let mut taken = false;
204            let mut drop = Some(drop);
205            guard(&mut || {
206                if let Some(drop) = drop.take() {
207                    taken = receive(drop);
208                }
209            });
210            taken
211        });
212        Target {
213            types,
214            accept,
215            enter,
216            leave,
217            receive,
218            hovering,
219        }
220    }
221    /// Whether a drag is over the target right now.
222    #[must_use]
223    pub fn is_hovering(&self) -> bool {
224        self.hovering.get()
225    }
226    /// What a drag at `location` would do, for the platform's hover feedback. Marks the
227    /// hover: the first accepting proposal of a session runs `on_enter`, and a proposal that
228    /// turns to [`Operation::None`] runs `on_leave`.
229    #[must_use]
230    pub fn proposal(&self, location: &Location) -> Operation {
231        let op = self.decide(location);
232        if op == Operation::None {
233            self.leave();
234        } else if !self.hovering.replace(true)
235            && let Some(enter) = &self.enter
236        {
237            crate::ffi_guard::contain((), || enter(location));
238        }
239        op
240    }
241    /// The drag left the target or the session was cancelled. A backend calls it from the
242    /// platform's drag-exit and drag-end callbacks; it is idempotent, and it runs `on_leave`
243    /// only when a hover was under way.
244    pub fn leave(&self) {
245        if self.hovering.replace(false)
246            && let Some(leave) = &self.leave
247        {
248            crate::ffi_guard::contain((), || leave());
249        }
250    }
251    /// The drop: consult the policy once more, hand the items to `on_drop` when it accepts,
252    /// then end the hover. Returns whether the data was taken.
253    #[must_use]
254    #[expect(
255        clippy::needless_pass_by_value,
256        reason = "public signature; toolkits pass the location they built for this drop"
257    )]
258    pub fn deliver(&self, location: Location, offer: Offer) -> bool {
259        let op = self.decide(&location);
260        let taken = op != Operation::None
261            && crate::ffi_guard::contain(false, || {
262                (self.receive)(Drop {
263                    local: location.local,
264                    position: location.position,
265                    operation: op,
266                    items: offer.items,
267                })
268            });
269        self.leave();
270        taken
271    }
272    fn decide(&self, location: &Location) -> Operation {
273        let op = match &self.accept {
274            Some(accept) => crate::ffi_guard::contain(Operation::None, || accept(location)),
275            None if self.types.iter().any(|t| location.has(t)) => Operation::Copy,
276            None => Operation::None,
277        };
278        if location.allowed.contains(&op) {
279            op
280        } else {
281            Operation::None
282        }
283    }
284}
285
286/// Bounded, versioned transport for multiple items through native MIME providers. Standard
287/// image and file formats are published alongside this, for applications that do not know Day.
288impl Offer {
289    #[must_use]
290    pub fn types(&self) -> Vec<String> {
291        let mut out = Vec::new();
292        for r in self.items.iter().flat_map(|i| &i.representations) {
293            if !out.contains(&r.mime) {
294                out.push(r.mime.clone());
295            }
296        }
297        out
298    }
299    #[must_use]
300    pub fn encode(&self) -> Option<Vec<u8>> {
301        if self.items.is_empty() || self.items.len() > MAX_ITEMS {
302            return None;
303        }
304        let mut out = b"DAYDND\0\x01".to_vec();
305        out.extend_from_slice(&(self.items.len() as u32).to_le_bytes());
306        for item in &self.items {
307            if item.representations.is_empty() || item.representations.len() > 32 {
308                return None;
309            }
310            out.extend_from_slice(&(item.representations.len() as u32).to_le_bytes());
311            let mut seen = std::collections::HashSet::new();
312            for r in &item.representations {
313                if !valid_mime(&r.mime) || r.mime == BUNDLE_MIME || !seen.insert(&r.mime) {
314                    return None;
315                }
316                if out
317                    .len()
318                    .checked_add(r.mime.len() + 8)?
319                    .checked_add(r.bytes.len())?
320                    > MAX_BYTES
321                {
322                    return None;
323                }
324                out.extend_from_slice(&(r.mime.len() as u32).to_le_bytes());
325                out.extend_from_slice(&(r.bytes.len() as u32).to_le_bytes());
326                out.extend_from_slice(r.mime.as_bytes());
327                out.extend_from_slice(&r.bytes);
328            }
329        }
330        Some(out)
331    }
332    #[must_use]
333    pub fn decode(mut bytes: &[u8]) -> Option<Self> {
334        fn take<'a>(b: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {
335            let (a, rest) = b.split_at_checked(n)?;
336            *b = rest;
337            Some(a)
338        }
339        fn number(b: &mut &[u8]) -> Option<usize> {
340            Some(u32::from_le_bytes(take(b, 4)?.try_into().ok()?) as usize)
341        }
342        if bytes.len() > MAX_BYTES || take(&mut bytes, 8)? != b"DAYDND\0\x01" {
343            return None;
344        }
345        let count = number(&mut bytes)?;
346        if count == 0 || count > MAX_ITEMS {
347            return None;
348        }
349        let mut items = Vec::new();
350        for _ in 0..count {
351            let count = number(&mut bytes)?;
352            if count == 0 || count > 32 {
353                return None;
354            }
355            let mut representations = Vec::new();
356            for _ in 0..count {
357                let m = number(&mut bytes)?;
358                let n = number(&mut bytes)?;
359                if m > 255 {
360                    return None;
361                }
362                let mime = std::str::from_utf8(take(&mut bytes, m)?).ok()?;
363                if !valid_mime(mime)
364                    || mime == BUNDLE_MIME
365                    || representations
366                        .iter()
367                        .any(|r: &Representation| r.mime == mime)
368                {
369                    return None;
370                }
371                representations.push(Representation::new(mime, take(&mut bytes, n)?));
372            }
373            items.push(Item { representations });
374        }
375        if !bytes.is_empty() {
376            return None;
377        }
378        Some(Self { items })
379    }
380}
381#[must_use]
382pub fn valid_mime(m: &str) -> bool {
383    m.len() <= 255
384        && m.split_once('/')
385            .is_some_and(|(a, b)| !a.is_empty() && !b.is_empty() && !b.contains('/'))
386        && m.bytes()
387            .all(|c| c.is_ascii_alphanumeric() || b"/!#$&^_.+-".contains(&c))
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    #[test]
394    fn items_and_alternatives_survive_untrusted_transport() {
395        let offer = Offer {
396            items: vec![
397                Item::new(vec![
398                    Representation::new("image/png", [0, 255]),
399                    Representation::new("application/x-test", [9, 0]),
400                ]),
401                Item::new(vec![Representation::new(
402                    "text/uri-list",
403                    b"file:///tmp/a%20b\r\n",
404                )]),
405            ],
406        };
407        let encoded = offer.encode().unwrap();
408        assert_eq!(Offer::decode(&encoded), Some(offer));
409        for n in 0..encoded.len() {
410            assert!(Offer::decode(&encoded[..n]).is_none());
411        }
412        let mut extra = encoded;
413        extra.push(0);
414        assert!(Offer::decode(&extra).is_none());
415    }
416    #[test]
417    fn location_guard_is_rechecked_and_cannot_escalate_operations() {
418        let target = Target::new(Vec::<String>::new())
419            .accept(|p| {
420                if p.position.x < 50.0 {
421                    Operation::Copy
422                } else {
423                    Operation::Move
424                }
425            })
426            .on_drop(|_| true);
427        let mut p = Location {
428            position: Point::new(5., 5.),
429            types: vec![],
430            allowed: vec![Operation::Copy],
431            local: true,
432        };
433        assert_eq!(target.proposal(&p), Operation::Copy);
434        p.position.x = 80.;
435        assert!(!target.deliver(p, Offer::default()));
436    }
437    #[test]
438    fn a_target_without_a_policy_copies_its_own_types_and_reads_dropped_files() {
439        use std::cell::RefCell;
440        let got = Rc::new(RefCell::new(Vec::new()));
441        let sink = got.clone();
442        let target = Target::files().on_drop(move |drop| {
443            *sink.borrow_mut() = drop.file_paths();
444            true
445        });
446        let at = |types: &[&str]| Location {
447            position: Point::ZERO,
448            types: types.iter().map(|t| (*t).to_owned()).collect(),
449            allowed: vec![Operation::Copy, Operation::Move],
450            local: false,
451        };
452        assert_eq!(target.proposal(&at(&["text/plain"])), Operation::None);
453        assert!(!target.is_hovering());
454        assert_eq!(target.proposal(&at(&["text/uri-list"])), Operation::Copy);
455        assert!(target.is_hovering());
456        let offer = Offer {
457            items: vec![Item::new(vec![Representation::new(
458                "text/uri-list",
459                "file:///tmp/a.txt\r\nfile:///tmp/b.txt\r\n",
460            )])],
461        };
462        assert!(target.deliver(at(&["text/uri-list"]), offer));
463        assert!(!target.is_hovering(), "a drop ends the hover");
464        assert_eq!(
465            *got.borrow(),
466            vec![
467                std::path::PathBuf::from("/tmp/a.txt"),
468                std::path::PathBuf::from("/tmp/b.txt")
469            ]
470        );
471    }
472}
473
474/// Parse native URI-list records without treating remote or opaque URIs as filesystem paths.
475/// Callers still need the platform's access lease for sandboxed/provider-backed references.
476pub fn file_paths(bytes: &[u8]) -> Option<Vec<std::path::PathBuf>> {
477    let text = std::str::from_utf8(bytes).ok()?;
478    let mut paths = Vec::new();
479    for line in text
480        .lines()
481        .map(str::trim)
482        .filter(|l| !l.is_empty() && !l.starts_with('#'))
483    {
484        let uri = line.strip_prefix("file://")?;
485        let path = if uri.starts_with('/') {
486            uri
487        } else {
488            uri.strip_prefix("localhost/")
489                .map(|p| &uri[uri.len() - p.len() - 1..])?
490        };
491        if path.contains(['?', '#']) {
492            return None;
493        }
494        let mut decoded = Vec::with_capacity(path.len());
495        let mut raw = path.bytes();
496        while let Some(b) = raw.next() {
497            let b = if b == b'%' {
498                let hi = (raw.next()? as char).to_digit(16)?;
499                let lo = (raw.next()? as char).to_digit(16)?;
500                (hi * 16 + lo) as u8
501            } else {
502                b
503            };
504            if b == 0 {
505                return None;
506            }
507            decoded.push(b);
508        }
509        #[cfg(unix)]
510        let path = {
511            use std::os::unix::ffi::OsStringExt;
512            std::path::PathBuf::from(std::ffi::OsString::from_vec(decoded))
513        };
514        #[cfg(not(unix))]
515        let path = {
516            let s = String::from_utf8(decoded).ok()?;
517            #[cfg(windows)]
518            let s = if s.as_bytes().get(2) == Some(&b':') {
519                s[1..].to_string()
520            } else {
521                s
522            };
523            std::path::PathBuf::from(s)
524        };
525        paths.push(path);
526        if paths.len() > MAX_ITEMS {
527            return None;
528        }
529    }
530    (!paths.is_empty()).then_some(paths)
531}
532
533#[cfg(test)]
534mod file_tests {
535    use super::*;
536    #[test]
537    fn uri_references_decode_without_fetching_remote_resources() {
538        assert_eq!(
539            file_paths(b"# files\r\nfile:///tmp/a%20b%23c.png\r\nfile://localhost/tmp/two\r\n")
540                .unwrap(),
541            vec![
542                std::path::PathBuf::from("/tmp/a b#c.png"),
543                std::path::PathBuf::from("/tmp/two")
544            ]
545        );
546        for s in [
547            "https://example.com/a",
548            "file://remote/a",
549            "file:///tmp/%00",
550            "file:///tmp/%xx",
551            "file:///tmp/a#fragment",
552        ] {
553            assert!(file_paths(s.as_bytes()).is_none());
554        }
555    }
556}