Skip to main content

ferrokit/
quicklook.rs

1//! Quick Look: the preview panel Finder opens with Space ([`quick_look`]),
2//! and file thumbnails ([`thumbnail`]), as Finder draws them.
3
4use ferrokit_core::kept::{UiCell, UiLocal};
5use std::cell::{Cell, RefCell};
6use std::path::PathBuf;
7use std::rc::Rc;
8
9use block2::RcBlock;
10use objc2::rc::Retained;
11use objc2::runtime::{AnyClass, AnyObject, NSObject, NSObjectProtocol};
12use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
13use objc2_app_kit::{NSImage, NSImageScaling, NSImageView, NSWorkspace};
14use objc2_core_graphics::CGImage;
15use objc2_foundation::{NSError, NSInteger, NSRect, NSSize, NSString, NSURL};
16
17use crate::signal::{Effect, untrack};
18use crate::view::{Cx, Node, Size, View};
19
20#[link(name = "QuickLookUI", kind = "framework")]
21unsafe extern "C" {
22    #[link_name = "OBJC_CLASS_$_QLPreviewPanel"]
23    static PREVIEW_PANEL: AnyClass;
24}
25
26#[link(name = "QuickLookThumbnailing", kind = "framework")]
27unsafe extern "C" {
28    #[link_name = "OBJC_CLASS_$_QLThumbnailGenerator"]
29    static GENERATOR: AnyClass;
30    #[link_name = "OBJC_CLASS_$_QLThumbnailGenerationRequest"]
31    static REQUEST: AnyClass;
32}
33
34fn file_url(path: &std::path::Path) -> Retained<NSURL> {
35    NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
36}
37
38// ---- the preview panel ----
39
40define_class!(
41    // The preview panel's data source: the files being previewed.
42    #[unsafe(super(NSObject))]
43    #[thread_kind = MainThreadOnly]
44    #[name = "FerrokitQuickLookSource"]
45    #[ivars = RefCell<Vec<Retained<NSURL>>>]
46    struct Source;
47
48    unsafe impl NSObjectProtocol for Source {}
49
50    impl Source {
51        #[unsafe(method(numberOfPreviewItemsInPreviewPanel:))]
52        fn count(&self, _panel: &AnyObject) -> NSInteger {
53            crate::failure::guard("Quick Look (count)", 0, || {
54                self.ivars().borrow().len() as NSInteger
55            })
56        }
57
58        // NSURL is a QLPreviewItem.
59        #[unsafe(method_id(previewPanel:previewItemAtIndex:))]
60        fn item(&self, _panel: &AnyObject, index: NSInteger) -> Option<Retained<NSURL>> {
61            crate::failure::guard("Quick Look (item)", None, || {
62                usize::try_from(index).ok().and_then(|i| self.ivars().borrow().get(i).cloned())
63            })
64        }
65    }
66);
67
68thread_local! {
69    static SOURCE: UiCell<Option<Retained<Source>>> = const { UiCell::new(None) };
70}
71
72fn panel() -> Retained<AnyObject> {
73    // SAFETY: QuickLookUI's shared panel, made on the main thread.
74    unsafe { msg_send![&PREVIEW_PANEL, sharedPreviewPanel] }
75}
76
77/// The data source, if [`quick_look`] has previewed something (for the app
78/// delegate, which takes control of the panel when it opens).
79pub(crate) fn source() -> Option<Retained<NSObject>> {
80    SOURCE.with_borrow(|s| s.clone().map(Retained::into_super))
81}
82
83/// Opens the Quick Look panel on `paths`, at `paths[index]`, as Space does
84/// in Finder (or shows them in the panel if it's open): the arrow keys move
85/// between them, and the panel offers Open With and Share.
86pub fn quick_look(paths: Vec<PathBuf>, index: usize) {
87    let Some(mtm) = MainThreadMarker::new() else { return };
88    crate::documents::install_delegate();
89    let urls: Vec<Retained<NSURL>> = paths.iter().map(|p| file_url(p)).collect();
90    let source = SOURCE.with_borrow_mut(|s| {
91        s.get_or_insert_with(|| {
92            let this = Source::alloc(mtm).set_ivars(RefCell::default());
93            // SAFETY: NSObject's designated initialiser.
94            unsafe { msg_send![super(this), init] }
95        })
96        .clone()
97    });
98    source.ivars().replace(urls);
99    let panel = panel();
100    // SAFETY: QLPreviewPanel's methods, on the main thread; the source is
101    // kept above (the panel holds it weakly).
102    unsafe {
103        let _: () = msg_send![&panel, updateController];
104        let _: () = msg_send![&panel, setDataSource: &*source];
105        let _: () = msg_send![&panel, reloadData];
106        let _: () = msg_send![&panel, setCurrentPreviewItemIndex: index as NSInteger];
107        let visible: bool = msg_send![&panel, isVisible];
108        if !visible {
109            let _: () = msg_send![&panel, makeKeyAndOrderFront: Option::<&AnyObject>::None];
110        }
111    }
112}
113
114/// Closes the Quick Look panel, if it's open.
115pub fn close_quick_look() {
116    if !is_quick_look_open() {
117        return;
118    }
119    // SAFETY: as in `quick_look`.
120    unsafe {
121        let _: () = msg_send![&panel(), orderOut: Option::<&AnyObject>::None];
122    }
123}
124
125/// Whether the Quick Look panel is open.
126pub fn is_quick_look_open() -> bool {
127    // SAFETY: as in `quick_look`.
128    unsafe {
129        let exists: bool = msg_send![&PREVIEW_PANEL, sharedPreviewPanelExists];
130        exists && msg_send![&panel(), isVisible]
131    }
132}
133
134/// What the Quick Look panel shows: its files and the one shown (for checks).
135pub(crate) fn quick_look_state() -> (Vec<PathBuf>, Option<usize>) {
136    let files = SOURCE.with_borrow(|s| s.as_ref().map(|s| s.ivars().borrow().iter().filter_map(|u| u.path()).map(|p| PathBuf::from(p.to_string())).collect()).unwrap_or_default());
137    if !is_quick_look_open() {
138        return (files, None);
139    }
140    // SAFETY: as in `quick_look`.
141    let index: NSInteger = unsafe { msg_send![&panel(), currentPreviewItemIndex] };
142    (files, usize::try_from(index).ok())
143}
144
145// ---- thumbnails ----
146
147thread_local! {
148    pub(crate) static THUMBNAILS: Cell<usize> = const { Cell::new(0) };
149}
150
151/// A thumbnail as a Core Graphics image, sent from Quick Look's queue.
152struct Picture(objc2_core_foundation::CFRetained<CGImage>);
153// SAFETY: CGImage is immutable and documented as safe to use from any thread.
154unsafe impl Send for Picture {}
155
156/// Asks Quick Look for a thumbnail of `path` at `size` points (`scale`
157/// pixels per point), waiting up to 10 seconds; on a worker thread.
158fn generate(path: PathBuf, size: (f64, f64), scale: f64) -> Option<Picture> {
159    let (tx, rx) = std::sync::mpsc::channel::<Option<Picture>>();
160    let block = RcBlock::new(move |rep: *mut AnyObject, _error: *mut NSError| {
161        // SAFETY: a QLThumbnailRepresentation or nil; its CGImage lives as
162        // long as it does, so it's retained before the block returns.
163        let picture = unsafe { rep.as_ref() }.and_then(|rep| {
164            let image: *mut CGImage = unsafe { msg_send![rep, CGImage] };
165            std::ptr::NonNull::new(image).map(|i| Picture(unsafe { objc2_core_foundation::CFRetained::retain(i) }))
166        });
167        let _ = tx.send(picture);
168    });
169    // SAFETY: QuickLookThumbnailing's documented API; it's thread-safe.
170    unsafe {
171        let request: Retained<AnyObject> = msg_send![msg_send![&REQUEST, alloc], initWithFileAtURL: &*file_url(&path), size: NSSize::new(size.0, size.1), scale: scale, representationTypes: usize::MAX];
172        let generator: Retained<AnyObject> = msg_send![&GENERATOR, sharedGenerator];
173        let _: () = msg_send![&generator, generateBestRepresentationForRequest: &*request, completionHandler: &*block];
174    }
175    rx.recv_timeout(std::time::Duration::from_secs(10)).ok().flatten()
176}
177
178/// A file's thumbnail (see [`thumbnail`]).
179pub struct Thumbnail {
180    path: Box<dyn Fn() -> Option<PathBuf>>,
181    size: (f64, f64),
182}
183
184impl Thumbnail {
185    /// Its size in points (64 × 64 unless set); the picture keeps its
186    /// proportions within it.
187    pub fn size(mut self, width: f64, height: f64) -> Self {
188        self.size = (width, height);
189        self
190    }
191}
192
193impl View for Thumbnail {
194    fn build(self, cx: &mut Cx) -> Node {
195        let mtm = cx.mtm;
196        let (w, h) = self.size;
197        let view = NSImageView::initWithFrame(NSImageView::alloc(mtm), NSRect::new(objc2_foundation::NSPoint::ZERO, NSSize::new(w, h)));
198        view.setImageScaling(NSImageScaling::ScaleProportionallyUpOrDown);
199        let (mut node, _) = Node::leaf(cx, Retained::into_super(Retained::into_super(view.clone())), (false, false), Size { w, h });
200        // A newer path's thumbnail wins over an older one still coming.
201        let made = Rc::new(Cell::new(0u64));
202        let scale = view.window().map_or(2.0, |win| win.backingScaleFactor());
203        let path = self.path;
204        node.own(Effect::new(move || {
205            let p = path();
206            untrack(|| {
207                let n = made.get() + 1;
208                made.set(n);
209                let Some(p) = p else {
210                    view.setImage(None);
211                    return;
212                };
213                // The file's icon at once, then its thumbnail when it's made.
214                view.setImage(Some(&NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&p.to_string_lossy()))));
215                let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
216                objc2_app_kit::NSAccessibility::setAccessibilityLabel(&*view, Some(&NSString::from_str(&name)));
217                let (v, made) = (view.clone(), made.clone());
218                crate::spawn(
219                    move || generate(p, (w, h), scale),
220                    move |picture| {
221                        let Some(Picture(cg)) = picture.filter(|_| made.get() == n) else { return };
222                        // Its own proportions (a page, a wide frame), in points.
223                        let size = NSSize::new(CGImage::width(Some(&cg)) as f64 / scale, CGImage::height(Some(&cg)) as f64 / scale);
224                        let image = NSImage::initWithCGImage_size(NSImage::alloc(), &cg, size);
225                        v.setImage(Some(&image));
226                        THUMBNAILS.with(|t| t.set(t.get() + 1));
227                    },
228                );
229            });
230        }));
231        node
232    }
233}
234
235/// A file's thumbnail, as Finder and the Open panel draw it: a page of a
236/// PDF, a frame of a video, a picture, a document's first page. Its icon
237/// shows until the thumbnail is made (on a worker thread); it follows
238/// `path()`'s signals, and VoiceOver reads the file's name.
239///
240/// ```no_run
241/// use ferrokit::*;
242///
243/// let file = Signal::new(Some(std::path::PathBuf::from("/Library/Desktop Pictures")));
244/// let picture = thumbnail(move || file.get()).size(96.0, 96.0);
245/// # let _ = picture;
246/// ```
247pub fn thumbnail(path: impl Fn() -> Option<PathBuf> + 'static) -> Thumbnail {
248    Thumbnail { path: Box::new(path), size: (64.0, 64.0) }
249}