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