use ferrokit_core::kept::{UiCell, UiLocal};
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::{AnyClass, AnyObject, NSObject, NSObjectProtocol};
use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSImage, NSImageScaling, NSImageView, NSWorkspace};
use objc2_core_graphics::CGImage;
use objc2_foundation::{NSError, NSInteger, NSRect, NSSize, NSString, NSURL};
use crate::signal::{Effect, untrack};
use crate::view::{Cx, Node, Size, View};
#[link(name = "QuickLookUI", kind = "framework")]
unsafe extern "C" {
#[link_name = "OBJC_CLASS_$_QLPreviewPanel"]
static PREVIEW_PANEL: AnyClass;
}
#[link(name = "QuickLookThumbnailing", kind = "framework")]
unsafe extern "C" {
#[link_name = "OBJC_CLASS_$_QLThumbnailGenerator"]
static GENERATOR: AnyClass;
#[link_name = "OBJC_CLASS_$_QLThumbnailGenerationRequest"]
static REQUEST: AnyClass;
}
fn file_url(path: &std::path::Path) -> Retained<NSURL> {
NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitQuickLookSource"]
#[ivars = RefCell<Vec<Retained<NSURL>>>]
struct Source;
unsafe impl NSObjectProtocol for Source {}
impl Source {
#[unsafe(method(numberOfPreviewItemsInPreviewPanel:))]
fn count(&self, _panel: &AnyObject) -> NSInteger {
self.ivars().borrow().len() as NSInteger
}
#[unsafe(method_id(previewPanel:previewItemAtIndex:))]
fn item(&self, _panel: &AnyObject, index: NSInteger) -> Option<Retained<NSURL>> {
usize::try_from(index).ok().and_then(|i| self.ivars().borrow().get(i).cloned())
}
}
);
thread_local! {
static SOURCE: UiCell<Option<Retained<Source>>> = const { UiCell::new(None) };
}
fn panel() -> Retained<AnyObject> {
unsafe { msg_send![&PREVIEW_PANEL, sharedPreviewPanel] }
}
pub(crate) fn source() -> Option<Retained<NSObject>> {
SOURCE.with_borrow(|s| s.clone().map(Retained::into_super))
}
pub fn quick_look(paths: Vec<PathBuf>, index: usize) {
let Some(mtm) = MainThreadMarker::new() else { return };
crate::documents::install_delegate();
let urls: Vec<Retained<NSURL>> = paths.iter().map(|p| file_url(p)).collect();
let source = SOURCE.with_borrow_mut(|s| {
s.get_or_insert_with(|| {
let this = Source::alloc(mtm).set_ivars(RefCell::default());
unsafe { msg_send![super(this), init] }
})
.clone()
});
source.ivars().replace(urls);
let panel = panel();
unsafe {
let _: () = msg_send![&panel, updateController];
let _: () = msg_send![&panel, setDataSource: &*source];
let _: () = msg_send![&panel, reloadData];
let _: () = msg_send![&panel, setCurrentPreviewItemIndex: index as NSInteger];
let visible: bool = msg_send![&panel, isVisible];
if !visible {
let _: () = msg_send![&panel, makeKeyAndOrderFront: Option::<&AnyObject>::None];
}
}
}
pub fn close_quick_look() {
if !is_quick_look_open() {
return;
}
unsafe {
let _: () = msg_send![&panel(), orderOut: Option::<&AnyObject>::None];
}
}
pub fn is_quick_look_open() -> bool {
unsafe {
let exists: bool = msg_send![&PREVIEW_PANEL, sharedPreviewPanelExists];
exists && msg_send![&panel(), isVisible]
}
}
pub(crate) fn quick_look_state() -> (Vec<PathBuf>, Option<usize>) {
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());
if !is_quick_look_open() {
return (files, None);
}
let index: NSInteger = unsafe { msg_send![&panel(), currentPreviewItemIndex] };
(files, usize::try_from(index).ok())
}
thread_local! {
pub(crate) static THUMBNAILS: Cell<usize> = const { Cell::new(0) };
}
struct Picture(objc2_core_foundation::CFRetained<CGImage>);
unsafe impl Send for Picture {}
fn generate(path: PathBuf, size: (f64, f64), scale: f64) -> Option<Picture> {
let (tx, rx) = std::sync::mpsc::channel::<Option<Picture>>();
let block = RcBlock::new(move |rep: *mut AnyObject, _error: *mut NSError| {
let picture = unsafe { rep.as_ref() }.and_then(|rep| {
let image: *mut CGImage = unsafe { msg_send![rep, CGImage] };
std::ptr::NonNull::new(image).map(|i| Picture(unsafe { objc2_core_foundation::CFRetained::retain(i) }))
});
let _ = tx.send(picture);
});
unsafe {
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];
let generator: Retained<AnyObject> = msg_send![&GENERATOR, sharedGenerator];
let _: () = msg_send![&generator, generateBestRepresentationForRequest: &*request, completionHandler: &*block];
}
rx.recv_timeout(std::time::Duration::from_secs(10)).ok().flatten()
}
pub struct Thumbnail {
path: Box<dyn Fn() -> Option<PathBuf>>,
size: (f64, f64),
}
impl Thumbnail {
pub fn size(mut self, width: f64, height: f64) -> Self {
self.size = (width, height);
self
}
}
impl View for Thumbnail {
fn build(self, cx: &mut Cx) -> Node {
let mtm = cx.mtm;
let (w, h) = self.size;
let view = NSImageView::initWithFrame(NSImageView::alloc(mtm), NSRect::new(objc2_foundation::NSPoint::ZERO, NSSize::new(w, h)));
view.setImageScaling(NSImageScaling::ScaleProportionallyUpOrDown);
let (mut node, _) = Node::leaf(cx, Retained::into_super(Retained::into_super(view.clone())), (false, false), Size { w, h });
let made = Rc::new(Cell::new(0u64));
let scale = view.window().map_or(2.0, |win| win.backingScaleFactor());
let path = self.path;
node.own(Effect::new(move || {
let p = path();
untrack(|| {
let n = made.get() + 1;
made.set(n);
let Some(p) = p else {
view.setImage(None);
return;
};
view.setImage(Some(&NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&p.to_string_lossy()))));
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
objc2_app_kit::NSAccessibility::setAccessibilityLabel(&*view, Some(&NSString::from_str(&name)));
let (v, made) = (view.clone(), made.clone());
crate::spawn(
move || generate(p, (w, h), scale),
move |picture| {
let Some(Picture(cg)) = picture.filter(|_| made.get() == n) else { return };
let size = NSSize::new(CGImage::width(Some(&cg)) as f64 / scale, CGImage::height(Some(&cg)) as f64 / scale);
let image = NSImage::initWithCGImage_size(NSImage::alloc(), &cg, size);
v.setImage(Some(&image));
THUMBNAILS.with(|t| t.set(t.get() + 1));
},
);
});
}));
node
}
}
pub fn thumbnail(path: impl Fn() -> Option<PathBuf> + 'static) -> Thumbnail {
Thumbnail { path: Box::new(path), size: (64.0, 64.0) }
}