#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;
#[cfg(any(windows, test))]
pub(crate) mod geometry;
use std::{
cell::RefCell,
future::Future,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll, Waker},
};
use crate::{
app::{
WindowHandle,
theme::{Theme, ThemePalette},
},
node::color::Color,
};
pub type Picked = Result<Option<Color>, Unsupported>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, lurq_macros::DevtoolsInspectable)]
pub struct Unsupported;
impl std::fmt::Display for Unsupported {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("picking a color from the screen is not supported on this platform")
}
}
impl std::error::Error for Unsupported {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Look {
pub background: Color,
pub foreground: Color,
pub border: Color,
}
impl Look {
fn of(palette: &ThemePalette) -> Self {
use crate::app::theme::PaletteColor::{Border, Popover, PopoverForeground};
Self {
background: palette.get(Popover),
foreground: palette.get(PopoverForeground),
border: palette.get(Border),
}
}
}
#[derive(Clone, Debug)]
pub struct EyeDropper {
look: Look,
}
impl Default for EyeDropper {
fn default() -> Self {
Self::new()
}
}
impl EyeDropper {
pub fn new() -> Self {
Self {
look: Look::of(&ThemePalette::dark()),
}
}
pub fn theme(mut self, theme: &Theme) -> Self {
self.look = Look::of(&theme.palette());
self
}
pub fn is_supported() -> bool {
STAND_IN.with(|stand_in| stand_in.borrow().is_some()) || cfg!(any(windows, target_os = "macos"))
}
pub fn pick(self, window: &WindowHandle) -> impl Future<Output = Picked> + Send + 'static + use<> {
let _ = window;
let (answer, answering) = Answer::new();
self.pick_then(move |picked| answering.give(picked));
answer
}
pub(crate) fn pick_then(self, then: impl FnOnce(Picked) + Send + 'static) {
if let Some(answer) = STAND_IN.with(|stand_in| stand_in.borrow().clone()) {
then(answer());
return;
}
native_pick(self.look, Box::new(then));
}
pub fn stand_in(answer: impl Fn() -> Picked + 'static) -> StandIn {
let previous = STAND_IN.with(|stand_in| stand_in.borrow_mut().replace(Rc::new(answer)));
StandIn { previous }
}
}
use std::rc::Rc;
thread_local! {
static STAND_IN: RefCell<Option<Rc<dyn Fn() -> Picked>>> = const { RefCell::new(None) };
}
#[must_use = "the stand-in is taken away as the guard is dropped"]
pub struct StandIn {
previous: Option<Rc<dyn Fn() -> Picked>>,
}
impl Drop for StandIn {
fn drop(&mut self) {
let previous = self.previous.take();
STAND_IN.with(|stand_in| *stand_in.borrow_mut() = previous);
}
}
#[cfg(windows)]
fn native_pick(look: Look, then: Box<dyn FnOnce(Picked) + Send>) {
windows::pick(look, then);
}
#[cfg(target_os = "macos")]
fn native_pick(_look: Look, then: Box<dyn FnOnce(Picked) + Send>) {
macos::pick(then);
}
#[cfg(not(any(windows, target_os = "macos")))]
fn native_pick(_look: Look, then: Box<dyn FnOnce(Picked) + Send>) {
then(Err(Unsupported));
}
struct Answer(Arc<Mutex<Slot>>);
#[derive(Default)]
struct Slot {
picked: Option<Picked>,
waker: Option<Waker>,
}
struct Answering(Arc<Mutex<Slot>>);
impl Answer {
fn new() -> (Self, Answering) {
let slot = Arc::new(Mutex::new(Slot::default()));
(Self(slot.clone()), Answering(slot))
}
}
impl Future for Answer {
type Output = Picked;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut slot = self.0.lock().unwrap();
match slot.picked.take() {
Some(picked) => Poll::Ready(picked),
None => {
slot.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
impl Answering {
fn give(self, picked: Picked) {
let waker = {
let mut slot = self.0.lock().unwrap();
slot.picked = Some(picked);
slot.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ready<F: Future>(future: F) -> F::Output {
let mut future = std::pin::pin!(future);
let waker = Waker::noop();
let mut cx = Context::from_waker(waker);
match future.as_mut().poll(&mut cx) {
Poll::Ready(output) => output,
Poll::Pending => panic!("the pick is not over"),
}
}
#[test]
fn a_stand_in_answers_a_pick_and_is_taken_away_with_its_guard() {
let blue = Color::from_hex("#2563EB");
{
let _guard = EyeDropper::stand_in(move || Ok(Some(blue)));
assert!(EyeDropper::is_supported());
let (answer, answering) = Answer::new();
EyeDropper::new().pick_then(move |picked| answering.give(picked));
assert_eq!(ready(answer), Ok(Some(blue)));
let _cancel = EyeDropper::stand_in(|| Ok(None));
let (answer, answering) = Answer::new();
EyeDropper::new().pick_then(move |picked| answering.give(picked));
assert_eq!(ready(answer), Ok(None));
}
assert_eq!(
EyeDropper::is_supported(),
cfg!(any(windows, target_os = "macos")),
"the guards took the stand-ins away"
);
}
#[test]
fn an_answer_given_later_wakes_what_waits_on_it() {
use std::sync::atomic::{AtomicBool, Ordering};
struct Flag(AtomicBool);
impl std::task::Wake for Flag {
fn wake(self: Arc<Self>) {
self.0.store(true, Ordering::SeqCst);
}
}
let flag = Arc::new(Flag(AtomicBool::new(false)));
let waker = Waker::from(flag.clone());
let mut cx = Context::from_waker(&waker);
let (answer, answering) = Answer::new();
let mut answer = std::pin::pin!(answer);
assert!(answer.as_mut().poll(&mut cx).is_pending(), "picking");
std::thread::spawn(move || answering.give(Err(Unsupported)))
.join()
.unwrap();
assert!(flag.0.load(Ordering::SeqCst), "woken");
assert_eq!(answer.as_mut().poll(&mut cx), Poll::Ready(Err(Unsupported)));
}
#[cfg(not(any(windows, target_os = "macos")))]
#[test]
fn a_platform_without_picking_says_so_at_once() {
assert!(!EyeDropper::is_supported());
let (answer, answering) = Answer::new();
EyeDropper::new().pick_then(move |picked| answering.give(picked));
assert_eq!(ready(answer), Err(Unsupported));
}
}