Skip to main content

ferrokit/
transfer.rs

1//! The clipboard and dragging data out: text, PNG images, files, and files
2//! written on demand where they're dropped (a CSV dragged to the Finder).
3
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use objc2::rc::Retained;
8use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
9use objc2::{AllocAnyThread, DefinedClass, define_class, msg_send};
10use objc2_app_kit::{
11    NSFilePromiseProvider, NSFilePromiseProviderDelegate, NSPasteboard, NSPasteboardItem, NSPasteboardTypeFileURL, NSPasteboardTypePNG,
12    NSPasteboardTypeString, NSPasteboardWriting,
13};
14use objc2_foundation::{NSArray, NSData, NSError, NSOperationQueue, NSString, NSURL};
15
16/// A pasteboard: [`Clipboard::general`] is the system clipboard (⌘C/⌘V);
17/// [`Clipboard::private`] is one of the app's own (for tests, or data that
18/// mustn't reach the clipboard).
19pub struct Clipboard(Retained<NSPasteboard>, bool);
20
21impl Clipboard {
22    /// The system clipboard.
23    pub fn general() -> Self {
24        Clipboard(NSPasteboard::generalPasteboard(), false)
25    }
26
27    /// A new pasteboard of the app's own, released when dropped.
28    pub fn private() -> Self {
29        Clipboard(NSPasteboard::pasteboardWithUniqueName(), true)
30    }
31
32    /// The `NSPasteboard`.
33    pub fn pasteboard(&self) -> &NSPasteboard {
34        &self.0
35    }
36
37    /// Replaces the contents with `text`.
38    pub fn set_text(&self, text: &str) {
39        self.0.clearContents();
40        // SAFETY: AppKit's pasteboard type constant.
41        self.0.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
42    }
43
44    /// The text on it, if any.
45    pub fn text(&self) -> Option<String> {
46        // SAFETY: AppKit's pasteboard type constant.
47        self.0.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string())
48    }
49
50    /// Replaces the contents with a PNG image.
51    pub fn set_png(&self, png: &[u8]) {
52        self.0.clearContents();
53        // SAFETY: AppKit's pasteboard type constant.
54        self.0.setData_forType(Some(&NSData::with_bytes(png)), unsafe { NSPasteboardTypePNG });
55    }
56
57    /// The PNG image on it, if any.
58    pub fn png(&self) -> Option<Vec<u8>> {
59        // SAFETY: AppKit's pasteboard type constant.
60        self.0.dataForType(unsafe { NSPasteboardTypePNG }).map(|d| d.to_vec())
61    }
62
63    /// Replaces the contents with files (as the Finder's ⌘C does).
64    pub fn set_files(&self, paths: &[PathBuf]) {
65        self.0.clearContents();
66        let urls: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = paths.iter().map(|p| ProtocolObject::from_retained(file_url(p))).collect();
67        self.0.writeObjects(&NSArray::from_retained_slice(&urls));
68    }
69
70    /// The files on it (copied in the Finder, or dragged).
71    pub fn files(&self) -> Vec<PathBuf> {
72        files_on(&self.0)
73    }
74
75    /// Empties it.
76    pub fn clear(&self) {
77        self.0.clearContents();
78    }
79
80    /// Puts `item` on it, as a drag would carry it. A promised file is
81    /// written now, into the temporary folder, and put on as that file.
82    pub fn set(&self, item: &DragItem) {
83        match item {
84            DragItem::Text(t) => self.set_text(t),
85            DragItem::Png(png) => self.set_png(png),
86            DragItem::File(p) => self.set_files(std::slice::from_ref(p)),
87            DragItem::Promise { name, write } => {
88                let dir = std::env::temp_dir().join(format!("ferrokit-{}", std::process::id()));
89                let _ = std::fs::create_dir_all(&dir);
90                let path = dir.join(name);
91                if write(&path).is_ok() {
92                    self.set_files(&[path]);
93                }
94            }
95        }
96    }
97}
98
99impl Drop for Clipboard {
100    fn drop(&mut self) {
101        if self.1 {
102            // SAFETY: frees a uniquely named pasteboard's resources.
103            let () = unsafe { msg_send![&*self.0, releaseGlobally] };
104        }
105    }
106}
107
108fn file_url(path: &Path) -> Retained<NSURL> {
109    NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
110}
111
112/// The file URLs on `pasteboard`, as paths.
113pub(crate) fn files_on(pasteboard: &NSPasteboard) -> Vec<PathBuf> {
114    let Some(items) = pasteboard.pasteboardItems() else { return Vec::new() };
115    items
116        .iter()
117        // SAFETY: AppKit's pasteboard type constant.
118        .filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }))
119        .filter_map(|s| NSURL::URLWithString(&s)?.path())
120        .map(|p| PathBuf::from(p.to_string()))
121        .collect()
122}
123
124/// A file's writer: called with where to write it.
125pub type WriteFile = Arc<dyn Fn(&Path) -> std::io::Result<()> + Send + Sync>;
126
127/// What a drag carries out of the app (see
128/// [`Canvas::draggable`](crate::Canvas::draggable)).
129#[derive(Clone)]
130pub enum DragItem {
131    /// Text.
132    Text(String),
133    /// A PNG image.
134    Png(Vec<u8>),
135    /// A file that exists.
136    File(PathBuf),
137    /// A file written where it's dropped (the Finder, Mail, a folder in
138    /// another app), named `name`: `write` gets its path when the drop
139    /// lands, so nothing is written for a cancelled drag.
140    Promise {
141        /// The file's name, with its extension (`results.csv`).
142        name: String,
143        /// Writes the file at the given path.
144        write: WriteFile,
145    },
146}
147
148impl DragItem {
149    /// A promised file named `name`, written by `write` when dropped.
150    pub fn promise(name: &str, write: impl Fn(&Path) -> std::io::Result<()> + Send + Sync + 'static) -> Self {
151        DragItem::Promise { name: name.into(), write: Arc::new(write) }
152    }
153
154    /// The pasteboard writer AppKit's drag takes.
155    pub(crate) fn writer(&self) -> Retained<ProtocolObject<dyn NSPasteboardWriting>> {
156        match self {
157            DragItem::Text(t) => ProtocolObject::from_retained(NSString::from_str(t)),
158            DragItem::File(p) => ProtocolObject::from_retained(file_url(p)),
159            DragItem::Png(png) => {
160                let item = NSPasteboardItem::new();
161                // SAFETY: AppKit's pasteboard type constant.
162                item.setData_forType(&NSData::with_bytes(png), unsafe { NSPasteboardTypePNG });
163                ProtocolObject::from_retained(item)
164            }
165            DragItem::Promise { name, write } => {
166                let delegate = Promiser::alloc().set_ivars(Promise { name: name.clone(), write: write.clone() });
167                // SAFETY: NSObject's designated initialiser.
168                let delegate: Retained<Promiser> = unsafe { msg_send![super(delegate), init] };
169                let kind = uti_for(name);
170                // SAFETY: a provider for one file of type `kind`; it keeps its
171                // delegate only weakly, so the provider's userInfo keeps it.
172                let provider = unsafe {
173                    let p = NSFilePromiseProvider::initWithFileType_delegate(NSFilePromiseProvider::alloc(), &NSString::from_str(&kind), ProtocolObject::from_ref(&*delegate));
174                    p.setUserInfo(Some(&delegate));
175                    p
176                };
177                ProtocolObject::from_retained(provider)
178            }
179        }
180    }
181}
182
183/// The type identifier for a file name's extension.
184fn uti_for(name: &str) -> String {
185    let ext = Path::new(name).extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
186    objc2_uniform_type_identifiers::UTType::typeWithFilenameExtension(&NSString::from_str(&ext))
187        .map(|t| t.identifier().to_string())
188        .unwrap_or_else(|| "public.data".into())
189}
190
191pub(crate) struct Promise {
192    name: String,
193    write: WriteFile,
194}
195
196define_class!(
197    // Names and writes a promised file when the drop lands.
198    #[unsafe(super(NSObject))]
199    #[name = "FerrokitFilePromise"]
200    #[ivars = Promise]
201    pub(crate) struct Promiser;
202
203    unsafe impl NSObjectProtocol for Promiser {}
204
205    unsafe impl NSFilePromiseProviderDelegate for Promiser {
206        #[unsafe(method_id(filePromiseProvider:fileNameForType:))]
207        fn file_name(&self, _provider: &NSFilePromiseProvider, _kind: &NSString) -> Retained<NSString> {
208            NSString::from_str(&self.ivars().name)
209        }
210
211        #[unsafe(method(filePromiseProvider:writePromiseToURL:completionHandler:))]
212        fn write_promise(&self, _provider: &NSFilePromiseProvider, url: &NSURL, done: &block2::DynBlock<dyn Fn(*mut NSError)>) {
213            let path = url.path().map(|p| PathBuf::from(p.to_string()));
214            // On a background queue: a panic in the app's writer becomes
215            // the promise's error, not an unwind into Foundation.
216            let result = path.ok_or_else(|| std::io::Error::other("not a file URL")).and_then(|p| {
217                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.ivars().write)(&p))).unwrap_or_else(|_| Err(std::io::Error::other("the writer panicked")))
218            });
219            match result {
220                Ok(()) => done.call((std::ptr::null_mut(),)),
221                Err(e) => {
222                    let error = NSError::new(-1, &NSString::from_str(&format!("ferrokit: {e}")));
223                    done.call((Retained::as_ptr(&error) as *mut NSError,));
224                }
225            }
226        }
227
228        #[unsafe(method_id(operationQueueForFilePromiseProvider:))]
229        fn queue(&self, _provider: &NSFilePromiseProvider) -> Retained<NSOperationQueue> {
230            // Off the main thread: writing a large file mustn't stall the UI.
231            NSOperationQueue::new()
232        }
233    }
234);
235
236/// Writes a promised item into `dir` as its drop would (for checks): the
237/// path written, or the error.
238pub(crate) fn fulfil(item: &DragItem, dir: &Path) -> std::io::Result<PathBuf> {
239    match item {
240        DragItem::Promise { name, write } => {
241            let path = dir.join(name);
242            write(&path)?;
243            Ok(path)
244        }
245        _ => Err(std::io::Error::other("not a promised file")),
246    }
247}