1use 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
38define_class!(
41 #[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 #[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 unsafe { msg_send![&PREVIEW_PANEL, sharedPreviewPanel] }
75}
76
77pub(crate) fn source() -> Option<Retained<NSObject>> {
80 SOURCE.with_borrow(|s| s.clone().map(Retained::into_super))
81}
82
83pub 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 unsafe { msg_send![super(this), init] }
95 })
96 .clone()
97 });
98 source.ivars().replace(urls);
99 let panel = panel();
100 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
114pub fn close_quick_look() {
116 if !is_quick_look_open() {
117 return;
118 }
119 unsafe {
121 let _: () = msg_send![&panel(), orderOut: Option::<&AnyObject>::None];
122 }
123}
124
125pub fn is_quick_look_open() -> bool {
127 unsafe {
129 let exists: bool = msg_send![&PREVIEW_PANEL, sharedPreviewPanelExists];
130 exists && msg_send![&panel(), isVisible]
131 }
132}
133
134pub(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 let index: NSInteger = unsafe { msg_send![&panel(), currentPreviewItemIndex] };
142 (files, usize::try_from(index).ok())
143}
144
145thread_local! {
148 pub(crate) static THUMBNAILS: Cell<usize> = const { Cell::new(0) };
149}
150
151struct Picture(objc2_core_foundation::CFRetained<CGImage>);
153unsafe impl Send for Picture {}
155
156fn 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 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 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
178pub struct Thumbnail {
180 path: Box<dyn Fn() -> Option<PathBuf>>,
181 size: (f64, f64),
182}
183
184impl Thumbnail {
185 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 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 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 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
235pub fn thumbnail(path: impl Fn() -> Option<PathBuf> + 'static) -> Thumbnail {
248 Thumbnail { path: Box::new(path), size: (64.0, 64.0) }
249}