use std::{cell::Cell, ffi::c_void};
use block2::RcBlock;
use objc2_app_kit::{NSColor, NSColorSampler, NSColorSpace};
use objc2_foundation::MainThreadMarker;
use super::Picked;
use crate::node::color::Color;
pub(super) fn pick(then: Box<dyn FnOnce(Picked) + Send>) {
match MainThreadMarker::new() {
Some(_) => show(then),
None => on_main_thread(Box::new(move || show(then))),
}
}
fn show(then: Box<dyn FnOnce(Picked) + Send>) {
let then = Cell::new(Some(then));
let handler = RcBlock::new(move |color: *mut NSColor| {
let Some(then) = then.take() else {
return;
};
let color = unsafe { color.as_ref() };
then(Ok(color.and_then(srgb)));
});
let sampler = NSColorSampler::new();
unsafe { sampler.showSamplerWithSelectionHandler(&handler) };
}
fn srgb(color: &NSColor) -> Option<Color> {
let color = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace())?;
let channel = |value: f64| (value.clamp(0.0, 1.0) * 255.0).round() as u8;
Some(Color::new(
channel(color.redComponent() as f64),
channel(color.greenComponent() as f64),
channel(color.blueComponent() as f64),
channel(color.alphaComponent() as f64),
))
}
unsafe extern "C" {
static _dispatch_main_q: c_void;
fn dispatch_async_f(queue: *const c_void, context: *mut c_void, work: extern "C" fn(*mut c_void));
}
fn on_main_thread(work: Box<dyn FnOnce() + Send>) {
extern "C" fn run(context: *mut c_void) {
let work = unsafe { Box::from_raw(context as *mut Box<dyn FnOnce() + Send>) };
work();
}
let context = Box::into_raw(Box::new(work)) as *mut c_void;
unsafe { dispatch_async_f(&raw const _dispatch_main_q, context, run) };
}