tauri-plugin-dragout 0.2.0

Native drag-out for Tauri 2 on macOS: drag real files, generated bytes or lazy file promises from your webview to Finder, the Desktop, Mail or any other app.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Native drag-out for Tauri 2.
//!
//! A webview cannot start an OS-level file drag on its own: an HTML `dragstart`
//! in WKWebView only carries text, URLs or in-page data, so users cannot drag a
//! document out of a Tauri app onto Finder, the Desktop, Mail or Slack. This
//! plugin starts a real `NSDraggingSession` from the window under the mouse and
//! lets you drag:
//!
//! * **existing files** ([`DragItem::File`]): the target receives the file itself;
//! * **copies of files** ([`DragItem::Copy`]): copied only when dropped, optionally under another name;
//! * **generated bytes** ([`DragItem::Data`]): written to the drop location on drop;
//! * **lazy promises** ([`DragItem::promise`], Rust only): your closure writes the file
//!   when (and only if) the user actually drops it, e.g. export, decrypt or download on demand.
//!
//! Supported on macOS. On other platforms the plugin compiles, [`is_supported`]
//! returns `false` and [`start_drag`] returns [`Error::Unsupported`].
//!
//! ```no_run
//! tauri::Builder::default()
//!     .plugin(tauri_plugin_dragout::init())
//!     # ;
//! ```

#![allow(unexpected_cfgs)]

use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

use serde::{Deserialize, Serialize, Serializer};
use tauri::{
    plugin::{Builder as PluginBuilder, TauriPlugin},
    Emitter, Manager, Runtime, WebviewWindow,
};

#[cfg(target_os = "macos")]
mod macos;

/// Event emitted when a promised item has been written at its drop location.
pub const EVENT_DROPPED: &str = "dragout://dropped";
/// Event emitted when a drag session ends (dropped or cancelled).
pub const EVENT_ENDED: &str = "dragout://ended";
/// Event emitted when writing a promised item failed.
pub const EVENT_ERROR: &str = "dragout://error";

/// Writer used by [`DragItem::Promise`]: receives the full destination path.
pub type PromiseWriter = Arc<dyn Fn(&Path) -> Result<(), String> + Send + Sync>;

/// One thing to drag.
///
/// From JavaScript items are tagged objects:
/// `{ type: "file", path }`, `{ type: "copy", source, fileName? }`,
/// `{ type: "data", fileName, data }` where `data` is base64.
#[derive(Clone, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum DragItem {
    /// An existing file or folder. The drop target gets the original path
    /// (Finder copies it, other apps attach or open it).
    File { path: PathBuf },
    /// Copy `source` to the drop location when the user drops it,
    /// optionally under a different `file_name`. Works for files and folders.
    Copy {
        source: PathBuf,
        #[serde(default)]
        file_name: Option<String>,
    },
    /// Write these bytes to `file_name` at the drop location.
    Data {
        file_name: String,
        #[serde(deserialize_with = "de_base64")]
        data: Vec<u8>,
    },
    /// Rust only: call `write` with the destination path when the item is dropped.
    /// Runs on a background queue, so it may block (render, decrypt, download...).
    #[serde(skip)]
    Promise {
        file_name: String,
        write: PromiseWriter,
    },
}

impl DragItem {
    /// An existing file or folder.
    pub fn file(path: impl Into<PathBuf>) -> Self {
        DragItem::File { path: path.into() }
    }
    /// A copy of `source`, made on drop.
    pub fn copy(source: impl Into<PathBuf>, file_name: Option<String>) -> Self {
        DragItem::Copy { source: source.into(), file_name }
    }
    /// Bytes written to `file_name` on drop.
    pub fn data(file_name: impl Into<String>, data: impl Into<Vec<u8>>) -> Self {
        DragItem::Data { file_name: file_name.into(), data: data.into() }
    }
    /// A lazy file: `write` receives the destination path when the user drops it.
    pub fn promise<F>(file_name: impl Into<String>, write: F) -> Self
    where
        F: Fn(&Path) -> Result<(), String> + Send + Sync + 'static,
    {
        DragItem::Promise { file_name: file_name.into(), write: Arc::new(write) }
    }

    /// File name the drop target will see.
    pub fn display_name(&self) -> String {
        match self {
            DragItem::File { path } => file_name_of(path),
            DragItem::Copy { source, file_name } => {
                file_name.clone().unwrap_or_else(|| file_name_of(source))
            }
            DragItem::Data { file_name, .. } | DragItem::Promise { file_name, .. } => {
                file_name.clone()
            }
        }
    }
}

impl fmt::Debug for DragItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DragItem::File { path } => f.debug_struct("File").field("path", path).finish(),
            DragItem::Copy { source, file_name } => f
                .debug_struct("Copy")
                .field("source", source)
                .field("file_name", file_name)
                .finish(),
            DragItem::Data { file_name, data } => f
                .debug_struct("Data")
                .field("file_name", file_name)
                .field("len", &data.len())
                .finish(),
            DragItem::Promise { file_name, .. } => {
                f.debug_struct("Promise").field("file_name", file_name).finish_non_exhaustive()
            }
        }
    }
}

/// Options for a drag session.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DragOptions {
    /// Image file used as the drag preview instead of the system file icon.
    #[serde(default)]
    pub icon: Option<PathBuf>,
    /// Encoded image (PNG/JPEG) used as the drag preview; base64 from JS.
    /// Handy for a canvas snapshot of the element being dragged.
    #[serde(default, deserialize_with = "de_base64_opt")]
    pub icon_data: Option<Vec<u8>>,
    /// Preview size in points (default 64).
    #[serde(default)]
    pub icon_size: Option<f64>,
    /// Allow dropping back onto this app's own windows (default `false`,
    /// so the webview does not receive its own drag as a file drop).
    #[serde(default)]
    pub allow_self_drop: bool,
}

/// Handle of a started drag; matches the `session` field of the plugin events.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DragSession {
    pub id: u64,
}

/// Errors returned by [`start_drag`].
#[derive(Debug, Clone)]
pub enum Error {
    /// Native drag-out is not implemented on this platform.
    Unsupported,
    /// No items were given.
    Empty,
    /// An item is invalid (missing file, bad file name, path not allowed...).
    InvalidItem(String),
    /// No mouse button is pressed: start the drag from a `mousedown` /
    /// `pointermove` handler while the button is held.
    NoMouse,
    /// The platform refused to start the drag.
    Platform(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Unsupported => f.write_str("native drag-out is not supported on this platform"),
            Error::Empty => f.write_str("no items to drag"),
            Error::InvalidItem(m) => write!(f, "invalid drag item: {m}"),
            Error::NoMouse => f.write_str(
                "no mouse button is pressed; call startDrag from a mousedown/pointermove handler while the button is held",
            ),
            Error::Platform(m) => write!(f, "drag failed: {m}"),
        }
    }
}

impl std::error::Error for Error {}

impl Serialize for Error {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_string())
    }
}

type PathFilter = Box<dyn Fn(&Path) -> bool + Send + Sync>;
type EmitFn = Box<dyn Fn(&str, serde_json::Value) + Send + Sync>;

static PATH_FILTER: OnceLock<PathFilter> = OnceLock::new();
static EMITTER: OnceLock<EmitFn> = OnceLock::new();

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) fn emit(event: &str, payload: serde_json::Value) {
    if let Some(e) = EMITTER.get() {
        e(event, payload);
    }
}

/// Plugin builder.
#[derive(Default)]
pub struct Builder {
    path_filter: Option<PathFilter>,
}

impl Builder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Restrict which paths the **frontend** may drag as `file` / `copy` items.
    /// Items built in Rust are not filtered. Without a filter every readable path is allowed.
    pub fn path_filter<F>(mut self, filter: F) -> Self
    where
        F: Fn(&Path) -> bool + Send + Sync + 'static,
    {
        self.path_filter = Some(Box::new(filter));
        self
    }

    pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
        let mut filter = self.path_filter;
        PluginBuilder::new("dragout")
            .invoke_handler(tauri::generate_handler![commands::start_drag, commands::is_supported])
            .setup(move |app, _api| {
                if let Some(f) = filter.take() {
                    let _ = PATH_FILTER.set(f);
                }
                let handle = app.app_handle().clone();
                let _ = EMITTER.set(Box::new(move |event, payload| {
                    let _ = handle.emit(event, payload);
                }));
                Ok(())
            })
            .build()
    }
}

/// Plugin with default settings.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    Builder::new().build()
}

/// Whether native drag-out works on this platform.
pub fn is_supported() -> bool {
    cfg!(target_os = "macos")
}

/// Start a native drag from `window` with `items`.
///
/// Must be called while a mouse button is held (from a mousedown/pointermove
/// handler). Safe to call from any thread: the work is dispatched to the main thread.
pub fn start_drag<R: Runtime>(
    window: &WebviewWindow<R>,
    items: Vec<DragItem>,
    options: DragOptions,
) -> Result<DragSession, Error> {
    validate(&items, false)?;
    platform_start(window, items, options)
}

fn validate(items: &[DragItem], from_js: bool) -> Result<(), Error> {
    if items.is_empty() {
        return Err(Error::Empty);
    }
    for item in items {
        match item {
            DragItem::File { path } => check_path(path, from_js)?,
            DragItem::Copy { source, file_name } => {
                check_path(source, from_js)?;
                if let Some(n) = file_name {
                    check_name(n)?;
                }
            }
            DragItem::Data { file_name, .. } | DragItem::Promise { file_name, .. } => {
                check_name(file_name)?
            }
        }
    }
    Ok(())
}

fn check_path(path: &Path, from_js: bool) -> Result<(), Error> {
    if !path.is_absolute() {
        return Err(Error::InvalidItem(format!("path must be absolute: {}", path.display())));
    }
    if from_js {
        if let Some(filter) = PATH_FILTER.get() {
            if !filter(path) {
                return Err(Error::InvalidItem(format!("path not allowed: {}", path.display())));
            }
        }
    }
    if !path.exists() {
        return Err(Error::InvalidItem(format!("no such file: {}", path.display())));
    }
    Ok(())
}

fn check_name(name: &str) -> Result<(), Error> {
    let bad = name.is_empty()
        || name == "."
        || name == ".."
        || name.contains('/')
        || name.contains('\\')
        || name.contains(':')
        || name.contains('\0');
    if bad {
        Err(Error::InvalidItem(format!("bad file name: {name:?}")))
    } else {
        Ok(())
    }
}

fn file_name_of(path: &Path) -> String {
    path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
}

#[cfg(target_os = "macos")]
fn platform_start<R: Runtime>(
    window: &WebviewWindow<R>,
    items: Vec<DragItem>,
    options: DragOptions,
) -> Result<DragSession, Error> {
    let ns_window = window.ns_window().map_err(|e| Error::Platform(e.to_string()))? as usize;
    if macos::is_main_thread() {
        return macos::start(ns_window, items, options);
    }
    let (tx, rx) = std::sync::mpsc::channel();
    window
        .run_on_main_thread(move || {
            let _ = tx.send(macos::start(ns_window, items, options));
        })
        .map_err(|e| Error::Platform(e.to_string()))?;
    rx.recv().map_err(|e| Error::Platform(e.to_string()))?
}

#[cfg(not(target_os = "macos"))]
fn platform_start<R: Runtime>(
    _window: &WebviewWindow<R>,
    _items: Vec<DragItem>,
    _options: DragOptions,
) -> Result<DragSession, Error> {
    Err(Error::Unsupported)
}

mod commands {
    use super::*;

    // A sync command runs on the main thread, which AppKit requires, and the
    // mouse-down event that triggered the IPC call is still current there.
    #[tauri::command]
    pub fn start_drag<R: Runtime>(
        window: WebviewWindow<R>,
        items: Vec<DragItem>,
        options: Option<DragOptions>,
    ) -> Result<DragSession, Error> {
        validate(&items, true)?;
        platform_start(&window, items, options.unwrap_or_default())
    }

    #[tauri::command]
    pub fn is_supported() -> bool {
        super::is_supported()
    }
}

fn decode_base64<E: serde::de::Error>(s: &str) -> Result<Vec<u8>, E> {
    use base64::Engine;
    // Accept data URLs too: "data:image/png;base64,...."
    let s = s.split_once(";base64,").map(|(_, b)| b).unwrap_or(s);
    base64::engine::general_purpose::STANDARD.decode(s.trim().as_bytes()).map_err(E::custom)
}

fn de_base64<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
    let s = String::deserialize(d)?;
    decode_base64(&s)
}

fn de_base64_opt<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
    match Option::<String>::deserialize(d)? {
        Some(s) => decode_base64(&s).map(Some),
        None => Ok(None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_js_items() {
        let v = serde_json::json!([
            {"type": "file", "path": "/tmp/a.pdf"},
            {"type": "copy", "source": "/tmp/b.docx", "fileName": "c.docx"},
            {"type": "data", "fileName": "d.txt", "data": "aGVsbG8="}
        ]);
        let items: Vec<DragItem> = serde_json::from_value(v).unwrap();
        assert!(matches!(&items[0], DragItem::File { path } if path == Path::new("/tmp/a.pdf")));
        assert_eq!(items[1].display_name(), "c.docx");
        assert!(matches!(&items[2], DragItem::Data { data, .. } if data == b"hello"));
    }

    #[test]
    fn parses_options() {
        let v = serde_json::json!({"iconData": "data:image/png;base64,aGk=", "iconSize": 48, "allowSelfDrop": true});
        let o: DragOptions = serde_json::from_value(v).unwrap();
        assert_eq!(o.icon_data.as_deref(), Some(&b"hi"[..]));
        assert_eq!(o.icon_size, Some(48.0));
        assert!(o.allow_self_drop);
        let o: DragOptions = serde_json::from_value(serde_json::json!({})).unwrap();
        assert!(o.icon_data.is_none() && !o.allow_self_drop);
    }

    #[test]
    fn rejects_promise_from_js_and_bad_items() {
        let v = serde_json::json!([{"type": "promise", "fileName": "x"}]);
        assert!(serde_json::from_value::<Vec<DragItem>>(v).is_err());
        assert!(check_name("../evil").is_err());
        assert!(check_name("a/b").is_err());
        assert!(check_name("ok.pdf").is_ok());
        assert!(matches!(validate(&[], true), Err(Error::Empty)));
        assert!(validate(&[DragItem::file("relative.txt")], true).is_err());
        assert!(validate(&[DragItem::file("/definitely/missing/file")], true).is_err());
        assert!(validate(&[DragItem::data("ok.txt", b"x".to_vec())], true).is_ok());
    }
}